forked from Aiko-IT-Systems/DisCatSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplicationCommandsExtension.cs
2622 lines (2329 loc) · 108 KB
/
ApplicationCommandsExtension.cs
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using DisCatSharp.ApplicationCommands.Attributes;
using DisCatSharp.ApplicationCommands.Context;
using DisCatSharp.ApplicationCommands.Entities;
using DisCatSharp.ApplicationCommands.Enums;
using DisCatSharp.ApplicationCommands.EventArgs;
using DisCatSharp.ApplicationCommands.Exceptions;
using DisCatSharp.ApplicationCommands.Workers;
using DisCatSharp.Common;
using DisCatSharp.Common.Utilities;
using DisCatSharp.Entities;
using DisCatSharp.Enums;
using DisCatSharp.Enums.Core;
using DisCatSharp.EventArgs;
using DisCatSharp.Exceptions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
// ReSharper disable HeuristicUnreachableCode
namespace DisCatSharp.ApplicationCommands;
/// <summary>
/// A class that handles slash commands for a client.
/// </summary>
public sealed class ApplicationCommandsExtension : BaseExtension
{
/// <summary>
/// A list of methods for top level commands.
/// </summary>
internal static List<CommandMethod> CommandMethods { get; set; } = [];
/// <summary>
/// List of groups.
/// </summary>
internal static List<GroupCommand> GroupCommands { get; set; } = [];
/// <summary>
/// List of groups with subgroups.
/// </summary>
internal static List<SubGroupCommand> SubGroupCommands { get; set; } = [];
/// <summary>
/// List of context menus.
/// </summary>
internal static List<ContextMenuCommand> ContextMenuCommands { get; set; } = [];
/// <summary>
/// List of global commands on discords backend.
/// </summary>
internal static List<DiscordApplicationCommand> GlobalDiscordCommands { get; set; } = [];
/// <summary>
/// List of guild commands on discords backend.
/// </summary>
internal static Dictionary<ulong, List<DiscordApplicationCommand>> GuildDiscordCommands { get; set; } = [];
/// <summary>
/// Singleton modules.
/// </summary>
private static List<object> s_singletonModules { get; set; } = [];
/// <summary>
/// List of modules to register.
/// </summary>
private readonly List<KeyValuePair<ulong?, ApplicationCommandsModuleConfiguration>> _updateList = [];
/// <summary>
/// Configuration for Discord.
/// </summary>
internal static ApplicationCommandsConfiguration Configuration;
/// <summary>
/// Set to true if anything fails when registering.
/// </summary>
private static bool s_errored { get; set; }
/// <summary>
/// Gets a list of registered commands. The key is the guild id (null if global).
/// </summary>
public IReadOnlyList<KeyValuePair<ulong?, IReadOnlyList<RegisteredDiscordApplicationCommand>>> RegisteredCommands
=> s_registeredCommands.Select(guild =>
new KeyValuePair<ulong?, IReadOnlyList<RegisteredDiscordApplicationCommand>>(guild.Key, guild.Value
.Select(parent => new RegisteredDiscordApplicationCommand(parent)).ToList())).ToList().AsReadOnly();
/// <summary>
/// Sets a list of registered commands. The key is the guild id (null if global).
/// </summary>
private static readonly List<KeyValuePair<ulong?, IReadOnlyList<DiscordApplicationCommand>>> s_registeredCommands = [];
/// <summary>
/// Gets a list of registered global commands.
/// </summary>
public IReadOnlyList<DiscordApplicationCommand> GlobalCommands
=> GlobalCommandsInternal;
/// <summary>
/// Sets a list of registered global commands.
/// </summary>
internal static readonly List<DiscordApplicationCommand> GlobalCommandsInternal = [];
/// <summary>
/// Gets a list of registered guild commands mapped by guild id.
/// </summary>
public IReadOnlyDictionary<ulong, IReadOnlyList<DiscordApplicationCommand>> GuildCommands
=> GuildCommandsInternal;
/// <summary>
/// Sets a list of registered guild commands mapped by guild id.
/// </summary>
internal static readonly Dictionary<ulong, IReadOnlyList<DiscordApplicationCommand>> GuildCommandsInternal = [];
/// <summary>
/// Gets the guild ids where the applications.commands scope is missing.
/// </summary>
private List<ulong> MISSING_SCOPE_GUILD_IDS { get; set; } = [];
/// <summary>
/// Gets the guild ids where the applications.commands scope is missing.
/// </summary>
private static List<ulong> s_missingScopeGuildIdsGlobal { get; set; } = [];
/// <summary>
/// Gets whether debug is enabled.
/// </summary>
internal static bool DebugEnabled { get; set; }
/// <summary>
/// Gets the debug level for the logs.
/// </summary>
internal static LogLevel ApplicationCommandsLogLevel
=> DebugEnabled ? LogLevel.Debug : LogLevel.Trace;
/// <summary>
/// Gets the logger.
/// </summary>
internal static ILogger Logger { get; set; }
/// <summary>
/// Gets whether check through all guilds is enabled.
/// </summary>
internal static bool CheckAllGuilds { get; set; }
/// <summary>
/// Gets whether the registration check should be manually overridden.
/// </summary>
internal static bool ManOr { get; set; }
/// <summary>
/// Gets whether interactions should be automatically deffered.
/// </summary>
internal static bool AutoDeferEnabled { get; set; }
/// <summary>
/// Whether this module finished the startup.
/// </summary>
internal bool ShardStartupFinished { get; set; } = false;
/// <summary>
/// Whether this module finished the startup.
/// </summary>
internal static bool StartupFinished { get; set; } = false;
/// <summary>
/// Gets the service provider this module was configured with.
/// </summary>
public IServiceProvider Services
=> Configuration.ServiceProvider;
/// <summary>
/// Whether this module is called by an unit test.
/// </summary>
internal static bool IsCalledByUnitTest { get; set; } = false;
/// <summary>
/// Gets a list of handled interactions. Fix for double interaction execution bug.
/// </summary>
internal static readonly List<ulong> HandledInteractions = [];
/// <summary>
/// Gets the shard count.
/// </summary>
internal static int ShardCount { get; set; } = 1;
/// <summary>
/// Gets the count of shards who finished initializing the module.
/// </summary>
internal static int FinishedShardCount { get; set; } = 0;
/// <summary>
/// Gets whether the finish event was fired.
/// </summary>
public static bool FinishFired { get; set; } = false;
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationCommandsExtension"/> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal ApplicationCommandsExtension(ApplicationCommandsConfiguration? configuration = null)
{
configuration ??= new();
Configuration = configuration;
DebugEnabled = configuration?.DebugStartup ?? false;
CheckAllGuilds = configuration?.CheckAllGuilds ?? false;
AutoDeferEnabled = configuration?.AutoDefer ?? false;
IsCalledByUnitTest = configuration?.UnitTestMode ?? false;
this._slashError = new("SLASHCOMMAND_ERRORED", TimeSpan.Zero, null!);
this._slashExecuted = new("SLASHCOMMAND_EXECUTED", TimeSpan.Zero, null!);
this._contextMenuErrored = new("CONTEXTMENU_ERRORED", TimeSpan.Zero, null!);
this._contextMenuExecuted = new("CONTEXTMENU_EXECUTED", TimeSpan.Zero, null!);
this._applicationCommandsModuleReady = new("APPLICATION_COMMANDS_MODULE_READY", TimeSpan.Zero, null!);
this._applicationCommandsModuleStartupFinished = new("APPLICATION_COMMANDS_MODULE_STARTUP_FINISHED", TimeSpan.Zero, null!);
this._globalApplicationCommandsRegistered = new("GLOBAL_COMMANDS_REGISTERED", TimeSpan.Zero, null!);
this._guildApplicationCommandsRegistered = new("GUILD_COMMANDS_REGISTERED", TimeSpan.Zero, null!);
this.ApplicationCommandsModuleStartupFinished += this.CheckStartupFinishAsync;
}
/// <summary>
/// Runs setup.
/// <note type="caution">DO NOT RUN THIS MANUALLY. DO NOT DO ANYTHING WITH THIS.</note>
/// </summary>
/// <param name="client">The client to setup on.</param>
protected internal override void Setup(DiscordClient client)
{
if (this.Client != null)
throw new InvalidOperationException("What did I tell you?");
this.Client = client;
ShardCount = client.ShardCount;
Logger = client.Logger;
this.Client.Ready += (c, e) =>
{
if (!this.ShardStartupFinished)
_ = Task.Run(async () => await this.UpdateAsync().ConfigureAwait(false));
return Task.CompletedTask;
};
this.Client.InteractionCreated += this.CatchInteractionsOnStartup;
this.Client.ContextMenuInteractionCreated += this.CatchContextMenuInteractionsOnStartup;
}
/// <summary>
/// Catches all interactions during the startup.
/// </summary>
/// <param name="sender">The client.</param>
/// <param name="e">The interaction create event args.</param>
/// <returns></returns>
private async Task CatchInteractionsOnStartup(DiscordClient sender, InteractionCreateEventArgs e)
{
if (!this.ShardStartupFinished)
await e.Interaction.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent("Attention: This application is still starting up. Application commands are unavailable for now.")).ConfigureAwait(false);
else
await Task.Delay(1).ConfigureAwait(false);
}
/// <summary>
/// Catches all context menu interactions during the startup.
/// </summary>
/// <param name="sender">The client.</param>
/// <param name="e">The context menu interaction create event args.</param>
private async Task CatchContextMenuInteractionsOnStartup(DiscordClient sender, ContextMenuInteractionCreateEventArgs e)
{
if (!this.ShardStartupFinished)
await e.Interaction.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent("Attention: This application is still starting up. Context menu commands are unavailable for now.")).ConfigureAwait(false);
else
await Task.Delay(1).ConfigureAwait(false);
}
/// <summary>
/// Fired when the startup is completed.
/// <para>Switches the interaction handling from <see cref="CatchInteractionsOnStartup"/> and <see cref="CatchContextMenuInteractionsOnStartup"/> to <see cref="InteractionHandler"/> and <see cref="ContextMenuHandler"/>.</para>
/// </summary>
private void FinishedRegistration()
{
this.Client.InteractionCreated -= this.CatchInteractionsOnStartup;
this.Client.ContextMenuInteractionCreated -= this.CatchContextMenuInteractionsOnStartup;
this.Client.InteractionCreated += this.InteractionHandler;
this.Client.ContextMenuInteractionCreated += this.ContextMenuHandler;
}
/// <summary>
/// Cleans the module for a new start of the bot.
/// DO NOT USE IF YOU DON'T KNOW WHAT IT DOES.
/// </summary>
public void CleanModule()
{
this._updateList.Clear();
s_singletonModules.Clear();
s_errored = false;
ShardCount = 1;
CommandMethods.Clear();
GroupCommands.Clear();
ContextMenuCommands.Clear();
SubGroupCommands.Clear();
s_singletonModules.Clear();
s_registeredCommands.Clear();
GlobalCommandsInternal.Clear();
GuildCommandsInternal.Clear();
s_missingScopeGuildIdsGlobal.Clear();
this.MISSING_SCOPE_GUILD_IDS.Clear();
HandledInteractions.Clear();
FinishedShardCount = 0;
FinishFired = false;
StartupFinished = false;
this.ShardStartupFinished = false;
this.Client.InteractionCreated += this.CatchInteractionsOnStartup;
this.Client.ContextMenuInteractionCreated += this.CatchContextMenuInteractionsOnStartup;
}
/// <summary>
/// Cleans all guild application commands.
/// <note type="caution">You normally don't need to execute it.</note>
/// </summary>
public async Task CleanGuildCommandsAsync()
{
foreach (var guild in this.Client.Guilds.Values)
await this.Client.BulkOverwriteGuildApplicationCommandsAsync(guild.Id, Array.Empty<DiscordApplicationCommand>()).ConfigureAwait(false);
}
/// <summary>
/// Cleans all global application commands.
/// <note type="caution">You normally don't need to execute it.</note>
/// </summary>
public async Task CleanGlobalCommandsAsync()
=> await this.Client.BulkOverwriteGlobalApplicationCommandsAsync(Array.Empty<DiscordApplicationCommand>()).ConfigureAwait(false);
/// <summary>
/// Registers all commands from a given assembly. The command classes need to be public to be considered for registration.
/// </summary>
/// <param name="assembly">Assembly to register commands from.</param>
/// <param name="guildId">The guild id to register it on.</param>
public void RegisterGuildCommands(Assembly assembly, ulong guildId)
{
var types = assembly.GetTypes().Where(xt =>
{
var xti = xt.GetTypeInfo();
return xti.IsModuleCandidateType() && !xti.IsNested;
});
foreach (var xt in types)
this.RegisterGuildCommands(xt, guildId, null);
}
/// <summary>
/// Registers all commands from a given assembly. The command classes need to be public to be considered for registration.
/// </summary>
/// <param name="assembly">Assembly to register commands from.</param>
public void RegisterGlobalCommands(Assembly assembly)
{
var types = assembly.GetTypes().Where(xt =>
{
var xti = xt.GetTypeInfo();
return xti.IsModuleCandidateType() && !xti.IsNested;
});
foreach (var xt in types)
this.RegisterGlobalCommands(xt, null);
}
/// <summary>
/// Registers a command class with optional translation setup for a guild.
/// </summary>
/// <typeparam name="T">The command class to register.</typeparam>
/// <param name="guildId">The guild id to register it on.</param>
/// <param name="translationSetup">A callback to setup translations with.</param>
public void RegisterGuildCommands<T>(ulong guildId, Action<ApplicationCommandsTranslationContext>? translationSetup = null) where T : ApplicationCommandsModule
=> this._updateList.Add(new(guildId, new(typeof(T), translationSetup)));
/// <summary>
/// Registers a command class with optional translation setup for a guild.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> of the command class to register.</param>
/// <param name="guildId">The guild id to register it on.</param>
/// <param name="translationSetup">A callback to setup translations with.</param>
public void RegisterGuildCommands(Type type, ulong guildId, Action<ApplicationCommandsTranslationContext>? translationSetup = null)
{
if (!typeof(ApplicationCommandsModule).IsAssignableFrom(type))
throw new ArgumentException("Command classes have to inherit from ApplicationCommandsModule", nameof(type));
this._updateList.Add(new(guildId, new(type, translationSetup)));
}
/// <summary>
/// Registers a command class with optional translation setup globally.
/// </summary>
/// <typeparam name="T">The command class to register.</typeparam>
/// <param name="translationSetup">A callback to setup translations with.</param>
public void RegisterGlobalCommands<T>(Action<ApplicationCommandsTranslationContext>? translationSetup = null) where T : ApplicationCommandsModule
=> this._updateList.Add(new(null, new(typeof(T), translationSetup)));
/// <summary>
/// Registers a command class with optional translation setup globally.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> of the command class to register.</param>
/// <param name="translationSetup">A callback to setup translations with.</param>
public void RegisterGlobalCommands(Type type, Action<ApplicationCommandsTranslationContext>? translationSetup = null)
{
if (!typeof(ApplicationCommandsModule).IsAssignableFrom(type))
throw new ArgumentException("Command classes have to inherit from ApplicationCommandsModule", nameof(type));
this._updateList.Add(new(null, new(type, translationSetup)));
}
/// <summary>
/// Fired when the application commands module is ready.
/// </summary>
public event AsyncEventHandler<ApplicationCommandsExtension, ApplicationCommandsModuleReadyEventArgs> ApplicationCommandsModuleReady
{
add => this._applicationCommandsModuleReady.Register(value);
remove => this._applicationCommandsModuleReady.Unregister(value);
}
/// <summary>
/// Fires the application command module ready event.
/// <para>This is fired when the whole module for the <see cref="DiscordClient"/> finished the startup and registration.</para>
/// </summary>
private readonly AsyncEvent<ApplicationCommandsExtension, ApplicationCommandsModuleReadyEventArgs> _applicationCommandsModuleReady;
/// <summary>
/// Fired when the application commands modules startup is finished.
/// </summary>
public event AsyncEventHandler<ApplicationCommandsExtension, ApplicationCommandsModuleStartupFinishedEventArgs> ApplicationCommandsModuleStartupFinished
{
add => this._applicationCommandsModuleStartupFinished.Register(value);
remove => this._applicationCommandsModuleStartupFinished.Unregister(value);
}
/// <summary>
/// Fires the application command module startup finished event.
/// </summary>
private readonly AsyncEvent<ApplicationCommandsExtension, ApplicationCommandsModuleStartupFinishedEventArgs> _applicationCommandsModuleStartupFinished;
/// <summary>
/// Fired when guild commands are registered on a guild.
/// </summary>
public event AsyncEventHandler<ApplicationCommandsExtension, GuildApplicationCommandsRegisteredEventArgs> GuildApplicationCommandsRegistered
{
add => this._guildApplicationCommandsRegistered.Register(value);
remove => this._guildApplicationCommandsRegistered.Unregister(value);
}
/// <summary>
/// Fires the guild application command registered event.
/// </summary>
private readonly AsyncEvent<ApplicationCommandsExtension, GuildApplicationCommandsRegisteredEventArgs> _guildApplicationCommandsRegistered;
/// <summary>
/// Fired when the global commands are registered.
/// </summary>
public event AsyncEventHandler<ApplicationCommandsExtension, GlobalApplicationCommandsRegisteredEventArgs> GlobalApplicationCommandsRegistered
{
add => this._globalApplicationCommandsRegistered.Register(value);
remove => this._globalApplicationCommandsRegistered.Unregister(value);
}
/// <summary>
/// Fires the global application command registered event.
/// </summary>
private readonly AsyncEvent<ApplicationCommandsExtension, GlobalApplicationCommandsRegisteredEventArgs> _globalApplicationCommandsRegistered;
/// <summary>
/// Used for RegisterCommands and the <see cref="DisCatSharp.DiscordClient.Ready"/> event.
/// </summary>
internal async Task UpdateAsync()
{
this.Client.Logger.Log(LogLevel.Information, "Request to register commands on shard {shard}", this.Client.ShardId);
try
{
if (this.ShardStartupFinished)
{
this.Client.Logger.Log(LogLevel.Information, "Shard {shard} already setup, skipping", this.Client.ShardId);
return;
}
GlobalDiscordCommands = [];
GuildDiscordCommands = [];
this.Client.Logger.Log(ApplicationCommandsLogLevel, "Shard {shard} has {guilds} guilds", this.Client.ShardId, this.Client.ReadyGuildIds.Count);
List<ulong> failedGuilds = [];
var globalCommands = IsCalledByUnitTest ? null : (await this.Client.GetGlobalApplicationCommandsAsync(Configuration?.EnableLocalization ?? false).ConfigureAwait(false))?.ToList() ?? null;
var guilds = CheckAllGuilds ? this.Client.ReadyGuildIds : this._updateList.Where(x => x.Key is not null)?.Select(x => x.Key.Value).Distinct().ToList();
var wrongShards = guilds is not null && this.Client.ReadyGuildIds.Count is not 0 ? guilds.Where(x => !this.Client.ReadyGuildIds.Contains(x)).ToList() : [];
if (wrongShards.Count is not 0)
{
this.Client.Logger.Log(ApplicationCommandsLogLevel, "Some guilds are not on the same shard as the client. Removing them from the update list");
foreach (var guild in wrongShards)
{
this._updateList.RemoveAll(x => x.Key == guild);
guilds?.Remove(guild);
}
}
var commandsPending = this._updateList.Select(x => x.Key).Distinct().ToList();
if (guilds is not null && guilds.Count != 0)
foreach (var guild in guilds)
{
List<DiscordApplicationCommand>? commands = null;
var unauthorized = false;
try
{
commands = (await this.Client.GetGuildApplicationCommandsAsync(guild, Configuration?.EnableLocalization ?? false).ConfigureAwait(false)).ToList() ?? null;
}
catch (UnauthorizedException)
{
unauthorized = true;
}
finally
{
switch (unauthorized)
{
case false when commands is not null && commands.Count is not 0:
GuildDiscordCommands.Add(guild, [.. commands]);
break;
case true:
failedGuilds.Add(guild);
break;
}
}
}
//Default should be to add the help and slash commands can be added without setting any configuration
//so this should still add the default help
if (Configuration is null || (Configuration is not null && Configuration.EnableDefaultHelp))
{
this._updateList.Add(new(null, new(typeof(DefaultHelpModule))));
commandsPending = this._updateList.Select(x => x.Key).Distinct().ToList();
}
else if (Configuration is not null && Configuration.EnableDefaultUserAppsHelp)
{
this._updateList.Add(new(null, new(typeof(DefaultUserAppsHelpModule))));
commandsPending = this._updateList.Select(x => x.Key).Distinct().ToList();
}
else
{
try
{
this._updateList.Remove(new(null, new(typeof(DefaultHelpModule))));
}
catch
{ }
commandsPending = this._updateList.Select(x => x.Key).Distinct().ToList();
}
if (globalCommands is not null && globalCommands.Count is not 0)
GlobalDiscordCommands.AddRange(globalCommands);
foreach (var key in commandsPending)
{
this.Client.Logger.Log(ApplicationCommandsLogLevel, key.HasValue ? $"Registering commands in guild {key.Value}" : "Registering global commands");
if (key.HasValue)
{
this.Client.Logger.Log(ApplicationCommandsLogLevel, "Found guild {guild} in shard {shard}!", key.Value, this.Client.ShardId);
this.Client.Logger.Log(ApplicationCommandsLogLevel, "Registering");
}
await this.RegisterCommands(this._updateList.Where(x => x.Key == key).Select(x => x.Value).ToList(), key).ConfigureAwait(false);
}
this.MISSING_SCOPE_GUILD_IDS = [..failedGuilds];
s_missingScopeGuildIdsGlobal.AddRange(failedGuilds);
this.ShardStartupFinished = true;
FinishedShardCount++;
StartupFinished = FinishedShardCount == ShardCount;
this.Client.Logger.Log(LogLevel.Information, "Application command setup finished for shard {ShardId}, enabling receiving", this.Client.ShardId);
await this._applicationCommandsModuleStartupFinished.InvokeAsync(this, new(Configuration?.ServiceProvider)
{
RegisteredGlobalCommands = GlobalCommandsInternal,
RegisteredGuildCommands = GuildCommandsInternal,
GuildsWithoutScope = this.MISSING_SCOPE_GUILD_IDS,
ShardId = this.Client.ShardId
}).ConfigureAwait(false);
this.FinishedRegistration();
}
catch (Exception ex)
{
this.Client.Logger.LogCritical(ex, "There was an error during the application commands setup");
this.Client.Logger.LogError(ex.Message);
this.Client.Logger.LogError(ex.StackTrace);
}
}
/// <summary>
/// Method for registering commands for a target from modules.
/// </summary>
/// <param name="types">The types.</param>
/// <param name="guildId">The optional guild id.</param>
private async Task RegisterCommands(List<ApplicationCommandsModuleConfiguration> types, ulong? guildId)
{
this.Client.Logger.Log(LogLevel.Information, "Registering commands on shard {shard}", this.Client.ShardId);
//Initialize empty lists to be added to the global ones at the end
var commandMethods = new List<CommandMethod>();
var groupCommands = new List<GroupCommand>();
var subGroupCommands = new List<SubGroupCommand>();
var contextMenuCommands = new List<ContextMenuCommand>();
var updateList = new List<DiscordApplicationCommand>();
var commandTypeSources = new List<KeyValuePair<Type, Type>>();
var groupTranslation = new List<GroupTranslator>();
var translation = new List<CommandTranslator>();
List<DiscordApplicationCommand> unitTestCommands = [];
//Iterates over all the modules
foreach (var config in types)
{
var type = config.Type;
try
{
var module = type.GetTypeInfo();
var classes = new List<TypeInfo>();
var ctx = new ApplicationCommandsTranslationContext(type, module.FullName);
config.Translations?.Invoke(ctx);
//Add module to classes list if it's a group
var extremeNestedGroup = false;
if (module.GetCustomAttribute<SlashCommandGroupAttribute>() is not null)
classes.Add(module);
else if (module.GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).Any(x => x.IsDefined(typeof(SlashCommandGroupAttribute))))
{
//Otherwise add the extreme nested groups
classes = module.GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)
.Where(x => x.IsDefined(typeof(SlashCommandGroupAttribute)))
.Select(x => module.GetNestedType(x.Name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).GetTypeInfo()).ToList();
extremeNestedGroup = true;
}
else
//Otherwise add the nested groups
classes = module.DeclaredNestedTypes.Where(x => x.GetCustomAttribute<SlashCommandGroupAttribute>() != null).ToList();
if (module.GetCustomAttribute<SlashCommandGroupAttribute>() is not null || extremeNestedGroup)
{
List<GroupTranslator> groupTranslations = null;
if (!string.IsNullOrEmpty(ctx.GroupTranslations))
groupTranslations = JsonConvert.DeserializeObject<List<GroupTranslator>>(ctx.GroupTranslations)!;
var slashGroupsTuple = await NestedCommandWorker.ParseSlashGroupsAsync(type, classes, guildId, groupTranslations).ConfigureAwait(false);
if (slashGroupsTuple.applicationCommands is not null && slashGroupsTuple.applicationCommands.Count is not 0)
{
if (IsCalledByUnitTest)
unitTestCommands.AddRange(slashGroupsTuple.applicationCommands);
updateList.AddRange(slashGroupsTuple.applicationCommands);
if (Configuration.GenerateTranslationFilesOnly)
{
var cgwsgs = new List<CommandGroupWithSubGroups>();
foreach (var cmd in slashGroupsTuple.applicationCommands)
if (cmd.Type is ApplicationCommandType.ChatInput)
{
var cgs = new List<CommandGroup>();
var cs2 = new List<Command>();
if (cmd.Options is not null)
{
foreach (var scg in cmd.Options.Where(x => x.Type is ApplicationCommandOptionType.SubCommandGroup))
{
var cs = new List<Command>();
if (scg.Options is not null)
foreach (var sc in scg.Options)
if (sc.Options is null || sc.Options.Count is 0)
cs.Add(new(sc.Name, sc.Description, null, null, sc.RawNameLocalizations, sc.RawDescriptionLocalizations));
else
cs.Add(new(sc.Name, sc.Description, [.. sc.Options], null, sc.RawNameLocalizations, sc.RawDescriptionLocalizations));
cgs.Add(new(scg.Name, scg.Description, cs, null, scg.RawNameLocalizations, scg.RawDescriptionLocalizations));
}
foreach (var sc2 in cmd.Options.Where(x => x.Type is ApplicationCommandOptionType.SubCommand))
if (sc2.Options == null || sc2.Options.Count == 0)
cs2.Add(new(sc2.Name, sc2.Description, null, null, sc2.RawNameLocalizations, sc2.RawDescriptionLocalizations));
else
cs2.Add(new(sc2.Name, sc2.Description, [.. sc2.Options], null, sc2.RawNameLocalizations, sc2.RawDescriptionLocalizations));
}
cgwsgs.Add(new(cmd.Name, cmd.Description, cgs, cs2, cmd.Type, cmd.RawNameLocalizations, cmd.RawDescriptionLocalizations));
}
if (cgwsgs.Count is not 0)
groupTranslation.AddRange(cgwsgs.Select(cgwsg => JsonConvert.DeserializeObject<GroupTranslator>(JsonConvert.SerializeObject(cgwsg))!));
}
}
if (slashGroupsTuple.commandTypeSources is not null && slashGroupsTuple.commandTypeSources.Count is not 0)
commandTypeSources.AddRange(slashGroupsTuple.commandTypeSources);
if (slashGroupsTuple.singletonModules is not null && slashGroupsTuple.singletonModules.Count is not 0)
s_singletonModules.AddRange(slashGroupsTuple.singletonModules);
if (slashGroupsTuple.groupCommands is not null && slashGroupsTuple.groupCommands.Count is not 0)
groupCommands.AddRange(slashGroupsTuple.groupCommands);
if (slashGroupsTuple.subGroupCommands is not null && slashGroupsTuple.subGroupCommands.Count is not 0)
subGroupCommands.AddRange(slashGroupsTuple.subGroupCommands);
}
//Handles methods and context menus, only if the module isn't a group itself
if (module.GetCustomAttribute<SlashCommandGroupAttribute>() is null)
{
List<CommandTranslator>? commandTranslations = null;
if (!string.IsNullOrEmpty(ctx.SingleTranslations))
commandTranslations = JsonConvert.DeserializeObject<List<CommandTranslator>>(ctx.SingleTranslations);
//Slash commands
var methods = module.DeclaredMethods.Where(x => x.GetCustomAttribute<SlashCommandAttribute>() is not null);
var slashCommands = await CommandWorker.ParseBasicSlashCommandsAsync(type, methods, guildId, commandTranslations).ConfigureAwait(false);
if (slashCommands.applicationCommands is not null && slashCommands.applicationCommands.Count is not 0)
{
if (IsCalledByUnitTest)
unitTestCommands.AddRange(slashCommands.applicationCommands);
updateList.AddRange(slashCommands.applicationCommands);
if (Configuration.GenerateTranslationFilesOnly)
{
var cs = new List<Command>();
foreach (var cmd in slashCommands.applicationCommands.Where(cmd => cmd.Type is ApplicationCommandType.ChatInput && (cmd.Options is null || !cmd.Options.Any(x => x.Type is ApplicationCommandOptionType.SubCommand or ApplicationCommandOptionType.SubCommandGroup))))
if (cmd.Options == null || cmd.Options.Count == 0)
cs.Add(new(cmd.Name, cmd.Description, null, ApplicationCommandType.ChatInput, cmd.RawNameLocalizations, cmd.RawDescriptionLocalizations));
else
cs.Add(new(cmd.Name, cmd.Description, [.. cmd.Options], ApplicationCommandType.ChatInput, cmd.RawNameLocalizations, cmd.RawDescriptionLocalizations));
if (cs.Count is not 0)
//translation.AddRange(cs.Select(c => JsonConvert.DeserializeObject<CommandTranslator>(JsonConvert.SerializeObject(c))!));
{
foreach (var c in cs)
{
var json = JsonConvert.SerializeObject(c);
var obj = JsonConvert.DeserializeObject<CommandTranslator>(json);
translation.Add(obj!);
}
}
}
}
if (slashCommands.commandTypeSources is not null && slashCommands.commandTypeSources.Count is not 0)
commandTypeSources.AddRange(slashCommands.commandTypeSources);
if (slashCommands.commandMethods is not null && slashCommands.commandMethods.Count is not 0)
commandMethods.AddRange(slashCommands.commandMethods);
//Context Menus
var contextMethods = module.DeclaredMethods.Where(x => x.GetCustomAttribute<ContextMenuAttribute>() is not null);
var contextCommands = await CommandWorker.ParseContextMenuCommands(type, contextMethods, commandTranslations).ConfigureAwait(false);
if (contextCommands.applicationCommands is not null && contextCommands.applicationCommands.Count is not 0)
{
if (IsCalledByUnitTest)
unitTestCommands.AddRange(contextCommands.applicationCommands);
updateList.AddRange(contextCommands.applicationCommands);
if (Configuration.GenerateTranslationFilesOnly)
{
var cs = new List<Command>();
foreach (var cmd in contextCommands.applicationCommands)
if (cmd.Type is ApplicationCommandType.Message or ApplicationCommandType.User)
cs.Add(new(cmd.Name, null, null, cmd.Type));
if (cs.Count != 0)
translation.AddRange(cs.Select(c => JsonConvert.DeserializeObject<CommandTranslator>(JsonConvert.SerializeObject(c))!));
}
}
if (contextCommands.commandTypeSources is not null && contextCommands.commandTypeSources.Count is not 0)
commandTypeSources.AddRange(contextCommands.commandTypeSources);
if (contextCommands.contextMenuCommands is not null && contextCommands.contextMenuCommands.Count is not 0)
contextMenuCommands.AddRange(contextCommands.contextMenuCommands);
//Accounts for lifespans
if (module.GetCustomAttribute<ApplicationCommandModuleLifespanAttribute>() is not null && module.GetCustomAttribute<ApplicationCommandModuleLifespanAttribute>().Lifespan is ApplicationCommandModuleLifespan.Singleton)
s_singletonModules.Add(CreateInstance(module, Configuration?.ServiceProvider));
}
}
catch (NullReferenceException ex)
{
this.Client.Logger.LogCritical(ex, "NRE Exception thrown: {msg}\nStack: {stack}", ex.Message, ex.StackTrace);
}
catch (Exception ex)
{
if (ex is BadRequestException brex)
this.Client.Logger.LogCritical(brex, @"There was an error registering application commands: {res}", brex.WebResponse.Response);
else
{
if (ex.InnerException is BadRequestException brex1)
this.Client.Logger.LogCritical(brex1, @"There was an error registering application commands: {res}", brex1.WebResponse.Response);
else
this.Client.Logger.LogCritical(ex, @"There was an error parsing the application commands");
}
s_errored = true;
}
}
if (!s_errored && !IsCalledByUnitTest)
{
updateList = updateList.DistinctBy(x => x.Name).ToList();
if (Configuration.GenerateTranslationFilesOnly)
await this.CheckRegistrationStartup(translation, groupTranslation, guildId);
else
try
{
List<DiscordApplicationCommand> commands = [];
try
{
if (guildId is null)
{
if (updateList.Count is not 0)
{
var regCommands = await RegistrationWorker.RegisterGlobalCommandsAsync(this.Client, updateList).ConfigureAwait(false);
if (regCommands is not null)
{
var actualCommands = regCommands.Distinct().ToList();
commands.AddRange(actualCommands);
GlobalCommandsInternal.AddRange(actualCommands);
}
}
else if (GlobalDiscordCommands.Count is not 0)
foreach (var cmd in GlobalDiscordCommands)
try
{
await this.Client.DeleteGlobalApplicationCommandAsync(cmd.Id).ConfigureAwait(false);
}
catch (NotFoundException)
{
this.Client.Logger.Log(ApplicationCommandsLogLevel, "Could not delete global command {cmdId}. Please clean up manually", cmd.Id);
}
}
else
{
if (updateList.Count is not 0)
{
var regCommands = await RegistrationWorker.RegisterGuildCommandsAsync(this.Client, guildId.Value, updateList).ConfigureAwait(false);
if (regCommands is not null)
{
var actualCommands = regCommands.Distinct().ToList();
commands.AddRange(actualCommands);
GuildCommandsInternal.Add(guildId.Value, actualCommands);
try
{
if (this.Client.Guilds.TryGetValue(guildId.Value, out var guild))
guild.InternalRegisteredApplicationCommands.AddRange(actualCommands);
}
catch (NullReferenceException)
{ }
}
}
else if (GuildDiscordCommands.Count is not 0)
foreach (var cmd in GuildDiscordCommands.First(x => x.Key == guildId.Value).Value)
try
{
await this.Client.DeleteGuildApplicationCommandAsync(guildId.Value, cmd.Id).ConfigureAwait(false);
}
catch (NotFoundException)
{
this.Client.Logger.Log(ApplicationCommandsLogLevel, "Could not delete guild command {cmdId} in guild {guildId}. Please clean up manually", cmd.Id, guildId.Value);
}
}
}
catch (UnauthorizedException ex)
{
this.Client.Logger.LogError("Could not register application commands for guild {guildId}.\nError: {exc}", guildId, ex.JsonMessage);
return;
}
//Creates a guild command if a guild id is specified, otherwise global
//Checks against the ids and adds them to the command method lists
foreach (var command in commands)
{
if (commandMethods!.TryGetFirstValueWhere(x => x.Name == command.Name, out var com))
com.CommandId = command.Id;
if (groupCommands!.TryGetFirstValueWhere(x => x.Name == command.Name, out var groupCom))
groupCom.CommandId = command.Id;
if (subGroupCommands!.TryGetFirstValueWhere(x => x.Name == command.Name, out var subCom))
subCom.CommandId = command.Id;
if (contextMenuCommands!.TryGetFirstValueWhere(x => x.Name == command.Name, out var cmCom))
cmCom.CommandId = command.Id;
}
//Adds to the global lists finally
CommandMethods.AddRange(commandMethods.DistinctBy(x => x.Name));
GroupCommands.AddRange(groupCommands.DistinctBy(x => x.Name));
SubGroupCommands.AddRange(subGroupCommands.DistinctBy(x => x.Name));
ContextMenuCommands.AddRange(contextMenuCommands.DistinctBy(x => x.Name));
s_registeredCommands.Add(new(guildId, commands.ToList()));
foreach (var app in commandMethods.Select(command => types.First(t => t.Type == command.Method.DeclaringType)))
{ }
if (guildId.HasValue)
await this._guildApplicationCommandsRegistered.InvokeAsync(this, new(Configuration?.ServiceProvider)
{
Handled = true,
GuildId = guildId.Value,
RegisteredCommands = GuildCommandsInternal.FirstOrDefault(c => c.Key == guildId.Value).Value ?? []
}).ConfigureAwait(false);
else
await this._globalApplicationCommandsRegistered.InvokeAsync(this, new(Configuration?.ServiceProvider)
{
Handled = true,
RegisteredCommands = GlobalCommandsInternal
}).ConfigureAwait(false);
await this.CheckRegistrationStartup(translation, groupTranslation, guildId);
}
catch (NullReferenceException ex)
{
this.Client.Logger.LogCritical(ex, "NRE Exception thrown: {msg}\nStack: {stack}", ex.Message, ex.StackTrace);
}
catch (Exception ex)
{
if (ex is BadRequestException brex)
this.Client.Logger.LogCritical(brex, @"There was an error registering application commands: {res}", brex.WebResponse.Response);
else
{
if (ex.InnerException is BadRequestException brex1)
this.Client.Logger.LogCritical(brex1, @"There was an error registering application commands: {res}", brex1.WebResponse.Response);
else
this.Client.Logger.LogCritical(ex, @"There was an general error registering application commands");
}
s_errored = true;
}
}
else if (IsCalledByUnitTest)
{
CommandMethods.AddRange(commandMethods.DistinctBy(x => x.Name));
GroupCommands.AddRange(groupCommands.DistinctBy(x => x.Name));
SubGroupCommands.AddRange(subGroupCommands.DistinctBy(x => x.Name));
ContextMenuCommands.AddRange(contextMenuCommands.DistinctBy(x => x.Name));
s_registeredCommands.Add(new(guildId, unitTestCommands.ToList()));
foreach (var app in commandMethods.Select(command => types.First(t => t.Type == command.Method.DeclaringType)))
{ }
if (guildId.HasValue)
await this._guildApplicationCommandsRegistered.InvokeAsync(this, new(Configuration?.ServiceProvider)
{
Handled = true,
GuildId = guildId.Value,
RegisteredCommands = GuildCommandsInternal.FirstOrDefault(c => c.Key == guildId.Value).Value ?? []
}).ConfigureAwait(false);
else
await this._globalApplicationCommandsRegistered.InvokeAsync(this, new(Configuration?.ServiceProvider)
{
Handled = true,
RegisteredCommands = GlobalCommandsInternal
}).ConfigureAwait(false);
}
}
/// <summary>
/// Checks the registration startup.
/// </summary>
/// <param name="translation">The optional translations.</param>
/// <param name="groupTranslation">The optional group translations.</param>
/// <param name="guildId">The optional guild id.</param>
private async Task CheckRegistrationStartup(List<CommandTranslator>? translation = null, List<GroupTranslator>? groupTranslation = null, ulong? guildId = null)
{
if (Configuration.GenerateTranslationFilesOnly)
{
try
{
if (translation is not null && translation.Count is not 0)
{
var fileName = $"translation_generator_export-shard{this.Client.ShardId}-SINGLE-{(guildId.HasValue ? guildId.Value : "global")}.json";
var fs = File.Create(fileName);
var ms = new MemoryStream();
var writer = new StreamWriter(ms);
await writer.WriteAsync(JsonConvert.SerializeObject(translation.DistinctBy(x => x.Name), Formatting.Indented)).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
ms.Position = 0;
await ms.CopyToAsync(fs).ConfigureAwait(false);
await fs.FlushAsync().ConfigureAwait(false);
fs.Close();
await fs.DisposeAsync().ConfigureAwait(false);
ms.Close();
await ms.DisposeAsync().ConfigureAwait(false);
this.Client.Logger.LogInformation("Exported base translation to {exppath}", fileName);
}
if (groupTranslation is not null && groupTranslation.Count is not 0)
{