-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cs
More file actions
746 lines (641 loc) Β· 31.4 KB
/
main.cs
File metadata and controls
746 lines (641 loc) Β· 31.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
using Bob.Database;
using Bob.Commands;
using static Bob.Monitoring.PerformanceStats;
using static Bob.Debug.Logger;
using Bob.Database.Types;
using Discord.Rest;
using Bob.Commands.Attributes;
using Bob.Commands.Helpers;
using Bob.BadgeInterface;
using static Bob.ApiInteractions.Interface;
using static Bob.Commands.Helpers.MessageReader;
using System.Net.Http;
using System.Text;
using DotNetEnv;
using System.IO;
using Bob.Monitoring;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using BobTheBot.Chat;
namespace Bob
{
public static class Bot
{
public static readonly DiscordShardedClient Client = new(new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMembers | GatewayIntents.GuildMessages | GatewayIntents.GuildMessageReactions | GatewayIntents.MessageContent | GatewayIntents.AutoModerationConfiguration,
UseInteractionSnowflakeDate = false
});
public static string Token = Environment.GetEnvironmentVariable("DISCORD_TOKEN");
// Purple (normal) Theme: 9261821 | Orange (halloween) Theme: 16760153
public static readonly Color theme = new(9261821);
public const ulong supportServerId = 1058077635692994651;
public static readonly ulong systemLogChannelId = 1160105468082004029;
private static readonly string[] statuses = ["/help | Games!", "/help | Premium! β€οΈ", "/help | Scheduling!", "/help | Automod!", "/help | bobthebot.net", "/help | RNG!", "/help | Quotes!", "/help | Confessions!"];
private static int _shardsReady = 0;
private static TaskCompletionSource<bool> _allShardsReady = new();
public static IServiceProvider Services;
public static async Task Main()
{
Env.Load();
if (Token is null)
{
throw new ArgumentException("Discord bot token not set properly.");
}
var services = new ServiceCollection();
var npgsqlConnectionString = DatabaseUtils.GetNpgsqlConnectionString();
services.AddDbContext<BobEntities>(options =>
{
options.UseNpgsql(
npgsqlConnectionString,
npgsqlOptions => npgsqlOptions
.EnableRetryOnFailure(
maxRetryCount: 1,
maxRetryDelay: TimeSpan.FromSeconds(5),
errorCodesToAdd: null
)
.UseVector()
);
});
services.AddSingleton(new InteractionService(Client, new InteractionServiceConfig
{
UseCompiledLambda = true,
ThrowOnError = true,
}));
Services = services.BuildServiceProvider();
Client.ShardReady += ShardReady;
Client.Log += Log;
Client.JoinedGuild += JoinedGuild;
Client.LeftGuild += Feedback.Prompt.LeftGuild;
Client.UserJoined += UserJoined;
Client.EntitlementCreated += EntitlementCreated;
Client.EntitlementDeleted += EntitlementDeleted;
Client.EntitlementUpdated += EntitlementUpdated;
Client.MessageReceived += MessageReceived;
Client.ReactionAdded += HandleReactionAddedAsync;
Client.ReactionRemoved += HandleReactionRemovedAsync;
Client.ReactionRemoved += HandleReactionClearedAsync;
await Client.LoginAsync(TokenType.Bot, Token);
await Client.StartAsync();
Uptime.StartHttpListener();
// Wait for all shards to be ready before proceeding
await _allShardsReady.Task;
await RegisterSlashCommands();
var cpuUsage = await GetCpuUsageForProcess();
Console.WriteLine("CPU at Ready: " + cpuUsage.ToString() + "%");
var ramUsage = GetRamUsageForProcess();
Console.WriteLine("RAM at Ready: " + ramUsage.ToString() + "%");
UpdateSiteStats();
// Restart / reset scheduled messages and announcements
_ = Task.Run(Schedule.LoadAndScheduleItemsAsync<ScheduledAnnouncement>);
_ = Task.Run(Schedule.LoadAndScheduleItemsAsync<ScheduledMessage>);
await Task.Delay(Timeout.Infinite);
}
private static void UpdateSiteStats()
{
if (Token != Environment.GetEnvironmentVariable("TEST_DISCORD_TOKEN"))
{
_ = Task.Run(async () =>
{
// Update third party stats
// Throwaway as to not block Gateway Tasks.
// Top GG
var topGGResult = await PostToAPI("https://top.gg/api/bots/705680059809398804/stats", Environment.GetEnvironmentVariable("TOP_GG_TOKEN"), new StringContent("{\"server_count\":" + Client.Guilds.Count + "}", Encoding.UTF8, "application/json"));
Console.WriteLine($"[Notice] TopGG POST status: {topGGResult}");
// Discord Bots GG
var discordBotsResult = await PostToAPI("https://discord.bots.gg/api/v1/bots/705680059809398804/stats", Environment.GetEnvironmentVariable("DISCORD_BOTS_TOKEN"), new StringContent("{\"guildCount\":" + Client.Guilds.Count + "}", Encoding.UTF8, "application/json"));
Console.WriteLine($"[Notice] Discord Bots GG POST status: {discordBotsResult}");
});
}
}
private static async Task RegisterSlashCommands()
{
var interactionService = Services.GetRequiredService<InteractionService>();
Dictionary<string, ulong> _commandIds = [];
try
{
await interactionService.AddModulesAsync(Assembly.GetEntryAssembly(), Services);
var globalCommands = await interactionService.RegisterCommandsGloballyAsync();
Help.PopulateCommandIds(globalCommands);
// Optional: Register per-guild debug commands
ModuleInfo[] debugCommands = interactionService.Modules
.Where(module => module.Preconditions.Any(precondition => precondition is RequireGuildAttribute)
&& module.SlashGroupName == "debug")
.ToArray();
IGuild supportServer = Client.GetGuild(supportServerId);
await interactionService.AddModulesToGuildAsync(supportServer, true, debugCommands);
}
catch (Discord.Net.HttpException ex)
{
// Only ignore BASE_TYPE_REQUIRED errors
if (ex.Message.Contains("BASE_TYPE_REQUIRED") ||
ex.Reason.Contains("BASE_TYPE_REQUIRED", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("[Notice] Ignoring known Discord API bug BASE_TYPE_REQUIRED. Continuing startup...");
if (_commandIds == null || _commandIds.Count == 0)
{
Console.WriteLine("[Notice] Attempting to fetch global command IDs via the REST client.");
var ids = await interactionService.RestClient.GetGlobalApplicationCommands();
Help.PopulateCommandIds(ids);
Console.WriteLine("[Notice] Successfully populated command IDs via the REST client.");
}
}
else
{
// Not known benign error
throw;
}
}
catch (Exception ex)
{
Console.WriteLine("[Unhandled] " + ex);
}
Client.InteractionCreated += InteractionCreated;
interactionService.SlashCommandExecuted += SlashCommandResulted;
Console.WriteLine("[Notice] Slash commands registered successfully.");
}
private static Task ShardReady(DiscordSocketClient shard)
{
_shardsReady++;
if (_shardsReady == Client.Shards.Count)
{
_allShardsReady.TrySetResult(true);
}
if (_shardsReady <= Client.Shards.Count)
{
// Status rotation
_ = Task.Run(async () =>
{
int index = 0;
var timer = new PeriodicTimer(TimeSpan.FromSeconds(16));
while (await timer.WaitForNextTickAsync())
{
await shard.SetCustomStatusAsync(statuses[index]);
index = index + 1 == statuses.Length ? 0 : index + 1;
}
});
}
return Task.CompletedTask;
}
private static Task UserJoined(SocketGuildUser user)
{
_ = Task.Run(async () =>
{
try
{
if (user.IsBot)
{
return;
}
Server server;
using (var scope = Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<BobEntities>();
server = await context.GetOrCreateServerAsync(user.Guild.Id);
}
if (server.Welcome == false)
{
return;
}
var systemChannel = user.Guild.SystemChannel;
if (systemChannel is not SocketTextChannel textChannel)
{
return;
}
var botUser = user.Guild.GetUser(Client.CurrentUser.Id);
if (botUser == null)
{
return;
}
var permissions = botUser.GetPermissions(textChannel);
if (!permissions.SendMessages || !permissions.ViewChannel)
{
return;
}
if (server.HasWelcomeImage && permissions.AttachFiles)
{
WelcomeImage welcomeImage = null;
using (var scope = Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<BobEntities>();
welcomeImage = await context.GetWelcomeImage(user.Guild.Id);
}
if (welcomeImage != null)
{
await textChannel.SendFileAsync(
new MemoryStream(welcomeImage.Image),
"welcome.webp",
text: Welcome.PrepareWelcomeMessage(server.CustomWelcomeMessage, user.Mention)
);
}
}
else
{
await textChannel.SendMessageAsync(text: Welcome.PrepareWelcomeMessage(server.CustomWelcomeMessage, user.Mention));
}
// If support server, then give the user the Friend badge
if (user.Guild.Id == supportServerId)
{
User dbUser;
using (var scope = Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<BobEntities>();
dbUser = await context.GetOrCreateUserAsync(user.Id);
}
await Badge.GiveUserBadge(dbUser, Badges.Badges.Friend);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
});
return Task.CompletedTask;
}
private static Task JoinedGuild(SocketGuild guild)
{
_ = Task.Run(async () =>
{
using var scope = Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<BobEntities>();
await context.GetOrCreateServerAsync(guild.Id);
});
return Task.CompletedTask;
}
private static Task EntitlementCreated(SocketEntitlement ent)
{
_ = Task.Run(async () =>
{
using var scope = Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<BobEntities>();
IUser entUser = await ent.User.Value.GetOrDownloadAsync();
User user = await context.GetOrCreateUserAsync(entUser.Id);
if (ent.EndsAt == null)
{
user.PremiumExpiration = DateTimeOffset.MaxValue;
}
else
{
user.PremiumExpiration = (DateTimeOffset)ent.EndsAt;
}
await context.SaveChangesAsync();
});
return Task.CompletedTask;
}
private static Task EntitlementUpdated(Cacheable<SocketEntitlement, ulong> before, SocketEntitlement after)
{
_ = Task.Run(async () =>
{
using var scope = Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<BobEntities>();
IUser entUser = await before.Value.User.Value.GetOrDownloadAsync();
User user = await context.GetOrCreateUserAsync(entUser.Id);
user.PremiumExpiration = (DateTimeOffset)after.EndsAt;
await context.SaveChangesAsync();
});
return Task.CompletedTask;
}
private static Task EntitlementDeleted(Cacheable<SocketEntitlement, ulong> ent)
{
return Task.CompletedTask;
}
private static Task MessageReceived(SocketMessage message)
{
_ = Task.Run(async () =>
{
try
{
// Ensure channel is not null (guild messages only)
if (message.Channel is not SocketGuildChannel channel)
return;
if (channel.Guild == null)
return;
SocketGuildUser fetchedBot = Client.GetGuild(channel.Guild.Id)
.GetUser(Client.CurrentUser.Id);
var botPerms = fetchedBot.GetPermissions(channel);
if (!botPerms.SendMessages)
return;
// Auto Publish if in a News Channel
if (channel.GetChannelType() == ChannelType.News &&
message.Components == null)
{
using var scope = Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<BobEntities>();
var newsChannel = await context.GetNewsChannel(channel.Id);
if (newsChannel != null)
{
if (message is IUserMessage userMessage)
await userMessage.CrosspostAsync();
return;
}
}
// Ignore bots
if (message.Author.IsBot)
return;
// Mention handling
if (channel.Guild.Id == supportServerId && message.Content.StartsWith("<@705680059809398804>"))
{
await ChatHandling.HandleMentionAsync(message);
}
// GitHub auto-embeds
Server server;
using (var scope = Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<BobEntities>();
server = await dbContext.GetOrCreateServerAsync(channel.Guild.Id);
}
if (server.AutoEmbedGitHubLinks)
{
var gitHubLink = GitHubLinkParse.GetUrl(message.Content);
if (gitHubLink != null)
{
switch (gitHubLink.Type)
{
case GitHubLinkParse.GitHubLinkType.CodeFile:
var linkInfo = CodeReader.CreateFileLinkInfo(gitHubLink.Url, true);
string previewLines = await CodeReader.GetPreview(linkInfo);
string preview =
$"π Showing {CodeReader.GetFormattedLineNumbers(linkInfo.LineNumbers)} of " +
$"[{linkInfo.Repository}/{linkInfo.Branch}/{linkInfo.File}](<{gitHubLink.Url}>)\n" +
$"```{linkInfo.File[(linkInfo.File.IndexOf('.') + 1)..]}\n{previewLines}```";
await message.Channel.SendMessageAsync(preview);
break;
case GitHubLinkParse.GitHubLinkType.PullRequest:
var prInfo = PullRequestReader.CreatePullRequestInfo(gitHubLink.Url);
await message.Channel.SendMessageAsync(
embed: await PullRequestReader.GetPreview(prInfo)
);
break;
case GitHubLinkParse.GitHubLinkType.Issue:
var issueInfo = IssueReader.CreateIssueInfo(gitHubLink.Url);
await message.Channel.SendMessageAsync(
embed: await IssueReader.GetPreview(issueInfo)
);
break;
}
return;
}
}
// Discord message link auto-embeds
if (server.AutoEmbedMessageLinks)
{
var discordLink = DiscordMessageLinkParse.GetUrl(message.Content);
if (discordLink != null)
{
var linkInfo = CreateMessageInfo(discordLink.Url);
var preview = await GetPreview(linkInfo);
if (preview != null)
await message.Channel.SendMessageAsync(embed: preview);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
});
return Task.CompletedTask;
}
private static Task HandleReactionAddedAsync(
Cacheable<IUserMessage, ulong> cacheable,
Cacheable<IMessageChannel, ulong> channelCache,
SocketReaction reaction)
{
_ = Task.Run(async () =>
{
try
{
if (await channelCache.GetOrDownloadAsync() is not SocketTextChannel textChannel)
{
return;
}
using var scope = Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<BobEntities>();
var server = await dbContext.GetOrCreateServerAsync(textChannel.Guild.Id);
if (!ReactBoardMethods.IsSetup(server))
{
return;
}
string key = reaction.Emote is Emote emote ? emote.Id.ToString() : reaction.Emote.Name;
var storedEmojiId = ReactBoardMethods.GetEmojiIdFromString(server.ReactBoardEmoji);
bool isMatchingEmoji = (storedEmojiId != null && key == storedEmojiId)
|| reaction.Emote.Name.Equals(server.ReactBoardEmoji, StringComparison.OrdinalIgnoreCase);
if (!isMatchingEmoji || textChannel.Id == server.ReactBoardChannelId)
{
return;
}
var botUser = textChannel.GetUser(Client.CurrentUser.Id);
var permissions = botUser?.GetPermissions(textChannel);
if (permissions == null || !permissions.Value.ViewChannel || !permissions.Value.ReadMessageHistory)
{
return;
}
var userMessage = await CachedMessages.GetOrDownloadAsync(textChannel, cacheable.Id);
if (userMessage == null)
{
return;
}
userMessage.IncreaseReactionCount(key);
var reactionCount = userMessage.GetReactionCount(key);
if (reactionCount == 0 || reactionCount < server.ReactBoardMinimumReactions)
{
return;
}
if (Client.GetChannel(server.ReactBoardChannelId.Value) is not SocketTextChannel reactBoardChannel)
{
return;
}
botUser = reactBoardChannel.GetUser(Client.CurrentUser.Id);
if (botUser == null || !botUser.GetPermissions(reactBoardChannel).SendMessages)
{
return;
}
if (await ReactBoardMethods.IsMessageOnBoardAsync(reactBoardChannel, userMessage.Message.Id))
{
return;
}
await reactBoardChannel.SendMessageAsync(
embeds: [.. ReactBoardMethods.GetReactBoardEmbeds(userMessage.Message)],
allowedMentions: AllowedMentions.None,
components: ReactBoardMethods.GetReactBoardComponents(userMessage.Message)
);
await ReactBoardMethods.AddToCacheAndDbAsync(reactBoardChannel, userMessage.Message.Id);
}
catch (Exception e)
{
Console.WriteLine($"Error handling reaction: {e.Message}");
Console.WriteLine(e.StackTrace);
}
});
return Task.CompletedTask;
}
public static Task HandleReactionRemovedAsync(
Cacheable<IUserMessage, ulong> cacheable,
Cacheable<IMessageChannel, ulong> channelCache,
SocketReaction reaction)
{
_ = Task.Run(async () =>
{
if (await channelCache.GetOrDownloadAsync() is not SocketTextChannel textChannel)
{
return;
}
var userMessage = await CachedMessages.GetOrDownloadAsync(textChannel, cacheable.Id);
if (userMessage == null)
{
return;
}
var key = reaction.Emote is Emote emote ? emote.Id.ToString() : reaction.Emote.Name;
userMessage.DecrementReactionCount(key);
});
return Task.CompletedTask;
}
public static Task HandleReactionClearedAsync(
Cacheable<IUserMessage, ulong> cacheable,
Cacheable<IMessageChannel, ulong> channelCache,
SocketReaction reaction)
{
_ = Task.Run(async () =>
{
if (await channelCache.GetOrDownloadAsync() is not SocketTextChannel textChannel)
{
return;
}
var userMessage = await CachedMessages.GetOrDownloadAsync(textChannel, cacheable.Id);
if (userMessage == null)
{
return;
}
var key = reaction.Emote is Emote emote ? emote.Id.ToString() : reaction.Emote.Name;
userMessage.SetReactionCount(key, 0);
});
return Task.CompletedTask;
}
private static async Task InteractionCreated(SocketInteraction interaction)
{
try
{
var interactionService = Services.GetRequiredService<InteractionService>();
var ctx = new ShardedInteractionContext(Client, interaction);
await interactionService.ExecuteCommandAsync(ctx, Services);
}
catch
{
if (interaction.Type == InteractionType.ApplicationCommand)
{
await interaction.GetOriginalResponseAsync()
.ContinueWith(async (msg) => await msg.Result.DeleteAsync());
}
}
}
private static async Task SlashCommandResulted(SlashCommandInfo info, IInteractionContext ctx, IResult res)
{
if (!res.IsSuccess)
{
switch (res.Error)
{
case InteractionCommandError.UnmetPrecondition:
if (ctx.Interaction.HasResponded)
{
await ctx.Interaction.FollowupAsync($"β Something went wrong:\n- {res.ErrorReason}", ephemeral: true);
}
else
{
await ctx.Interaction.RespondAsync($"β Something went wrong:\n- {res.ErrorReason}", ephemeral: true);
}
break;
case InteractionCommandError.UnknownCommand:
if (ctx.Interaction.HasResponded)
{
await ctx.Interaction.FollowupAsync("β Unknown command\n- Try refreshing your Discord client.", ephemeral: true);
}
else
{
await ctx.Interaction.RespondAsync("β Unknown command\n- Try refreshing your Discord client.", ephemeral: true);
}
break;
case InteractionCommandError.BadArgs:
if (ctx.Interaction.HasResponded)
{
await ctx.Interaction.FollowupAsync("β Invalid number or arguments.", ephemeral: true);
}
else
{
await ctx.Interaction.RespondAsync("β Invalid number or arguments.", ephemeral: true);
}
break;
case InteractionCommandError.Exception:
await ctx.Interaction.FollowupAsync($"β Something went wrong...\n- Ensure Bob has the `View Channel` and `Send Messages` permissions.\n- Try again later.\n- The developers have been notified.\n- Or, join [Bob's Official Server](https://discord.gg/HvGMRZD8jQ) and let us know about it.", ephemeral: true);
var executionResult = (ExecuteResult)res;
Console.WriteLine($"Error: {executionResult.Exception}");
await LogErrorToDiscord(ctx, info, $"{executionResult.ErrorReason}\n{executionResult.Exception}");
// Live Debugging
// Server Logging
if (ctx.Interaction.GuildId.HasValue && DebugGroup.LogGroup.ServersToLog.ContainsKey(ctx.Interaction.GuildId.Value))
{
DebugGroup.LogGroup.ServerLogChannels.TryGetValue(ctx.Interaction.GuildId.Value, out RestTextChannel debugLogChannel);
await LogServerUseToDiscord(debugLogChannel, ctx, info, res.ErrorReason);
}
break;
case InteractionCommandError.Unsuccessful:
await ctx.Interaction.FollowupAsync("β Command could not be executed. This is odd...\n- Try again later.\n- You can also join [Bob's Official Server](https://discord.gg/HvGMRZD8jQ) and let us know about it.", ephemeral: true);
break;
default:
await ctx.Interaction.FollowupAsync("β Command could not be executed, but it is not Bob's fault (it is most likely Discord's API failing). Please try again later while the developers work out what is wrong.\n- You can join [Bob's Official Server](https://discord.gg/HvGMRZD8jQ) and to let us know anything and/or stay posted on updates.", ephemeral: true);
break;
}
}
else
{
var cpuUsage = await GetCpuUsageForProcess();
var ramUsage = GetRamUsageForProcess();
string location = (ctx.Interaction.GuildId == null) ? "a DM" : (Client.GetGuild((ulong)ctx.Interaction.GuildId) == null ? "User Install" : Client.GetGuild((ulong)ctx.Interaction.GuildId).ToString());
int? shardId = ctx.Interaction.GuildId == null ? null : (ctx as ShardedInteractionContext).Client.GetShardIdFor(ctx.Guild);
var commandName = info.IsTopLevelCommand ? $"/{info.Name}" : $"/{info.Module.SlashGroupName} {info.Name}";
Console.WriteLine($"{DateTime.Now:dd/MM. H:mm:ss} | {FormatPerformance(cpuUsage, ramUsage)} | Shard: {(shardId == null ? "N" : shardId)} | Location: {location} | Command: {commandName}");
// Live Debugging
// Server Logging
if (ctx.Interaction.GuildId.HasValue && DebugGroup.LogGroup.ServersToLog.ContainsKey(ctx.Interaction.GuildId.Value))
{
DebugGroup.LogGroup.ServerLogChannels.TryGetValue(ctx.Interaction.GuildId.Value, out RestTextChannel debugLogChannel);
await LogServerUseToDiscord(debugLogChannel, ctx, info);
}
if (DebugGroup.LogGroup.LogEverything == true)
{
await LogErrorToDiscord(ctx, info);
}
}
}
private static Task Log(LogMessage logMessage)
{
Console.ForegroundColor = SeverityToConsoleColor(logMessage.Severity);
Console.WriteLine($"{DateTime.Now:dd/MM. H:mm:ss} [{logMessage.Source}] {logMessage.Message}");
Console.ResetColor();
return Task.CompletedTask;
}
private static ConsoleColor SeverityToConsoleColor(LogSeverity severity)
{
return severity switch
{
LogSeverity.Critical => ConsoleColor.Red,
LogSeverity.Debug => ConsoleColor.Blue,
LogSeverity.Error => ConsoleColor.Yellow,
LogSeverity.Info => ConsoleColor.Cyan,
LogSeverity.Verbose => ConsoleColor.Green,
LogSeverity.Warning => ConsoleColor.Magenta,
_ => ConsoleColor.White,
};
}
}
}