aboutsummaryrefslogtreecommitdiff
path: root/Handlers/DiscordHandler.cs
blob: 7701a3d15a243b221ae03bcffce3fdd2daf38983 (plain)
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
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.RegularExpressions;
using Discord;
using Discord.Rest;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using PagerParser.Handlers;

namespace PagerParser {
    public partial class PagerContext {
        public DbSet<DiscordAlertChannel>      DiscordAlertChannels      { get; set; }
        public DbSet<DiscordAlertSubscription> DiscordAlertSubscriptions { get; set; }
        public DbSet<DiscordAlertMessage>      DiscordAlertMessages      { get; set; }
    }
}

namespace PagerParser.Handlers {
    [PagerHandler]
    internal class DiscordHandler : IPagerHandler {
        // TODO: consolidate this with the map used by TTS
        private readonly Dictionary<string, string> IncidentTypes = new() {
            { "ALAR", "FIRE ALARM"        },
            { "G&S",  "GRASS & SCRUB"     },
            { "HIAR", "HIGH-ANGLE RESCUE" },
            { "INCI", "INCIDENT"          },
            { "NOST", "NON-STRUCTURE"     },
            { "RESC", "RESCUE"            },
            { "STRU", "STRUCTURE"         }
        };

        private readonly CommandBuilder[] CommandBuilders;

        private DiscordSocketClient discordClient;

        private Dictionary<int, DateTime> recentMessages = new();

        private string botToken;

        private ILogger          logger;
        private IServiceProvider serviceProvider;

        public DiscordHandler() {
            // Initialize the command builders here so that instance
            // methods may be used for command handling.
            CommandBuilders = [
                new CommandBuilder() {
                    Name           = "get-channel",
                    Description    = "Get the channel to which alerts will be sent",
                    ContextTypes   = [ InteractionContextType.Guild ],
                    CommandHandler = OnGetChannelCommand,
                },
                new CommandBuilder() {
                    Name           = "set-channel",
                    Description    = "Set the channel to which alerts will be sent",
                    ContextTypes   = [ InteractionContextType.Guild ],
                    CommandHandler = OnSetChannelCommand,
                    Options        = [
                        new() {
                            Name        = "channel",
                            Description = "Channel to which alerts will be sent",
                            Type        = ApplicationCommandOptionType.Channel,
                            IsRequired  = true
                        },
                        new() {
                            Name        = "all-messages",
                            Description = "Send messages even if nobody is subcribed (defaults to 'False')",
                            Type        = ApplicationCommandOptionType.Boolean,
                        }
                    ]
                },
                new CommandBuilder() {
                    Name           = "remove-channel",
                    Description    = "Reset the configured alert channel, effectively disabling alerts for this server",
                    CommandHandler = OnRemoveChannelCommand
                },
                new CommandBuilder() {
                    Name           = "subscribe",
                    Description    = "Subscribe a user/role to alerts for the specified brigade/appliance",
                    ContextTypes   = [ InteractionContextType.Guild ],
                    CommandHandler = OnSubscribeChannelCommand,
                    Options        = [
                        new() {
                            Name        = "mention",
                            Description = "User/role to subscribe",
                            Type        = ApplicationCommandOptionType.Mentionable,
                            IsRequired  = true
                        },
                        new() {
                            Name        = "brigade",
                            Description = "Paged brigade/appliance to match (e.g. BERW, FS88, etc)",
                            Type        = ApplicationCommandOptionType.String,
                            IsRequired  = true
                        }
                    ]
                },
                new CommandBuilder() {
                    Name           = "unsubscribe",
                    Description    = "Unsubscribe a user/role from alerts for the specified brigade/appliance",
                    ContextTypes   = [ InteractionContextType.Guild ],
                    CommandHandler = OnUnsubscribeChannelCommand,
                    Options        = [
                        new() {
                            Name        = "mention",
                            Description = "User/role to unsubscribe",
                            Type        = ApplicationCommandOptionType.Mentionable,
                            IsRequired  = true
                        },
                        new() {
                            Name        = "brigade",
                            Description = "Paged brigade/appliance to match (e.g. BERW, FS88, etc)",
                            Type        = ApplicationCommandOptionType.String,
                            IsRequired  = true
                        }
                    ]
                },
                new CommandBuilder() {
                    Name           = "list-subscriptions",
                    Description    = "List the brigades/appliances whose pager messages the user/role is subscribed to",
                    ContextTypes   = [ InteractionContextType.Guild ],
                    CommandHandler = OnListSubscriptionsCommand,
                    Options        = [
                        new() {
                            Name        = "mention",
                            Description = "User/role whose subscriptions will be listed (defaults to the current user)",
                            Type        = ApplicationCommandOptionType.Mentionable
                        }
                    ]
                }
            ];
        }

        public async Task HandleMessageAsync(PagerMessage message, ParsedPagerMessage? pm) {
            if(pm is null)
                return;

            // Calculate a hash to eliminate duplicate messages
            var hash = (
                pm.AssignmentArea,
                pm.JobType,
                pm.AlertLevel,
                pm.Description,
                pm.FireGroundChannel,
                pm.FirecomJobNo).GetHashCode();

            // Prune the hash list
            recentMessages
                .Where(kv => DateTime.Now - kv.Value > TimeSpan.FromMinutes(2))
                .Select(kv => kv.Key)
                .ToList()
                .ForEach(h => recentMessages.Remove(h));

            // Ignore this message if we've seen a similar one recently
            if(recentMessages.Keys.Contains(hash))
                return;

            // Record the hash of this message for future deduplication
            recentMessages[hash] = DateTime.Now;

            // Get a simplified list of paged services
            var pagedServices = pm.PagedServices
                .Select(ps => Regex.Replace(ps, "^C([A-Z]{4})$", "$1"))
                .Select(ps => Regex.Replace(ps, "^[A-Z]*([0-9]{2})[A-Z]*", "FS$1"))
                .Order()
                .Distinct();

            // Translate the job type to a more friendly string
            string mapType = PagerMessageParserService.MapTypeMap
                .FirstOrDefault(kv => kv.Value == pm.MapType).Key;
            IncidentTypes.TryGetValue(pm.JobType, out var incidentType);

            // Compose a base message to be posted to each configured webhook
            string[] messageComponents = [
                Color(AnsiColor.Red, "ALERT"),
                Color(pm.AlertLevel == AlertLevel.Code1 ? AnsiColor.Red : AnsiColor.White, $"CODE {(int) pm.AlertLevel}"),
                pm.AssignmentArea,
                Color(AnsiColor.Cyan, incidentType ?? pm.JobType),
                pm.Description,
                Color(AnsiColor.Blue, $"{mapType} {pm.MapNo} {pm.MapGrid} ({pm.GridReference})"),
                Color(AnsiColor.Cyan, pm.Note ?? ""),
                pm.FireGroundChannel is null ? "" : Color(AnsiColor.Yellow, $"FGD{pm.FireGroundChannel}"),
                Color(AnsiColor.Magenta, $"F{pm.FirecomJobNo}")
            ];

            string baseMessage =
                $"```ansi\n{string.Join(' ', messageComponents.Where(x => !string.IsNullOrEmpty(x)))}\n```";

            using var scope = serviceProvider.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService<PagerContext>();

            foreach(var guild in discordClient.Guilds) {
                // Check that a notification channel is assigned for this guild,
                // otherwise, skip it.
                var alertChannel = db.DiscordAlertChannels
                    .Where(ac => ac.GuildId == guild.Id)
                    .FirstOrDefault();
                if(alertChannel is null)
                    continue;

                // Get a list of alert groups matching the page we've just received
                var subscriptions = db.DiscordAlertSubscriptions
                    .Where(s => s.GuildId == guild.Id)
                    .Where(s => pagedServices.Contains(s.PageDestination))
                    .ToArray();

                // Don't post the message to the server if nobody has subscribed
                // and this alert channel is configured for alerts to only be
                // posted when they mention a specific user or role.
                if(subscriptions.Count() == 0 && alertChannel.RequireMention)
                    continue;

                // Figure out which roles and users we need to @ mention
                // and generate appropriate Discord mention strings
                var roleMentions = subscriptions
                    .Where(s => s.PrincipalType == DiscordPrincipalType.Role)
                    .Distinct()
                    .Select(s => MentionUtils.MentionRole(s.PrincipalId));

                var userMentions = subscriptions
                    .Where(s => s.PrincipalType == DiscordPrincipalType.User)
                    .Distinct()
                    .Select(s => MentionUtils.MentionUser(s.PrincipalId));

                var mentions = string.Join(' ', roleMentions.Concat(userMentions));

                // Generate a list of paged services to be highlighted.
                // Services are highlighted if they exist in one of the
                // pre-configured alert groups and have therefore caused
                // a role to be mentioned.
                var hl = subscriptions
                    .Select(s => s.PageDestination)
                    .Distinct()
                    .ToArray();

                // Cleanup the list of paged services and generate
                // text to be displayed
                var pagedServicesText = string.Join(' ', pagedServices
                    .Select(ps => hl.Contains(ps) ? $"***{ps}***" : $"*{ps}*"));

                // Generate a message tailored to the
                // specific webhook we're posting to
                string discordMessage =
                    $"{(string.IsNullOrEmpty(mentions) ? "" : mentions + '\n')}" +
                    baseMessage +
                    $"\nPaged Services: {pagedServicesText}";

                // Actually post the message
                RestUserMessage messageResult;
                try {
                    messageResult = await guild
                        .GetTextChannel(alertChannel.ChannelId)
                        .SendMessageAsync(discordMessage);
                } catch(Exception e) {
                    logger.LogError(
                        e,
                        "Error sending Discord message");
                    return;
                }

                // Create a record linking the pager message in the database to the Discord
                // message we've just posted so that the Discord message may be amended later
                // if so required.
                var messageRecord = new DiscordAlertMessage() {
                    DiscordMessageId   = messageResult.Id,
                    ParsedPagerMessage = pm
                };

                // Commit the record to the database
                try {
                    await db.AddAsync(messageRecord);
                    await db.SaveChangesAsync();
                } catch (Exception e) {
                    logger.LogError(
                        e,
                        "Error committing Discord message result to the database");
                }
            }
        }

        private async Task OnGetChannelCommand(SocketSlashCommand command) {
            using var scope = serviceProvider.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService<PagerContext>();

            var alertChannel = db.DiscordAlertChannels
                .FirstOrDefault(c => c.GuildId == command.GuildId);

            if(alertChannel is null) {
                await command.RespondAsync(
                    ephemeral: true,
                    text:      "No alert channel has been configured for this server!");
                return;
            }

            await command.RespondAsync(
                ephemeral: true,
                text: string.Join(' ', [
                    $"The configured alert channel for this server is",
                    $"<#{alertChannel.ChannelId}>",
                    alertChannel.RequireMention ? null : "(all messages will be sent)"
                ]));
        }

        private async Task OnSetChannelCommand(SocketSlashCommand command) {
            logger.LogDebug("Executing the 'set-channel' command...");

            using var scope = serviceProvider.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService<PagerContext>();

            await db.Database.BeginTransactionAsync();

            var alertChannel = await db.DiscordAlertChannels
                .FirstOrDefaultAsync(c => c.GuildId == command.GuildId);

            // Ensure the selected channel is actually a
            // text channel and not a channel category.
            if(command.Data.Options.First().Value is not SocketTextChannel) {
                await command.RespondAsync(
                    ephemeral: true,
                    text:      "Error: Pager message notifications can only be posted to text channels");
                return;
            }

            var channel = (SocketTextChannel) command.Data.Options.First().Value;
            var requireMention = !command.Data.Options
                .Where(o => o.Type == ApplicationCommandOptionType.Boolean)
                .Select(o => (bool?) o.Value)
                .FirstOrDefault() ?? true;

            if(alertChannel is null) {
                alertChannel = new() {
                    GuildId        = (ulong) command.GuildId!,
                    ChannelId      = channel.Id,
                    RequireMention = requireMention
                };
                await db.DiscordAlertChannels.AddAsync(alertChannel);
            } else {
                alertChannel.ChannelId      = channel.Id;
                alertChannel.RequireMention = requireMention;
            }

            await db.SaveChangesAsync();
            await db.Database.CommitTransactionAsync();

            await command.RespondAsync(
                ephemeral: true,
                text: string.Join(' ', [
                    "The alert channel for this server has been set to",
                    $"<#{channel.Id}>",
                    requireMention ? null : "(all messages will be sent)"
                ]));
        }

        private async Task OnRemoveChannelCommand(SocketSlashCommand command) {
            using var scope = serviceProvider.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService<PagerContext>();

            await db.Database.BeginTransactionAsync();

            var alertChannel = await db.DiscordAlertChannels
                .FirstOrDefaultAsync(c => c.GuildId == command.GuildId);

            if(alertChannel is null) {
                await command.RespondAsync(
                    ephemeral: true,
                    text:      "No alert channel was configured for this server!");
                return;
            }

            db.Remove(alertChannel);

            await db.SaveChangesAsync();
            await db.Database.CommitTransactionAsync();

            await command.RespondAsync(
                ephemeral: true,
                text:      $"Removed the configured alert channel for this server");
        }

        private async Task OnSubscribeChannelCommand(SocketSlashCommand command) {
            using var scope = serviceProvider.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService<PagerContext>();

            string mention = string.Empty;

            var subscription = new DiscordAlertSubscription() {
                GuildId         = (ulong) command.GuildId!,
                PageDestination = (string) command.Data.Options.Last().Value
            };

            switch(command.Data.Options.First().Value) {
                case SocketUser user:
                    subscription.PrincipalType = DiscordPrincipalType.User;
                    subscription.PrincipalId   = user.Id;
                    mention                    = $"<@!{user.Id}>";
                    break;
                case SocketRole role:
                    subscription.PrincipalType = DiscordPrincipalType.Role;
                    subscription.PrincipalId   = role.Id;
                    mention                    = $"<@&{role.Id}>";
                    break;
            }

            await db.Database.BeginTransactionAsync();

            var exists = db.DiscordAlertSubscriptions
                .Where(s => s.GuildId == command.GuildId)
                .Where(s => s.PrincipalType == subscription.PrincipalType)
                .Where(s => s.PrincipalId == subscription.PrincipalId)
                .Where(s => s.PageDestination == subscription.PageDestination)
                .Any();

            if(exists) {
                await command.RespondAsync(
                    ephemeral: true,
                    text: string.Join(' ', [
                        mention,
                        subscription.PrincipalType == DiscordPrincipalType.User ? "is" : "are",
                        "already subscribed to pager messages for",
                        $"`{subscription.PageDestination}`"
                    ]));
                return;
            }

            db.DiscordAlertSubscriptions.Add(subscription);
            await db.SaveChangesAsync();
            await db.Database.CommitTransactionAsync();

            await command.RespondAsync(
                ephemeral: true,
                text: string.Join(' ', [
                    "Subscribed",
                    $"<@{subscription.PrincipalId}>",
                    "to pager messages for",
                    $"`{subscription.PageDestination}`"
                ]));
        }

        private async Task OnUnsubscribeChannelCommand(SocketSlashCommand command) {
            using var scope = serviceProvider.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService<PagerContext>();

            string mention = string.Empty;

            var subscription = new DiscordAlertSubscription() {
                GuildId         = (ulong) command.GuildId!,
                PageDestination = (string) command.Data.Options.Last().Value
            };

            switch(command.Data.Options.First().Value) {
                case SocketUser user:
                    subscription.PrincipalType = DiscordPrincipalType.User;
                    subscription.PrincipalId   = user.Id;
                    mention                    = $"<@!{user.Id}>";
                    break;
                case SocketRole role:
                    subscription.PrincipalType = DiscordPrincipalType.Role;
                    subscription.PrincipalId   = role.Id;
                    mention                    = $"<@&{role.Id}>";
                    break;
            }

            await db.Database.BeginTransactionAsync();

            var existing = db.DiscordAlertSubscriptions
                .Where(s => s.GuildId == command.GuildId)
                .Where(s => s.PrincipalType == subscription.PrincipalType)
                .Where(s => s.PrincipalId == subscription.PrincipalId)
                .Where(s => s.PageDestination == subscription.PageDestination);

            if(!existing.Any()) {
                await command.RespondAsync(
                    ephemeral: true,
                    text: string.Join(' ', [
                        mention,
                        subscription.PrincipalType == DiscordPrincipalType.User ? "was" : "are",
                        "not subscribed to pager messages for",
                        $"`{subscription.PageDestination}`"
                    ]));
                return;
            }

            db.DiscordAlertSubscriptions.RemoveRange(existing);
            await db.SaveChangesAsync();
            await db.Database.CommitTransactionAsync();

            await command.RespondAsync(
                ephemeral: true,
                text: string.Join(' ', [
                    "Unsubscribed",
                    $"<@{subscription.PrincipalId}>",
                    "from pager messages for",
                    $"`{subscription.PageDestination}`"
                ]));
        }

        private async Task OnListSubscriptionsCommand(SocketSlashCommand command) {
            using var scope = serviceProvider.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService<PagerContext>();

            DiscordPrincipalType principalType;
            ulong                principalId;
            string               mention;

            switch(command.Data.Options.FirstOrDefault()?.Value) {
                case SocketUser user:
                    principalType = DiscordPrincipalType.User;
                    principalId   = user.Id;
                    mention       = $"<@!{user.Id}> is";
                    break;
                case SocketRole role:
                    principalType = DiscordPrincipalType.Role;
                    principalId   = role.Id;
                    mention       = $"<@&{role.Id}> are";
                    break;
                default:
                    principalType = DiscordPrincipalType.User;
                    principalId   = command.User.Id;
                    mention       = $"<@!{command.User.Id}> is";
                    break;
            }

            var subscriptions = db.DiscordAlertSubscriptions
                .Where(s => s.GuildId == command.GuildId)
                .Where(s => s.PrincipalType == principalType)
                .Where(s => s.PrincipalId == principalId)
                .OrderBy(s => s.PageDestination)
                .Select(s => s.PageDestination)
                .Distinct()
                .ToArray();

            if(subscriptions.Count() == 0) {
                await command.RespondAsync(
                    ephemeral: true,
                    text:      $"{mention} not subscribed to any pager messages");
                return;
            }

            await command.RespondAsync(
                ephemeral: true,
                text: string.Join(
                    "\n - ",
                    Enumerable.Concat(
                        [ $"{mention} subscribed to pager messages for the following brigades/appliances:" ],
                        subscriptions.Select(s => $"`{s}`"))));
        }

        private async Task OnSlashCommand(SocketSlashCommand command) {
            logger.LogDebug($"Slash command executed: {command.Data.Name}");

            try {
                // Search the list of command builders, find the command
                // that was executed and attempt to invoke it's handler.
                var builder = CommandBuilders
                    .First(cb => cb.Name == command.Data.Name);
                await builder.CommandHandler(command);
            } catch(Exception e) {
                // Handle any exceptions by writing a detailed error description
                // to the log and responding to the user with an message and identifier
                // that can be used to identify the corresponding log entry.
                var reference = string.Format("{0:X8}", Random.Shared.Next());
                logger.LogError(e, string.Join(' ', [
                    $"Error executing Discord slash command:",
                    command.Data.Name,
                    "(error reference:",
                    string.Format("{0:X8}", reference),
                    ")"
                ]));
                try {
                    await command.RespondAsync(
                        ephemeral: true,
                        text: string.Join(' ', [
                            "An unknown error occurred whilst attempting to execute the command.",
                                "Error reference:",
                                $"`{reference}`"
                        ]));
                } catch {}
            }
        }

        private async Task OnReady() {
            // Register slash commands
            try {
                await discordClient.BulkOverwriteGlobalApplicationCommandsAsync(
                    CommandBuilders.Select(b => b.Build()).ToArray());
            } catch(Exception e) {
                logger.LogError(
                    e,
                    "Error registering Discord slash commands");
            }
        }

        public void OnConfiguring(
            ILogger logger,
            IConfiguration config,
            IServiceProvider serviceProvider) {

            this.logger          = logger;
            this.serviceProvider = serviceProvider;

            botToken = config.GetValue<string>("PagerParser:DiscordBot:Token")!;

            if(botToken is null) {
                logger.LogError("No bot token configured");
                throw new InvalidOperationException("Bot token is null!");
            }
        }

        public async Task StartAsync(CancellationToken ct) {
            discordClient = new();

            discordClient.Ready                += OnReady;
            discordClient.SlashCommandExecuted += OnSlashCommand;

            await discordClient.LoginAsync(TokenType.Bot, botToken);
            await discordClient.StartAsync();
        }

        public async Task StopAsync(CancellationToken ct) {
            await discordClient.StopAsync();
            await discordClient.DisposeAsync();
        }

        private string Color(AnsiColor color, string text) {
            if(!string.IsNullOrEmpty(text))
                return $"\x1B[{(int) color}m{text}\x1B[0m";
            else
                return "";
        }

        private enum AnsiColor {
            Black     = 30, Red          = 31, Green      = 32, Yellow      = 33,
            Blue      = 34, Magenta      = 35, Cyan       = 36, LightGray   = 37,
            DarkGray  = 90, LightRed     = 91, LightGreen = 92, LightYellow = 93,
            LightBlue = 94, LightMagenta = 95, LightCyan  = 96, White       = 97,
        }

        private class CommandBuilder : SlashCommandBuilder {
            public Func<SocketSlashCommand, Task> CommandHandler { get; set; }
        }
    }

    [Index(nameof(GuildId), IsUnique = true)]
    public class DiscordAlertChannel {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int   DiscordAlertChannelId { get; set; }
        public ulong GuildId               { get; set; }
        public ulong ChannelId             { get; set; }
        public bool  RequireMention        { get; set; }
    }

    [Index(nameof(GuildId))]
    public class DiscordAlertSubscription {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int                  DiscordAlertSubscriptionId { get; set; }
        public string               PageDestination            { get; set; }
        public ulong                GuildId                    { get; set; }
        public ulong                PrincipalId                { get; set; }
        public DiscordPrincipalType PrincipalType              { get; set; }
    }

    public class DiscordAlertMessage {
        [Key]
        public ulong              DiscordMessageId   { get; set; }
        public ParsedPagerMessage ParsedPagerMessage { get; set; }
    }

    public enum DiscordPrincipalType {
        User,
        Role
    }
}