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;
|
|
|
|
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
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
namespace PluralKit.Bot;
|
|
|
|
|
|
|
|
public class Bot
|
2019-04-19 18:48:37 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
private readonly IDiscordCache _cache;
|
|
|
|
|
|
|
|
private readonly Cluster _cluster;
|
|
|
|
private readonly PeriodicStatCollector _collector;
|
|
|
|
private readonly CommandMessageService _commandMessageService;
|
|
|
|
private readonly BotConfig _config;
|
|
|
|
private readonly ErrorMessageService _errorMessageService;
|
|
|
|
private readonly ILogger _logger;
|
|
|
|
private readonly IMetrics _metrics;
|
|
|
|
private readonly DiscordApiClient _rest;
|
2022-03-31 00:42:57 +00:00
|
|
|
private readonly RedisService _redis;
|
2021-11-27 02:10:56 +00:00
|
|
|
private readonly ILifetimeScope _services;
|
|
|
|
|
|
|
|
private Timer _periodicTask; // Never read, just kept here for GC reasons
|
|
|
|
|
|
|
|
public Bot(ILifetimeScope services, ILogger logger, PeriodicStatCollector collector, IMetrics metrics,
|
2022-03-31 00:42:57 +00:00
|
|
|
BotConfig config, RedisService redis,
|
2021-11-27 02:10:56 +00:00
|
|
|
ErrorMessageService errorMessageService, CommandMessageService commandMessageService,
|
|
|
|
Cluster cluster, DiscordApiClient rest, IDiscordCache cache)
|
2019-04-19 18:48:37 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
_logger = logger.ForContext<Bot>();
|
|
|
|
_services = services;
|
|
|
|
_collector = collector;
|
|
|
|
_metrics = metrics;
|
|
|
|
_config = config;
|
|
|
|
_errorMessageService = errorMessageService;
|
|
|
|
_commandMessageService = commandMessageService;
|
|
|
|
_cluster = cluster;
|
|
|
|
_rest = rest;
|
2022-03-31 00:42:57 +00:00
|
|
|
_redis = redis;
|
2021-11-27 02:10:56 +00:00
|
|
|
_cache = cache;
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2022-03-31 00:42:57 +00:00
|
|
|
private string BotStatus => $"{(_config.Prefixes ?? BotConfig.DefaultPrefixes)[0]}help"
|
|
|
|
+ (CustomStatusMessage != null ? $" | {CustomStatusMessage}" : "");
|
|
|
|
public string CustomStatusMessage = null;
|
2022-01-20 10:52:40 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
public void Init()
|
|
|
|
{
|
2022-01-14 23:39:03 +00:00
|
|
|
_cluster.EventReceived += (shard, evt) => OnEventReceived(shard.ShardId, evt);
|
2022-01-20 10:52:40 +00:00
|
|
|
_cluster.DiscordPresence = new GatewayStatusUpdate
|
|
|
|
{
|
|
|
|
Status = GatewayStatusUpdate.UserStatus.Online,
|
|
|
|
Activities = new[]
|
|
|
|
{
|
|
|
|
new Activity
|
|
|
|
{
|
|
|
|
Type = ActivityType.Game,
|
|
|
|
Name = BotStatus
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2021-11-27 02:10:56 +00:00
|
|
|
|
|
|
|
// Init the shard stuff
|
|
|
|
_services.Resolve<ShardInfoService>().Init();
|
2019-04-19 18:48:37 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Not awaited, just needs to run in the background
|
|
|
|
// 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(_ =>
|
2019-04-19 18:48:37 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
var __ = UpdatePeriodic();
|
|
|
|
}, null, timeTillNextWholeMinute, TimeSpan.FromMinutes(1));
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2022-01-14 23:39:03 +00:00
|
|
|
private async Task OnEventReceived(int shardId, IGatewayEvent evt)
|
2021-11-27 02:10:56 +00:00
|
|
|
{
|
2022-01-14 23:39:03 +00:00
|
|
|
// we HandleGatewayEvent **before** getting the own user, because the own user is set in HandleGatewayEvent for ReadyEvent
|
2021-11-27 02:10:56 +00:00
|
|
|
await _cache.HandleGatewayEvent(evt);
|
|
|
|
|
2022-01-14 23:39:03 +00:00
|
|
|
var userId = await _cache.GetOwnUser();
|
|
|
|
await _cache.TryUpdateSelfMember(userId, evt);
|
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// 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)
|
2022-01-14 23:39:03 +00:00
|
|
|
await HandleEvent(shardId, mc);
|
2021-11-27 02:10:56 +00:00
|
|
|
if (evt is MessageUpdateEvent mu)
|
2022-01-14 23:39:03 +00:00
|
|
|
await HandleEvent(shardId, mu);
|
2021-11-27 02:10:56 +00:00
|
|
|
if (evt is MessageDeleteEvent md)
|
2022-01-14 23:39:03 +00:00
|
|
|
await HandleEvent(shardId, md);
|
2021-11-27 02:10:56 +00:00
|
|
|
if (evt is MessageDeleteBulkEvent mdb)
|
2022-01-14 23:39:03 +00:00
|
|
|
await HandleEvent(shardId, mdb);
|
2021-11-27 02:10:56 +00:00
|
|
|
if (evt is MessageReactionAddEvent mra)
|
2022-01-14 23:39:03 +00:00
|
|
|
await HandleEvent(shardId, mra);
|
2021-11-27 02:10:56 +00:00
|
|
|
if (evt is InteractionCreateEvent ic)
|
2022-01-14 23:39:03 +00:00
|
|
|
await HandleEvent(shardId, ic);
|
2021-11-27 02:10:56 +00:00
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
|
2021-11-27 02:10:56 +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
|
2022-01-20 10:52:40 +00:00
|
|
|
await Task.WhenAll(_cluster.Shards.Values.Select(shard =>
|
|
|
|
shard.UpdateStatus(new GatewayStatusUpdate
|
|
|
|
{
|
|
|
|
Activities = new[]
|
2021-11-27 02:10:56 +00:00
|
|
|
{
|
2022-03-30 08:36:22 +00:00
|
|
|
new Activity
|
|
|
|
{
|
|
|
|
Name = "Restarting... (please wait)",
|
|
|
|
Type = ActivityType.Game
|
|
|
|
}
|
2022-01-20 10:52:40 +00:00
|
|
|
},
|
|
|
|
Status = GatewayStatusUpdate.UserStatus.Idle
|
|
|
|
})));
|
2021-11-27 02:10:56 +00:00
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
|
2022-01-14 23:39:03 +00:00
|
|
|
private Task HandleEvent<T>(int shardId, T evt) where T : IGatewayEvent
|
2021-11-27 02:10:56 +00:00
|
|
|
{
|
|
|
|
// We don't want to stall the event pipeline, so we'll "fork" inside here
|
|
|
|
var _ = HandleEventInner();
|
|
|
|
return Task.CompletedTask;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
async Task HandleEventInner()
|
2020-05-05 16:12:34 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
await Task.Yield();
|
2020-05-05 16:12:34 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
await using var serviceScope = _services.BeginLifetimeScope();
|
|
|
|
|
|
|
|
// Find an event handler that can handle the type of event (<T>) we're given
|
|
|
|
IEventHandler<T> handler;
|
|
|
|
try
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
handler = serviceScope.Resolve<IEventHandler<T>>();
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
_logger.Error(e, "Error instantiating handler class");
|
|
|
|
return;
|
2020-12-22 12:15:26 +00:00
|
|
|
}
|
2020-05-01 23:52:52 +00:00
|
|
|
|
2022-01-21 04:38:58 +00:00
|
|
|
using var _ = LogContext.PushProperty("EventId", Guid.NewGuid());
|
|
|
|
using var __ = LogContext.Push(await serviceScope.Resolve<SerilogGatewayEnricherFactory>().GetEnricher(shardId, evt));
|
|
|
|
_logger.Verbose("Received gateway event: {@Event}", evt);
|
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
try
|
2020-05-01 23:52:52 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
var queue = serviceScope.ResolveOptional<HandlerQueue<T>>();
|
2021-06-10 12:21:05 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// 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>>();
|
2022-01-14 23:39:03 +00:00
|
|
|
sentryEnricher?.Enrich(serviceScope.Resolve<Scope>(), shardId, evt);
|
2020-11-16 08:57:16 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
using var timer = _metrics.Measure.Timer.Time(BotMetrics.EventsHandled,
|
|
|
|
new MetricTags("event", typeof(T).Name.Replace("Event", "")));
|
|
|
|
|
|
|
|
// 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
|
|
|
|
if (queue == null || !await queue.TryHandle(evt))
|
2022-01-14 23:39:03 +00:00
|
|
|
await handler.Handle(shardId, evt);
|
2021-11-27 02:10:56 +00:00
|
|
|
}
|
|
|
|
catch (Exception exc)
|
|
|
|
{
|
2022-01-14 23:39:03 +00:00
|
|
|
await HandleError(handler, evt, serviceScope, exc);
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
2019-07-19 00:29:08 +00:00
|
|
|
}
|
2021-11-27 02:10:56 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2022-01-14 23:39:03 +00:00
|
|
|
private async Task HandleError<T>(IEventHandler<T> handler, T evt, ILifetimeScope serviceScope,
|
2021-11-27 02:10:56 +00:00
|
|
|
Exception exc)
|
|
|
|
where T : IGatewayEvent
|
|
|
|
{
|
|
|
|
_metrics.Measure.Meter.Mark(BotMetrics.BotErrors, exc.GetType().FullName);
|
|
|
|
|
2022-01-14 23:39:03 +00:00
|
|
|
var ourUserId = await _cache.GetOwnUser();
|
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Make this beforehand so we can access the event ID for logging
|
|
|
|
var sentryEvent = new SentryEvent(exc);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// If the event is us responding to our own error messages, don't bother logging
|
2022-01-14 23:39:03 +00:00
|
|
|
if (evt is MessageCreateEvent mc && mc.Author.Id == ourUserId)
|
2021-11-27 02:10:56 +00:00
|
|
|
return;
|
2020-05-05 14:42:14 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
var shouldReport = exc.IsOurProblem();
|
|
|
|
if (shouldReport)
|
|
|
|
{
|
|
|
|
// only log exceptions if they're our problem
|
|
|
|
_logger.Error(exc, "Exception in event handler: {SentryEventId}", sentryEvent.EventId);
|
|
|
|
|
|
|
|
// Report error to Sentry
|
|
|
|
// This will just no-op if there's no URL set
|
|
|
|
var sentryScope = serviceScope.Resolve<Scope>();
|
|
|
|
|
|
|
|
// Add some specific info about Discord error responses, as a breadcrumb
|
|
|
|
// 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));
|
|
|
|
|
|
|
|
SentrySdk.CaptureEvent(sentryEvent, sentryScope);
|
|
|
|
|
|
|
|
// most of these errors aren't useful...
|
|
|
|
if (_config.DisableErrorReporting)
|
2020-08-27 16:20:20 +00:00
|
|
|
return;
|
2019-07-19 00:29:08 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Once we've sent it to Sentry, report it to the user (if we have permission to)
|
2022-01-14 20:05:46 +00:00
|
|
|
var reportChannel = handler.ErrorChannelFor(evt, ourUserId);
|
2021-11-27 02:10:56 +00:00
|
|
|
if (reportChannel == null)
|
|
|
|
return;
|
|
|
|
|
|
|
|
var botPerms = await _cache.PermissionsIn(reportChannel.Value);
|
|
|
|
if (botPerms.HasFlag(PermissionSet.SendMessages | PermissionSet.EmbedLinks))
|
|
|
|
await _errorMessageService.SendErrorMessage(reportChannel.Value, sentryEvent.EventId.ToString());
|
2019-04-19 18:48:37 +00:00
|
|
|
}
|
2021-11-27 02:10:56 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
private async Task UpdatePeriodic()
|
|
|
|
{
|
|
|
|
_logger.Debug("Running once-per-minute scheduled tasks");
|
2020-05-05 16:12:34 +00:00
|
|
|
|
2022-03-31 00:42:57 +00:00
|
|
|
// Check from a new custom status from Redis and update Discord accordingly
|
|
|
|
if (_redis.Connection != null)
|
|
|
|
{
|
|
|
|
var newStatus = await _redis.Connection.GetDatabase().StringGetAsync("pluralkit:botstatus");
|
|
|
|
if (newStatus != CustomStatusMessage)
|
|
|
|
{
|
|
|
|
CustomStatusMessage = newStatus;
|
|
|
|
|
|
|
|
_logger.Information("Pushing new bot status message to Discord");
|
|
|
|
await Task.WhenAll(_cluster.Shards.Values.Select(shard =>
|
|
|
|
shard.UpdateStatus(new GatewayStatusUpdate
|
|
|
|
{
|
|
|
|
Activities = new[]
|
|
|
|
{
|
|
|
|
new Activity
|
|
|
|
{
|
|
|
|
Name = BotStatus,
|
|
|
|
Type = ActivityType.Game
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Status = GatewayStatusUpdate.UserStatus.Online
|
|
|
|
})));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Collect some stats, submit them to the metrics backend
|
|
|
|
await _collector.CollectStats();
|
2022-03-23 23:28:51 +00:00
|
|
|
await Task.WhenAll(((IMetricsRoot)_metrics).ReportRunner.RunAllAsync());
|
|
|
|
_logger.Debug("Submitted metrics to backend");
|
2021-11-27 02:10:56 +00:00
|
|
|
}
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|