mirror of
https://github.com/PluralKit/PluralKit.git
synced 2026-02-07 14:27:54 +00:00
Split message/proxy data up in MessageContext and ProxyMember
This commit is contained in:
parent
ba441a15cc
commit
3d62a0d33c
18 changed files with 296 additions and 499 deletions
|
|
@ -11,10 +11,6 @@ using DSharpPlus.EventArgs;
|
|||
|
||||
using PluralKit.Core;
|
||||
|
||||
using Sentry;
|
||||
|
||||
using Serilog;
|
||||
|
||||
namespace PluralKit.Bot
|
||||
{
|
||||
public class MessageCreated: IEventHandler<MessageCreateEventArgs>
|
||||
|
|
@ -22,83 +18,84 @@ namespace PluralKit.Bot
|
|||
private readonly CommandTree _tree;
|
||||
private readonly DiscordShardedClient _client;
|
||||
private readonly LastMessageCacheService _lastMessageCache;
|
||||
private readonly ILogger _logger;
|
||||
private readonly LoggerCleanService _loggerClean;
|
||||
private readonly IMetrics _metrics;
|
||||
private readonly ProxyService _proxy;
|
||||
private readonly ProxyCache _proxyCache;
|
||||
private readonly Scope _sentryScope;
|
||||
private readonly ILifetimeScope _services;
|
||||
|
||||
public MessageCreated(LastMessageCacheService lastMessageCache, ILogger logger, LoggerCleanService loggerClean, IMetrics metrics, ProxyService proxy, ProxyCache proxyCache, Scope sentryScope, DiscordShardedClient client, CommandTree tree, ILifetimeScope services)
|
||||
private readonly DbConnectionFactory _db;
|
||||
private readonly IDataStore _data;
|
||||
|
||||
public MessageCreated(LastMessageCacheService lastMessageCache, LoggerCleanService loggerClean,
|
||||
IMetrics metrics, ProxyService proxy, DiscordShardedClient client,
|
||||
CommandTree tree, ILifetimeScope services, DbConnectionFactory db, IDataStore data)
|
||||
{
|
||||
_lastMessageCache = lastMessageCache;
|
||||
_logger = logger;
|
||||
_loggerClean = loggerClean;
|
||||
_metrics = metrics;
|
||||
_proxy = proxy;
|
||||
_proxyCache = proxyCache;
|
||||
_sentryScope = sentryScope;
|
||||
_client = client;
|
||||
_tree = tree;
|
||||
_services = services;
|
||||
_db = db;
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public DiscordChannel ErrorChannelFor(MessageCreateEventArgs evt) => evt.Channel;
|
||||
|
||||
private bool IsDuplicateMessage(DiscordMessage evt) =>
|
||||
// We consider a message duplicate if it has the same ID as the previous message that hit the gateway
|
||||
_lastMessageCache.GetLastMessage(evt.ChannelId) == evt.Id;
|
||||
|
||||
public async Task Handle(MessageCreateEventArgs evt)
|
||||
{
|
||||
// Drop the message if we've already received it.
|
||||
// Gateway occasionally resends events for whatever reason and it can break stuff relying on IDs being unique
|
||||
// Not a perfect fix since reordering could still break things but... it's good enough for now
|
||||
// (was considering checking the order of the IDs but IDs aren't guaranteed to be *perfectly* in order, so that'd cause false positives)
|
||||
// LastMessageCache is updated in RegisterMessageMetrics so the ordering here is correct.
|
||||
if (_lastMessageCache.GetLastMessage(evt.Channel.Id) == evt.Message.Id) return;
|
||||
RegisterMessageMetrics(evt);
|
||||
if (evt.Message.MessageType != MessageType.Default) return;
|
||||
if (IsDuplicateMessage(evt.Message)) return;
|
||||
|
||||
// Ignore system messages (member joined, message pinned, etc)
|
||||
var msg = evt.Message;
|
||||
if (msg.MessageType != MessageType.Default) return;
|
||||
|
||||
var cachedGuild = await _proxyCache.GetGuildDataCached(msg.Channel.GuildId);
|
||||
var cachedAccount = await _proxyCache.GetAccountDataCached(msg.Author.Id);
|
||||
// this ^ may be null, do remember that down the line
|
||||
// Log metrics and message info
|
||||
_metrics.Measure.Meter.Mark(BotMetrics.MessagesReceived);
|
||||
_lastMessageCache.AddMessage(evt.Channel.Id, evt.Message.Id);
|
||||
|
||||
// Pass guild bot/WH messages onto the logger cleanup service
|
||||
if (msg.Author.IsBot && msg.Channel.Type == ChannelType.Text)
|
||||
{
|
||||
await _loggerClean.HandleLoggerBotCleanup(msg, cachedGuild);
|
||||
return;
|
||||
}
|
||||
|
||||
// First try parsing a command, then try proxying
|
||||
if (await TryHandleCommand(evt, cachedGuild, cachedAccount)) return;
|
||||
await TryHandleProxy(evt, cachedGuild, cachedAccount);
|
||||
// Try each handler until we find one that succeeds
|
||||
var ctx = await _db.Execute(c => c.QueryMessageContext(evt.Author.Id, evt.Channel.GuildId, evt.Channel.Id));
|
||||
var _ = await TryHandleLogClean(evt, ctx) ||
|
||||
await TryHandleCommand(evt, ctx) ||
|
||||
await TryHandleProxy(evt, ctx);
|
||||
}
|
||||
|
||||
private async Task<bool> TryHandleCommand(MessageCreateEventArgs evt, GuildConfig cachedGuild, CachedAccount cachedAccount)
|
||||
private async ValueTask<bool> TryHandleLogClean(MessageCreateEventArgs evt, MessageContext ctx)
|
||||
{
|
||||
var msg = evt.Message;
|
||||
|
||||
int argPos = -1;
|
||||
if (!evt.Message.Author.IsBot || evt.Message.Channel.Type != ChannelType.Text ||
|
||||
!ctx.LogCleanupEnabled) return false;
|
||||
|
||||
await _loggerClean.HandleLoggerBotCleanup(evt.Message);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async ValueTask<bool> TryHandleCommand(MessageCreateEventArgs evt, MessageContext ctx)
|
||||
{
|
||||
var content = evt.Message.Content;
|
||||
if (content == null) return false;
|
||||
|
||||
var argPos = -1;
|
||||
// Check if message starts with the command prefix
|
||||
if (msg.Content.StartsWith("pk;", StringComparison.InvariantCultureIgnoreCase)) argPos = 3;
|
||||
else if (msg.Content.StartsWith("pk!", StringComparison.InvariantCultureIgnoreCase)) argPos = 3;
|
||||
else if (msg.Content != null && StringUtils.HasMentionPrefix(msg.Content, ref argPos, out var id)) // Set argPos to the proper value
|
||||
if (content.StartsWith("pk;", StringComparison.InvariantCultureIgnoreCase)) argPos = 3;
|
||||
else if (content.StartsWith("pk!", StringComparison.InvariantCultureIgnoreCase)) argPos = 3;
|
||||
else if (StringUtils.HasMentionPrefix(content, ref argPos, out var id)) // Set argPos to the proper value
|
||||
if (id != _client.CurrentUser.Id) // But undo it if it's someone else's ping
|
||||
argPos = -1;
|
||||
|
||||
|
||||
// If we didn't find a prefix, give up handling commands
|
||||
if (argPos == -1) return false;
|
||||
|
||||
|
||||
// Trim leading whitespace from command without actually modifying the wring
|
||||
// This just moves the argPos pointer by however much whitespace is at the start of the post-argPos string
|
||||
var trimStartLengthDiff = msg.Content.Substring(argPos).Length - msg.Content.Substring(argPos).TrimStart().Length;
|
||||
var trimStartLengthDiff = content.Substring(argPos).Length - content.Substring(argPos).TrimStart().Length;
|
||||
argPos += trimStartLengthDiff;
|
||||
|
||||
try
|
||||
{
|
||||
await _tree.ExecuteCommand(new Context(_services, evt.Client, msg, argPos, cachedAccount?.System));
|
||||
var system = ctx.SystemId != null ? await _data.GetSystemById(ctx.SystemId.Value) : null;
|
||||
await _tree.ExecuteCommand(new Context(_services, evt.Client, evt.Message, argPos, system));
|
||||
}
|
||||
catch (PKError)
|
||||
{
|
||||
|
|
@ -109,31 +106,21 @@ namespace PluralKit.Bot
|
|||
return true;
|
||||
}
|
||||
|
||||
private async Task<bool> TryHandleProxy(MessageCreateEventArgs evt, GuildConfig cachedGuild, CachedAccount cachedAccount)
|
||||
private async ValueTask<bool> TryHandleProxy(MessageCreateEventArgs evt, MessageContext ctx)
|
||||
{
|
||||
var msg = evt.Message;
|
||||
|
||||
// If we don't have any cached account data, this means no member in the account has a proxy tag set
|
||||
if (cachedAccount == null) return false;
|
||||
|
||||
try
|
||||
{
|
||||
await _proxy.HandleIncomingMessage(evt.Message, allowAutoproxy: true);
|
||||
return await _proxy.HandleIncomingMessage(evt.Message, ctx, allowAutoproxy: true);
|
||||
}
|
||||
catch (PKError e)
|
||||
{
|
||||
// User-facing errors, print to the channel properly formatted
|
||||
var msg = evt.Message;
|
||||
if (msg.Channel.Guild == null || msg.Channel.BotHasAllPermissions(Permissions.SendMessages))
|
||||
await msg.Channel.SendMessageAsync($"{Emojis.Error} {e.Message}");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void RegisterMessageMetrics(MessageCreateEventArgs evt)
|
||||
{
|
||||
_metrics.Measure.Meter.Mark(BotMetrics.MessagesReceived);
|
||||
_lastMessageCache.AddMessage(evt.Channel.Id, evt.Message.Id);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +1,9 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using DSharpPlus.EventArgs;
|
||||
|
||||
using PluralKit.Core;
|
||||
|
||||
using Sentry;
|
||||
|
||||
|
||||
namespace PluralKit.Bot
|
||||
{
|
||||
|
|
@ -14,38 +11,26 @@ namespace PluralKit.Bot
|
|||
{
|
||||
private readonly LastMessageCacheService _lastMessageCache;
|
||||
private readonly ProxyService _proxy;
|
||||
private readonly ProxyCache _proxyCache;
|
||||
private readonly Scope _sentryScope;
|
||||
private readonly DbConnectionFactory _db;
|
||||
|
||||
public MessageEdited(LastMessageCacheService lastMessageCache, ProxyService proxy, ProxyCache proxyCache, Scope sentryScope)
|
||||
public MessageEdited(LastMessageCacheService lastMessageCache, ProxyService proxy, DbConnectionFactory db)
|
||||
{
|
||||
_lastMessageCache = lastMessageCache;
|
||||
_proxy = proxy;
|
||||
_proxyCache = proxyCache;
|
||||
_sentryScope = sentryScope;
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task Handle(MessageUpdateEventArgs evt)
|
||||
{
|
||||
// Sometimes edit message events arrive for other reasons (eg. an embed gets updated server-side)
|
||||
// If this wasn't a *content change* (ie. there's message contents to read), bail
|
||||
// It'll also sometimes arrive with no *author*, so we'll go ahead and ignore those messages too
|
||||
if (evt.Message.Content == null) return;
|
||||
if (evt.Author == null) return;
|
||||
// Edit message events sometimes arrive with missing data; double-check it's all there
|
||||
if (evt.Message.Content == null || evt.Author == null || evt.Channel.Guild == null) return;
|
||||
|
||||
// Also, if this is in DMs don't bother either
|
||||
if (evt.Channel.Guild == null) return;
|
||||
|
||||
// If this isn't the last message in the channel, don't do anything
|
||||
// Only react to the last message in the channel
|
||||
if (_lastMessageCache.GetLastMessage(evt.Channel.Id) != evt.Message.Id) return;
|
||||
|
||||
// Fetch account and guild info from cache if there is any
|
||||
var account = await _proxyCache.GetAccountDataCached(evt.Author.Id);
|
||||
if (account == null) return; // Again: no cache = no account = no system = no proxy
|
||||
var guild = await _proxyCache.GetGuildDataCached(evt.Channel.GuildId);
|
||||
|
||||
// Just run the normal message handling stuff, with a flag to disable autoproxying
|
||||
await _proxy.HandleIncomingMessage(evt.Message, allowAutoproxy: false);
|
||||
// Just run the normal message handling code, with a flag to disable autoproxying
|
||||
var ctx = await _db.Execute(c => c.QueryMessageContext(evt.Author.Id, evt.Channel.GuildId, evt.Channel.Id));
|
||||
await _proxy.HandleIncomingMessage(evt.Message, ctx, allowAutoproxy: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -20,11 +20,11 @@ namespace PluralKit.Bot
|
|||
_clock = clock;
|
||||
}
|
||||
|
||||
public bool TryMatch(IReadOnlyCollection<ProxyMember> members, out ProxyMatch match, string messageContent,
|
||||
public bool TryMatch(MessageContext ctx, IReadOnlyCollection<ProxyMember> members, out ProxyMatch match, string messageContent,
|
||||
bool hasAttachments, bool allowAutoproxy)
|
||||
{
|
||||
if (TryMatchTags(members, messageContent, hasAttachments, out match)) return true;
|
||||
if (allowAutoproxy && TryMatchAutoproxy(members, messageContent, out match)) return true;
|
||||
if (allowAutoproxy && TryMatchAutoproxy(ctx, members, messageContent, out match)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -37,33 +37,44 @@ namespace PluralKit.Bot
|
|||
return hasAttachments || match.Content.Length > 0;
|
||||
}
|
||||
|
||||
private bool TryMatchAutoproxy(IReadOnlyCollection<ProxyMember> members, string messageContent,
|
||||
private bool TryMatchAutoproxy(MessageContext ctx, IReadOnlyCollection<ProxyMember> members, string messageContent,
|
||||
out ProxyMatch match)
|
||||
{
|
||||
match = default;
|
||||
|
||||
// We handle most autoproxy logic in the database function, so we just look for the member that's marked
|
||||
var info = members.FirstOrDefault(i => i.IsAutoproxyMember);
|
||||
if (info == null) return false;
|
||||
|
||||
// If we're in latch mode and the latch message is too old, fail the match too
|
||||
if (info.AutoproxyMode == AutoproxyMode.Latch && info.LatchMessage != null)
|
||||
// Find the member we should autoproxy (null if none)
|
||||
var member = ctx.AutoproxyMode switch
|
||||
{
|
||||
var timestamp = DiscordUtils.SnowflakeToInstant(info.LatchMessage.Value);
|
||||
if (_clock.GetCurrentInstant() - timestamp > LatchExpiryTime) return false;
|
||||
}
|
||||
AutoproxyMode.Member when ctx.AutoproxyMember != null =>
|
||||
members.FirstOrDefault(m => m.Id == ctx.AutoproxyMember),
|
||||
|
||||
AutoproxyMode.Front when ctx.LastSwitchMembers.Count > 0 =>
|
||||
members.FirstOrDefault(m => m.Id == ctx.LastSwitchMembers[0]),
|
||||
|
||||
AutoproxyMode.Latch when ctx.LastMessageMember != null && !IsLatchExpired(ctx.LastMessage) =>
|
||||
members.FirstOrDefault(m => m.Id == ctx.LastMessageMember.Value),
|
||||
|
||||
_ => null
|
||||
};
|
||||
|
||||
// Match succeeded, build info object and return
|
||||
if (member == null) return false;
|
||||
match = new ProxyMatch
|
||||
{
|
||||
Content = messageContent,
|
||||
Member = info,
|
||||
|
||||
Member = member,
|
||||
|
||||
// We're autoproxying, so not using any proxy tags here
|
||||
// we just find the first pair of tags (if any), otherwise null
|
||||
ProxyTags = info.ProxyTags.FirstOrDefault()
|
||||
ProxyTags = member.ProxyTags.FirstOrDefault()
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool IsLatchExpired(ulong? messageId)
|
||||
{
|
||||
if (messageId == null) return true;
|
||||
var timestamp = DiscordUtils.SnowflakeToInstant(messageId.Value);
|
||||
return _clock.GetCurrentInstant() - timestamp > LatchExpiryTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -20,11 +20,11 @@ namespace PluralKit.Bot
|
|||
{
|
||||
public static readonly TimeSpan MessageDeletionDelay = TimeSpan.FromMilliseconds(1000);
|
||||
|
||||
private LogChannelService _logChannel;
|
||||
private DbConnectionFactory _db;
|
||||
private IDataStore _data;
|
||||
private ILogger _logger;
|
||||
private WebhookExecutorService _webhookExecutor;
|
||||
private readonly LogChannelService _logChannel;
|
||||
private readonly DbConnectionFactory _db;
|
||||
private readonly IDataStore _data;
|
||||
private readonly ILogger _logger;
|
||||
private readonly WebhookExecutorService _webhookExecutor;
|
||||
private readonly ProxyMatcher _matcher;
|
||||
|
||||
public ProxyService(LogChannelService logChannel, IDataStore data, ILogger logger,
|
||||
|
|
@ -38,35 +38,57 @@ namespace PluralKit.Bot
|
|||
_logger = logger.ForContext<ProxyService>();
|
||||
}
|
||||
|
||||
public async Task HandleIncomingMessage(DiscordMessage message, bool allowAutoproxy)
|
||||
public async Task<bool> HandleIncomingMessage(DiscordMessage message, MessageContext ctx, bool allowAutoproxy)
|
||||
{
|
||||
// Quick context checks to quit early
|
||||
if (!IsMessageValid(message)) return;
|
||||
if (!ShouldProxy(message, ctx)) return false;
|
||||
|
||||
// Fetch members and try to match to a specific member
|
||||
var members = await FetchProxyMembers(message.Author.Id, message.Channel.GuildId);
|
||||
if (!_matcher.TryMatch(members, out var match, message.Content, message.Attachments.Count > 0,
|
||||
allowAutoproxy)) return;
|
||||
var members = (await _db.Execute(c => c.QueryProxyMembers(message.Author.Id, message.Channel.GuildId))).ToList();
|
||||
if (!_matcher.TryMatch(ctx, members, out var match, message.Content, message.Attachments.Count > 0,
|
||||
allowAutoproxy)) return false;
|
||||
|
||||
// Do some quick permission checks before going through with the proxy
|
||||
// (do channel checks *after* checking other perms to make sure we don't spam errors when eg. channel is blacklisted)
|
||||
if (!IsProxyValid(message, match)) return;
|
||||
if (!await CheckBotPermissionsOrError(message.Channel)) return;
|
||||
if (!CheckProxyNameBoundsOrError(match)) return;
|
||||
// Permission check after proxy match so we don't get spammed when not actually proxying
|
||||
if (!await CheckBotPermissionsOrError(message.Channel)) return false;
|
||||
if (!CheckProxyNameBoundsOrError(match)) return false;
|
||||
|
||||
// Everything's in order, we can execute the proxy!
|
||||
await ExecuteProxy(message, match);
|
||||
await ExecuteProxy(message, ctx, match);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task ExecuteProxy(DiscordMessage trigger, ProxyMatch match)
|
||||
|
||||
private bool ShouldProxy(DiscordMessage msg, MessageContext ctx)
|
||||
{
|
||||
// Make sure author has a system
|
||||
if (ctx.SystemId == null) return false;
|
||||
|
||||
// Make sure channel is a guild text channel and this is a normal message
|
||||
if (msg.Channel.Type != ChannelType.Text || msg.MessageType != MessageType.Default) return false;
|
||||
|
||||
// Make sure author is a normal user
|
||||
if (msg.Author.IsSystem == true || msg.Author.IsBot || msg.WebhookMessage) return false;
|
||||
|
||||
// Make sure proxying is enabled here
|
||||
if (!ctx.ProxyEnabled || ctx.InBlacklist) return false;
|
||||
|
||||
// Make sure we have either an attachment or message content
|
||||
var isMessageBlank = msg.Content == null || msg.Content.Trim().Length == 0;
|
||||
if (isMessageBlank && msg.Attachments.Count == 0) return false;
|
||||
|
||||
// All good!
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task ExecuteProxy(DiscordMessage trigger, MessageContext ctx, ProxyMatch match)
|
||||
{
|
||||
// Send the webhook
|
||||
var id = await _webhookExecutor.ExecuteWebhook(trigger.Channel, match.Member.ProxyName, match.Member.ProxyAvatar,
|
||||
var id = await _webhookExecutor.ExecuteWebhook(trigger.Channel, match.Member.ProxyName,
|
||||
match.Member.ProxyAvatar,
|
||||
match.Content, trigger.Attachments);
|
||||
|
||||
|
||||
// Handle post-proxy actions
|
||||
await _data.AddMessage(trigger.Author.Id, trigger.Channel.GuildId, trigger.Channel.Id, id, trigger.Id, match.Member.MemberId);
|
||||
await _logChannel.LogMessage(match, trigger, id);
|
||||
await _data.AddMessage(trigger.Author.Id, trigger.Channel.GuildId, trigger.Channel.Id, id, trigger.Id,
|
||||
match.Member.Id);
|
||||
await _logChannel.LogMessage(ctx, match, trigger, id);
|
||||
|
||||
// Wait a second or so before deleting the original message
|
||||
await Task.Delay(MessageDeletionDelay);
|
||||
|
|
@ -81,14 +103,6 @@ namespace PluralKit.Bot
|
|||
}
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyCollection<ProxyMember>> FetchProxyMembers(ulong account, ulong guild)
|
||||
{
|
||||
await using var conn = await _db.Obtain();
|
||||
var members = await conn.QueryAsync<ProxyMember>("proxy_info",
|
||||
new {account_id = account, guild_id = guild}, commandType: CommandType.StoredProcedure);
|
||||
return members.ToList();
|
||||
}
|
||||
|
||||
private async Task<bool> CheckBotPermissionsOrError(DiscordChannel channel)
|
||||
{
|
||||
var permissions = channel.BotPermissions();
|
||||
|
|
@ -114,43 +128,15 @@ namespace PluralKit.Bot
|
|||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
private bool CheckProxyNameBoundsOrError(ProxyMatch match)
|
||||
{
|
||||
var proxyName = match.Member.ProxyName;
|
||||
if (proxyName.Length < 2) throw Errors.ProxyNameTooShort(proxyName);
|
||||
if (proxyName.Length > Limits.MaxProxyNameLength) throw Errors.ProxyNameTooLong(proxyName);
|
||||
|
||||
|
||||
// TODO: this never returns false as it throws instead, should this happen?
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool IsMessageValid(DiscordMessage message)
|
||||
{
|
||||
return
|
||||
// Must be a guild text channel
|
||||
message.Channel.Type == ChannelType.Text &&
|
||||
|
||||
// Must not be a system message
|
||||
message.MessageType == MessageType.Default &&
|
||||
!(message.Author.IsSystem ?? false) &&
|
||||
|
||||
// Must not be a bot or webhook message
|
||||
!message.WebhookMessage &&
|
||||
!message.Author.IsBot &&
|
||||
|
||||
// Must have either an attachment or content (or both, but not neither)
|
||||
(message.Attachments.Count > 0 || (message.Content != null && message.Content.Trim().Length > 0));
|
||||
}
|
||||
|
||||
private bool IsProxyValid(DiscordMessage message, ProxyMatch match)
|
||||
{
|
||||
return
|
||||
// System and member must have proxying enabled in this guild
|
||||
match.Member.ProxyEnabled &&
|
||||
|
||||
// Channel must not be blacklisted here
|
||||
!match.Member.ChannelBlacklist.Contains(message.ChannelId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -28,12 +28,12 @@ namespace PluralKit.Bot {
|
|||
_logger = logger.ForContext<LogChannelService>();
|
||||
}
|
||||
|
||||
public async Task LogMessage(ProxyMatch proxy, DiscordMessage trigger, ulong hookMessage)
|
||||
public async ValueTask LogMessage(MessageContext ctx, ProxyMatch proxy, DiscordMessage trigger, ulong hookMessage)
|
||||
{
|
||||
if (proxy.Member.LogChannel == null || proxy.Member.LogBlacklist.Contains(trigger.ChannelId)) return;
|
||||
if (ctx.SystemId == null || ctx.LogChannel == null || ctx.InLogBlacklist) return;
|
||||
|
||||
// Find log channel and check if valid
|
||||
var logChannel = await FindLogChannel(trigger.Channel.GuildId, proxy);
|
||||
var logChannel = await FindLogChannel(trigger.Channel.GuildId, ctx.LogChannel.Value);
|
||||
if (logChannel == null || logChannel.Type != ChannelType.Text) return;
|
||||
|
||||
// Check bot permissions
|
||||
|
|
@ -41,25 +41,23 @@ namespace PluralKit.Bot {
|
|||
|
||||
// Send embed!
|
||||
await using var conn = await _db.Obtain();
|
||||
var embed = _embed.CreateLoggedMessageEmbed(await _data.GetSystemById(proxy.Member.SystemId),
|
||||
await _data.GetMemberById(proxy.Member.MemberId), hookMessage, trigger.Id, trigger.Author, proxy.Content,
|
||||
var embed = _embed.CreateLoggedMessageEmbed(await _data.GetSystemById(ctx.SystemId.Value),
|
||||
await _data.GetMemberById(proxy.Member.Id), hookMessage, trigger.Id, trigger.Author, proxy.Content,
|
||||
trigger.Channel);
|
||||
var url = $"https://discord.com/channels/{trigger.Channel.GuildId}/{trigger.ChannelId}/{hookMessage}";
|
||||
await logChannel.SendMessageAsync(content: url, embed: embed);
|
||||
}
|
||||
|
||||
private async Task<DiscordChannel> FindLogChannel(ulong guild, ProxyMatch proxy)
|
||||
private async Task<DiscordChannel> FindLogChannel(ulong guild, ulong channel)
|
||||
{
|
||||
var logChannel = proxy.Member.LogChannel.Value;
|
||||
|
||||
try
|
||||
{
|
||||
return await _rest.GetChannelAsync(logChannel);
|
||||
return await _rest.GetChannelAsync(channel);
|
||||
}
|
||||
catch (NotFoundException)
|
||||
{
|
||||
// Channel doesn't exist, let's remove it from the database too
|
||||
_logger.Warning("Attempted to fetch missing log channel {LogChannel}, removing from database", logChannel);
|
||||
_logger.Warning("Attempted to fetch missing log channel {LogChannel}, removing from database", channel);
|
||||
await using var conn = await _db.Obtain();
|
||||
await conn.ExecuteAsync("update servers set log_channel = null where server = @Guild",
|
||||
new {Guild = guild});
|
||||
|
|
|
|||
|
|
@ -64,10 +64,8 @@ namespace PluralKit.Bot
|
|||
|
||||
public ICollection<LoggerBot> Bots => _bots.Values;
|
||||
|
||||
public async ValueTask HandleLoggerBotCleanup(DiscordMessage msg, GuildConfig cachedGuild)
|
||||
public async ValueTask HandleLoggerBotCleanup(DiscordMessage msg)
|
||||
{
|
||||
// Bail if not enabled, or if we don't have permission here
|
||||
if (!cachedGuild.LogCleanupEnabled) return;
|
||||
if (msg.Channel.Type != ChannelType.Text) return;
|
||||
if (!msg.Channel.BotHasAllPermissions(Permissions.ManageMessages)) return;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue