1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-01-31 09:09:00 +03:00

Log exceptions thrown during "fire-and-forget" async method calls

This commit is contained in:
Octol1ttle 2022-11-16 23:27:10 +05:00
parent 14ebcb1f1c
commit 29c2332ad9
Signed by: Octol1ttle
GPG key ID: B77C34313AEE1FFF
3 changed files with 44 additions and 28 deletions

View file

@ -11,7 +11,9 @@ public static class Boyfriend {
private static readonly DiscordSocketConfig Config = new() { private static readonly DiscordSocketConfig Config = new() {
MessageCacheSize = 250, MessageCacheSize = 250,
GatewayIntents = (GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent | GatewayIntents.GuildMembers) & ~GatewayIntents.GuildInvites, GatewayIntents
= (GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent | GatewayIntents.GuildMembers) &
~GatewayIntents.GuildInvites,
AlwaysDownloadUsers = true, AlwaysDownloadUsers = true,
AlwaysResolveStickers = false, AlwaysResolveStickers = false,
AlwaysDownloadDefaultStickers = false, AlwaysDownloadDefaultStickers = false,
@ -59,7 +61,7 @@ public static class Boyfriend {
private static async Task Init() { private static async Task Init() {
var token = (await File.ReadAllTextAsync("token.txt")).Trim(); var token = (await File.ReadAllTextAsync("token.txt")).Trim();
Client.Log += Log; Client.Log += x => Log(x);
await Client.LoginAsync(TokenType.Bot, token); await Client.LoginAsync(TokenType.Bot, token);
await Client.StartAsync(); await Client.StartAsync();
@ -75,7 +77,7 @@ public static class Boyfriend {
// ReSharper disable once FunctionNeverReturns // ReSharper disable once FunctionNeverReturns
} }
private static Task Log(LogMessage msg) { public static Task Log(LogMessage msg) {
switch (msg.Severity) { switch (msg.Severity) {
case LogSeverity.Critical: case LogSeverity.Critical:
Console.ForegroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.DarkRed;
@ -103,7 +105,8 @@ public static class Boyfriend {
} }
public static async Task WriteGuildConfigAsync(ulong id) { public static async Task WriteGuildConfigAsync(ulong id) {
await File.WriteAllTextAsync($"config_{id}.json", JsonConvert.SerializeObject(GuildConfigDictionary[id], Formatting.Indented)); await File.WriteAllTextAsync($"config_{id}.json",
JsonConvert.SerializeObject(GuildConfigDictionary[id], Formatting.Indented));
if (RemovedRolesDictionary.TryGetValue(id, out var removedRoles)) if (RemovedRolesDictionary.TryGetValue(id, out var removedRoles))
await File.WriteAllTextAsync($"removedroles_{id}.json", await File.WriteAllTextAsync($"removedroles_{id}.json",

View file

@ -47,13 +47,15 @@ public sealed class CommandProcessor {
var list = Context.Message.Content.Split("\n"); var list = Context.Message.Content.Split("\n");
var cleanList = Context.Message.CleanContent.Split("\n"); var cleanList = Context.Message.CleanContent.Split("\n");
for (var i = 0; i < list.Length; i++) { for (var i = 0; i < list.Length; i++)
RunCommandOnLine(list[i], cleanList[i], config["Prefix"]); _tasks.Add(RunCommandOnLine(list[i], cleanList[i], config["Prefix"]));
if (_stackedReplyMessage.Length > 0) _ = Context.Channel.TriggerTypingAsync(); try { Task.WaitAll(_tasks.ToArray()); } catch (AggregateException e) {
foreach (var ex in e.InnerExceptions)
await Boyfriend.Log(new LogMessage(LogSeverity.Error, nameof(CommandProcessor),
"Exception while executing commands", ex));
} }
await Task.WhenAll(_tasks);
_tasks.Clear(); _tasks.Clear();
if (ConfigWriteScheduled) await Boyfriend.WriteGuildConfigAsync(guild.Id); if (ConfigWriteScheduled) await Boyfriend.WriteGuildConfigAsync(guild.Id);
@ -61,7 +63,7 @@ public sealed class CommandProcessor {
SendFeedbacks(); SendFeedbacks();
} }
private void RunCommandOnLine(string line, string cleanLine, string prefix) { private async Task RunCommandOnLine(string line, string cleanLine, string prefix) {
var prefixed = line.StartsWith(prefix); var prefixed = line.StartsWith(prefix);
if (!prefixed && !line.StartsWith(Mention)) return; if (!prefixed && !line.StartsWith(Mention)) return;
foreach (var command in Commands) { foreach (var command in Commands) {
@ -70,7 +72,8 @@ public sealed class CommandProcessor {
var args = lineNoMention.Trim().Split().Skip(1).ToArray(); var args = lineNoMention.Trim().Split().Skip(1).ToArray();
var cleanArgs = cleanLine.Split().Skip(lineNoMention.StartsWith(" ") ? 2 : 1).ToArray(); var cleanArgs = cleanLine.Split().Skip(lineNoMention.StartsWith(" ") ? 2 : 1).ToArray();
_tasks.Add(command.RunAsync(this, args, cleanArgs)); await command.RunAsync(this, args, cleanArgs);
if (_stackedReplyMessage.Length > 0) _ = Context.Channel.TriggerTypingAsync();
return; return;
} }
} }

View file

@ -74,10 +74,15 @@ public static class Utils {
} }
public static async Task SilentSendAsync(SocketTextChannel? channel, string text, bool allowRoles = false) { public static async Task SilentSendAsync(SocketTextChannel? channel, string text, bool allowRoles = false) {
try {
if (channel is null || text.Length is 0 or > 2000) if (channel is null || text.Length is 0 or > 2000)
throw new Exception($"Message length is out of range: {text.Length}"); throw new Exception($"Message length is out of range: {text.Length}");
await channel.SendMessageAsync(text, false, null, null, allowRoles ? AllowRoles : AllowedMentions.None); await channel.SendMessageAsync(text, false, null, null, allowRoles ? AllowRoles : AllowedMentions.None);
} catch (Exception e) {
await Boyfriend.Log(new LogMessage(LogSeverity.Error, nameof(Utils),
"Exception while silently sending message", e));
}
} }
public static RequestOptions GetRequestOptions(string reason) { public static RequestOptions GetRequestOptions(string reason) {
@ -154,6 +159,7 @@ public static class Utils {
public static async Task SendEarlyEventStartNotificationAsync(SocketTextChannel? channel, public static async Task SendEarlyEventStartNotificationAsync(SocketTextChannel? channel,
SocketGuildEvent scheduledEvent, int minuteOffset) { SocketGuildEvent scheduledEvent, int minuteOffset) {
try {
await Task.Delay(scheduledEvent.StartTime.Subtract(DateTimeOffset.Now) await Task.Delay(scheduledEvent.StartTime.Subtract(DateTimeOffset.Now)
.Subtract(TimeSpan.FromMinutes(minuteOffset))); .Subtract(TimeSpan.FromMinutes(minuteOffset)));
var guild = scheduledEvent.Guild; var guild = scheduledEvent.Guild;
@ -171,6 +177,10 @@ public static class Utils {
await channel?.SendMessageAsync(string.Format(Messages.EventEarlyNotification, mentions, await channel?.SendMessageAsync(string.Format(Messages.EventEarlyNotification, mentions,
Wrap(scheduledEvent.Name), scheduledEvent.StartTime.ToUnixTimeSeconds().ToString()))!; Wrap(scheduledEvent.Name), scheduledEvent.StartTime.ToUnixTimeSeconds().ToString()))!;
mentions.Clear(); mentions.Clear();
} catch (Exception e) {
await Boyfriend.Log(new LogMessage(LogSeverity.Error, nameof(Utils),
"Exception while sending early event start notification", e));
}
} }
public static SocketTextChannel? GetEventNotificationChannel(SocketGuild guild) { public static SocketTextChannel? GetEventNotificationChannel(SocketGuild guild) {