2021-11-08 05:46:26 +00:00
|
|
|
|
global using Discord;
|
|
|
|
|
global using Discord.WebSocket;
|
2022-05-07 04:38:36 +00:00
|
|
|
|
using Discord.Interactions;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using System.Reflection;
|
2021-11-08 05:46:26 +00:00
|
|
|
|
using System.Text;
|
2022-06-29 04:46:58 +00:00
|
|
|
|
using WorldTime.Data;
|
2021-11-08 05:46:26 +00:00
|
|
|
|
|
|
|
|
|
namespace WorldTime;
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Main class for the program. Configures the client on start and occasionally prints status information.
|
|
|
|
|
/// </summary>
|
|
|
|
|
internal class WorldTime : IDisposable {
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Number of seconds between each time the status task runs, in seconds.
|
|
|
|
|
/// </summary>
|
|
|
|
|
#if DEBUG
|
2022-08-29 21:51:27 +00:00
|
|
|
|
internal const int StatusInterval = 20;
|
2021-11-08 05:46:26 +00:00
|
|
|
|
#else
|
2022-08-29 21:51:27 +00:00
|
|
|
|
internal const int StatusInterval = 300;
|
2021-11-08 05:46:26 +00:00
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
private readonly Task _statusTask;
|
2022-08-29 21:51:27 +00:00
|
|
|
|
private readonly CancellationTokenSource _statusCancel;
|
2022-05-07 04:38:36 +00:00
|
|
|
|
private readonly IServiceProvider _services;
|
2022-08-29 21:51:27 +00:00
|
|
|
|
private readonly BackgroundUserListLoad _bgFetch;
|
2021-11-08 05:46:26 +00:00
|
|
|
|
|
|
|
|
|
internal Configuration Config { get; }
|
2022-05-07 04:38:36 +00:00
|
|
|
|
internal DiscordShardedClient DiscordClient => _services.GetRequiredService<DiscordShardedClient>();
|
2021-11-08 05:46:26 +00:00
|
|
|
|
|
2022-06-29 04:46:58 +00:00
|
|
|
|
public WorldTime(Configuration cfg) {
|
|
|
|
|
var ver = Assembly.GetExecutingAssembly().GetName().Version;
|
2021-11-08 05:46:26 +00:00
|
|
|
|
Program.Log(nameof(WorldTime), $"Version {ver!.ToString(3)} is starting...");
|
|
|
|
|
|
|
|
|
|
Config = cfg;
|
|
|
|
|
|
2022-05-07 04:38:36 +00:00
|
|
|
|
// Configure client, set up command handling
|
|
|
|
|
var clientConf = new DiscordSocketConfig() {
|
2021-11-08 05:46:26 +00:00
|
|
|
|
LogLevel = LogSeverity.Info,
|
|
|
|
|
DefaultRetryMode = RetryMode.RetryRatelimit,
|
|
|
|
|
MessageCacheSize = 0, // disable message cache
|
2022-08-29 21:51:27 +00:00
|
|
|
|
GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMembers,
|
2022-08-10 01:21:03 +00:00
|
|
|
|
SuppressUnknownDispatchWarnings = true,
|
2023-09-09 17:42:08 +00:00
|
|
|
|
LogGatewayIntentWarnings = false,
|
|
|
|
|
FormatUsersInBidirectionalUnicode = false
|
2022-05-07 04:38:36 +00:00
|
|
|
|
};
|
|
|
|
|
_services = new ServiceCollection()
|
|
|
|
|
.AddSingleton(new DiscordShardedClient(clientConf))
|
|
|
|
|
.AddSingleton(s => new InteractionService(s.GetRequiredService<DiscordShardedClient>()))
|
2022-06-29 04:46:58 +00:00
|
|
|
|
.AddTransient(typeof(BotDatabaseContext))
|
2022-05-07 04:38:36 +00:00
|
|
|
|
.BuildServiceProvider();
|
2021-11-08 05:46:26 +00:00
|
|
|
|
DiscordClient.Log += DiscordClient_Log;
|
|
|
|
|
DiscordClient.ShardReady += DiscordClient_ShardReady;
|
2022-05-07 04:38:36 +00:00
|
|
|
|
var iasrv = _services.GetRequiredService<InteractionService>();
|
|
|
|
|
DiscordClient.InteractionCreated += DiscordClient_InteractionCreated;
|
|
|
|
|
iasrv.SlashCommandExecuted += InteractionService_SlashCommandExecuted;
|
|
|
|
|
|
2021-11-08 05:46:26 +00:00
|
|
|
|
// Start status reporting thread
|
2022-08-29 21:51:27 +00:00
|
|
|
|
_statusCancel = new CancellationTokenSource();
|
|
|
|
|
_statusTask = Task.Factory.StartNew(StatusLoop, _statusCancel.Token,
|
2021-11-08 05:46:26 +00:00
|
|
|
|
TaskCreationOptions.LongRunning, TaskScheduler.Default);
|
2022-08-29 21:51:27 +00:00
|
|
|
|
|
|
|
|
|
_bgFetch = new(_services);
|
2021-11-08 05:46:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task StartAsync() {
|
2022-05-07 04:38:36 +00:00
|
|
|
|
await _services.GetRequiredService<InteractionService>().AddModulesAsync(Assembly.GetExecutingAssembly(), _services);
|
2021-11-08 05:46:26 +00:00
|
|
|
|
await DiscordClient.LoginAsync(TokenType.Bot, Config.BotToken).ConfigureAwait(false);
|
|
|
|
|
await DiscordClient.StartAsync().ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose() {
|
2022-08-29 21:51:27 +00:00
|
|
|
|
_statusCancel.Cancel();
|
2021-11-08 05:46:26 +00:00
|
|
|
|
_statusTask.Wait(10000);
|
|
|
|
|
if (!_statusTask.IsCompleted)
|
|
|
|
|
Program.Log(nameof(WorldTime), "Warning: Main thread did not cleanly finish up in time. Continuing...");
|
|
|
|
|
|
2022-08-29 21:51:27 +00:00
|
|
|
|
_statusCancel.Dispose();
|
2021-11-08 05:46:26 +00:00
|
|
|
|
|
|
|
|
|
Program.Log(nameof(WorldTime), $"Uptime: {Program.BotUptime}");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task StatusLoop() {
|
|
|
|
|
try {
|
2022-08-29 21:51:27 +00:00
|
|
|
|
await Task.Delay(30000, _statusCancel.Token).ConfigureAwait(false); // initial 30 second delay
|
|
|
|
|
while (!_statusCancel.IsCancellationRequested) {
|
2021-11-08 05:46:26 +00:00
|
|
|
|
Program.Log(nameof(WorldTime), $"Bot uptime: {Program.BotUptime}");
|
|
|
|
|
|
2022-08-29 21:51:27 +00:00
|
|
|
|
await PeriodicReport(DiscordClient.CurrentUser.Id, DiscordClient.Guilds.Count, _statusCancel.Token).ConfigureAwait(false);
|
|
|
|
|
await Task.Delay(StatusInterval * 1000, _statusCancel.Token).ConfigureAwait(false);
|
2021-11-08 05:46:26 +00:00
|
|
|
|
}
|
|
|
|
|
} catch (TaskCanceledException) { }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static readonly HttpClient _httpClient = new();
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Called by the status loop. Reports guild count to the console and to external services.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task PeriodicReport(ulong botId, int guildCount, CancellationToken cancellationToken) {
|
|
|
|
|
var avg = (float)guildCount / Config.ShardTotal;
|
|
|
|
|
Program.Log("Report", $"Currently in {guildCount} guilds. Average shard load: {avg:0.0}.");
|
|
|
|
|
if (botId == 0) return;
|
|
|
|
|
|
|
|
|
|
// Discord Bots
|
|
|
|
|
if (!string.IsNullOrEmpty(Config.DBotsToken)) {
|
|
|
|
|
try {
|
2024-05-10 06:22:51 +00:00
|
|
|
|
var dBotsApiUrl = $"https://discord.bots.gg/api/v1/bots/{ botId }/stats";
|
2021-11-08 05:46:26 +00:00
|
|
|
|
var body = $"{{ \"guildCount\": {guildCount} }}";
|
|
|
|
|
var uri = new Uri(string.Format(dBotsApiUrl));
|
|
|
|
|
|
|
|
|
|
var post = new HttpRequestMessage(HttpMethod.Post, uri);
|
|
|
|
|
post.Headers.Add("Authorization", Config.DBotsToken);
|
|
|
|
|
post.Content = new StringContent(body,
|
|
|
|
|
Encoding.UTF8, "application/json");
|
|
|
|
|
|
|
|
|
|
await _httpClient.SendAsync(post, cancellationToken);
|
|
|
|
|
Program.Log("Discord Bots", "Update successful.");
|
|
|
|
|
} catch (Exception ex) {
|
|
|
|
|
Program.Log("Discord Bots", "Exception encountered during update: " + ex.Message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#region Event handling
|
|
|
|
|
private Task DiscordClient_Log(LogMessage arg) {
|
|
|
|
|
// Suppress certain messages
|
|
|
|
|
if (arg.Message != null) {
|
2022-08-10 01:21:03 +00:00
|
|
|
|
switch (arg.Message) { // Connection status messages replaced by ShardManager's output
|
2021-11-18 02:07:28 +00:00
|
|
|
|
case "Connecting":
|
|
|
|
|
case "Connected":
|
|
|
|
|
case "Ready":
|
|
|
|
|
case "Disconnecting":
|
|
|
|
|
case "Disconnected":
|
2022-01-04 22:48:35 +00:00
|
|
|
|
case "Resumed previous session":
|
|
|
|
|
case "Failed to resume previous session":
|
|
|
|
|
case "Discord.WebSocket.GatewayReconnectException: Server requested a reconnect":
|
2021-11-18 02:07:28 +00:00
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
2021-11-08 05:46:26 +00:00
|
|
|
|
Program.Log("Discord.Net", $"{arg.Severity}: {arg.Message}");
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-18 02:07:28 +00:00
|
|
|
|
// Suppress certain exceptions
|
|
|
|
|
if (arg.Exception != null) {
|
|
|
|
|
if (arg.Exception is not GatewayReconnectException)
|
|
|
|
|
Program.Log("Discord.Net exception", arg.Exception.ToString());
|
|
|
|
|
}
|
2021-11-08 05:46:26 +00:00
|
|
|
|
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-07 04:38:36 +00:00
|
|
|
|
private async Task DiscordClient_ShardReady(DiscordSocketClient arg) {
|
|
|
|
|
#if !DEBUG
|
|
|
|
|
// Update slash/interaction commands
|
|
|
|
|
if (arg.ShardId == 0) {
|
|
|
|
|
await _services.GetRequiredService<InteractionService>().RegisterCommandsGloballyAsync();
|
|
|
|
|
Program.Log("Command registration", "Updated global command registration.");
|
|
|
|
|
}
|
|
|
|
|
#else
|
|
|
|
|
// Debug: Register our commands locally instead, in each guild we're in
|
2022-08-10 01:18:38 +00:00
|
|
|
|
if (arg.Guilds.Count > 5) {
|
|
|
|
|
Program.Log("Command registration", "Are you debugging in production?! Skipping DEBUG command registration.");
|
|
|
|
|
} else {
|
|
|
|
|
var iasrv = _services.GetRequiredService<InteractionService>();
|
|
|
|
|
foreach (var g in arg.Guilds) {
|
|
|
|
|
await iasrv.RegisterCommandsToGuildAsync(g.Id, true).ConfigureAwait(false);
|
|
|
|
|
Program.Log("Command registration", $"Updated DEBUG command registration in guild {g.Id}.");
|
|
|
|
|
}
|
2022-05-07 04:38:36 +00:00
|
|
|
|
}
|
|
|
|
|
#endif
|
|
|
|
|
}
|
2021-11-08 05:46:26 +00:00
|
|
|
|
|
2022-05-07 04:38:36 +00:00
|
|
|
|
const string InternalError = ":x: An unknown error occurred. If it persists, please notify the bot owner.";
|
|
|
|
|
|
|
|
|
|
// Slash command preparation and invocation
|
|
|
|
|
private async Task DiscordClient_InteractionCreated(SocketInteraction arg) {
|
|
|
|
|
var context = new ShardedInteractionContext(DiscordClient, arg);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await _services.GetRequiredService<InteractionService>().ExecuteCommandAsync(context, _services);
|
|
|
|
|
} catch (Exception ex) {
|
|
|
|
|
Program.Log(nameof(DiscordClient_InteractionCreated), $"Unhandled exception. {ex}");
|
|
|
|
|
if (arg.Type == InteractionType.ApplicationCommand) {
|
|
|
|
|
if (arg.HasResponded) await arg.ModifyOriginalResponseAsync(prop => prop.Content = InternalError);
|
|
|
|
|
else await arg.RespondAsync(InternalError);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Slash command logging and failed execution handling
|
|
|
|
|
private static async Task InteractionService_SlashCommandExecuted(SlashCommandInfo info, IInteractionContext context, IResult result) {
|
|
|
|
|
string sender;
|
|
|
|
|
if (context.Guild != null) {
|
|
|
|
|
sender = $"{context.Guild}!{context.User}";
|
|
|
|
|
} else {
|
|
|
|
|
sender = $"{context.User} in non-guild context";
|
|
|
|
|
}
|
|
|
|
|
var logresult = $"{(result.IsSuccess ? "Success" : "Fail")}: `/{info}` by {sender}.";
|
|
|
|
|
|
|
|
|
|
if (result.Error != null) {
|
|
|
|
|
// Additional log information with error detail
|
|
|
|
|
logresult += " " + Enum.GetName(typeof(InteractionCommandError), result.Error) + ": " + result.ErrorReason;
|
|
|
|
|
|
2023-01-15 05:54:23 +00:00
|
|
|
|
// Generic error response
|
|
|
|
|
// TODO when implementing proper application error logging, see here
|
|
|
|
|
var ia = context.Interaction;
|
|
|
|
|
if (ia.HasResponded) await ia.ModifyOriginalResponseAsync(p => p.Content = InternalError);
|
|
|
|
|
else await ia.RespondAsync(InternalError);
|
2022-05-07 04:38:36 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Program.Log("Command", logresult);
|
|
|
|
|
}
|
2021-11-08 05:46:26 +00:00
|
|
|
|
#endregion
|
|
|
|
|
}
|