-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoleCommands.cs
1253 lines (1184 loc) · 68.7 KB
/
RoleCommands.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.ComponentModel;
using System.Drawing;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Remora.Commands.Attributes;
using Remora.Commands.Groups;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.API.Abstractions.Rest;
using Remora.Discord.Commands.Attributes;
using Remora.Discord.Commands.Contexts;
using Remora.Discord.Commands.Feedback.Messages;
using Remora.Discord.Commands.Feedback.Services;
using Remora.Discord.Extensions.Embeds;
using Remora.Rest.Core;
using Remora.Results;
using System.Reflection;
using Remora.Discord.API.Objects;
using Remora.Discord.Commands.Results;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using Color = System.Drawing.Color;
using Image = SixLabors.ImageSharp.Image;
namespace DiscordBoostRoleBot
{
public class RoleCommands : CommandGroup
{
private readonly FeedbackService _feedbackService;
private readonly ICommandContext _context;
private static IDiscordRestGuildAPI _restGuildApi;
private readonly IDiscordRestUserAPI _restUserApi;
private static IDiscordRestChannelAPI _restChannelApi;
private static ILogger<RoleCommands> _log;
private readonly Database _database;
/// <summary>
/// Initializes a new instance of the <see cref="RoleCommands"/> class.
/// </summary>
/// <param name="feedbackService">The feedback service.</param>
/// <param name="context">The command context.</param>
/// <param name="restGuildApi">The DiscordRestGuildAPI to allow guild api access.</param>
/// <param name="log">The logger used</param>
/// <param name="restUserApi">Access to the User rest API</param>
/// <param name="restChannelApi">Access to the Channel rest API</param>
public RoleCommands(FeedbackService feedbackService, ICommandContext context, IDiscordRestGuildAPI restGuildApi, ILogger<RoleCommands> log, IDiscordRestUserAPI restUserApi, IDiscordRestChannelAPI restChannelApi, Database database)
{
_feedbackService = feedbackService;
_context = context;
_restGuildApi = restGuildApi;
_log = log;
_restUserApi = restUserApi;
_restChannelApi = restChannelApi;
_database = database;
}
public static Color GetColorFromString(string colorString) => ColorTranslator.FromHtml(colorString);
public static readonly Regex Base64Regex = new(@"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$");
public static async Task<Result<IGuildMember>> ExecutorHasPermissions(ICommandContext _context, params DiscordPermission[] permissions)
{
IGuildMember executorGuildMember;
switch (_context)
{
case InteractionContext interactionContext:
executorGuildMember = interactionContext.Interaction.Member.Value;
break;
case TextCommandContext messageContext:
{
Result<IGuildMember> guildMemberResult = await _restGuildApi.GetGuildMemberAsync(guildID: messageContext.GuildID.Value, userID: messageContext.Message.Author.Value.ID).ConfigureAwait(false);
if (!guildMemberResult.IsSuccess)
{
_log.LogWarning($"Error responding to message {messageContext.Message} because {guildMemberResult.Error}");
return Result<IGuildMember>.FromError(new InvalidOperationError("Make sure you are in a server"));
}
executorGuildMember = guildMemberResult.Entity;
break;
}
default:
_log.LogWarning("I don't know how you invoked this command");
return Result<IGuildMember>.FromError(new InvalidOperationError("I don't know how you invoked this command"));
}
if (!executorGuildMember.HasAllPermsAdminOrOwner(permissions))
{
return Result<IGuildMember>.FromError(new PermissionDeniedError($"You do not have the required permission{(permissions.Length != 1 ? (permissions.Length != 0 ? "s:" : "s") : ":")} {string.Join(", ", permissions)}"));
}
return Result<IGuildMember>.FromSuccess(executorGuildMember);
}
public async Task<Result<IGuildMember>> ExecutorHasPermissions(params DiscordPermission[] permissions) =>
await ExecutorHasPermissions(_context, permissions);
[Command("role-creator-add")]
[CommandType(ApplicationCommandType.ChatInput)]
[Description("Add a role that is allowed to make their own custom roles")]
public async Task<IResult> AddAllowedRoleMaker([Description("The Role to allow to make their own Custom Roles")] IRole roleToAdd)
{
Result<IGuildMember> permCheckResult = await ExecutorHasPermissions(DiscordPermission.ManageRoles);
if (!permCheckResult.IsSuccess)
{
Result<IReadOnlyList<IMessage>> errResponse = await _feedbackService.SendContextualErrorAsync(permCheckResult.Error.Message);
return errResponse.IsSuccess ?
Result.FromSuccess() :
Result.FromError(errResponse);
}
PartialGuild executionGuild = new(_context switch
{
InteractionContext interactionContext => interactionContext.Interaction.GuildID.Value,
TextCommandContext messageContext => messageContext.GuildID.Value,
_ => throw new ArgumentOutOfRangeException(nameof(_context)),
});
Result<IReadOnlyList<IMessage>> response;
var addRoleResult = await _database.AddAllowedRole(executionGuild.ID.Value, roleToAdd.ID).ConfigureAwait(false);
if (!addRoleResult.IsSuccess)
{
response = await _feedbackService.SendContextualInfoAsync(
$"Role {roleToAdd.Mention()} was unable to be added to the database, contact the developer");
return response.IsSuccess ? Result.FromSuccess() : Result.FromError(response);
}
response = await _feedbackService.SendContextualInfoAsync(
$"Role {roleToAdd.Mention()} is now allowed to make custom roles");
return response.IsSuccess ? Result.FromSuccess() : Result.FromError(response);
}
[Command("role-creator-remove")]
[CommandType(ApplicationCommandType.ChatInput)]
[Description("Remove a role that is allowed to make their own custom roles")]
public async Task<IResult> RemoveAllowedRoleMaker([Description("The Role to remove the ability to make their own Custom Roles")] IRole roleToRemove)
{
Result<IGuildMember> permCheckResult = await ExecutorHasPermissions(DiscordPermission.ManageRoles);
if (!permCheckResult.IsSuccess)
{
Result<IReadOnlyList<IMessage>> errResponse = await _feedbackService.SendContextualErrorAsync(permCheckResult.Error.Message);
return errResponse.IsSuccess ?
Result.FromSuccess() :
Result.FromError(errResponse);
}
PartialGuild executionGuild = new(_context switch
{
InteractionContext interactionContext => interactionContext.Interaction.GuildID.Value,
TextCommandContext messageContext => messageContext.GuildID.Value,
_ => throw new ArgumentOutOfRangeException(nameof(_context)),
});
Result<IReadOnlyList<IMessage>> response;
var removeWarning = "(Note: mods, role admins, and boosters are still allowed, use slash command permissions to ban users/roles)";
var numModified = await _database.RemoveAllowedRole(executionGuild.ID.Value, roleToRemove.ID).ConfigureAwait(false);
response = await _feedbackService.SendContextualInfoAsync(
$"Role {roleToRemove.Mention()} is now not allowed to make custom roles {removeWarning}");
return response.IsSuccess ? Result.FromSuccess() : Result.FromError(response);
}
[Command("role-creator-list")]
[CommandType(ApplicationCommandType.ChatInput)]
[Description("Lists roles allowed to make their own custom roles")]
public async Task<IResult> ListAllowedRolemaker()
{
Result<IReadOnlyList<IMessage>> response;
PartialGuild executionGuild = new(_context switch
{
InteractionContext interactionContext => interactionContext.Interaction.GuildID.Value,
TextCommandContext messageContext => messageContext.GuildID.Value,
_ => throw new ArgumentOutOfRangeException(nameof(_context)),
});
List<Snowflake> allowedRolesSnowflakes = await _database.GetAllowedRoles(executionGuild.ID.Value);
if (allowedRolesSnowflakes is not { Count: > 0 })
{
response = await _feedbackService.SendContextualInfoAsync(
$"No specific roles are setup to allow role creation, only mods, admins, and boosters");
return response.IsSuccess ? Result.FromSuccess() : Result.FromError(response);
}
string responseString =
$@"Current roles allowed to make custom roles:
{string.Join('\n', allowedRolesSnowflakes.Select(snowflake => snowflake.Role()))}
Note: All users with server role change permissions and boosters are allowed to make custom roles.";
response = await _feedbackService.SendContextualInfoAsync(responseString);
return response.IsSuccess ? Result.FromSuccess() : Result.FromError(response);
}
public string? EmoteToDiscordUrl(string emote)
{
Match regexMatch = AddReactionsToMediaArchiveMessageResponder.EmoteWithRequiredIdRegex.Match(emote);
return regexMatch.Success ? $"https://cdn.discordapp.com/emojis/{regexMatch.Groups["id"]}.{(regexMatch.Groups["animated"].Success ? "gif" : "png")}" : null;
}
[Command("make-role")]
[CommandType(ApplicationCommandType.ChatInput)]
[DiscordDefaultDMPermission(false)]
[Description("Make a new role, attach an image to add it to the role")]
public async Task<IResult> MakeNewRole([Description("Role Name")] string role_name,
[Description("Color in #XxXxXx format or common name, use black or #000000 to keep current color")] string color = "#000000",
[Description("The User to assign the role to")] IGuildMember? assign_to_member = null,
[Description("The image url to use for the icon")] string? image_url = null
)
{
IGuildMember executorGuildMember;
IPartialChannel executionChannel;
IPartialGuild executionGuild;
Result<IReadOnlyList<IMessage>> errResponse;
Result deleteResponse;
switch (_context)
{
case InteractionContext interactionContext:
executorGuildMember = interactionContext.Interaction.Member.Value;
executionGuild = new PartialGuild(interactionContext.Interaction.GuildID.Value);
Optional<IMessage> interactionMessage = interactionContext.Interaction.Message;
if (interactionMessage.HasValue)
{
IReadOnlyList<IAttachment> attachments = interactionMessage.Value.Attachments;
if (attachments[0].ContentType is { HasValue: true, Value: "image/jpeg" or "image/png" or "image/gif" })
{
image_url = attachments[0].Url;
}
}
executionChannel = interactionContext.Interaction.Channel.Value;
// Result<IReadOnlyList<IMessage>> errResponse = await _feedbackService.SendContextualErrorAsync("This can only be executed via slash command");
// return errResponse.IsSuccess
// ? Result.FromSuccess()
// : Result.FromError(errResponse);
break;
case TextCommandContext messageContext:
{
Optional<IUser> commandUser = messageContext.Message.Author;
executionChannel = new PartialChannel(messageContext.Message.ChannelID);
executionGuild = new PartialGuild(messageContext.GuildID.Value);
Result<IGuildMember> guildMemberResult = await _restGuildApi.GetGuildMemberAsync(guildID: messageContext.GuildID.Value, userID: commandUser.Value.ID).ConfigureAwait(false);
if (!guildMemberResult.IsSuccess)
{
_log.LogWarning($"Error responding to message {messageContext.Message.ID.Value} because {guildMemberResult.Error}");
errResponse = await _feedbackService.SendContextualErrorAsync("Make sure you are in a server").ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
executorGuildMember = guildMemberResult.Entity;
if (messageContext.Message.Attachments.HasValue && messageContext.Message.Attachments.Value.Count > 0)
{
IReadOnlyList<IAttachment> attachments = messageContext.Message.Attachments.Value;
if (attachments[0].ContentType == "image/jpeg" || attachments[0].ContentType == "image/png" ||
attachments[0].ContentType == "image/gif")
{
image_url = attachments[0].Url;
}
}
break;
}
default:
errResponse = await _feedbackService.SendContextualErrorAsync("I don't know how you invoked this command").ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
break;
}
if (!executorGuildMember.Permissions.HasValue)
{
Result<IGuildMember> getPermsResult = await Program.AddGuildMemberPermissions(executorGuildMember, executionGuild.ID.Value);
if (!getPermsResult.IsSuccess)
{
errResponse = await _feedbackService.SendContextualErrorAsync("Could not determine User's permission, please invoke via slash command", options: new FeedbackMessageOptions
{
MessageFlags = MessageFlags.Ephemeral
}).ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
assign_to_member ??= executorGuildMember;
//Run input checks
//If you are (not the user you're trying to assign to or are not premium) and you are not a mod/owner then deny you
if (!executorGuildMember.IsRoleModAdminOrOwner())
{
//Not a mod, check if assigning to self
if (executorGuildMember.User.Value.ID != assign_to_member.User.Value.ID)
{
errResponse = await _feedbackService.SendContextualErrorAsync(
$"Non-mods can only assign roles to themselves").ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
//Not mod and assigning to "assign_to_member", check if boosting
if (assign_to_member.IsNotBoosting())
{
//Not Boosting, check if has allowed role
// await using Database.DiscordDbContext database = new();
List<Snowflake> allowedRolesSnowflakes = await _database.GetAllowedRoles(executionGuild.ID.Value).ConfigureAwait(false);
bool hasAllowedRole = false;
if (allowedRolesSnowflakes != null)
{
if (allowedRolesSnowflakes.Any(allowedRoleSnowflake => assign_to_member.Roles.Contains(allowedRoleSnowflake)))
{
hasAllowedRole = true;
}
}
if (!hasAllowedRole)
{
errResponse = await _feedbackService.SendContextualErrorAsync(
$"Non-boosters need an approved role to be allowed to use this bot").ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
}
//Check if you are not a mod and have more than one role
if (!executorGuildMember.IsRoleModAdminOrOwner() && 0 < await _database.GetRoleCount(executionGuild.ID.Value, assign_to_member.User.Value.ID).ConfigureAwait(false))
{
// TODO: Debug, doesn't seem to work
return await SendErrorReply("You are only allowed one booster role on this server").ConfigureAwait(false);
}
//Declare necessary variables
Result<IReadOnlyList<IMessage>> reply;
//Check arguments and initialize variables
//Prepare Color
Color roleColor;
try
{
roleColor = GetColorFromString(color);
} catch (ArgumentException e)
{
_log.LogWarning("Color not found {color} because {e}", color, e);
errResponse = await _feedbackService
.SendContextualErrorAsync(
$"Invalid color {color}, must be in the format #XxXxXx or a common color name, check your spelling")
.ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
} catch (FormatException e) {
_log.LogWarning("Color not found {color} because {e}", color, e);
errResponse = await _feedbackService
.SendContextualErrorAsync(
$"Invalid color {color}, must be in the format #XxXxXx or a common color name, check your spelling (e.g. make sure 0s aren't Os, hex codes are only 0-9 and a-f letters)")
.ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
} catch (Exception e)
{
_log.LogError(e, "Error getting color from string {color}: {reason}", color, e.Message);
errResponse = await _feedbackService.SendContextualErrorAsync($"Error getting color from string {color}").ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
if (!executionGuild.ID.HasValue)
{
errResponse = await _feedbackService.SendContextualErrorAsync("You are not sending this command in a guild, somehow your permissions are broken", ct: this.CancellationToken).ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
//Prepare server
Snowflake requestServer = executionGuild.ID.Value;
//Prepare Image
MemoryStream? iconStream = null;
IImageFormat? iconFormat = null;
if (image_url is not null)
{
if (AddReactionsToMediaArchiveMessageResponder.EmoteWithRequiredIdRegex.IsMatch(image_url))
{
image_url = EmoteToDiscordUrl(image_url);
} else if(AddReactionsToMediaArchiveMessageResponder.EmoteWithoutRequiredIdRegex.IsMatch(image_url))
{
errResponse = await _feedbackService.SendContextualErrorAsync("Please Choose Emoji from selection menu, simply typing the emoji make getting the image impossible");
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(errResponse);
}
Result<(MemoryStream?, IImageFormat?)> imageToStreamResult = await ImageUrlToBase64(imageUrl: image_url).ConfigureAwait(false);
if (!imageToStreamResult.IsSuccess)
{
errResponse = await _feedbackService.SendContextualErrorAsync(imageToStreamResult.Error.Message);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(errResponse);
}
(iconStream, iconFormat) = imageToStreamResult.Entity;
}
Result<IRole> roleResult = await _restGuildApi.CreateGuildRoleAsync(guildID: requestServer, name: role_name, colour: roleColor, icon: iconStream ?? default,
isHoisted: false, isMentionable: true, ct: this.CancellationToken).ConfigureAwait(false);
if (!roleResult.IsSuccess)
{
_log.LogError($"Could not create role for {assign_to_member.User.Value.Mention()} because {roleResult.Error}");
errResponse = await _feedbackService.SendContextualErrorAsync(
$"Could not create role for {assign_to_member.User.Value.Mention()}, make sure the bot's permissions are set correctly. Error = {roleResult.Error.Message}", ct: this.CancellationToken).ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
IRole role = roleResult.Entity;
bool addedToDb = await _database.AddRoleToDatabase(executionGuild.ID.Value, assign_to_member.User.Value.ID,
role.ID, color: color, name: role.Name, imageUrl: image_url, role.Icon.HasValue ? role.Icon.Value?.Value : null).ConfigureAwait(false);
if (!addedToDb)
{
_log.LogError($"Could not add role to database");
errResponse = await _feedbackService.SendContextualErrorAsync(
"Failed to track role, try again later", ct: this.CancellationToken).ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
Result roleApplyResult = await _restGuildApi.AddGuildMemberRoleAsync(guildID: executionGuild.ID.Value,
userID: assign_to_member.User.Value.ID, roleID: role.ID,
"User is boosting, role request via BoostRoleManager bot", ct: this.CancellationToken).ConfigureAwait(false);
if (!roleApplyResult.IsSuccess)
{
_log.LogError($"Could not make role because {roleApplyResult.Error}");
errResponse = await _feedbackService.SendContextualErrorAsync(
"Could not make role, make sure the bot's permissions are set correctly", ct: this.CancellationToken).ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
var msg = string.Empty;
Result<IReadOnlyList<IRole>> getRolesResult = await _restGuildApi.GetGuildRolesAsync(executionGuild.ID.Value, ct: this.CancellationToken).ConfigureAwait(false);
if (getRolesResult.IsSuccess)
{
IReadOnlyList<IRole> guildRoles = getRolesResult.Entity;
Result<IUser> currentBotUserResult =
await _restUserApi.GetCurrentUserAsync(ct: this.CancellationToken).ConfigureAwait(false);
if (currentBotUserResult.IsSuccess)
{
IUser currentBotUser = currentBotUserResult.Entity;
Result<IGuildMember> currentBotMemberResult =
await _restGuildApi.GetGuildMemberAsync(executionGuild.ID.Value, currentBotUser.ID,
this.CancellationToken).ConfigureAwait(false);
if (currentBotMemberResult.IsSuccess)
{
IGuildMember currentBotMember = currentBotMemberResult.Entity;
IEnumerable<IRole> botRoles = guildRoles.Where(gr => currentBotMember.Roles.Contains(gr.ID));
IRole? maxPosRole = botRoles.MaxBy(br => br.Position);
_log.LogDebug("Bot's highest role is {role_name}: {roleId}", maxPosRole.Name, maxPosRole.ID);
int maxPos = maxPosRole.Position;
Result<IReadOnlyList<IRole>> roleMovePositionResult = await _restGuildApi
.ModifyGuildRolePositionsAsync(executionGuild.ID.Value,
new (Snowflake RoleID, Optional<int?> Position)[] { (role.ID, maxPos) }).ConfigureAwait(false);
if (!roleMovePositionResult.IsSuccess)
{
_log.LogWarning("Could not move the role because {error}", roleMovePositionResult.Error);
errResponse = await _feedbackService
.SendContextualErrorAsync(
"Could not move role in list, check the bot's permissions and try again",
ct: this.CancellationToken).ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
IRole thisRoleData = roleMovePositionResult.Entity.Single(r => r.ID == role.ID);
_log.LogDebug("Role {role_name} moved to position {position}", thisRoleData.Name, thisRoleData.Position);
}
else
{
_log.LogWarning("Could not get bot member because {error}", currentBotMemberResult.Error);
msg += "Could not move role in list, check the bot's permissions (and role position) and try again or move the role manually\n";
}
}
else
{
_log.LogWarning("Could not get bot user because {error}", currentBotUserResult.Error);
msg += "Could not move role in list, check the bot's permissions (and role position) and try again or move the role manually\n";
}
}
else
{
_log.LogWarning("Could not move the role because {error}", getRolesResult.Error);
msg += "Could not move role in list, check the bot's permissions (and role position) and try again or move the role manually\n";
}
msg += $"Made Role {role.Mention()} and assigned to {assign_to_member.Mention()}\n";
FeedbackMessage message = new(msg.TrimEnd(), Colour: role.Colour);
reply = await _feedbackService.SendContextualMessageAsync(message: message, ct: this.CancellationToken).ConfigureAwait(false);
if (true)
{
return reply.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: reply);
}
}
//TODO: Convert to Result<(MemoryStream?, IImageFormat?)> or something similar
internal static async Task<Result<(MemoryStream?, IImageFormat?)>> ImageUrlToBase64(string imageUrl, CancellationToken ct = new())
{
MemoryStream? iconStream = null;
//if this isn't the base64, we overwrite it anyway
string dataUri = imageUrl;
IImageFormat? imageFormat = null;
byte[]? imgData;
if (Base64Regex.IsMatch(input: dataUri))
{
return Result<(MemoryStream?, IImageFormat?)>.FromError(new ArgumentInvalidError("Image Url", "This is not a url, give an image URL"));
}
Result<IReadOnlyList<IMessage>> errResponse;
try
{
imgData = await Program.httpClient
.GetByteArrayAsync(requestUri: imageUrl, cancellationToken: ct)
.ConfigureAwait(false);
MemoryStream imageStream = new(imgData);
imageFormat = await Image.DetectFormatAsync(imageStream, ct);
if (imageFormat is not JpegFormat && imageFormat is not PngFormat && imageFormat is not GifFormat)
{
try
{
Image? imgToConvert = Image.Load(imgData);
#if FORCE_IMAGES_SQUARE
if (imgToConvert.Height != imgToConvert.Width)
{
//Seemingly not needed, discord pads non-square icons
return Result<(MemoryStream?, IImageFormat?)>.FromError(
new ArgumentInvalidError("Image Url", "Image is not square"));
}
#endif
if (imgToConvert is null)
{
Result<(MemoryStream?, IImageFormat?)> imgConvFailResult = Result<(MemoryStream?, IImageFormat?)>.FromError(new ArgumentInvalidError("Image Url", $"Format {imageFormat.Name} is not allowed please convert to JPG or PNG"));
return imgConvFailResult;
}
iconStream = new MemoryStream();
await imgToConvert.SaveAsync(iconStream, new PngEncoder(), ct).ConfigureAwait(false);
iconStream.Position = 0;
}
catch
{
return Result<(MemoryStream?, IImageFormat?)>.FromError(new ArgumentInvalidError("Image Url", $"Format {imageFormat.Name} is not allowed please convert to JPG or PNG"));
}
}
else
{
iconStream = new MemoryStream(imgData);
}
// dataUri = $"data:{imageFormat.DefaultMimeType};base64,{Convert.ToBase64String(inArray: imgData)}";
// _log.LogInformation("Image is {dataUri}", dataUri);
}
catch (Exception e)
{
Program.log.LogWarning(e.ToString());
return Result<(MemoryStream?, IImageFormat?)>.FromError(new ArgumentInvalidError("Image Url", $"{imageUrl} is an invalid url, make sure that you can load this in a browser and that it is a link directly to an image (i.e. not an image on a website)"));
}
const long maxImageSize = 256_000;
if (iconStream.Length > maxImageSize)
{
Program.log.LogDebug("Image too large {length} > {max}{conv}", iconStream.Length, maxImageSize, imageFormat is not JpegFormat && imageFormat is not PngFormat && imageFormat is not GifFormat ? " after conversion, convert to a jpg or png before submitting" : "");
return Result<(MemoryStream?, IImageFormat?)>.FromError(new ArgumentInvalidError("Image Url", $"{imageUrl} is larger than 256KB, please resize it"));
}
return Result<(MemoryStream? iconStream, IImageFormat? imageFormat)>.FromSuccess((iconStream, imageFormat));
}
[Command("untrack-role")]
[Description("Stops the bot from managing this role")]
public async Task<IResult> UntrackRole([Description("The role to stop tracking")] IRole role, [Description("Whether the role should be deleted")] bool delete_role = true)
{
Result<IReadOnlyList<IMessage>> replyResult;
IGuildMember executingMember;
PartialGuild executionGuild;
Result<IReadOnlyList<IMessage>> errResponse;
switch (_context)
{
case InteractionContext interactionContext:
executionGuild = new PartialGuild(interactionContext.Interaction.GuildID);
executingMember = interactionContext.Interaction.Member.Value;
break;
case TextCommandContext messageContext:
{
executionGuild = new PartialGuild(messageContext.GuildID);
Result<IGuildMember> guildMemberResult = await _restGuildApi.GetGuildMemberAsync(guildID: messageContext.GuildID.Value, userID: messageContext.Message.Author.Value.ID).ConfigureAwait(false);
if (!guildMemberResult.IsSuccess)
{
_log.LogWarning($"Error responding to message {messageContext.Message.ID} because {guildMemberResult.Error}");
errResponse = await _feedbackService.SendContextualErrorAsync("Make sure you are in a server").ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
executingMember = guildMemberResult.Entity;
break;
}
default:
errResponse = await _feedbackService.SendContextualErrorAsync("I don't know how you invoked this command").ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
if (!executingMember.Permissions.HasValue)
{
Result<IGuildMember> getPermsResult = await Program.AddGuildMemberPermissions(executingMember, executionGuild.ID.Value);
if (!getPermsResult.IsSuccess)
{
errResponse = await _feedbackService.SendContextualErrorAsync("Could not determine User's permission, please evoke via slash command", options: new FeedbackMessageOptions
{
MessageFlags = MessageFlags.Ephemeral
}).ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
if (!delete_role && !executingMember.IsRoleModAdminOrOwner())
{
return await SendErrorReply("Only mods are allowed to untrack a role without deleting it").ConfigureAwait(false);
}
//Run input checks
//If you are (not the user you're trying to assign to or are not premium) and you are not a mod/owner then deny you
List<Database.RoleData> rolesCreated = await _database.GetRoles(executionGuild.ID.Value, roleId: role.ID).ConfigureAwait(false);
Database.RoleData? roleCreated = rolesCreated.FirstOrDefault();
if (roleCreated is null)
{
replyResult = await _feedbackService.SendContextualErrorAsync(
$"Role {role.Mention()} not found in database, make sure it was created using the bot or added using /track-role",
ct: this.CancellationToken).ConfigureAwait(false);
return !replyResult.IsSuccess
? Result.FromError(replyResult)
: Result.FromSuccess();
}
if (roleCreated.RoleUserId != executingMember.User.Value.ID.Value && !executingMember.IsRoleModAdminOrOwner())
{
return await SendErrorReply("You do not have permission to untrack this role, you either you did not create it or do not have it and you don't have the mod permissions to manage roles").ConfigureAwait(false);
}
var ownerId = roleCreated.RoleUserId;
var result = await _database.RemoveRoleFromDatabase(executionGuild.ID.Value, role).ConfigureAwait(false);
string replyMessageText = "";
switch (result)
{
case -1:
{
replyMessageText += $"Role {role.Mention()} not found in database, make sure it was created using the bot or added using /track-role";
replyResult = await _feedbackService.SendContextualErrorAsync(
replyMessageText,
ct: this.CancellationToken).ConfigureAwait(false);
return !replyResult.IsSuccess
? Result.FromError(replyResult)
: Result.FromSuccess();
}
case 0:
{
replyMessageText += $"Role {role.Mention()} could not be removed from database";
_log.LogWarning(replyMessageText);
replyResult = await _feedbackService.SendContextualErrorAsync(
$"Role {role.Mention()} could not be removed from database, try again later",
ct: this.CancellationToken).ConfigureAwait(false);
return !replyResult.IsSuccess
? Result.FromError(replyResult)
: Result.FromSuccess();
}
case 1:
{
replyMessageText += $"Role {role.Mention()} untracked successfully";
replyResult = await _feedbackService.SendContextualSuccessAsync(
replyMessageText,
ct: this.CancellationToken).ConfigureAwait(false);
if (!replyResult.IsSuccess)
return Result.FromError(replyResult);
if (!delete_role)
{
// Role wont be deleted, remove from user
Result removeRoleResult = await _restGuildApi.RemoveGuildMemberRoleAsync(executionGuild.ID.Value, ownerId, role.ID, reason: "Removing role to prep for deletion", ct: this.CancellationToken).ConfigureAwait(false);
if (!removeRoleResult.IsSuccess)
{
_log.LogError("Could not remove role {role} : {roleMention} from member {memberId} because {error}",
role.Name, role.Mention(), ownerId.User(), removeRoleResult.Error);
}
return Result.FromSuccess();
}
Result deleteResult = await _restGuildApi.DeleteGuildRoleAsync(executionGuild.ID.Value, role.ID, reason: $"User requested deletion", ct: this.CancellationToken).ConfigureAwait(false);
if (!deleteResult.IsSuccess)
{
_log.LogError("Could not remove role {role} : {roleMention} because {error}", role.Name,
role.Mention(), deleteResult.Error);
return await SendErrorReply($"Could not remove role {role.Mention()}, remove it manually").ConfigureAwait(false);
}
//TODO: Add editing reply message
replyMessageText = $"Deleted role {role.Name} : {role.Mention()} from server";
// await _restChannelApi.DeleteMessageAsync(_context.ChannelID, replyResult.Entity.First().ID);
replyResult =
await _feedbackService.SendContextualSuccessAsync(replyMessageText).ConfigureAwait(false);
return replyResult.IsSuccess
? Result.FromSuccess()
: Result.FromError(replyResult);
}
default:
_log.LogCritical($"Role {role.Mention()} removed multiple times from the database, somehow, oh no");
replyResult = await _feedbackService.SendContextualErrorAsync(
$"Role {role.Mention()} removed multiple times from the database, somehow, oh no",
ct: this.CancellationToken).ConfigureAwait(false);
return !replyResult.IsSuccess
? Result.FromError(replyResult)
: Result.FromSuccess();
}
}
[Command("track-role")]
[Description("Track an existing role with the bot")]
public async Task<IResult> TrackRole([Description("The role to track")] IRole role,
[Description("If this role has no members, assign it to this user")] IUser? new_owner = null)
{
if ((await _database.GetRoles(roleId: role.ID)) is not { Count: 0 })
{
return await SendErrorReply("This role is already being tracked").ConfigureAwait(false);
}
IGuildMember executorGuildMember;
PartialGuild executionGuild;
Result<IReadOnlyList<IMessage>> errResponse;
switch (_context)
{
case InteractionContext interactionContext:
executorGuildMember = interactionContext.Interaction.Member.Value;
executionGuild = new(interactionContext.Interaction.GuildID);
break;
case TextCommandContext messageContext:
{
executionGuild = new(messageContext.GuildID);
Result<IGuildMember> guildMemberResult = await _restGuildApi.GetGuildMemberAsync(guildID: messageContext.GuildID.Value, userID: messageContext.Message.Author.Value.ID).ConfigureAwait(false);
if (!guildMemberResult.IsSuccess)
{
_log.LogWarning($"Error responding to message {messageContext.Message.ID} because {guildMemberResult.Error}");
errResponse = await _feedbackService.SendContextualErrorAsync("Make sure you are in a server").ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
executorGuildMember = guildMemberResult.Entity;
break;
}
default:
errResponse = await _feedbackService.SendContextualErrorAsync("I don't know how you invoked this command").ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
if (!executorGuildMember.Permissions.HasValue)
{
Result<IGuildMember> getPermsResult = await Program.AddGuildMemberPermissions(executorGuildMember, executionGuild.ID.Value);
if (!getPermsResult.IsSuccess)
{
errResponse = await _feedbackService.SendContextualErrorAsync("Could not determine User's permission, please evoke via slash command", options: new FeedbackMessageOptions
{
MessageFlags = MessageFlags.Ephemeral
}).ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
//If you are not a mod/owner then deny you
//Boosters are not allowed this perm due to the off chance 1 boosting member claims a (non-booster) role where they
if (!executorGuildMember.IsRoleModAdminOrOwner())
{
if (await _database.GetRoleCount(executionGuild.ID.Value, executorGuildMember.User.Value.ID).ConfigureAwait(false) > 0 && !executorGuildMember.IsRoleModAdminOrOwner())
{
return await SendErrorReply("You are only allowed one booster role on this server").ConfigureAwait(false);
}
errResponse = await _feedbackService.SendContextualErrorAsync(
$"You do not have the required permissions to create this role for {executorGuildMember.Mention()}, you don't have ManageRoles mod permissions").ConfigureAwait(false);
return !errResponse.IsSuccess
? Result.FromError(result: errResponse)
: Result.FromSuccess();
}
//Check role meets criteria to be added
List<IGuildMember> membersList = new();
Result<List <IGuildMember>> membersListResult;
Optional<Snowflake> lastGuildMemberSnowflake = default;
while (true)
{
Result<IReadOnlyList<IGuildMember>> getMembersResult =
await _restGuildApi.ListGuildMembersAsync(executionGuild.ID.Value, limit: 1000, after: lastGuildMemberSnowflake).ConfigureAwait(false);
if (!getMembersResult.IsSuccess)
{
return await SendErrorReply(
"Could not find how many have this role, invalid. Try again or recreate this role using the bot if necessary.").ConfigureAwait(false);
}
if (getMembersResult.Entity.Any())
{
membersList.AddRange(getMembersResult.Entity.Where(gm => gm.Roles.Contains(role.ID)));
lastGuildMemberSnowflake = new Optional<Snowflake>(getMembersResult.Entity.Last().User.Value.ID);
}
else
{
break;
}
}
Snowflake ownerMemberSnowflake = new(0);
switch (membersList.Count)
{
//TODO: handle when new_owner specified but different member found with role
case > 1:
return await SendErrorReply("More than 1 member has this role, cannot add to the bot").ConfigureAwait(false);
case 1:
ownerMemberSnowflake = membersList.First().User.Value.ID;
break;
case 0:
if (new_owner is null)
{
return await SendErrorReply("No user has this role; Add a user or specify one in this command before tracking it").ConfigureAwait(false);
}
ownerMemberSnowflake = new_owner.ID;
Result addRoleResult = await _restGuildApi.AddGuildMemberRoleAsync(executionGuild.ID.Value,
ownerMemberSnowflake, role.ID,
reason: $"User added role when starting tracking").ConfigureAwait(false);
if (!addRoleResult.IsSuccess)
{
return await SendErrorReply($"No user has this role and the bot failed to add {new_owner.Mention()}").ConfigureAwait(false);
}
break;
}
Database.RoleData roleData = new()
{
Color = ColorTranslator.ToHtml(role.Colour),
Name = role.Name,
RoleId = role.ID,
ServerId = executionGuild.ID.Value,
RoleUserId = ownerMemberSnowflake,
};
await _database.AddRoleToDatabase(roleData);
return await SendSuccessReply($"Successfully started tracking {role.Mention()}, you can now modify it via bot commands").ConfigureAwait(false);
}
private const int DeleteOwnerMessageDelay = 1000;
[Command("modify-role")]
[Description("Modify a role's properties")]
public async Task<IResult> ModifyRole([Description("The role to change")] IRole role,
[Description("The new name to give it")]string? new_name = null,
[Description("Color in #XxXxXx format, leave blank or #000000 to keep current color")] string? new_color_string = null,
[Description("The image url to use for the icon")] string? new_image = null
)
{
if (new_name == null && new_color_string == null && new_image == null)
{
return await SendErrorReply("You must specify at least one property of the role to change").ConfigureAwait(false);
}
//Check Server Member has permissions to use command
IGuildMember executingMember;
PartialGuild executionGuild;
Result<IReadOnlyList<IMessage>> errResponse;
Result deleteResponse;
switch (_context)
{
case InteractionContext interactionContext:
executionGuild = new(interactionContext.Interaction.GuildID);
executingMember = interactionContext.Interaction.Member.Value;
break;
case TextCommandContext messageContext:
executionGuild = new PartialGuild(messageContext.GuildID);
Result<IGuildMember> guildMemberResult = await _restGuildApi.GetGuildMemberAsync(guildID: messageContext.GuildID.Value, userID: messageContext.Message.Author.Value.ID).ConfigureAwait(false);
if (!guildMemberResult.IsSuccess)
{
_log.LogWarning($"Error responding to message {messageContext.Message.Author.Value} because {guildMemberResult.Error}");
errResponse = await _feedbackService.SendContextualErrorAsync("Make sure you are in a server").ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
executingMember = guildMemberResult.Entity;
break;
default:
errResponse = await _feedbackService.SendContextualErrorAsync("I don't know how you invoked this command").ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
if (!executingMember.Permissions.HasValue)
{
Result<IGuildMember> getPermsResult = await Program.AddGuildMemberPermissions(executingMember, executionGuild.ID.Value);
if (!getPermsResult.IsSuccess)
{
errResponse = await _feedbackService.SendContextualErrorAsync("Could not determine User's permission, please evoke via slash command", options: new FeedbackMessageOptions
{
MessageFlags = MessageFlags.Ephemeral
}).ConfigureAwait(false);
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
List<Database.RoleData> roleDatas = await _database.GetRoles(guildId: executionGuild.ID.Value, roleId: role.ID).ConfigureAwait(false);
Database.RoleData? roleData = roleDatas.FirstOrDefault();
if (roleData == null)
{
errResponse = await _feedbackService.SendContextualErrorAsync("Role not found in database, check that this command is tracking it").ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
// If they don't have ManageRoles perm and if they either did not create the role or do not have the role, deny access
if (roleData.RoleUserId != executingMember.User.Value.ID.Value && !executingMember.IsRoleModAdminOrOwner())
{
errResponse = await _feedbackService.SendContextualErrorAsync("You do not have permission to modify this role, you either you did not create it or do not have it and you don't have the mod permissions to manage roles").ConfigureAwait(false);
if (true)
{
return errResponse.IsSuccess
? Result.FromSuccess()
: Result.FromError(result: errResponse);
}
}
//Handle Name Change
if (new_name is not null)
{
roleData.Name = new_name;
}
//Handle Color Change
Color? newRoleColor = null;
if (new_color_string is not null)
{
try
{
newRoleColor = GetColorFromString(new_color_string);
roleData.Color = ColorTranslator.ToHtml(newRoleColor.Value);
}
catch (ArgumentException e)
{
_log.LogWarning("Color not found {color} because {e}", new_color_string, e);
errResponse = await _feedbackService.SendContextualErrorAsync($"Invalid color {new_color_string}, must be in the format #XxXxXx or a common color name, check your spelling").ConfigureAwait(false);
if (true)
{
return !errResponse.IsSuccess
? Result.FromError(result: errResponse)
: Result.FromSuccess();
}
}
}
//Handle Image Change
IImageFormat? newIconFormat = null;
Result<IRole> modifyRoleResult;
if (new_image is null)
{
modifyRoleResult = await _restGuildApi.ModifyGuildRoleAsync(executionGuild.ID.Value, role.ID,
new_name ?? default(Optional<string?>),
color: newRoleColor ?? default(Optional<Color?>),
reason: $"Member requested to modify role").ConfigureAwait(false);
roleData.ImageHash = null;
}
else if (IsUnicodeEmoji(new_image))
{
modifyRoleResult = await _restGuildApi.ModifyGuildRoleAsync(executionGuild.ID.Value, role.ID,
new_name ?? default(Optional<string?>),