NadekoBot/NadekoBot.Core/Common/SocketMessageEventWrapper.cs

92 lines
2.7 KiB
C#
Raw Normal View History

2017-01-06 23:00:55 +00:00
using Discord;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
2017-09-29 22:46:33 +00:00
namespace NadekoBot.Common
2017-01-06 23:00:55 +00:00
{
public class ReactionEventWrapper : IDisposable
{
public IUserMessage Message { get; }
2017-01-06 23:00:55 +00:00
public event Action<SocketReaction> OnReactionAdded = delegate { };
public event Action<SocketReaction> OnReactionRemoved = delegate { };
public event Action OnReactionsCleared = delegate { };
public ReactionEventWrapper(DiscordSocketClient client, IUserMessage msg)
2017-01-06 23:00:55 +00:00
{
2017-04-15 00:54:19 +00:00
Message = msg ?? throw new ArgumentNullException(nameof(msg));
2017-05-22 23:59:31 +00:00
_client = client;
2017-01-06 23:00:55 +00:00
2017-05-22 23:59:31 +00:00
_client.ReactionAdded += Discord_ReactionAdded;
_client.ReactionRemoved += Discord_ReactionRemoved;
_client.ReactionsCleared += Discord_ReactionsCleared;
2017-01-06 23:00:55 +00:00
}
2017-04-15 00:54:19 +00:00
private Task Discord_ReactionsCleared(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel)
2017-01-06 23:00:55 +00:00
{
Task.Run(() =>
{
try
{
if (msg.Id == Message.Id)
OnReactionsCleared?.Invoke();
}
catch { }
});
2017-01-15 01:28:33 +00:00
return Task.CompletedTask;
2017-01-06 23:00:55 +00:00
}
2017-04-15 00:54:19 +00:00
private Task Discord_ReactionRemoved(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel, SocketReaction reaction)
2017-01-06 23:00:55 +00:00
{
Task.Run(() =>
{
try
{
if (msg.Id == Message.Id)
OnReactionRemoved?.Invoke(reaction);
}
catch { }
});
2017-01-15 01:28:33 +00:00
return Task.CompletedTask;
2017-01-06 23:00:55 +00:00
}
2017-04-15 00:54:19 +00:00
private Task Discord_ReactionAdded(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel, SocketReaction reaction)
2017-01-06 23:00:55 +00:00
{
Task.Run(() =>
{
try
{
if (msg.Id == Message.Id)
OnReactionAdded?.Invoke(reaction);
}
catch { }
});
2017-01-15 01:28:33 +00:00
return Task.CompletedTask;
2017-01-06 23:00:55 +00:00
}
public void UnsubAll()
{
2017-05-22 23:59:31 +00:00
_client.ReactionAdded -= Discord_ReactionAdded;
_client.ReactionRemoved -= Discord_ReactionRemoved;
_client.ReactionsCleared -= Discord_ReactionsCleared;
OnReactionAdded = null;
OnReactionRemoved = null;
OnReactionsCleared = null;
2017-01-06 23:00:55 +00:00
}
private bool disposing = false;
private readonly DiscordSocketClient _client;
2017-05-22 23:59:31 +00:00
2017-01-06 23:00:55 +00:00
public void Dispose()
{
if (disposing)
return;
disposing = true;
UnsubAll();
}
}
}