-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Valkyrja-commands.cs
1720 lines (1531 loc) · 68 KB
/
Valkyrja-commands.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;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Discord;
using Discord.Rest;
using Valkyrja.entities;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using guid = System.UInt64;
namespace Valkyrja.core
{
public partial class ValkyrjaClient : IValkyrjaClient, IDisposable
{
private readonly Regex RegexMentionHelp = new Regex(".*(help|commands).*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly Regex RegexPrefixHelp = new Regex(".*(command character|prefix).*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly Regex RegexHardwareHelp = new Regex(".*(hardware|server).*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private const string HardwareString = "I used to run on Dual Xeon server. It bork. Now it's the below!\n```md\n" +
"| [Mainboard][Asus PRIME x570-Pro]\n" +
"| [CPU][AMD Ryzen 3950X @4.2GHz 16c](32t)\n" +
"| 4x [Memory][G.Skill Ripjaws V 32GB DDR4-3200 CL16](128GB)\n" +
"| 2x [Storage][Samsung 830 Pro 128GB SSD](raid1)\n" +
"| 4x [Storage][Corsair MP510 512GB NVMe PCIe3.0](raid5|write2.1GB/s)\n" +
"| 4x [Storage][Hitachi NAS 4TB 7200RPM](raid5|write1.4GB/s)\n" +
"| [Cooling][Noctua]\n" +
"```\n" +
"...running on UPS to keep all the network gear and the server running for half an hour. And I'm connected through an APU2C4 router running pfSense, with 1.2 gigabit fibre and LTE failover. Pics here: <https://rhea.dev/persephone>";
private async Task HandleMentionResponse(Server server, SocketTextChannel channel, SocketMessage message)
{
if( this.GlobalConfig.LogDebug )
Console.WriteLine("ValkyrjaClient: MentionReceived");
string responseString = "";
if( this.RegexMentionHelp.Match(message.Content).Success )
responseString = Localisation.SystemStrings.MentionHelp;
else if( this.RegexPrefixHelp.Match(message.Content).Success )
responseString = string.IsNullOrEmpty(server.Config.CommandPrefix) ? Localisation.SystemStrings.MentionPrefixEmpty : string.Format(Localisation.SystemStrings.MentionPrefix, server.Config.CommandPrefix);
else if( this.RegexHardwareHelp.Match(message.Content).Success )
responseString = HardwareString;
else
responseString = "<:ValkyrjaNomPing:509482352028942358>";
if( !string.IsNullOrEmpty(responseString) )
await SendRawMessageToChannel(channel, responseString);
}
private async Task InitSlashCommands()
{
try
{
SlashCommandBuilder pingCommand = new SlashCommandBuilder().WithName("ping").WithDescription("Verify basic functionality.")
.WithNameLocalizations(new Dictionary<string, string>()).WithDescriptionLocalizations(new Dictionary<string, string>()); //D.NET bug #2453
await this.DiscordClient.CreateGlobalApplicationCommandAsync(pingCommand.Build());
}
catch( Exception e )
{
await LogException(e, "InitSlashCommands");
}
}
private async Task ExecuteSlashCommand(SocketSlashCommand command)
{
if( command.CommandName == "ping" && command.GuildId.HasValue && this.Servers.ContainsKey(command.GuildId.Value) )
{
TimeSpan time = DateTime.UtcNow - Utils.GetTimeFromId(command.Id);
await command.RespondAsync(GetStatusString(time, this.Servers[command.GuildId.Value]), ephemeral: true);
}
}
private Task InitCommands()
{
Command newCommand = null;
// !commandStats
newCommand = new Command("commandStats");
newCommand.Type = CommandType.LargeOperation;
newCommand.IsCoreCommand = true;
newCommand.Description = "Display all teh command numbers.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
await e.SendReplySafe("I'm counting! Do not disturb!! >_<");
StringBuilder message = new StringBuilder("Lifetime Command stats:\n```md\n");
try
{
Dictionary<string, int> count = new Dictionary<string, int>();
ServerContext serverContext = ServerContext.Create(this.DbConnectionString);
Dictionary<guid, ServerConfig> configCache = serverContext.ServerConfigurations.ToDictionary(s => s.ServerId);
serverContext.Dispose();
GlobalContext dbContext = GlobalContext.Create(this.DbConnectionString);
IEnumerable<LogEntry> logs = dbContext.Log.AsQueryable().Where(l => l.Type == LogType.Command);
foreach( LogEntry log in logs )
{
if( !configCache.ContainsKey(log.ServerId) )
continue;
ServerConfig config = configCache[log.ServerId];
string msg = log.Message.StartsWith(config.CommandPrefix) ? log.Message.Substring(config.CommandPrefix.Length) :
!string.IsNullOrWhiteSpace(config.CommandPrefixAlt) && log.Message.StartsWith(config.CommandPrefixAlt) ? log.Message.Substring(config.CommandPrefixAlt.Length) : null;
if( msg == null )
continue;
GetCommandAndParams(msg, out string cmdString, out _, out _);
cmdString = cmdString.ToLower();
Command cmd = null;
if( (this.Commands.ContainsKey(cmdString) && (cmd = this.Commands[cmdString]) != null) ||
(this.Servers.ContainsKey(config.ServerId) && this.Servers[config.ServerId].CustomAliases.ContainsKey(cmdString) && (cmdString = this.Servers[config.ServerId].CustomAliases[cmdString].CommandId) != null &&
this.Commands.ContainsKey(cmdString) && (cmd = this.Commands[cmdString]) != null) )
{
//Command cmd = this.Commands[cmdString];
string key = cmd.Id;
if( cmd.IsAlias && !string.IsNullOrEmpty(cmd.ParentId) )
key = cmd.ParentId;
if( !count.ContainsKey(key) )
count.Add(key, 0);
count[key]++;
}
}
dbContext.Dispose();
int total = 0;
foreach( KeyValuePair<string, int> pair in count.OrderByDescending(p => p.Value) )
{
total += pair.Value;
string newMessage = $"[{pair.Key.PrependSpaces(24)} ][{pair.Value.ToString().PrependSpaces(7)} ]\n";
if( message.Length + newMessage.Length >= GlobalConfig.MessageCharacterLimit )
{
message.Append("```");
await e.SendReplySafe(message.ToString(), modify: false);
message.Clear();
message.Append("```md\n");
}
message.Append(newMessage);
}
message.Append("```");
message.Append($"Total commands used: `{total}`");
}
catch( Exception ex )
{
message.Append(ex.Message);
message.Append(ex.StackTrace);
}
await e.SendReplySafe(message.ToString(), modify: false);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !global
newCommand = new Command("global");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Display all teh numbers. Use with `long` arg for more numbers.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
StringBuilder shards = new StringBuilder();
GlobalContext dbContext = GlobalContext.Create(this.DbConnectionString);
Shard globalCount = new Shard();
bool longStats = e.TrimmedMessage == "long";
foreach( Shard shard in dbContext.Shards.AsEnumerable() )
{
globalCount.ServerCount += shard.ServerCount;
globalCount.UserCount += shard.UserCount;
globalCount.MemoryUsed += shard.MemoryUsed;
globalCount.ThreadsActive += shard.ThreadsActive;
globalCount.MessagesTotal += shard.MessagesTotal;
globalCount.MessagesPerMinute += shard.MessagesPerMinute;
globalCount.OperationsRan += shard.OperationsRan;
globalCount.OperationsActive += shard.OperationsActive;
globalCount.Disconnects += shard.Disconnects;
shards.AppendLine(longStats ? shard.GetStatsString() : shard.GetStatsStringShort());
}
string message = "Server Status: <http://status.valkyrja.app>\n\n" +
$"Global Servers: `{globalCount.ServerCount}`\n" +
$"Global Members `{globalCount.UserCount}`\n" +
$"Global Allocated data Memory: `{globalCount.MemoryUsed} MB`\n" +
$"Global Threads: `{globalCount.ThreadsActive}`\n" +
$"Global Messages received: `{globalCount.MessagesTotal}`\n" +
$"Global Messages per minute: `{globalCount.MessagesPerMinute}`\n" +
$"Global Operations ran: `{globalCount.OperationsRan}`\n" +
$"Global Operations active: `{globalCount.OperationsActive}`\n" +
$"Global Disconnects: `{globalCount.Disconnects}`\n" +
$"\n**Shards: `{dbContext.Shards.Count()}`**\n\n" +
$"{shards.ToString()}";
dbContext.Dispose();
await e.SendReplySafe(message);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !getServers
newCommand = new Command("getServers");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Query for servers with min - max users.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
int min = 0;
int max = int.MaxValue;
if( e.MessageArgs == null || e.MessageArgs.Length == 0 || !int.TryParse(e.MessageArgs[0], out min) )
{
await e.SendReplySafe("Requires min max users.");
return;
}
if( e.MessageArgs.Length < 2 || !int.TryParse(e.MessageArgs[1], out max) )
max = int.MaxValue;
ServerContext dbContext = ServerContext.Create(this.DbConnectionString);
StringBuilder response = new StringBuilder();
IEnumerable<ServerStats> foundServers = dbContext.ServerStats.AsQueryable().Where(s =>
s.UserCount > min && s.UserCount < max ).AsEnumerable().OrderByDescending(s => s.UserCount);
if( !foundServers.Any() )
{
await e.SendReplySafe("There aren't any servers matching your query.");
dbContext.Dispose();
return;
}
int count = foundServers.Count();
response.AppendLine($"Found **{count}** servers between `{min}` and `{max}` users.\n");
foreach(ServerStats server in foundServers.Take(5))
{
response.AppendLine(server.ToStringShort( IsSubscriber(server.OwnerId) || IsPartner(server.ServerId) ));
response.AppendLine();
}
dbContext.Dispose();
await e.SendReplySafe(response.ToString());
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !getServer
newCommand = new Command("getServer");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.IsSupportCommand = true;
newCommand.Description = "Display some info about specific server with id/name, or owners id/username.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
if( string.IsNullOrEmpty(e.TrimmedMessage) )
{
await e.SendReplySafe("Requires parameters.");
return;
}
if( !guid.TryParse(e.TrimmedMessage, out guid id) )
id = 0;
string expression = e.TrimmedMessage.ToLower();
ServerContext dbContext = ServerContext.Create(this.DbConnectionString);
StringBuilder response = new StringBuilder();
IEnumerable<ServerStats> foundServers = null;
if( !(foundServers = dbContext.ServerStats.AsEnumerable().Where(s =>
s.ServerId == id || s.OwnerId == id ||
s.ServerName.ToLower().Contains(expression) ||
s.OwnerName.ToLower().Contains(expression)
)).Any() )
{
dbContext.Dispose();
await e.SendReplySafe("Server not found.");
return;
}
if( foundServers.Count() > 5 )
{
response.AppendLine("__**Found more than 5 servers!**__\n");
}
foreach(ServerStats server in foundServers.Take(5))
{
response.AppendLine(server.ToString( IsSubscriber(server.OwnerId) || IsPartner(server.ServerId) ));
response.AppendLine();
}
dbContext.Dispose();
await e.SendReplySafe(response.ToString());
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !getReactionRoles
newCommand = new Command("getReactionRoles");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.IsSupportCommand = true;
newCommand.Description = "Get configuration for emoji reaction assigned roles on the current server, or optional serverId.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
guid serverId = e.Server.Id;
if( e.MessageArgs != null && e.MessageArgs.Length > 0 && !guid.TryParse(e.MessageArgs[0], out serverId) )
{
await e.SendReplySafe("Invalid ServerId.");
return;
}
ServerContext dbContext = ServerContext.Create(this.DbConnectionString);
List<ReactionAssignedRole> roles = dbContext.ReactionAssignedRoles.AsQueryable().Where(s => s.ServerId == serverId).ToList();
if( !roles.Any() )
{
await e.SendReplySafe("Roles not found.");
return;
}
StringBuilder response = new StringBuilder();
response.AppendLine($"```md\n[{"MessageId".PrependSpaces(20)} ]({"RoleId".PrependSpaces(20)} )| Emoji");
foreach( ReactionAssignedRole role in roles )
{
response.AppendLine($"[{role.MessageId.ToString().PrependSpaces(20)} ]({role.RoleId.ToString().PrependSpaces(20)} )| {role.Emoji}");
}
response.AppendLine($"```");
dbContext.Dispose();
await e.SendReplySafe(response.ToString());
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !getProperty
newCommand = new Command("getProperty");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.IsSupportCommand = true;
newCommand.Description = "Get a server config property by its exact name. Defaults to the current server - use with serverid as the first parameter to explicitly specify different one.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
if( e.MessageArgs.Length < 1 )
{
await e.SendReplySafe(e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));
return;
}
ServerContext dbContext = ServerContext.Create(this.DbConnectionString);
guid serverId = e.Server.Id;
ServerConfig config = e.Server.Config;
if( e.MessageArgs.Length > 1 && (!guid.TryParse(e.MessageArgs[0], out serverId) ||
(config = dbContext.ServerConfigurations.FirstOrDefault(s => s.ServerId == serverId)) == null) )
{
await e.SendReplySafe("Used with two parameters to specify serverId, but I couldn't find a server.");
return;
}
string propertyName = e.MessageArgs.Length == 1 ? e.MessageArgs[0] : e.MessageArgs[1];
string propertyValue = config.GetPropertyValue(propertyName);
if( string.IsNullOrEmpty(propertyValue) )
propertyValue = "Unknown property.";
else
propertyValue = $"`{serverId}`.`{propertyName}`: `{propertyValue}`";
dbContext.Dispose();
await e.SendReplySafe(propertyValue);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !setProperty
newCommand = new Command("setProperty");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.IsSupportCommand = true;
newCommand.Description = "Set a server config property referenced by its exact name. Use with serverid, the exact property name, and the new value (use `i`, `u` and `f` for number type)";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
if( e.MessageArgs.Length < 3 )
{
await e.SendReplySafe(e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));
return;
}
guid serverId = 0;
ServerConfig config = null;
ServerContext dbContext = ServerContext.Create(this.DbConnectionString);
if( !guid.TryParse(e.MessageArgs[0], out serverId) ||
(config = dbContext.ServerConfigurations.AsQueryable().FirstOrDefault(s => s.ServerId == serverId)) == null )
{
await e.SendReplySafe("Server not found in the database. Use with three parameters: serverid, the exact property name, and the new value.");
return;
}
string propertyName = e.MessageArgs[1];
string propertyValueString = e.MessageArgs[2];
string propertyValueOld = "";
object propertyValue = null;
if( bool.TryParse(propertyValueString, out bool boolie) )
propertyValue = boolie;
else if( propertyValueString.EndsWith("i") && Int64.TryParse(propertyValueString.TrimEnd('i'), out Int64 number) )
propertyValue = number;
else if( propertyValueString.EndsWith("u") && UInt64.TryParse(propertyValueString.TrimEnd('u'), out UInt64 id) )
propertyValue = id;
else if( propertyValueString.EndsWith("f") && float.TryParse(propertyValueString.TrimEnd('f'), out float floatingpoint) )
propertyValue = floatingpoint;
else propertyValue = propertyValueString;
propertyValueOld = config.SetPropertyValue(propertyName, propertyValue);
if( string.IsNullOrEmpty(propertyValueOld) )
propertyValueOld = "Unknown property.";
else
{
dbContext.SaveChanges();
propertyValueOld = $"Property `{serverId}`.`{propertyName}`: `{propertyValueOld}` was changed to `{propertyValueString}`";
}
dbContext.Dispose();
await e.SendReplySafe(propertyValueOld);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !getInvite
newCommand = new Command("getInvite");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.IsSupportCommand = true;
newCommand.Description = "Get an invite url with serverid.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
guid id;
ServerConfig foundServer = null;
if( string.IsNullOrEmpty(e.TrimmedMessage) ||
!guid.TryParse(e.TrimmedMessage, out id) ||
(foundServer = ServerContext.Create(this.DbConnectionString).ServerConfigurations.FirstOrDefault(s => s.ServerId == id)) == null )
{
await e.SendReplySafe("Server not found.");
return;
}
if( string.IsNullOrEmpty(foundServer.InviteUrl) )
{
await e.SendReplySafe("I don't have permissions to create this InviteUrl.");
return;
}
await e.SendReplySafe(foundServer.InviteUrl);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !clearInvite
newCommand = new Command("clearInvite");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.IsSupportCommand = true;
newCommand.Description = "Clear the Invite url to be re-created, with serverid.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
guid id;
if( string.IsNullOrEmpty(e.TrimmedMessage) ||
!guid.TryParse(e.TrimmedMessage, out id) )
{
await e.SendReplySafe("Invalid parameters.");
return;
}
string response = "Server not found.";
ServerContext dbContext = ServerContext.Create(this.DbConnectionString);
ServerConfig foundServer = dbContext.ServerConfigurations.AsQueryable().FirstOrDefault(s => s.ServerId == id);
if( foundServer != null )
{
response = "Done.";
foundServer.InviteUrl = "";
dbContext.SaveChanges();
}
await e.SendReplySafe(response);
dbContext.Dispose();
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !restart
newCommand = new Command("restart");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Shut down the bot.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
await e.SendReplySafe("bai");
await Task.Delay(1000);
Environment.Exit(0);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
this.Commands.Add("shutdown", newCommand.CreateAlias("shutdown"));
// !getExceptions
newCommand = new Command("getExceptions");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Get a list of exceptions.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
StringBuilder response = new StringBuilder();
if( string.IsNullOrEmpty(e.TrimmedMessage) || !int.TryParse(e.TrimmedMessage, out int n) || n <= 0 )
n = 5;
GlobalContext dbContext = GlobalContext.Create(this.DbConnectionString);
foreach( ExceptionEntry exception in dbContext.Exceptions.AsQueryable().Skip(Math.Max(0, dbContext.Exceptions.Count() - n)) )
{
response.AppendLine(exception.GetMessage());
}
dbContext.Dispose();
string responseString = response.ToString();
if( string.IsNullOrWhiteSpace(responseString) )
responseString = "I did not record any errors :stuck_out_tongue:";
await e.SendReplySafe(responseString);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !getException
newCommand = new Command("getException");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Get an exception stack for specific ID.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
string responseString = "I couldn't find that exception.";
ExceptionEntry exception = null;
GlobalContext dbContext = GlobalContext.Create(this.DbConnectionString);
if( !string.IsNullOrEmpty(e.TrimmedMessage) && int.TryParse(e.TrimmedMessage, out int id) && (exception = dbContext.Exceptions.AsQueryable().FirstOrDefault(ex => ex.Id == id)) != null )
responseString = exception.GetStack();
dbContext.Dispose();
await e.SendReplySafe(responseString);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !blacklist
newCommand = new Command("blacklist");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Add or remove an ID to or from the blacklist.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e => {
guid id = 0;
string responseString = "Invalid parameters.";
if( e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[1], out id) )
{
if( !e.Message.MentionedUsers.Any() )
{
await e.SendReplySafe(responseString);
return;
}
id = e.Message.MentionedUsers.First().Id;
}
GlobalContext dbContext = GlobalContext.Create(this.DbConnectionString);
ServerStats server = ServerContext.Create(this.DbConnectionString).ServerStats
.FirstOrDefault(s => s.ServerId == id || s.OwnerId == id);
switch(e.MessageArgs[0])
{
case "check":
responseString = "Not eating bananas.";
if( dbContext.Blacklist.AsQueryable().Any(b => b.Id == id) )
responseString = "Banana'd.";
break;
case "add":
if( dbContext.Blacklist.AsQueryable().Any(b => b.Id == id) )
{
responseString = "That ID is already blacklisted.";
break;
}
dbContext.Blacklist.Add(new BlacklistEntry(){Id = id});
dbContext.SaveChanges();
responseString = server == null ? "Done." : server.ServerId == id ?
$"I'll be leaving `{server.OwnerName}`'s server `{server.ServerName}` shortly." :
$"All of `{server.OwnerName}`'s servers are now blacklisted.";
break;
case "remove":
BlacklistEntry entry = dbContext.Blacklist.AsQueryable().FirstOrDefault(b => b.Id == id);
if( entry == null )
{
responseString = "That ID was not blacklisted.";
break;
}
dbContext.Blacklist.Remove(entry);
dbContext.SaveChanges();
responseString = server == null ? "Done." : server.ServerId == id ?
$"Entry for `{server.OwnerName}`'s server `{server.ServerName}` was removed from the blacklist." :
$"Entries for all `{server.OwnerName}`'s servers were removed from the blacklist.";
break;
default:
responseString = "Invalid keyword.";
break;
}
dbContext.Dispose();
await e.SendReplySafe(responseString);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !subscriber
newCommand = new Command("subscriber");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Add or remove an ID to or from the subscribers, use with optional bonus or premium parameter.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e =>{
guid id = 0;
string responseString = "Invalid parameters.";
if( e.MessageArgs == null || e.MessageArgs.Length < 2 ||
!guid.TryParse(e.MessageArgs[1], out id) )
{
if( !e.Message.MentionedUsers.Any() )
{
await e.SendReplySafe(responseString);
return;
}
id = e.Message.MentionedUsers.First().Id;
}
GlobalContext dbContext = GlobalContext.Create(this.DbConnectionString);
Subscriber subscriber = dbContext.Subscribers.AsQueryable().FirstOrDefault(s => s.UserId == id);
switch(e.MessageArgs[0]) //Nope - mentioned users above mean that there is a parameter.
{
case "add":
if( subscriber == null )
dbContext.Subscribers.Add(subscriber = new Subscriber(){UserId = id});
for( int i = 2; i < e.MessageArgs.Length; i++ )
{
subscriber.HasBonus = subscriber.HasBonus || e.MessageArgs[i] == "bonus";
subscriber.IsPremium = subscriber.IsPremium || e.MessageArgs[i] == "premium";
}
dbContext.SaveChanges();
responseString = "Done.";
break;
case "remove":
if( subscriber == null )
{
responseString = "That ID was not a subscriber.";
break;
}
responseString = "Done.";
if( e.MessageArgs.Length < 3 )
{
dbContext.Subscribers.Remove(subscriber);
dbContext.SaveChanges();
break;
}
for( int i = 2; i < e.MessageArgs.Length; i++ )
{
subscriber.HasBonus = subscriber.HasBonus && e.MessageArgs[i] != "bonus";
subscriber.IsPremium = subscriber.IsPremium && e.MessageArgs[i] != "premium";
}
dbContext.SaveChanges();
break;
default:
responseString = "Invalid keyword.";
break;
}
dbContext.Dispose();
await e.SendReplySafe(responseString);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !partner
newCommand = new Command("partner");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Add or remove an ID to or from the partners, use with optional premium parameter.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.OwnerOnly;
newCommand.OnExecute += async e =>{
guid id = 0;
string responseString = "Invalid parameters.";
if( e.MessageArgs == null || e.MessageArgs.Length < 2 ||
!guid.TryParse(e.MessageArgs[1], out id) )
{
if( !e.Message.MentionedUsers.Any() )
{
await e.SendReplySafe(responseString);
return;
}
id = e.Message.MentionedUsers.First().Id;
}
GlobalContext dbContext = GlobalContext.Create(this.DbConnectionString);
PartneredServer partner = dbContext.PartneredServers.AsQueryable().FirstOrDefault(s => s.ServerId == id);
switch(e.MessageArgs[0]) //Nope - mentioned users above mean that there is a parameter.
{
case "add":
if( partner == null )
dbContext.PartneredServers.Add(partner = new PartneredServer(){ServerId = id});
if( e.MessageArgs.Length > 2 )
partner.IsPremium = partner.IsPremium || e.MessageArgs[2] == "premium";
dbContext.SaveChanges();
responseString = "Done.";
break;
case "remove":
if( partner == null )
{
responseString = "That ID was not a partner.";
break;
}
responseString = "Done.";
if( e.MessageArgs.Length < 3 )
{
dbContext.PartneredServers.Remove(partner);
dbContext.SaveChanges();
break;
}
if( e.MessageArgs.Length > 2 )
partner.IsPremium = partner.IsPremium && e.MessageArgs[2] != "premium";
dbContext.SaveChanges();
break;
default:
responseString = "Invalid keyword.";
break;
}
dbContext.Dispose();
await e.SendReplySafe(responseString);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !operations
newCommand = new Command("operations");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Display info about all queued or running operations on your server.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
newCommand.OnExecute += async e => {
StringBuilder response = new StringBuilder();
bool allOperations = IsGlobalAdmin(e.Message.Author.Id);
response.AppendLine($"Total operations in the queue: `{this.CurrentOperations.Count}`");
if( allOperations )
response.AppendLine($"Currently allocated data Memory: `{(GC.GetTotalMemory(false) / 1000000f):#0.00} MB`");
response.AppendLine();
lock( this.OperationsLock )
{
foreach( Operation op in this.CurrentOperations )
{
if( !allOperations && op.CommandArgs.Server.Id != e.Server.Id )
continue;
response.AppendLine(op.ToString());
if( allOperations )
response.AppendLine($"Server: `{op.CommandArgs.Server.Guild.Name}`\n" +
$"ServerID: `{op.CommandArgs.Server.Id}`\n" +
$"Allocated DataMemory: `{op.AllocatedMemoryStarted:#0.00} MB`\n");
}
}
string responseString = response.ToString();
if( string.IsNullOrEmpty(responseString) )
responseString = "There are no operations running.";
await e.SendReplySafe(responseString);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !cancel
newCommand = new Command("cancel");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Cancel queued or running operation - use in the same channel. (nuke, promoteEveryone, etc...)";
newCommand.ManPage = new ManPage("<CommandId>", "`<CommandId>` - running operation type command which this will interrupt.");
newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
newCommand.OnExecute += async e => {
string responseString = "Operation not found.";
Operation operation = null;
if( !string.IsNullOrEmpty(e.TrimmedMessage) &&
(operation = this.CurrentOperations.FirstOrDefault(
op => op.CommandArgs.Channel.Id == e.Channel.Id &&
op.CommandArgs.Command.Id == e.TrimmedMessage)) != null )
responseString = "Operation canceled:\n\n" + operation.ToString();
await e.SendReplySafe(responseString);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !say
newCommand = new Command("say");
newCommand.Type = CommandType.Standard;
newCommand.Description = "Make the bot say something!";
newCommand.ManPage = new ManPage("<text>", "`<text>` - Text which the bot will repeat.");
newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
newCommand.DeleteRequest = true;
newCommand.IsBonusCommand = true;
newCommand.IsBonusAdminCommand = true;
newCommand.IsSupportCommand = true;
newCommand.OnExecute += async e => {
if( string.IsNullOrWhiteSpace(e.TrimmedMessage) )
{
await e.SendReplySafe("Say what?");
return;
}
await e.SendReplySafe(e.TrimmedMessage, messageReference: false);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !edit
newCommand = new Command("edit");
newCommand.Type = CommandType.Standard;
newCommand.Description = "Edit a message the bot previously said!";
newCommand.ManPage = new ManPage("<MessageId> <text>", "`<MessageId>` - An ID of a message that will be edited.\n\n`<text>` - Text which the bot will repeat.");
newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
newCommand.DeleteRequest = true;
newCommand.IsBonusCommand = true;
newCommand.IsBonusAdminCommand = true;
newCommand.IsSupportCommand = true;
newCommand.OnExecute += async e => {
IMessage msg = null;
if( e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[0], out guid id) || (msg = await e.Channel.GetMessageAsync(id)) == null )
{
await e.SendReplySafe("Edit what?");
return;
}
switch( msg )
{
case RestUserMessage message:
await message?.ModifyAsync(m => m.Content = e.TrimmedMessage.Substring(e.MessageArgs[0].Length + 1));
break;
case SocketUserMessage message:
await message?.ModifyAsync(m => m.Content = e.TrimmedMessage.Substring(e.MessageArgs[0].Length + 1));
break;
default:
await e.SendReplySafe("GetMessage went bork.");
break;
}
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
// !status
newCommand = new Command("status");
newCommand.Type = CommandType.Standard;
newCommand.IsCoreCommand = true;
newCommand.Description = "Display basic server status.";
newCommand.ManPage = new ManPage("", "");
newCommand.RequiredPermissions = PermissionType.Everyone;
newCommand.OnExecute += async e => {
TimeSpan time = DateTime.UtcNow - Utils.GetTimeFromId(e.Message.Id);
await e.SendReplySafe(GetStatusString(time, e.Server));
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
this.Commands.Add("ping", newCommand.CreateAlias("ping"));
// !man
newCommand = new Command("man");
newCommand.Type = CommandType.Standard;
newCommand.Description = "Show detailed manual page for a command.";
newCommand.ManPage = new ManPage("<command>", "`<command>` - Command ID for which to display .");
newCommand.RequiredPermissions = PermissionType.Everyone;
newCommand.OnExecute += async e => {
string commandId = e.TrimmedMessage.ToLower();
string response = "I ain't got no real command like that. (This feature isn't a thing for Custom Commands!)";
if( string.IsNullOrEmpty(commandId) || (!e.Server.Commands.ContainsKey(commandId) && (!e.Server.CustomAliases.ContainsKey(commandId) || !e.Server.Commands.ContainsKey(commandId = e.Server.CustomAliases[commandId].CommandId))) )
{
await e.SendReplySafe(response);
return;
}
Command cmd = e.Server.Commands[commandId];
if( !string.IsNullOrEmpty(cmd.ParentId) && e.Server.Commands.ContainsKey(cmd.ParentId) )
cmd = e.Server.Commands[cmd.ParentId];
Embed embed = e.Server.GetManPage(cmd);
await e.SendReplySafe(null, embed);
};
this.Commands.Add(newCommand.Id.ToLower(), newCommand);
this.Commands.Add("manual", newCommand.CreateAlias("manual"));
// !help
newCommand = new Command("help");
newCommand.Type = CommandType.Standard;
newCommand.Description = "PMs a list of Custom Commands for the server if used without arguments, or search for specific commands.";
newCommand.ManPage = new ManPage("[search expression]", "[search expression] - Optional argument to search for specific commands.");
newCommand.RequiredPermissions = PermissionType.Everyone;
newCommand.OnExecute += async e => {
StringBuilder response = new StringBuilder("Please refer to the website documentation for the full list of features and commands: <https://valkyrja.app/docs>\n\n");
StringBuilder commandStrings = new StringBuilder();
bool isSpecific = !string.IsNullOrWhiteSpace(e.TrimmedMessage);
string prefix = e.Server.Config.CommandPrefix;
List<string> includedCommandIds = new List<string>();
int count = 0;
bool cantPm = false;
async Task Append(string newString)
{
string pm = commandStrings.ToString();
if( !isSpecific && pm.Length + newString.Length >= GlobalConfig.MessageCharacterLimit )
{
try
{
await e.Message.Author.SendMessageAsync(pm);
}
catch( Exception )
{
cantPm = true;
}
commandStrings.Clear();
}
commandStrings.AppendLine(newString);
}
async Task AddCustomAlias(string commandId)
{
string newString = "";
List<CustomAlias> aliases = e.Server.CustomAliases.Values.Where(a => a.CommandId == commandId).ToList();
int aliasCount = aliases.Count;
if( aliasCount > 0 )
{
newString = aliasCount == 1 ? " **-** Custom Alias: " : " **-** Custom Aliases: ";
for( int i = 0; i < aliasCount; i++ )
newString += $"{(i == 0 ? "`" : i == aliasCount - 1 ? " and `" : ", `")}{prefix}{aliases[i].Alias}`";
await Append(newString);
}
}
async Task AddCommand(Command cmd)
{
if( includedCommandIds.Contains(cmd.Id) )
return;
includedCommandIds.Add(cmd.Id);
string newString = $"\n```diff\n{(cmd.CanExecute(this, e.Server, e.Channel, e.Message.Author as SocketGuildUser) ? "+" : "-")}" +
$" {prefix}{cmd.Id}```" +
$" **-** {cmd.Description}";
if( cmd.Aliases != null && cmd.Aliases.Any() )
{
int aliasCount = cmd.Aliases.Count;
newString += aliasCount == 1 ? "\n **-** Alias: " : "\n **-** Aliases: ";
for( int i = 0; i < aliasCount; i++ )
newString += $"{(i == 0 ? "`" : i == aliasCount - 1 ? " and `" : ", `")}{prefix}{cmd.Aliases[i]}`";
}
if( cmd.ManPage != null )
newString += $"\n **-** Use `{prefix}man {cmd.Id}` to display full manual page.";
await Append(newString);
await AddCustomAlias(cmd.Id);
}
async Task AddCustomCommand(CustomCommand cmd)
{
if( includedCommandIds.Contains(cmd.CommandId) )
return;
includedCommandIds.Add(cmd.CommandId);
string newString = $"\n```diff\n{(cmd.CanExecute(this, e.Server, e.Channel, e.Message.Author as SocketGuildUser) ? "+" : "-")}" +
$" {prefix}{cmd.CommandId}```";
if( !string.IsNullOrWhiteSpace(cmd.Description) )
newString += $"\n **-** {cmd.Description}";
await Append(newString);
await AddCustomAlias(cmd.CommandId);
}
if( isSpecific )
{
string expression = e.TrimmedMessage.Replace(" ", "|") + ")\\w*";
if( e.MessageArgs.Length > 1 )
expression += "(" + expression;
Regex regex = new Regex($"\\w*({expression}", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(10f));
foreach( Command cmd in e.Server.Commands.Values )