Skip to content

Instantly share code, notes, and snippets.

@ivanmem
Created December 7, 2019 18:23
Show Gist options
  • Save ivanmem/4aa1229b26c7619fc06e99e0fdeaf75c to your computer and use it in GitHub Desktop.
Save ivanmem/4aa1229b26c7619fc06e99e0fdeaf75c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using VkNet.Abstractions;
using VkNet.Exception;
using VkNet.Model;
using VkNet.Model.GroupUpdate;
using VkNet.Model.RequestParams;
using XeleosBotCore;
using XeleosBotCore.App;
using XeleosBotCore.App.Login;
namespace XeleosBot2LongPool.LongPool
{
public class LongPool
{
public LongPool(OptionsXeleosBotObj options)
{
this._api = Authorization.GetInstance(options.AccessKey);
if (_api == null)
{
Logger.ErrorAsync(_api, null, "Ошибка авторизации.").GetAwaiter().GetResult();
return;
}
this.uploads = new Uploads(_api);
GroupId = Convert.ToUInt64(options.GroupId);
}
private IVkApi _api;
private Uploads uploads;
private ulong GroupId;
public string CommandsPath;
private void MonteceVkBot_Logout(IVkApi owner)
{
Console.WriteLine("Отключение от VK...", ConsoleColor.Red);
}
private Timer WatchTimer = null;
private string _ts;
private string _key;
private string _server;
private delegate void MessagesRecievedDelegate(IVkApi owner, IEnumerable<GroupUpdate> groupUpdate);
private event MessagesRecievedDelegate NewMessages;
/// <summary>
/// Запустить слежение за обновлениями в группе
/// </summary>
public async void StartAsync()
{
try
{
var Pool = await _api.Messages.GetLongPollServerAsync(true);
ulong? ts = null;
if (Pool.Ts == "" || Pool.Ts == null)
{
ts = null;
}
else
{
ts = Convert.ToUInt64(Pool.Ts);
}
await StartTimerAsync();
NewMessages += uploads.GetUpdates;
_api.OnTokenExpires += MonteceVkBot_Logout;
Console.WriteLine("Слежение за сообщениями активировано.", ConsoleColor.Yellow);
}
catch (HttpRequestException)
{
Console.WriteLine("Нет соединения с интернетом!", ConsoleColor.Red);
}
}
private async Task<LongPollServerResponse> GetLongPoolServerAsync()
{
var longPollServer = await _api.Groups.GetLongPollServerAsync(GroupId);
_ts = longPollServer.Ts;
_key = longPollServer.Key;
_server = longPollServer.Server;
return longPollServer;
}
private async Task<IEnumerable<GroupUpdate>> GetLongPoolHistoryAsync()
{
try
{
var response = await _api.Groups.GetBotsLongPollHistoryAsync(
new BotsLongPollHistoryParams
{
Key = _key,
Server = _server,
Ts = _ts,
});
if (!response.Updates.Any())
{
return null;
}
_ts = response.Ts;
return response.Updates;
}
catch (LongPollException exception)
{
if (exception is LongPollOutdateException outdateException)
{
_ts = outdateException.Ts;
}
else
{
try
{
var server = await _api.Groups.GetLongPollServerAsync(GroupId);
_ts = server.Ts;
_key = server.Key;
_server = server.Server;
}
catch (HttpRequestException)
{
Console.WriteLine("Нет соединения с интернетом! " + DateTime.Now, ConsoleColor.Red);
}
catch (PublicServerErrorException ex)
{
Console.WriteLine($"{DateTime.Now} Вконтакте недоступен!\n{ex.Message}", ConsoleColor.Red);
return null;
}
#if !DEBUG
catch (Exception ex)
{
if
(
ex is System.Net.Sockets.SocketException ||
ex is System.Threading.Tasks.TaskCanceledException ||
ex is Flurl.Http.FlurlHttpException ||
ex is IOException ||
ex is System.Net.WebException
)
{
return null;
}
Logger.ErrorAsync(_api, ex, "Ошибка в GetLongPollServer!").GetAwaiter().GetResult();
return null;
}
#endif
}
}
catch (HttpRequestException)
{
Console.WriteLine("Нет соединения с интернетом! " + DateTime.Now, ConsoleColor.Red);
}
catch (PublicServerErrorException ex)
{
Console.WriteLine($"{DateTime.Now} Вконтакте недоступен!\n{ex.Message}", ConsoleColor.Red);
return null;
}
#if !DEBUG
catch (Exception ex)
{
if
(
ex is System.Net.Sockets.SocketException ||
ex is TaskCanceledException ||
ex is Flurl.Http.FlurlHttpException ||
ex is IOException ||
ex is System.Net.WebException
)
{
return null;
}
Logger.ErrorAsync(_api, ex, "Ошибка в GetLongPoolHistory!").GetAwaiter().GetResult();
}
#endif
return null;
}
private async void WatchAsync(object state)
{
var history = await GetLongPoolHistoryAsync();
if (history != null)
{
NewMessages?.Invoke(_api, history);
}
WatchTimer.Change(333, Timeout.Infinite);
}
private async Task StartTimerAsync()
{
await GetLongPoolServerAsync();
WatchTimer = new Timer(new TimerCallback(WatchAsync), null, 333, Timeout.Infinite);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment