2019-04-19 18:48:37 +00:00
|
|
|
using System;
|
2020-12-22 12:15:26 +00:00
|
|
|
using System.Collections.Concurrent;
|
2020-05-12 19:23:05 +00:00
|
|
|
using System.Collections.Generic;
|
2019-04-19 18:48:37 +00:00
|
|
|
using System.Linq;
|
2020-04-24 21:47:35 +00:00
|
|
|
using System.Net.WebSockets;
|
2020-05-05 16:12:34 +00:00
|
|
|
using System.Threading;
|
2019-04-19 18:48:37 +00:00
|
|
|
using System.Threading.Tasks;
|
2020-05-01 23:52:52 +00:00
|
|
|
|
2019-07-16 19:59:06 +00:00
|
|
|
using App.Metrics;
|
2019-12-23 00:49:21 +00:00
|
|
|
|
2020-01-26 00:27:45 +00:00
|
|
|
using Autofac;
|
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
using Myriad.Cache;
|
2020-12-23 01:19:02 +00:00
|
|
|
using Myriad.Extensions;
|
2020-12-22 12:15:26 +00:00
|
|
|
using Myriad.Gateway;
|
|
|
|
using Myriad.Rest;
|
|
|
|
using Myriad.Types;
|
2020-04-17 21:10:01 +00:00
|
|
|
|
2020-04-28 23:14:49 +00:00
|
|
|
using NodaTime;
|
|
|
|
|
2020-01-26 00:27:45 +00:00
|
|
|
using PluralKit.Core;
|
2019-10-05 05:41:00 +00:00
|
|
|
|
2019-07-15 19:02:50 +00:00
|
|
|
using Sentry;
|
2020-01-26 00:27:45 +00:00
|
|
|
|
2019-07-18 15:13:42 +00:00
|
|
|
using Serilog;
|
2020-08-26 20:29:24 +00:00
|
|
|
using Serilog.Context;
|
2019-04-19 18:48:37 +00:00
|
|
|
|
2019-04-21 13:33:22 +00:00
|
|
|
namespace PluralKit.Bot
|
2019-04-19 18:48:37 +00:00
|
|
|
{
|
2020-05-01 23:52:52 +00:00
|
|
|
public class Bot
|
2019-04-19 18:48:37 +00:00
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
private readonly ConcurrentDictionary<ulong, GuildMemberPartial> _guildMembers = new();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
private readonly Cluster _cluster;
|
|
|
|
private readonly DiscordApiClient _rest;
|
2020-05-01 23:52:52 +00:00
|
|
|
private readonly ILogger _logger;
|
|
|
|
private readonly ILifetimeScope _services;
|
|
|
|
private readonly PeriodicStatCollector _collector;
|
|
|
|
private readonly IMetrics _metrics;
|
2020-09-20 20:35:05 +00:00
|
|
|
private readonly ErrorMessageService _errorMessageService;
|
2020-10-23 10:18:28 +00:00
|
|
|
private readonly CommandMessageService _commandMessageService;
|
2020-12-22 12:15:26 +00:00
|
|
|
private readonly IDiscordCache _cache;
|
2019-04-19 18:48:37 +00:00
|
|
|
|
2020-05-09 13:49:45 +00:00
|
|
|
private bool _hasReceivedReady = false;
|
2020-05-05 16:12:34 +00:00
|
|
|
private Timer _periodicTask; // Never read, just kept here for GC reasons
|
2019-07-18 15:13:42 +00:00
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
public Bot(ILifetimeScope services, ILogger logger, PeriodicStatCollector collector, IMetrics metrics,
|
2020-12-22 12:15:26 +00:00
|
|
|
ErrorMessageService errorMessageService, CommandMessageService commandMessageService, Cluster cluster, DiscordApiClient rest, IDiscordCache cache)
|
2019-04-19 18:48:37 +00:00
|
|
|
{
|
2020-10-18 05:18:52 +00:00
|
|
|
_logger = logger.ForContext<Bot>();
|
2020-05-01 23:52:52 +00:00
|
|
|
_services = services;
|
2019-07-16 21:34:22 +00:00
|
|
|
_collector = collector;
|
2020-05-01 23:52:52 +00:00
|
|
|
_metrics = metrics;
|
2020-09-20 20:35:05 +00:00
|
|
|
_errorMessageService = errorMessageService;
|
2020-10-23 10:18:28 +00:00
|
|
|
_commandMessageService = commandMessageService;
|
2020-12-22 12:15:26 +00:00
|
|
|
_cluster = cluster;
|
|
|
|
_rest = rest;
|
|
|
|
_cache = cache;
|
2019-04-19 18:48:37 +00:00
|
|
|
}
|
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
public void Init()
|
2019-04-19 18:48:37 +00:00
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
_cluster.EventReceived += OnEventReceived;
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
// Init the shard stuff
|
2020-05-09 13:44:56 +00:00
|
|
|
_services.Resolve<ShardInfoService>().Init();
|
2019-10-05 05:41:00 +00:00
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
// Not awaited, just needs to run in the background
|
2020-05-05 16:12:34 +00:00
|
|
|
// Trying our best to run it at whole minute boundaries (xx:00), with ~250ms buffer
|
|
|
|
// This *probably* doesn't matter in practice but I jut think it's neat, y'know.
|
|
|
|
var timeNow = SystemClock.Instance.GetCurrentInstant();
|
|
|
|
var timeTillNextWholeMinute = TimeSpan.FromMilliseconds(60000 - timeNow.ToUnixTimeMilliseconds() % 60000 + 250);
|
|
|
|
_periodicTask = new Timer(_ =>
|
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
var __ = UpdatePeriodic();
|
2020-05-05 16:12:34 +00:00
|
|
|
}, null, timeTillNextWholeMinute, TimeSpan.FromMinutes(1));
|
|
|
|
}
|
|
|
|
|
2020-12-23 01:19:02 +00:00
|
|
|
public PermissionSet PermissionsIn(ulong channelId)
|
|
|
|
{
|
2021-07-15 10:41:19 +00:00
|
|
|
var channel = _cache.GetRootChannel(channelId);
|
2020-12-23 01:19:02 +00:00
|
|
|
|
|
|
|
if (channel.GuildId != null)
|
|
|
|
{
|
|
|
|
var member = _guildMembers.GetValueOrDefault(channel.GuildId.Value);
|
2021-08-02 20:18:39 +00:00
|
|
|
return _cache.PermissionsFor(channelId, _cluster.User?.Id ?? default, member);
|
2020-12-23 01:19:02 +00:00
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
|
2020-12-23 01:19:02 +00:00
|
|
|
return PermissionSet.Dm;
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
private async Task OnEventReceived(Shard shard, IGatewayEvent evt)
|
|
|
|
{
|
|
|
|
await _cache.HandleGatewayEvent(evt);
|
|
|
|
|
|
|
|
TryUpdateSelfMember(shard, evt);
|
|
|
|
|
|
|
|
// HandleEvent takes a type parameter, automatically inferred by the event type
|
|
|
|
// It will then look up an IEventHandler<TypeOfEvent> in the DI container and call that object's handler method
|
|
|
|
// For registering new ones, see Modules.cs
|
|
|
|
if (evt is MessageCreateEvent mc)
|
|
|
|
await HandleEvent(shard, mc);
|
|
|
|
if (evt is MessageUpdateEvent mu)
|
|
|
|
await HandleEvent(shard, mu);
|
|
|
|
if (evt is MessageDeleteEvent md)
|
|
|
|
await HandleEvent(shard, md);
|
|
|
|
if (evt is MessageDeleteBulkEvent mdb)
|
|
|
|
await HandleEvent(shard, mdb);
|
|
|
|
if (evt is MessageReactionAddEvent mra)
|
|
|
|
await HandleEvent(shard, mra);
|
2021-05-26 20:27:52 +00:00
|
|
|
if (evt is InteractionCreateEvent ic)
|
|
|
|
await HandleEvent(shard, ic);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
// Update shard status for shards immediately on connect
|
|
|
|
if (evt is ReadyEvent re)
|
|
|
|
await HandleReady(shard, re);
|
|
|
|
if (evt is ResumedEvent)
|
|
|
|
await HandleResumed(shard);
|
|
|
|
}
|
|
|
|
|
|
|
|
private void TryUpdateSelfMember(Shard shard, IGatewayEvent evt)
|
|
|
|
{
|
|
|
|
if (evt is GuildCreateEvent gc)
|
|
|
|
_guildMembers[gc.Id] = gc.Members.FirstOrDefault(m => m.User.Id == shard.User?.Id);
|
|
|
|
if (evt is MessageCreateEvent mc && mc.Member != null && mc.Author.Id == shard.User?.Id)
|
|
|
|
_guildMembers[mc.GuildId!.Value] = mc.Member;
|
|
|
|
if (evt is GuildMemberAddEvent gma && gma.User.Id == shard.User?.Id)
|
|
|
|
_guildMembers[gma.GuildId] = gma;
|
|
|
|
if (evt is GuildMemberUpdateEvent gmu && gmu.User.Id == shard.User?.Id)
|
|
|
|
_guildMembers[gmu.GuildId] = gmu;
|
|
|
|
}
|
|
|
|
|
|
|
|
private Task HandleResumed(Shard shard)
|
|
|
|
{
|
|
|
|
return UpdateBotStatus(shard);
|
|
|
|
}
|
|
|
|
|
|
|
|
private Task HandleReady(Shard shard, ReadyEvent _)
|
|
|
|
{
|
|
|
|
_hasReceivedReady = true;
|
|
|
|
return UpdateBotStatus(shard);
|
|
|
|
}
|
|
|
|
|
2020-05-05 16:12:34 +00:00
|
|
|
public async Task Shutdown()
|
|
|
|
{
|
|
|
|
// This will stop the timer and prevent any subsequent invocations
|
|
|
|
await _periodicTask.DisposeAsync();
|
|
|
|
|
|
|
|
// Send users a lil status message
|
|
|
|
// We're not actually properly disconnecting from the gateway (lol) so it'll linger for a few minutes
|
|
|
|
// Should be plenty of time for the bot to connect again next startup and set the real status
|
2020-05-09 13:49:45 +00:00
|
|
|
if (_hasReceivedReady)
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
|
|
|
await Task.WhenAll(_cluster.Shards.Values.Select(shard =>
|
|
|
|
shard.UpdateStatus(new GatewayStatusUpdate
|
|
|
|
{
|
|
|
|
Activities = new[]
|
|
|
|
{
|
|
|
|
new ActivityPartial
|
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
Name = "Restarting... (please wait)",
|
2020-12-22 12:15:26 +00:00
|
|
|
Type = ActivityType.Game
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Status = GatewayStatusUpdate.UserStatus.Idle
|
|
|
|
})));
|
|
|
|
}
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
private Task HandleEvent<T>(Shard shard, T evt) where T : IGatewayEvent
|
2020-05-01 23:52:52 +00:00
|
|
|
{
|
|
|
|
// We don't want to stall the event pipeline, so we'll "fork" inside here
|
|
|
|
var _ = HandleEventInner();
|
2019-10-05 05:41:00 +00:00
|
|
|
return Task.CompletedTask;
|
2020-05-01 23:52:52 +00:00
|
|
|
|
|
|
|
async Task HandleEventInner()
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
await Task.Yield();
|
2021-06-10 12:21:05 +00:00
|
|
|
|
2020-06-14 22:52:20 +00:00
|
|
|
await using var serviceScope = _services.BeginLifetimeScope();
|
2021-07-28 06:09:52 +00:00
|
|
|
|
2020-05-05 14:03:46 +00:00
|
|
|
// Find an event handler that can handle the type of event (<T>) we're given
|
2021-08-23 20:53:58 +00:00
|
|
|
IEventHandler<T> handler;
|
|
|
|
try
|
|
|
|
{
|
|
|
|
handler = serviceScope.Resolve<IEventHandler<T>>();
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
_logger.Error(e, "Error instantiating handler class");
|
|
|
|
return;
|
|
|
|
}
|
2020-11-16 08:57:16 +00:00
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
try
|
|
|
|
{
|
2021-08-23 20:53:58 +00:00
|
|
|
var queue = serviceScope.ResolveOptional<HandlerQueue<T>>();
|
|
|
|
|
2021-07-28 06:09:52 +00:00
|
|
|
using var _ = LogContext.PushProperty("EventId", Guid.NewGuid());
|
|
|
|
using var __ = LogContext.Push(serviceScope.Resolve<SerilogGatewayEnricherFactory>().GetEnricher(shard, evt));
|
|
|
|
_logger.Verbose("Received gateway event: {@Event}", evt);
|
|
|
|
|
|
|
|
// Also, find a Sentry enricher for the event type (if one is present), and ask it to put some event data in the Sentry scope
|
|
|
|
var sentryEnricher = serviceScope.ResolveOptional<ISentryEnricher<T>>();
|
|
|
|
sentryEnricher?.Enrich(serviceScope.Resolve<Scope>(), shard, evt);
|
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
using var timer = _metrics.Measure.Timer.Time(BotMetrics.EventsHandled,
|
2020-12-22 12:15:26 +00:00
|
|
|
new MetricTags("event", typeof(T).Name.Replace("Event", "")));
|
2020-11-16 08:57:16 +00:00
|
|
|
|
2020-05-05 14:03:46 +00:00
|
|
|
// Delegate to the queue to see if it wants to handle this event
|
|
|
|
// the TryHandle call returns true if it's handled the event
|
|
|
|
// Usually it won't, so just pass it on to the main handler
|
2021-08-27 15:03:47 +00:00
|
|
|
if (queue == null || !await queue.TryHandle(evt))
|
2020-11-15 12:53:31 +00:00
|
|
|
await handler.Handle(shard, evt);
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
|
|
|
catch (Exception exc)
|
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
await HandleError(shard, handler, evt, serviceScope, exc);
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
|
|
|
}
|
2019-07-19 00:29:08 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
private async Task HandleError<T>(Shard shard, IEventHandler<T> handler, T evt, ILifetimeScope serviceScope, Exception exc)
|
2021-08-27 15:03:47 +00:00
|
|
|
where T : IGatewayEvent
|
2019-07-19 00:29:08 +00:00
|
|
|
{
|
2020-11-16 08:57:16 +00:00
|
|
|
_metrics.Measure.Meter.Mark(BotMetrics.BotErrors, exc.GetType().FullName);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-05-05 14:42:14 +00:00
|
|
|
// Make this beforehand so we can access the event ID for logging
|
|
|
|
var sentryEvent = new SentryEvent(exc);
|
|
|
|
|
2021-06-10 12:21:05 +00:00
|
|
|
_logger.Error(exc, "Exception in event handler: {SentryEventId}", sentryEvent.EventId);
|
2020-08-27 16:20:20 +00:00
|
|
|
|
|
|
|
// If the event is us responding to our own error messages, don't bother logging
|
2020-12-22 12:15:26 +00:00
|
|
|
if (evt is MessageCreateEvent mc && mc.Author.Id == shard.User?.Id)
|
2020-08-27 16:20:20 +00:00
|
|
|
return;
|
2019-07-19 00:29:08 +00:00
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
var shouldReport = exc.IsOurProblem();
|
|
|
|
if (shouldReport)
|
|
|
|
{
|
|
|
|
// Report error to Sentry
|
|
|
|
// This will just no-op if there's no URL set
|
|
|
|
var sentryScope = serviceScope.Resolve<Scope>();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-05-12 19:23:05 +00:00
|
|
|
// Add some specific info about Discord error responses, as a breadcrumb
|
2020-12-22 12:15:26 +00:00
|
|
|
// TODO: headers to dict
|
|
|
|
// if (exc is BadRequestException bre)
|
|
|
|
// sentryScope.AddBreadcrumb(bre.Response, "response.error", data: new Dictionary<string, string>(bre.Response.Headers));
|
|
|
|
// if (exc is NotFoundException nfe)
|
|
|
|
// sentryScope.AddBreadcrumb(nfe.Response, "response.error", data: new Dictionary<string, string>(nfe.Response.Headers));
|
|
|
|
// if (exc is UnauthorizedException ue)
|
|
|
|
// sentryScope.AddBreadcrumb(ue.Response, "response.error", data: new Dictionary<string, string>(ue.Response.Headers));
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
SentrySdk.CaptureEvent(sentryEvent, sentryScope);
|
|
|
|
|
|
|
|
// Once we've sent it to Sentry, report it to the user (if we have permission to)
|
|
|
|
var reportChannel = handler.ErrorChannelFor(evt);
|
2021-10-29 21:34:28 +00:00
|
|
|
if (reportChannel == null)
|
|
|
|
return;
|
|
|
|
|
|
|
|
var botPerms = PermissionsIn(reportChannel.Value);
|
|
|
|
if (botPerms.HasFlag(PermissionSet.SendMessages | PermissionSet.EmbedLinks))
|
|
|
|
await _errorMessageService.SendErrorMessage(reportChannel.Value, sentryEvent.EventId.ToString());
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
2019-04-19 18:48:37 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-04-25 16:50:07 +00:00
|
|
|
private async Task UpdatePeriodic()
|
2019-04-20 20:25:03 +00:00
|
|
|
{
|
2020-08-27 19:28:36 +00:00
|
|
|
_logger.Debug("Running once-per-minute scheduled tasks");
|
2020-05-05 16:12:34 +00:00
|
|
|
|
|
|
|
await UpdateBotStatus();
|
|
|
|
|
|
|
|
// Collect some stats, submit them to the metrics backend
|
|
|
|
await _collector.CollectStats();
|
2021-08-27 15:03:47 +00:00
|
|
|
await Task.WhenAll(((IMetricsRoot)_metrics).ReportRunner.RunAllAsync());
|
2020-08-27 19:28:36 +00:00
|
|
|
_logger.Debug("Submitted metrics to backend");
|
2020-05-05 16:12:34 +00:00
|
|
|
}
|
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
private async Task UpdateBotStatus(Shard specificShard = null)
|
2020-05-05 16:12:34 +00:00
|
|
|
{
|
2020-05-09 13:49:45 +00:00
|
|
|
// If we're not on any shards, don't bother (this happens if the periodic timer fires before the first Ready)
|
|
|
|
if (!_hasReceivedReady) return;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
var totalGuilds = await _cache.GetAllGuilds().CountAsync();
|
|
|
|
|
2020-05-05 16:12:34 +00:00
|
|
|
try // DiscordClient may throw an exception if the socket is closed (e.g just after OP 7 received)
|
2020-04-24 21:47:35 +00:00
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
Task UpdateStatus(Shard shard) =>
|
|
|
|
shard.UpdateStatus(new GatewayStatusUpdate
|
|
|
|
{
|
|
|
|
Activities = new[]
|
|
|
|
{
|
|
|
|
new ActivityPartial
|
|
|
|
{
|
2021-06-08 08:20:59 +00:00
|
|
|
Name = $"pk;help | in {totalGuilds:N0} servers | shard #{shard.ShardId}",
|
2020-12-22 12:15:26 +00:00
|
|
|
Type = ActivityType.Game,
|
|
|
|
Url = "https://pluralkit.me/"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2020-05-05 16:12:34 +00:00
|
|
|
if (specificShard != null)
|
|
|
|
await UpdateStatus(specificShard);
|
|
|
|
else // Run shard updates concurrently
|
2020-12-22 12:15:26 +00:00
|
|
|
await Task.WhenAll(_cluster.Shards.Values.Select(UpdateStatus));
|
|
|
|
}
|
|
|
|
catch (WebSocketException)
|
|
|
|
{
|
|
|
|
// TODO: this still thrown?
|
2020-04-28 23:14:49 +00:00
|
|
|
}
|
2019-04-25 16:50:07 +00:00
|
|
|
}
|
2019-08-09 10:47:46 +00:00
|
|
|
}
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|