PluralKit/PluralKit.Bot/Services/LogChannelService.cs

69 lines
2.7 KiB
C#
Raw Normal View History

using System;
2019-04-19 18:48:37 +00:00
using System.Threading.Tasks;
using Dapper;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using PluralKit.Core;
2019-07-18 15:13:42 +00:00
using Serilog;
2019-04-19 18:48:37 +00:00
namespace PluralKit.Bot {
public class LogChannelService {
private readonly EmbedService _embed;
2020-06-13 17:36:43 +00:00
private readonly IDatabase _db;
private readonly IDataStore _data;
private readonly ILogger _logger;
private readonly DiscordRestClient _rest;
2019-04-19 18:48:37 +00:00
2020-06-13 17:36:43 +00:00
public LogChannelService(EmbedService embed, ILogger logger, DiscordRestClient rest, IDatabase db, IDataStore data)
2019-04-19 18:48:37 +00:00
{
2019-10-27 22:01:20 +00:00
_embed = embed;
_rest = rest;
_db = db;
2019-10-27 22:01:20 +00:00
_data = data;
2019-07-18 15:13:42 +00:00
_logger = logger.ForContext<LogChannelService>();
2019-04-19 18:48:37 +00:00
}
public async ValueTask LogMessage(MessageContext ctx, ProxyMatch proxy, DiscordMessage trigger, ulong hookMessage)
{
if (ctx.SystemId == null || ctx.LogChannel == null || ctx.InLogBlacklist) return;
// Find log channel and check if valid
var logChannel = await FindLogChannel(trigger.Channel.GuildId, ctx.LogChannel.Value);
if (logChannel == null || logChannel.Type != ChannelType.Text) return;
// Check bot permissions
if (!trigger.Channel.BotHasAllPermissions(Permissions.SendMessages | Permissions.EmbedLinks)) return;
// Send embed!
await using var conn = await _db.Obtain();
2020-06-13 17:42:04 +00:00
var embed = _embed.CreateLoggedMessageEmbed(await conn.QuerySystem(ctx.SystemId.Value),
await conn.QueryMember(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.SendMessageFixedAsync(content: url, embed: embed);
}
private async Task<DiscordChannel> FindLogChannel(ulong guild, ulong channel)
{
try
{
return await _rest.GetChannelAsync(channel);
}
catch (Exception e) when (e is NotFoundException || e is UnauthorizedException)
{
// Channel doesn't exist or we don't have permission to access it, let's remove it from the database too
_logger.Warning("Attempted to fetch missing log channel {LogChannel}, removing from database", channel);
await using var conn = await _db.Obtain();
2020-06-26 13:06:46 +00:00
await conn.ExecuteAsync("update servers set log_channel = null where id = @Guild",
new {Guild = guild});
}
2019-04-19 18:48:37 +00:00
return null;
}
2019-04-19 18:48:37 +00:00
}
}