Skip to content

Instantly share code, notes, and snippets.

@ivanmem
Last active February 14, 2020 20:24
Show Gist options
  • Save ivanmem/fe4aa3d53be95c367e5f11b16c9f1727 to your computer and use it in GitHub Desktop.
Save ivanmem/fe4aa3d53be95c367e5f11b16c9f1727 to your computer and use it in GitHub Desktop.
LongPoolGroup.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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 is null)
{
Logger.Error(_api, null, "Ошибка авторизации.");
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 bool IsActive;
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 void Start()
{
try
{
LongPollServerResponse Pool = _api.Messages.GetLongPollServer(true);
ulong? ts = null;
if (Pool.Ts == "" || Pool.Ts == null)
{
ts = null;
}
else
{
ts = Convert.ToUInt64(Pool.Ts);
}
StartAsync(ts, Pool.Pts);
NewMessages += uploads.GetUpdate;
_api.OnTokenExpires += MonteceVkBot_Logout;
Console.WriteLine("Слежение за сообщениями активировано.", ConsoleColor.Yellow);
}
catch (System.Net.Http.HttpRequestException ex)
{
Console.WriteLine("Нет соединения с интернетом!", ConsoleColor.Red);
}
}
private LongPollServerResponse GetLongPoolServer(ulong? lastPts = null)
{
LongPollServerResponse longPollServer = _api.Groups.GetLongPollServer(GroupId);
_ts = longPollServer.Ts;
_key = longPollServer.Key;
_server = longPollServer.Server;
return longPollServer;
}
private Task<LongPollServerResponse> GetLongPoolServerAsync(ulong? lastPts = null)
{
return Task.Run(() =>
{
return GetLongPoolServer(lastPts);
});
}
private IEnumerable<GroupUpdate> GetLongPoolHistory()
{
try
{
BotsLongPollHistoryResponse response = _api.Groups.GetBotsLongPollHistory(
new BotsLongPollHistoryParams
{
Key = _key,
Server = _server,
Ts = _ts,
});
if (response.Updates.Count() == 0)
{
return null;
}
_ts = response.Ts;
return response.Updates;
}
catch (LongPollException exception)
{
if (exception is LongPollOutdateException outdateException)
{
_ts = outdateException.Ts;
}
else
{
try
{
LongPollServerResponse server = _api.Groups.GetLongPollServer(GroupId);
_ts = server.Ts;
_key = server.Key;
_server = server.Server;
}
catch (System.Net.Http.HttpRequestException ex)
{
Console.WriteLine("Нет соединения с интернетом! " + DateTime.Now, ConsoleColor.Red);
}
catch (VkNet.Exception.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.Error(_api, ex, "Ошибка в GetLongPollServer!");
return null;
}
#endif
}
}
catch (System.Net.Http.HttpRequestException ex)
{
Console.WriteLine("Нет соединения с интернетом! " + DateTime.Now, ConsoleColor.Red);
}
catch (VkNet.Exception.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.Error(_api, ex, "Ошибка в GetLongPoolHistory!");
}
#endif
return null;
}
private Task<IEnumerable<GroupUpdate>> GetLongPoolHistoryAsync()
{
return Task.Run(() => { return GetLongPoolHistory(); });
}
private async void WatchAsync(object state)
{
IEnumerable<GroupUpdate> history = await GetLongPoolHistoryAsync();
if (!(history is null))
{
//CurrentSleepSteps = 0;
NewMessages?.Invoke(_api, history);
}
//else if (CurrentSleepSteps < MaxSleepSteps)
//{
// CurrentSleepSteps++;
//}
WatchTimer.Change(333, Timeout.Infinite);
}
private async void StartAsync(ulong? lastTs = null, ulong? lastPts = null)
{
if (IsActive)
{
Console.WriteLine("Messages for {0} already watching", ConsoleColor.Red);
}
IsActive = true;
await GetLongPoolServerAsync(lastPts);
WatchTimer = new Timer(new TimerCallback(WatchAsync), null, 333, Timeout.Infinite);
}
private void Stop()
{
if (WatchTimer != null)
{
WatchTimer.Dispose();
}
IsActive = false;
WatchTimer = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment