-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiscordBot.cs
1819 lines (1535 loc) · 82.1 KB
/
DiscordBot.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.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using DiscordBot.Models;
using DiscordBot.Services;
using Google.Apis.Sheets.v4.Data;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using PoliceMP.Shared.Models.Weather;
using Color = Discord.Color;
using Timer = System.Timers.Timer;
namespace DiscordBot
{
public class DiscordBot
{
private static DiscordSocketClient _discord;
private static SocketGuild _mainGuild;
private static readonly ulong MainGuildId = 598107702652043264;
private readonly string LogoUrl =
"https://pbs.twimg.com/profile_images/1487001710782562306/bKuWVjEd_400x400.jpg";
#region Channels
public static ITextChannel NewUserRulesChannel;
private static readonly ulong NewUserRulesChannelId = 826179180071878676;
private static ITextChannel _systemMessagesChannel;
private static readonly ulong SystemMessagesId = 663062545308844043;
private static ITextChannel _roleAssignmentChannel;
private static readonly ulong _roleAssignmentChannelId = 848264958164336640;
private static IVoiceChannel _onlinePlayerCountChannel;
private static readonly ulong _onlinePlayerCountChannelId = 903759769502904410;
private static IVoiceChannel _serverStatusChannel;
private static readonly ulong _serverStatusChannelId = 903762970293723136;
#endregion Channels
#region Roles
private static IRole _nonVerifiedRole;
private static readonly ulong NonVerifiedRoleId = 861989523235405854;
private static IRole _loaRole;
private static readonly ulong LoaRoleId = 849742751474122802;
private static IRole _verifiedRole;
private static readonly ulong VerifiedRoleId = 826178299335278602;
private static IRole _devSubscriberRole;
private static readonly ulong _devSubscriberRoleId = 777852649637937184;
private static IRole _twitterSubscriberRole;
private static readonly ulong _twitterSubscriberRoleId = 848265532779659327;
private static IRole _readyOrNotRole;
private static readonly ulong _readyOrNotRoleId = 925118930371088416;
#endregion Roles
#region Reactions
private static readonly string _twitterEmoteName = "bird";
private static readonly string _devSubscriberEmoteName = "construction_worker";
private static IEmote twitterEmote = new Emoji($"🐦");
private static IEmote devEmote = new Emoji("👷");
private static IEmote readyOrNotEmote = new Emoji("🔫");
#endregion
public DiscordBot()
{
}
public async Task StartDiscordBot()
{
Console.WriteLine("Starting PoliceMP Bot");
var services = ConfigureServices();
_discord = new DiscordSocketClient(new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.All,
AlwaysDownloadUsers = true
});
_discord.Log += Log;
services.GetRequiredService<CommandService>().Log += Log;
await _discord.LoginAsync(TokenType.Bot, "tokenhere");
await _discord.StartAsync();
await services.GetRequiredService<CommandHandlingService>().InitializeAsync();
_discord.ReactionAdded += DiscordOnReactionAdded;
_discord.ReactionRemoved += DiscordOnReactionRemoved;
_discord.GuildMemberUpdated += DiscordOnGuildMemberUpdated;
_discord.UserJoined += DiscordOnUserJoined;
_discord.MessageReceived += DiscordOnMessageReceived;
_discord.InteractionCreated += DiscordOnInteractionCreated;
_discord.Ready += DiscordOnReady;
_discord.UserLeft += DiscordOnUserLeft;
_discord.Ready += DiscordOnReady;
_discord.MessageReceived += DiscordMessageReceived;
}
#region User Left
private async Task DiscordOnUserLeft(SocketGuild guild, SocketUser user)
{
var leaveEmbed = new EmbedBuilder
{
Title = "User Left",
Description = $"{user.Mention} has left the server!",
Timestamp = DateTimeOffset.Now,
Color = Color.Red,
ThumbnailUrl = user.GetAvatarUrl(),
Footer = new EmbedFooterBuilder
{
Text = $"User ID: {user.Id}"
}
};
await _systemMessagesChannel.SendMessageAsync(embed: leaveEmbed.Build());
}
#endregion
#region Interaction
private async Task DiscordOnInteractionCreated(SocketInteraction interaction)
{
#region Drop Down If
if (interaction is SocketMessageComponent componentInteraction)
{
if (componentInteraction.Data.Type == ComponentType.Button)
{
if (componentInteraction.Data.CustomId == "closeSupportTicket")
{
await componentInteraction.DeferAsync(true);
// Close Support Ticket
var channel = (ITextChannel)componentInteraction.Channel;
if (channel.CategoryId == 815240585995878420) return;
await channel.ModifyAsync(async properties =>
{
properties.Name = $"closed-{channel.Name}";
properties.CategoryId = 815240585995878420;
properties.PermissionOverwrites = await SupportSystem.FetchClosedChannelPermissions();
});
var buttons = new ComponentBuilder().WithButton("Complete Ticket", "completeSupportTicket", ButtonStyle.Success).Build();
await channel.SendMessageAsync(
$"{componentInteraction.User.Mention} has closed this ticket. You may now complete it.",
components: buttons);
}
if (componentInteraction.Data.CustomId == "completeSupportTicket")
{
await componentInteraction.DeferAsync();
var channel = (ITextChannel)componentInteraction.Channel;
await channel.DeleteAsync();
}
}
if (componentInteraction.Data.Type == ComponentType.SelectMenu)
{
if (componentInteraction.Data.CustomId == "supportMenu")
{
await componentInteraction.DeferAsync(true);
if(componentInteraction.Data.Values.First() == "bugReport")
{
await componentInteraction.FollowupAsync(
"Hey. We've moved the Bug Reports over the forum!\nhttps://forum.policemp.com/index.php?forums/bug-reports.232/");
return;
}
var channel = await CreateSupportTicket(componentInteraction);
await componentInteraction.FollowupAsync(
$"A Channel has been created! Thanks for requesting support. Head over to it! {channel.Mention}", ephemeral: true);
return;
}
}
}
#endregion
#region Command If
if (interaction is SocketSlashCommand command)
{
switch (command.Data.Name)
{
case "ping":
await command.RespondAsync($"{command.User.Mention} Pong!", ephemeral: true);
break;
case "bug":
var mentionedUser = command.User;
var hasUser = command.Data.Options.Any();
if (hasUser)
{
mentionedUser = (SocketGuildUser)command.Data.Options.First().Value ?? command.User;
}
await command.RespondAsync($"**Bug Reports**\n" +
$"*Thank you for sharing your findings with us {mentionedUser.Mention}. The development team are very busy resolving any issues and adding in new features!*\n" +
$"Please head over to the forums and post a bug report! Don't forget to use as much information as possible!\n" +
$"https://forum.policemp.com/index.php?form/bug-report.5/select");
break;
case "myid":
await command.RespondAsync($"Your Discord User ID is: {command.User.Id}", ephemeral: true);
break;
case "connect":
await command.RespondAsync(
$"You can direct connect to the server! fivem://connect/play.policemp.com");
break;
case "donate":
await command.RespondAsync(
"You can subscribe through our Tebex! https://policemp.com/store");
break;
case "subscribe":
await command.RespondAsync(
"You can subscribe through our Tebex! https://policemp.com/store");
break;
case "pclink":
await command.RespondAsync($"You can head over to the forums and apply for PC!\n" +
$"Once your application is submitted, it will be automatically scored and you'll receive access to the training lounge!\n" +
$"https://forum.policemp.com/index.php?categories/police-constable-application-form.203/");
break;
case "laslink":
await command.RespondAsync($"You can head over to the forums and apply for LAS Paramedic!\n" +
$"Once your application is submitted, it will be automatically scored and you'll receive access to the training lounge!\n" +
$"https://forum.policemp.com/index.php?categories/student-paramedic-application-form.205/");
break;
case "loalink":
await command.RespondAsync($"You can head over to the Google Forms to apply for a Leave of Absence (LOA).\n" +
$"Once you submit the form, the LOA tag will be added within few hours. You only need to apply for LOA if you are a PC+ or LAS Paramedic+.\n" +
$"https://forms.gle/k2MnRM9dqTe5Sspd9");
break;
case "verify":
await command.RespondAsync($"Head over to {NewUserRulesChannel.Mention} to verify yourself!");
break;
case "guides":
await command.RespondAsync($"We have a lot of helpful guides you can check out.\n" +
$"You can check out some useful guides on our forums!\n" +
$"https://policemp.com/guides\n" +
$"We also have a cadet video!\n" +
$"https://policemp.com/guides/getting-started");
break;
case "pchelp":
await command.RespondAsync(
"**1.** Go to https://forum.policemp.com/index.php?categories/police-constable-application-form.203/\n" +
"**2**. If it says \"Oops! We ran into some problems.\", go to the top right where it either says your name or login/sign up.\n" +
"**3.** Create an account if you haven't got one already but if you have, just signin.\n" +
"**4.** Click your name at the top right, account settings and go down to \"Connected Accounts\" or just click this link https://forum.policemp.com/index.php?account/connected-accounts/\n" +
"**5.** Click \"associate with discord\" and follow the steps.\n" +
"**6.** Now you have linked your discord, go back to the forums, go to Police Constable Application and fill that in OR click this link again https://forum.policemp.com/index.php?categories/police-constable-application-form.203/");
break;
case "lashelp":
await command.RespondAsync(
"**1.** Go to https://forum.policemp.com/index.php?categories/student-paramedic-application-form.205/\n" +
"**2**. If it says \"Oops! We ran into some problems.\", go to the top right where it either says your name or login/sign up.\n" +
"**3.** Create an account if you haven't got one already but if you have, just signin.\n" +
"**4.** Click your name at the top right, account settings and go down to \"Connected Accounts\" or just click this link https://forum.policemp.com/index.php?account/connected-accounts/\n" +
"**5.** Click \"associate with discord\" and follow the steps.\n" +
"**6.** Now you have linked your discord, go back to the forums, go to Student Paramedic Application and fill that in OR click this link again https://forum.policemp.com/index.php?categories/student-paramedic-application-form.205/");
break;
case "cadhelp":
await command.RespondAsync(
"To set-up CAD, follow the steps in the CAD Guide: https://docs.google.com/presentation/d/11QesgNGFh6RfUTGT8s0SHej-SqR9F_Ozzvk3qZTMm3I/edit\n" +
"Pleas note, to use the CAD you need to be at least a **Police Constable** or **Student Paramedic**."
);
break;
case "mentee":
await command.RespondAsync(
"Use this link to become a mentee - https://forms.gle/VPYvxBqUWvSZ4VQs6");
break;
case "support":
await command.RespondAsync("Please select an option from the menu.", components: await SupportSystem.CreateSupportSystemMessageButtons(), ephemeral: true);
break;
case "getid":
var getIdUser = (SocketGuildUser)command.Data.Options.First().Value ?? command.User;
await command.RespondAsync($"The ID of the user is ```{getIdUser.Id}```", ephemeral: true);
break;
case "loaremove":
var loaRemoveUser = command.User as SocketGuildUser;
var loaRole = loaRemoveUser.Roles.FirstOrDefault(x => x.Id == LoaRoleId);
if (loaRole != null)
{
await loaRemoveUser.RemoveRoleAsync(loaRole);
var policeBand2Channel = _mainGuild.GetTextChannel(892178538181038080);
var loaRemoveEmbedBuilder = new EmbedBuilder();
loaRemoveEmbedBuilder.Color = Color.DarkerGrey;
loaRemoveEmbedBuilder.Title = "LOA Role Removed";
loaRemoveEmbedBuilder.Description = $"{command.User.Username} has requested removal of their LOA role.";
await policeBand2Channel.SendMessageAsync(embed: loaRemoveEmbedBuilder.Build());
await command.RespondAsync($"Your LOA has role has been removed.", ephemeral: true);
}
else
{
Console.WriteLine($"User ID {loaRemoveUser.Id} has requested LOA removal, but does not currently have it.");
await command.RespondAsync($"You currently do not have an LOA role. Please only use this command if you have the role present.", ephemeral: true);
}
break;
case "weather":
var weather = await FetchWeather();
var cultureInfo = Thread.CurrentThread.CurrentCulture;
var textInfo = cultureInfo.TextInfo;
var embedBuilder = new EmbedBuilder
{
Color = Color.Blue,
Description =
$"Current Weather: {textInfo.ToTitleCase(weather.weather.First().description)}",
ThumbnailUrl =
$"https://openweathermap.org/img/wn/{weather.weather.FirstOrDefault()?.icon}.png",
Timestamp = DateTimeOffset.Now,
Title = $"Current Weather for {weather.name}."
}.AddField("Temperature", $"{Math.Round(weather.main.temp)}°C")
.AddField("High Temperature", $"{Math.Round(weather.main.temp_max)}°C")
.AddField("Low Temperature", $"{Math.Round(weather.main.temp_min)}°C")
.AddField("Humidity", $"{weather.main.humidity} %RH")
.AddField("Visibility", $"{weather.visibility} meters")
.WithFooter("PoliceMP Weather Integration", "https://pbs.twimg.com/profile_images/1487001710782562306/bKuWVjEd_400x400.jpg");
await command.RespondAsync(embed: embedBuilder.Build());
break;
case "post":
var channel = (SocketChannel)command.Data.Options.First(d => d.Name == "channel").Value;
var title = command.Data.Options.First(d => d.Name == "title").Value.ToString();
var message = command.Data.Options.First(d => d.Name == "message").Value.ToString();
var role = (SocketRole)command.Data.Options.FirstOrDefault(d => d.Name == "role")?.Value;
var hasEmbedData = command.Data.Options.Any(d => d.Name == "embed");
var embedMessage = true;
if (hasEmbedData)
{
embedMessage = (bool) command.Data.Options.FirstOrDefault(d => d.Name == "embed")?.Value;
}
var textChannel = (ITextChannel) channel;
if (textChannel == null)
{
await command.RespondAsync($"Channel must be a text channel!", ephemeral: true);
return;
}
if (embedMessage)
{
var postEmbedBuilder = new EmbedBuilder
{
Title = title,
Description = message,
ThumbnailUrl =
"https://pbs.twimg.com/profile_images/1487001710782562306/bKuWVjEd_400x400.jpg",
Timestamp = DateTimeOffset.Now,
Color = Color.Blue
};
if (role != null)
{
await textChannel.SendMessageAsync($"{role.Mention}", embed: postEmbedBuilder.Build());
}
else
{
await textChannel.SendMessageAsync(embed: postEmbedBuilder.Build());
}
}
else
{
if (role != null)
{
await textChannel.SendMessageAsync($"{role.Mention}\n{message}");
}
else
{
await textChannel.SendMessageAsync(message);
}
}
await command.RespondAsync("Message Sent!");
break;
case "removerole":
var roleToRemove = (SocketRole)command.Data.Options.FirstOrDefault(d => d.Name == "role")?.Value;
var userToRemove = (IGuildUser)command.Data.Options.FirstOrDefault(d => d.Name == "user")?.Value;
var removeRoleCommandTrigger = command.User as SocketGuildUser;
List<ulong> allowedRoleIds = new List<ulong>();
allowedRoleIds.Add(849742751474122802); //LOA Role
allowedRoleIds.Add(755152624369795102); //LFB Role
allowedRoleIds.Add(797934748185264158); //PC Role
allowedRoleIds.Add(864592335730900992); //ERT Role
allowedRoleIds.Add(755152618229072014); //LAS Para Role
allowedRoleIds.Add(886449681104769085); //Highways Role
if (roleToRemove != null && userToRemove != null)
{
if (allowedRoleIds.Contains(roleToRemove.Id) && userToRemove.RoleIds.Contains(roleToRemove.Id))
{
await userToRemove.RemoveRoleAsync(roleToRemove);
await _systemMessagesChannel.SendMessageAsync(
$"{userToRemove.Username} has been removed from the {roleToRemove.Name} role by {removeRoleCommandTrigger.Username}.");
await command.RespondAsync($"{userToRemove.Username} has been removed from the {roleToRemove.Name} role.", ephemeral: true);
}
else if (allowedRoleIds.Contains(roleToRemove.Id) && !userToRemove.RoleIds.Contains(roleToRemove.Id))
{
await command.RespondAsync($"{userToRemove.Username} does not have the {roleToRemove.Name} role.", ephemeral: true);
}
else
{
await command.RespondAsync($"The role which you are trying to remove cannot be removed using this command.", ephemeral: true);
}
}
else
{
await command.RespondAsync($"Error - Please raise a bug report.", ephemeral: true);
}
break;
case "donatorcallsign":
var discordId = command.User.Id;
var callsign = (double)command.Data.Options.First(d => d.Name == "callsign").Value;
var serviceValues = SheetInterface.GetSheetsService().Spreadsheets.Values;
await SheetInterface.OnSendDonatorCallsignCommand(serviceValues, $"D{callsign}", discordId);
await command.RespondAsync(
"Thank you for giving us this. We will cross-reference and any issues we'll be in contact!", ephemeral: true);
break;
}
}
#endregion
}
#endregion
#region Weather
private async Task<OpenWeather> FetchWeather()
{
var locationId = "2643743";
var appId = "37c1a999011411a01b4d200ea16e9b9a";
var url = new Uri(
$"http://api.openweathermap.org/data/2.5/weather?id={locationId}&mode=json&units=metric&APPID={appId}");
using var webClient = new WebClient();
var currentWeatherJson = await webClient.DownloadStringTaskAsync(url);
if (string.IsNullOrEmpty(currentWeatherJson)) return null;
var currentWeather = JsonConvert.DeserializeObject<OpenWeather>(currentWeatherJson);
return currentWeather;
}
#endregion
#region User Joined
private async Task DiscordOnUserJoined(SocketGuildUser user)
{
Console.WriteLine("User Join Event");
if (user == null)
{
Console.WriteLine("User is Null");
return;
}
try
{
var joinEmbed = new EmbedBuilder
{
Title = "User Joined",
Description = $"{user.Mention} has joined the server!",
Timestamp = DateTimeOffset.Now,
Color = Color.Green,
ThumbnailUrl = user.GetAvatarUrl(),
Footer = new EmbedFooterBuilder
{
Text = $"User ID: {user.Id}"
}
};
await user.AddRoleAsync(_nonVerifiedRole);
await _systemMessagesChannel.SendMessageAsync(embed: joinEmbed.Build());
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
return;
}
#endregion
#region Member Updated
private async Task DiscordOnGuildMemberUpdated(Cacheable<SocketGuildUser, ulong> userBefore, SocketGuildUser userAfter)
{
var rolesAdded = userAfter.Roles.Count > userBefore.Value.Roles.Count;
if (rolesAdded)
{
var newRoles = userAfter.Roles.Except(userBefore.Value.Roles);
var rolesAddedEmbed = new EmbedBuilder
{
Title = "Roles Added",
Description = $"{userAfter.Mention} has been granted some new roles!",
Color = Color.Green,
Timestamp = DateTimeOffset.Now,
ThumbnailUrl = LogoUrl,
Footer = new EmbedFooterBuilder
{
Text = $"User ID: {userAfter.Id}"
}
};
foreach (var newRole in newRoles)
{
if (newRole.Id is 793170213759746049 or 673911514004062208)
{
// Donator Pro
var serviceValues = SheetInterface.GetSheetsService().Spreadsheets.Values;
var newDonatorCallsign = await SheetInterface.OnDonatorRoleAdded(serviceValues, userAfter.Id, newRole.Id == 793170213759746049);
await userAfter.SendMessageAsync(
$"Thank you for Donating to PoliceMP! :partying_face: :partying_face: - Your new Donator callsign is {newDonatorCallsign}!");
var donatorChannel = _mainGuild.GetTextChannel(717172337660657716);
await donatorChannel.SendMessageAsync(
$"Thank you for Donating to PoliceMP {userAfter.Mention}! :partying_face: :partying_face: - Your new Donator callsign is {newDonatorCallsign}!");
}
rolesAddedEmbed.AddField("New Role", newRole.Name);
}
await _systemMessagesChannel.SendMessageAsync(embed: rolesAddedEmbed.Build());
}
var rolesRemoved = userBefore.Value.Roles.Count > userAfter.Roles.Count;
if (rolesRemoved)
{
var removedRoles = userBefore.Value.Roles.Except(userAfter.Roles);
var rolesRemovedEmbed = new EmbedBuilder
{
Title = "Roles Added",
Description = $"{userAfter.Mention} has had some roles removed!",
Color = Color.Red,
Timestamp = DateTimeOffset.Now,
ThumbnailUrl = LogoUrl,
Footer = new EmbedFooterBuilder
{
Text = $"User ID: {userBefore.Id}"
}
};
foreach (var removedRole in removedRoles)
{
if (removedRole.Id is 793170213759746049 or 673911514004062208)
{
// Donator Pro
var serviceValues = SheetInterface.GetSheetsService().Spreadsheets.Values;
await SheetInterface.OnDonatorRoleRemoved(serviceValues, userAfter.Id);
await userAfter.SendMessageAsync(
$"We are sorry to hear that you have stopped donating to PoliceMP. Your previous call sign has been marked to be reallocated");
}
rolesRemovedEmbed.AddField("Removed Role", removedRole.Name);
}
await _systemMessagesChannel.SendMessageAsync(embed: rolesRemovedEmbed.Build());
}
}
#endregion
#region Reaction Removed
private async Task DiscordOnReactionRemoved(Cacheable<IUserMessage, ulong> message, Cacheable<IMessageChannel, ulong> channel, SocketReaction reaction)
{
var users = await _mainGuild.GetUsersAsync().FlattenAsync();
var user = users.FirstOrDefault(i => i.Id == reaction.User.Value.Id);
if (user == null) return;
if (user.IsBot) return;
if (channel.Value == _roleAssignmentChannel)
{
if (reaction.Emote.Name == twitterEmote.Name)
{
if (!reaction.User.IsSpecified) return;
if (user == null) return;
await user.RemoveRoleAsync(_twitterSubscriberRole);
await _systemMessagesChannel.SendMessageAsync(
$"{user.Username} has been removed from the {_twitterSubscriberRole.Name} role.");
}
if (reaction.Emote.Name == readyOrNotEmote.Name)
{
if (!reaction.User.IsSpecified) return;
if (user == null) return;
await user.RemoveRoleAsync(_readyOrNotRole);
await _systemMessagesChannel.SendMessageAsync(
$"{user.Username} has been removed from the {_readyOrNotRole.Name} role.");
}
if (reaction.Emote.Name == devEmote.Name)
{
if (!reaction.User.IsSpecified) return;
if (user == null) return;
await user.RemoveRoleAsync(_devSubscriberRole);
await _systemMessagesChannel.SendMessageAsync(
$"{user.Username} has been removed from the {_devSubscriberRole.Name} role.");
}
}
}
#endregion
#region Reaction Added
private async Task DiscordOnReactionAdded(Cacheable<IUserMessage, ulong> message, Cacheable<IMessageChannel, ulong> channel, SocketReaction reaction)
{
var users = await _mainGuild.GetUsersAsync().FlattenAsync();
var user = users.FirstOrDefault(i => i.Id == reaction.User.Value.Id);
if (user == null) return;
if (user.IsBot) return;
if (channel.Value == NewUserRulesChannel)
{
if (reaction.Emote.Name != "jobdone") return;
if (!reaction.User.IsSpecified) return;
if (user == null) return;
await user.AddRoleAsync(_verifiedRole);
await user.RemoveRoleAsync(_nonVerifiedRole);
if (user.CreatedAt > DateTimeOffset.Now.AddHours(-24))
{
try
{
var modNotesChannel = (ITextChannel)_mainGuild.GetChannel(863173222651265074);
var embedNewUserWarning = new EmbedBuilder
{
Description =
$"A user who has registered in the last 24h has joined Discord.",
Title = $"WARNING! New User Registered!",
Color = Color.Orange,
ThumbnailUrl = "https://pbs.twimg.com/profile_images/1487001710782562306/bKuWVjEd_400x400.jpg"
}
.AddField("Discord ID", user.Id)
.AddField("Discord Name", user.Username)
.AddField("Registration date", user.CreatedAt.ToString()).Build();
await modNotesChannel.SendMessageAsync(embed: embedNewUserWarning);
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
}
try
{
var embed = new EmbedBuilder
{
Description =
$"{user.Mention}, Welcome to PoliceMP!" +
$"\n\nIf you're new to the community, make sure you checkout the Getting Started Guide to help you get up and running: https://policemp.com/guides/getting-started " +
$"\n\nYou can apply for a Police Constable role, which will unlock a taser, new uniforms and new cars by following the steps: https://policemp.com/apply " +
$"\n\n Lastly, if you need any support or looking for a member of staff, please use /support in any of our channels to raise a request. We have a team on stand-by to help with any queries, our Senior Staff are very busy, therefore please don't message them directly." +
$"\n\nEnjoy your stay at PoliceMP, we're looking forward to seeing your on our server!",
Title = $"Welcome to {_mainGuild.Name}!",
Color = Color.Blue,
ThumbnailUrl = "https://pbs.twimg.com/profile_images/1487001710782562306/bKuWVjEd_400x400.jpg"
}.Build();
await user.SendMessageAsync(embed: embed);
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
await _systemMessagesChannel.SendMessageAsync(
$"{user.Username} has been assigned to the {_verifiedRole.Name} role.");
}
if (channel.Value == _roleAssignmentChannel)
{
if (reaction.Emote.Name == twitterEmote.Name)
{
if (!reaction.User.IsSpecified) return;
if (user == null) return;
await user.AddRoleAsync(_twitterSubscriberRole);
await _systemMessagesChannel.SendMessageAsync(
$"{user.Username} has been added to the {_twitterSubscriberRole.Name} role.");
}
if (reaction.Emote.Name == readyOrNotEmote.Name)
{
if (!reaction.User.IsSpecified) return;
if (user == null) return;
await user.AddRoleAsync(_readyOrNotRole);
await _systemMessagesChannel.SendMessageAsync(
$"{user.Username} has been added to the {_readyOrNotRole.Name} role.");
}
if (reaction.Emote.Name == devEmote.Name)
{
if (!reaction.User.IsSpecified) return;
if (user == null) return;
await user.AddRoleAsync(_devSubscriberRole);
await _systemMessagesChannel.SendMessageAsync(
$"{user.Username} has been added to the {_devSubscriberRole.Name} role.");
}
}
return;
}
#endregion
#region Discord Ready
private async Task DiscordOnReady()
{
_mainGuild = _discord.GetGuild(MainGuildId);
int count = 0;
while (_mainGuild == null && count < 10)
{
Console.WriteLine("Waiting to get main guild");
count++;
_mainGuild = _discord.GetGuild(MainGuildId);
await Task.Delay(100);
}
if (_mainGuild is null)
{
Console.WriteLine("Unable to connect to the Guild!");
return;
}
await _discord.SetStatusAsync(UserStatus.Invisible);
Console.WriteLine($"Connected to {_mainGuild.Name}");
#region Fetch Channels
NewUserRulesChannel = _mainGuild.GetTextChannel(NewUserRulesChannelId);
if (NewUserRulesChannel is null)
{
Console.WriteLine("Unable to fetch the main support channel!");
return;
}
Console.WriteLine($"Found {NewUserRulesChannel.Name}");
_systemMessagesChannel = _mainGuild.GetTextChannel(SystemMessagesId);
if (_systemMessagesChannel is null)
{
Console.WriteLine($"Unable to get the system messages channel!");
return;
}
_roleAssignmentChannel = _mainGuild.GetTextChannel(_roleAssignmentChannelId);
if (_roleAssignmentChannel is null)
{
Console.WriteLine("Unable to get the Role Assignment channel!");
return;
}
_onlinePlayerCountChannel = _mainGuild.GetVoiceChannel(_onlinePlayerCountChannelId);
if (_onlinePlayerCountChannel is null)
{
Console.WriteLine("Unable to get the player count channel!");
return;
}
_serverStatusChannel = _mainGuild.GetVoiceChannel(_serverStatusChannelId);
if (_serverStatusChannel is null)
{
Console.WriteLine("Unable to get the service status channel");
return;
}
#endregion
#region Fetch Roles
_verifiedRole = _mainGuild.GetRole(VerifiedRoleId);
_nonVerifiedRole = _mainGuild.GetRole(NonVerifiedRoleId);
_devSubscriberRole = _mainGuild.GetRole(_devSubscriberRoleId);
_twitterSubscriberRole = _mainGuild.GetRole(_twitterSubscriberRoleId);
_readyOrNotRole = _mainGuild.GetRole(_readyOrNotRoleId);
if (_verifiedRole == null)
{
Console.WriteLine("Unable to find verified role");
}
if (_nonVerifiedRole == null)
{
Console.WriteLine("Unable to find non-verified role");
}
if (_devSubscriberRole == null)
{
Console.WriteLine("Unable to find dev subscriber role");
}
if (_twitterSubscriberRole == null)
{
Console.WriteLine("Unable to find twitter subscriber role");
}
Console.WriteLine("Found Discord Roles?");
#endregion
var users = await _mainGuild.GetUsersAsync().FlattenAsync();
foreach (var guildUser in await _mainGuild.GetUsersAsync().FlattenAsync())
{
var user = _mainGuild.GetUser(guildUser.Id);
if (user.Roles.Contains(_nonVerifiedRole)) continue;
if (user.Roles.Contains(_verifiedRole)) continue;
await guildUser.AddRoleAsync(_nonVerifiedRole);
Console.WriteLine($"Added {guildUser.Nickname} to Non-Verified");
}
#region Commands
var pingCommand = new SlashCommandBuilder
{
Name = "ping",
Description = "Ping Command",
};
var bugCommand = new SlashCommandBuilder
{
Name = "bug",
Description = "Fetches the Bug Report forum link!"
}.AddOption("user", ApplicationCommandOptionType.User, "If you wish to mention a user", false);
var idCommand = new SlashCommandBuilder
{
Name = "myid",
Description = "Fetches your Discord ID!"
};
var connectCommand = new SlashCommandBuilder
{
Name = "connect",
Description = "Used to fetch the connection URL for the server"
};
var donateCommand = new SlashCommandBuilder
{
Name = "donate",
Description = "Used to fetch the store link for the server."
};
var subscribeCommand = new SlashCommandBuilder
{
Name = "subscribe",
Description = "Used to fetch the store link for the server."
};
var pcCommand = new SlashCommandBuilder
{
Name = "pclink",
Description = "Used to post the PC application link."
};
var lasLinkCommand = new SlashCommandBuilder
{
Name = "laslink",
Description = "Used to post the LAS application link."
};
var loaLinkCommand = new SlashCommandBuilder
{
Name = "loalink",
Description = "Used to post the LOA form link."
};
var verifyCommand = new SlashCommandBuilder
{
Name = "verify",
Description = "Used to share how to get verified on Discord!"
};
var guideCommand = new SlashCommandBuilder
{
Name = "guides",
Description = "Shares a link to the PoliceMP guides!"
};
var pcHelpCommand = new SlashCommandBuilder
{
Name = "pchelp",
Description = "Used to send out how to apply for PC!"
};
var lasHelpCommand = new SlashCommandBuilder
{
Name = "lashelp",
Description = "Used to send out how to apply for Student Paramedic!"
};
var cadHelpCommand = new SlashCommandBuilder
{
Name = "cadhelp",
Description = "Used to send out how to set-up the CAD."
};
var menteeCommand = new SlashCommandBuilder
{
Name = "mentee",
Description = "Used to send out the Mentee Signup Link!"
};
var loaRemoveCommand = new SlashCommandBuilder
{
Name = "loaremove",
Description = "Used to remove the LOA role. Can only be used by the user with the LOA role."
};
var supportCommand = new SlashCommandBuilder
{
Name = "support",
Description = "Request a Ticket for some support!"
};
var findIdCommand = new SlashCommandBuilder
{
Name = "getid",
Description = "Used to get a users discord ID"
}.AddOption("user", ApplicationCommandOptionType.User, "The user you want the ID for", true);
var weatherCommand = new SlashCommandBuilder
{
Name = "weather",
Description = "Fetches the latest weather in the server!"
};
var convertDonatorCallsignCommand = new SlashCommandBuilder
{
Name = "donatorcallsign",
Description = "Convert your Donator Callsign to our new system!"
}
.AddOption("callsign", ApplicationCommandOptionType.Number, "Your Donator Callsign", true);
var postCommandBuilder = new SlashCommandBuilder
{
Name = "post",
Description = "Post as the PoliceMP Bot",
IsDefaultPermission = false,
}.AddOption("channel", ApplicationCommandOptionType.Channel, "The channel you wish to post in", true)
.AddOption("title", ApplicationCommandOptionType.String, "The Title of the Embed Message", true)
.AddOption("message", ApplicationCommandOptionType.String, "The message you wish to type.", true)
.AddOption("role", ApplicationCommandOptionType.Role, "The Role you wish to Tag", false)