Catalogger.NET/Catalogger.Backend/Bot/Responders/Messages/MessageDeleteResponder.cs

180 lines
6.7 KiB
C#
Raw Permalink Normal View History

// Copyright (C) 2021-present sam (starshines.gay)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
using Catalogger.Backend.Cache.InMemoryCache;
using Catalogger.Backend.Database.Repositories;
2024-08-13 13:08:50 +02:00
using Catalogger.Backend.Extensions;
using Catalogger.Backend.Services;
using Humanizer;
using Remora.Discord.API;
using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.API.Objects;
using Remora.Discord.Extensions.Embeds;
using Remora.Discord.Gateway.Responders;
using Remora.Rest.Core;
2024-08-13 13:08:50 +02:00
using Remora.Results;
namespace Catalogger.Backend.Bot.Responders.Messages;
2024-08-13 13:08:50 +02:00
public class MessageDeleteResponder(
ILogger logger,
GuildRepository guildRepository,
MessageRepository messageRepository,
2024-08-13 13:08:50 +02:00
WebhookExecutorService webhookExecutor,
ChannelCache channelCache,
UserCache userCache,
2024-10-09 17:35:11 +02:00
PluralkitApiService pluralkitApi
) : IResponder<IMessageDelete>
2024-08-13 13:08:50 +02:00
{
private readonly ILogger _logger = logger.ForContext<MessageDeleteResponder>();
2024-10-09 17:35:11 +02:00
private static bool MaybePkProxyTrigger(Snowflake id) =>
id.Timestamp > DateTimeOffset.Now - 1.Minutes();
2024-10-14 14:19:14 +02:00
public async Task<Result> RespondAsync(IMessageDelete evt, CancellationToken ct = default)
2024-08-13 13:08:50 +02:00
{
using var _ = LogUtils.Enrich(evt);
2024-10-14 14:19:14 +02:00
if (!evt.GuildID.IsDefined())
2024-10-09 17:35:11 +02:00
return Result.Success;
2024-08-13 13:08:50 +02:00
2024-10-14 14:19:14 +02:00
if (MaybePkProxyTrigger(evt.ID))
2024-08-13 13:08:50 +02:00
{
_logger.Debug(
"Deleted message {MessageId} is less than 1 minute old, delaying 5 seconds to give PK time to catch up",
2024-10-14 14:19:14 +02:00
evt.ID
2024-10-09 17:35:11 +02:00
);
2024-08-13 13:08:50 +02:00
await Task.Delay(5.Seconds(), ct);
}
if (await messageRepository.IsMessageIgnoredAsync(evt.ID.Value))
2024-10-09 17:35:11 +02:00
return Result.Success;
2024-08-13 13:08:50 +02:00
var guild = await guildRepository.GetAsync(evt.GuildID);
2024-10-14 14:19:14 +02:00
var msg = await messageRepository.GetMessageAsync(evt.ID.Value, ct);
2024-08-13 13:08:50 +02:00
// Sometimes a message that *should* be logged isn't stored in the database, notify the user of that
if (msg == null)
{
_logger.Debug(
"Deleted message {MessageId} should be logged but is not in the database",
evt.ID
);
2024-10-09 17:35:11 +02:00
webhookExecutor.QueueLog(
webhookExecutor.GetLogChannel(guild, LogChannelType.MessageDelete, evt.ChannelID),
2024-10-09 17:35:11 +02:00
new Embed(
Title: "Message deleted",
2024-10-14 14:19:14 +02:00
Description: $"A message not found in the database was deleted in <#{evt.ChannelID}> ({evt.ChannelID}).",
Footer: new EmbedFooter(Text: $"ID: {evt.ID} | Original sent at"),
Timestamp: evt.ID.Timestamp
2024-10-09 17:35:11 +02:00
)
);
2024-08-13 13:08:50 +02:00
return Result.Success;
}
2024-08-15 01:12:34 +02:00
// Check if the message is an edit trigger message.
// If it is, the API will return a valid message for its ID, but the ID won't match either `Id` or `Original`.
// (We also won't have any system/member information stored for it)
2024-10-14 14:19:14 +02:00
if (msg is { System: null, Member: null } && MaybePkProxyTrigger(evt.ID))
{
2024-10-14 14:19:14 +02:00
var pkMsg = await pluralkitApi.GetPluralKitMessageAsync(evt.ID.Value, ct);
if (pkMsg != null && pkMsg.Id != evt.ID.Value && pkMsg.Original != evt.ID.Value)
{
2024-10-09 17:35:11 +02:00
_logger.Debug(
"Deleted message {MessageId} is a `pk;edit` message, ignoring",
2024-10-14 14:19:14 +02:00
evt.ID
2024-10-09 17:35:11 +02:00
);
return Result.Success;
}
}
var logChannel = webhookExecutor.GetLogChannel(
2024-10-09 17:35:11 +02:00
guild,
LogChannelType.MessageDelete,
2024-10-14 14:19:14 +02:00
evt.ChannelID,
2024-10-09 17:35:11 +02:00
msg.UserId
);
if (logChannel is null or 0)
{
_logger.Debug(
"Message {MessageId} should not be logged; either ignored or message delete logs are disabled",
evt.ID
);
}
2024-08-13 13:08:50 +02:00
var user = await userCache.GetUserAsync(DiscordSnowflake.New(msg.UserId));
var builder = new EmbedBuilder()
.WithTitle("Message deleted")
.WithDescription(msg.Content)
.WithColour(DiscordUtils.Red)
.WithFooter($"ID: {msg.Id} | Original sent at")
2024-10-14 14:19:14 +02:00
.WithTimestamp(evt.ID);
2024-08-13 13:08:50 +02:00
if (user != null)
builder.WithAuthor(user.Tag(), url: null, iconUrl: user.AvatarUrl());
2024-10-09 17:35:11 +02:00
if (msg.Member != null)
builder.WithTitle($"Message by {msg.Username} deleted");
2024-08-13 13:08:50 +02:00
string channelMention;
2024-10-14 14:19:14 +02:00
if (!channelCache.TryGet(evt.ChannelID, out var channel))
2024-08-13 13:08:50 +02:00
channelMention = $"<#{msg.ChannelId}>";
2024-10-09 17:35:11 +02:00
else if (
channel.Type
is ChannelType.AnnouncementThread
or ChannelType.PrivateThread
or ChannelType.PublicThread
)
2024-08-13 13:08:50 +02:00
channelMention =
$"<#{channel.ParentID.Value}>\nID: {channel.ParentID.Value}\n\nThread: {channel.Name} (<#{channel.ID}>)";
2024-10-09 17:35:11 +02:00
else
channelMention = $"<#{channel.ID}>\nID: {channel.ID}";
2024-08-13 13:08:50 +02:00
2024-10-09 17:35:11 +02:00
var userMention =
user != null
? $"<@{user.ID}>\n{user.Tag()}\nID: {user.ID}"
: $"<@{msg.UserId}>\nID: {msg.UserId}";
2024-08-13 13:08:50 +02:00
builder.AddField("Channel", channelMention, true);
2024-10-09 17:35:11 +02:00
builder.AddField(
msg.System != null ? "Linked Discord account" : "Sender",
userMention,
true
);
2024-08-13 13:08:50 +02:00
if (msg is { System: not null, Member: not null })
{
builder.AddField("\u200b", "**PluralKit information**", false);
builder.AddField("System ID", msg.System, true);
builder.AddField("Member ID", msg.Member, true);
}
2024-08-15 01:12:34 +02:00
if (msg.Metadata != null)
{
2024-10-09 17:35:11 +02:00
var attachmentInfo = string.Join(
"\n",
2024-08-15 01:12:34 +02:00
msg.Metadata.Attachments.Select(a =>
2024-10-09 17:35:11 +02:00
$"{a.Filename} ({a.ContentType}, {a.Size.Bytes().Humanize()})"
)
);
if (!string.IsNullOrWhiteSpace(attachmentInfo))
builder.AddField("Attachments", attachmentInfo, false);
2024-08-15 01:12:34 +02:00
}
webhookExecutor.QueueLog(logChannel, builder.Build().GetOrThrow());
2024-08-13 13:08:50 +02:00
return Result.Success;
}
2024-10-09 17:35:11 +02:00
}