PluralKit/PluralKit.Bot/Handlers/MessageEdited.cs

77 lines
2.9 KiB
C#
Raw Normal View History

2021-01-31 13:42:28 +00:00
using System;
using System.Threading.Tasks;
2020-06-14 20:19:12 +00:00
using App.Metrics;
2021-01-31 13:42:28 +00:00
using Myriad.Cache;
using Myriad.Extensions;
2020-12-22 12:15:26 +00:00
using Myriad.Gateway;
2021-01-31 13:42:28 +00:00
using Myriad.Types;
using PluralKit.Core;
namespace PluralKit.Bot
{
2020-12-22 12:15:26 +00:00
public class MessageEdited: IEventHandler<MessageUpdateEvent>
{
private readonly LastMessageCacheService _lastMessageCache;
private readonly ProxyService _proxy;
2020-06-13 17:36:43 +00:00
private readonly IDatabase _db;
2020-08-29 11:46:27 +00:00
private readonly ModelRepository _repo;
2020-06-14 20:19:12 +00:00
private readonly IMetrics _metrics;
2021-01-31 13:42:28 +00:00
private readonly Cluster _client;
private readonly IDiscordCache _cache;
private readonly Bot _bot;
2021-01-31 13:42:28 +00:00
public MessageEdited(LastMessageCacheService lastMessageCache, ProxyService proxy, IDatabase db, IMetrics metrics, ModelRepository repo, Cluster client, IDiscordCache cache, Bot bot)
{
_lastMessageCache = lastMessageCache;
_proxy = proxy;
_db = db;
2020-06-14 20:19:12 +00:00
_metrics = metrics;
2020-08-29 11:46:27 +00:00
_repo = repo;
2020-09-20 19:49:52 +00:00
_client = client;
2021-01-31 13:42:28 +00:00
_cache = cache;
_bot = bot;
}
2020-12-22 12:15:26 +00:00
public async Task Handle(Shard shard, MessageUpdateEvent evt)
{
2021-01-31 13:42:28 +00:00
if (evt.Author.Value?.Id == _client.User?.Id) return;
// Edit message events sometimes arrive with missing data; double-check it's all there
if (!evt.Content.HasValue || !evt.Author.HasValue || !evt.Member.HasValue)
return;
var channel = _cache.GetChannel(evt.ChannelId);
if (channel.Type != Channel.ChannelType.GuildText)
return;
var guild = _cache.GetGuild(channel.GuildId!.Value);
// Only react to the last message in the channel
if (_lastMessageCache.GetLastMessage(evt.ChannelId) != evt.Id)
return;
// Just run the normal message handling code, with a flag to disable autoproxying
MessageContext ctx;
await using (var conn = await _db.Obtain())
using (_metrics.Measure.Timer.Time(BotMetrics.MessageContextQueryTime))
ctx = await _repo.GetMessageContext(conn, evt.Author.Value!.Id, channel.GuildId!.Value, evt.ChannelId);
// TODO: is this missing anything?
var equivalentEvt = new MessageCreateEvent
{
Id = evt.Id,
ChannelId = evt.ChannelId,
GuildId = channel.GuildId,
Author = evt.Author.Value,
Member = evt.Member.Value,
Content = evt.Content.Value,
Attachments = evt.Attachments.Value ?? Array.Empty<Message.Attachment>()
};
var botPermissions = _bot.PermissionsIn(channel.Id);
await _proxy.HandleIncomingMessage(shard, equivalentEvt, ctx, allowAutoproxy: false, guild: guild, channel: channel, botPermissions: botPermissions);
}
}
}