-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathEventsBaseCommand.cs
623 lines (567 loc) · 28.4 KB
/
EventsBaseCommand.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CompatApiClient.Utils;
using CompatBot.Commands.Attributes;
using CompatBot.Database;
using CompatBot.Database.Providers;
using CompatBot.Utils;
using CompatBot.Utils.Extensions;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.Interactivity.Extensions;
using Microsoft.EntityFrameworkCore;
namespace CompatBot.Commands;
internal partial class EventsBaseCommand: BaseCommandModuleCustom
{
private static readonly TimeSpan InteractTimeout = TimeSpan.FromMinutes(5);
[GeneratedRegex(@"((?<days>\d+)(\.|d\s*))?((?<hours>\d+)(\:|h\s*))?((?<mins>\d+)m?)?", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.ExplicitCapture)]
private static partial Regex Duration();
protected static async Task NearestEvent(CommandContext ctx, string? eventName = null)
{
var originalEventName = eventName = eventName?.Trim(40);
var current = DateTime.UtcNow;
var currentTicks = current.Ticks;
await using var db = new BotDb();
var currentEvents = await db.EventSchedule.OrderBy(e => e.End).Where(e => e.Start <= currentTicks && e.End >= currentTicks).ToListAsync().ConfigureAwait(false);
var nextEvent = await db.EventSchedule.OrderBy(e => e.Start).FirstOrDefaultAsync(e => e.Start > currentTicks).ConfigureAwait(false);
if (string.IsNullOrEmpty(eventName))
{
var nearestEventMsg = "";
if (currentEvents.Count > 0)
{
if (currentEvents.Count == 1)
nearestEventMsg = $"Current event: {currentEvents[0].Name} (going for {FormatCountdown(current - currentEvents[0].Start.AsUtc())})\n";
else
{
nearestEventMsg = "Current events:\n";
foreach (var e in currentEvents)
nearestEventMsg += $"{e.Name} (going for {FormatCountdown(current - e.Start.AsUtc())})\n";
}
}
if (nextEvent != null)
nearestEventMsg += $"Next event: {nextEvent.Name} (starts in {FormatCountdown(nextEvent.Start.AsUtc() - current)})";
await ctx.Channel.SendMessageAsync(nearestEventMsg.TrimEnd()).ConfigureAwait(false);
return;
}
eventName = await FuzzyMatchEventName(db, eventName).ConfigureAwait(false);
var promo = "";
if (currentEvents.Count > 0)
promo = $"\nMeanwhile check out this {(string.IsNullOrEmpty(currentEvents[0].EventName) ? "" : currentEvents[0].EventName + " " + currentEvents[0].Year + " ")}event in progress: {currentEvents[0].Name} (going for {FormatCountdown(current - currentEvents[0].Start.AsUtc())})";
else if (nextEvent != null)
promo = $"\nMeanwhile check out this upcoming {(string.IsNullOrEmpty(nextEvent.EventName) ? "" : nextEvent.EventName + " " + nextEvent.Year + " ")}event: {nextEvent.Name} (starts in {FormatCountdown(nextEvent.Start.AsUtc() - current)})";
var firstNamedEvent = await db.EventSchedule.OrderBy(e => e.Start).FirstOrDefaultAsync(e => e.Year >= current.Year && e.EventName == eventName).ConfigureAwait(false);
if (firstNamedEvent == null)
{
var scheduleEntry = await FuzzyMatchEntryName(db, originalEventName).ConfigureAwait(false);
var events = await db.EventSchedule.OrderBy(e => e.Start).Where(e => e.End > current.Ticks && e.Name == scheduleEntry).ToListAsync().ConfigureAwait(false);
if (events.Any())
{
var eventListMsg = new StringBuilder();
foreach (var eventEntry in events)
{
if (eventEntry.Start < current.Ticks)
eventListMsg.AppendLine($"{eventEntry.Name} ends in {FormatCountdown(eventEntry.End.AsUtc() - current)}");
else
eventListMsg.AppendLine($"{eventEntry.Name} starts in {FormatCountdown(eventEntry.Start.AsUtc() - current)}");
}
await ctx.SendAutosplitMessageAsync(eventListMsg.ToString(), blockStart: "", blockEnd: "").ConfigureAwait(false);
return;
}
var noEventMsg = $"No information about the upcoming {eventName?.Sanitize(replaceBackTicks: true)} at the moment";
if (eventName?.Length > 10)
noEventMsg = "No information about such event at the moment";
else if (ctx.User.Id is 259997001880436737ul or 377190919327318018ul)
{
noEventMsg = $"Haha, very funny, {ctx.User.Mention}. So original. Never saw this joke before.";
promo = null;
}
if (!string.IsNullOrEmpty(promo))
noEventMsg += promo;
await ctx.Channel.SendMessageAsync(noEventMsg).ConfigureAwait(false);
return;
}
if (firstNamedEvent.Start >= currentTicks)
{
var upcomingNamedEventMsg = $"__{FormatCountdown(firstNamedEvent.Start.AsUtc() - current)} until {eventName} {firstNamedEvent.Year}!__";
if (string.IsNullOrEmpty(promo) || nextEvent?.Id == firstNamedEvent.Id)
upcomingNamedEventMsg += $"\nFirst event: {firstNamedEvent.Name}";
else
upcomingNamedEventMsg += promo;
await ctx.Channel.SendMessageAsync(upcomingNamedEventMsg).ConfigureAwait(false);
return;
}
var lastNamedEvent = await db.EventSchedule.OrderByDescending(e => e.End).FirstOrDefaultAsync(e => e.Year == current.Year && e.EventName == eventName).ConfigureAwait(false);
if (lastNamedEvent is not null && lastNamedEvent.End <= currentTicks)
{
if (lastNamedEvent.End < current.AddMonths(-1).Ticks)
{
firstNamedEvent = await db.EventSchedule.OrderBy(e => e.Start).FirstOrDefaultAsync(e => e.Year >= current.Year + 1 && e.EventName == eventName).ConfigureAwait(false);
if (firstNamedEvent == null)
{
var noEventMsg = $"No information about the upcoming {eventName?.Sanitize(replaceBackTicks: true)} at the moment";
if (eventName?.Length > 10)
noEventMsg = "No information about such event at the moment";
else if (ctx.User.Id is 259997001880436737ul or 377190919327318018ul)
{
noEventMsg = $"Haha, very funny, {ctx.User.Mention}. So original. Never saw this joke before.";
promo = null;
}
if (!string.IsNullOrEmpty(promo))
noEventMsg += promo;
await ctx.Channel.SendMessageAsync(noEventMsg).ConfigureAwait(false);
return;
}
var upcomingNamedEventMsg = $"__{FormatCountdown(firstNamedEvent.Start.AsUtc() - current)} until {eventName} {firstNamedEvent.Year}!__";
if (string.IsNullOrEmpty(promo) || nextEvent?.Id == firstNamedEvent.Id)
upcomingNamedEventMsg += $"\nFirst event: {firstNamedEvent.Name}";
else
upcomingNamedEventMsg += promo;
await ctx.Channel.SendMessageAsync(upcomingNamedEventMsg).ConfigureAwait(false);
return;
}
var e3EndedMsg = $"__{eventName} {current.Year} has concluded. See you next year! (maybe)__";
if (!string.IsNullOrEmpty(promo))
e3EndedMsg += promo;
await ctx.Channel.SendMessageAsync(e3EndedMsg).ConfigureAwait(false);
return;
}
var currentNamedEvent = await db.EventSchedule.OrderBy(e => e.End).FirstOrDefaultAsync(e => e.Start <= currentTicks && e.End >= currentTicks && e.EventName == eventName).ConfigureAwait(false);
var nextNamedEvent = await db.EventSchedule.OrderBy(e => e.Start).FirstOrDefaultAsync(e => e.Start > currentTicks && e.EventName == eventName).ConfigureAwait(false);
var msg = $"__{eventName} {current.Year} is already in progress!__\n";
if (currentNamedEvent != null)
msg += $"Current event: {currentNamedEvent.Name} (going for {FormatCountdown(current - currentNamedEvent.Start.AsUtc())})\n";
if (nextNamedEvent != null)
msg += $"Next event: {nextNamedEvent.Name} (starts in {FormatCountdown(nextNamedEvent.Start.AsUtc() - current)})";
await ctx.SendAutosplitMessageAsync(msg.TrimEnd(), blockStart: "", blockEnd: "").ConfigureAwait(false);
}
protected static async Task Add(CommandContext ctx, string? eventName = null)
{
var evt = new EventSchedule();
var (success, msg) = await EditEventPropertiesAsync(ctx, evt, eventName).ConfigureAwait(false);
if (success)
{
await using var db = new BotDb();
await db.EventSchedule.AddAsync(evt).ConfigureAwait(false);
await db.SaveChangesAsync().ConfigureAwait(false);
await ctx.ReactWithAsync(Config.Reactions.Success).ConfigureAwait(false);
if (LimitedToSpamChannel.IsSpamChannel(ctx.Channel))
await msg.UpdateOrCreateMessageAsync(ctx.Channel, embed: FormatEvent(evt).WithTitle("Created new event schedule entry #" + evt.Id)).ConfigureAwait(false);
else
await msg.UpdateOrCreateMessageAsync(ctx.Channel, "Added a new schedule entry").ConfigureAwait(false);
}
else
await msg.UpdateOrCreateMessageAsync(ctx.Channel, "Event creation aborted").ConfigureAwait(false);
}
protected static async Task Remove(CommandContext ctx, params int[] ids)
{
await using var db = new BotDb();
var eventsToRemove = await db.EventSchedule.Where(e3e => ids.Contains(e3e.Id)).ToListAsync().ConfigureAwait(false);
db.EventSchedule.RemoveRange(eventsToRemove);
var removedCount = await db.SaveChangesAsync().ConfigureAwait(false);
if (removedCount == ids.Length)
await ctx.Channel.SendMessageAsync($"Event{StringUtils.GetSuffix(ids.Length)} successfully removed!").ConfigureAwait(false);
else
await ctx.Channel.SendMessageAsync($"Removed {removedCount} event{StringUtils.GetSuffix(removedCount)}, but was asked to remove {ids.Length}").ConfigureAwait(false);
}
protected static async Task Clear(CommandContext ctx, int? year = null)
{
var currentYear = DateTime.UtcNow.Year;
await using var db = new BotDb();
var itemsToRemove = await db.EventSchedule.Where(e =>
year.HasValue
? e.Year == year
: e.Year < currentYear
).ToListAsync().ConfigureAwait(false);
db.EventSchedule.RemoveRange(itemsToRemove);
var removedCount = await db.SaveChangesAsync().ConfigureAwait(false);
await ctx.Channel.SendMessageAsync($"Removed {removedCount} event{(removedCount == 1 ? "" : "s")}").ConfigureAwait(false);
}
protected static async Task Update(CommandContext ctx, int id, string? eventName = null)
{
await using var db = new BotDb();
var evt = eventName == null
? db.EventSchedule.FirstOrDefault(e => e.Id == id)
: db.EventSchedule.FirstOrDefault(e => e.Id == id && e.EventName == eventName);
if (evt == null)
{
await ctx.ReactWithAsync(Config.Reactions.Failure, $"No event with id {id}").ConfigureAwait(false);
return;
}
var (success, msg) = await EditEventPropertiesAsync(ctx, evt, eventName).ConfigureAwait(false);
if (success)
{
await db.SaveChangesAsync().ConfigureAwait(false);
if (LimitedToSpamChannel.IsSpamChannel(ctx.Channel))
await msg.UpdateOrCreateMessageAsync(ctx.Channel, embed: FormatEvent(evt).WithTitle("Updated event schedule entry #" + evt.Id)).ConfigureAwait(false);
else
await msg.UpdateOrCreateMessageAsync(ctx.Channel, "Updated the schedule entry").ConfigureAwait(false);
}
else
await msg.UpdateOrCreateMessageAsync(ctx.Channel, "Event update aborted, changes weren't saved").ConfigureAwait(false);
}
protected static async Task List(CommandContext ctx, string? eventName = null, int? year = null)
{
var showAll = "all".Equals(eventName, StringComparison.InvariantCultureIgnoreCase);
var currentTicks = DateTime.UtcNow.Ticks;
await using var db = new BotDb();
IQueryable<EventSchedule> query = db.EventSchedule;
if (year.HasValue)
query = query.Where(e => e.Year == year);
else if (!showAll)
query = query.Where(e => e.End > currentTicks);
if (!string.IsNullOrEmpty(eventName) && !showAll)
{
eventName = await FuzzyMatchEventName(db, eventName).ConfigureAwait(false);
query = query.Where(e => e.EventName == eventName);
}
List<EventSchedule> events = await query
.OrderBy(e => e.Start)
.ToListAsync()
.ConfigureAwait(false);
if (events.Count == 0)
{
await ctx.Channel.SendMessageAsync("There are no events to show").ConfigureAwait(false);
return;
}
var msg = new StringBuilder();
var currentYear = -1;
var currentEvent = Guid.NewGuid().ToString();
foreach (var evt in events)
{
if (evt.Year != currentYear)
{
if (currentYear > 0)
msg.AppendLine().AppendLine($"__Year {evt.Year}__");
currentEvent = Guid.NewGuid().ToString();
currentYear = evt.Year;
}
var evtName = evt.EventName ?? "";
if (currentEvent != evtName)
{
currentEvent = evtName;
var printName = string.IsNullOrEmpty(currentEvent) ? "Various independent events" : $"**{currentEvent} {currentYear} schedule**";
msg.AppendLine($"{printName} (UTC):");
}
msg.Append(StringUtils.InvisibleSpacer).Append('`');
if (ModProvider.IsMod(ctx.Message.Author.Id))
msg.Append($"[{evt.Id:0000}] ");
msg.Append($"{evt.Start.AsUtc():u}");
if (ctx.Channel.IsPrivate)
msg.Append($@" - {evt.End.AsUtc():u}");
msg.AppendLine($@" ({evt.End.AsUtc() - evt.Start.AsUtc():h\:mm})`: {evt.Name}");
}
var ch = await ctx.GetChannelForSpamAsync().ConfigureAwait(false);
await ch.SendAutosplitMessageAsync(msg, blockStart: "", blockEnd: "").ConfigureAwait(false);
}
private static async Task<(bool success, DiscordMessage? message)> EditEventPropertiesAsync(CommandContext ctx, EventSchedule evt, string? eventName = null)
{
var interact = ctx.Client.GetInteractivity();
var abort = new DiscordButtonComponent(ButtonStyle.Danger, "event:edit:abort", "Cancel", emoji: new(DiscordEmoji.FromUnicode("✖")));
var lastPage = new DiscordButtonComponent(ButtonStyle.Secondary, "event:edit:last", "To Last Field", emoji: new(DiscordEmoji.FromUnicode("⏭")));
var firstPage = new DiscordButtonComponent(ButtonStyle.Secondary, "event:edit:first", "To First Field", emoji: new(DiscordEmoji.FromUnicode("⏮")));
var previousPage = new DiscordButtonComponent(ButtonStyle.Secondary, "event:edit:previous", "Previous", emoji: new(DiscordEmoji.FromUnicode("◀")));
var nextPage = new DiscordButtonComponent(ButtonStyle.Primary, "event:edit:next", "Next", emoji: new(DiscordEmoji.FromUnicode("▶")));
var trash = new DiscordButtonComponent(ButtonStyle.Secondary, "event:edit:trash", "Clear", emoji: new(DiscordEmoji.FromUnicode("🗑")));
var saveEdit = new DiscordButtonComponent(ButtonStyle.Success, "event:edit:save", "Save", emoji: new(DiscordEmoji.FromUnicode("💾")));
var skipEventNameStep = !string.IsNullOrEmpty(eventName);
DiscordMessage? msg = null;
string? errorMsg = null;
DiscordMessage? txt;
ComponentInteractionCreateEventArgs? btn;
DiscordMessageBuilder messageBuilder;
step1:
// step 1: get the new start date
saveEdit.SetEnabled(evt.IsComplete());
messageBuilder = new DiscordMessageBuilder()
.WithContent("Please specify a new **start date and time**")
.WithEmbed(FormatEvent(evt, errorMsg, 1).WithDescription($"""
Example: `{DateTime.UtcNow:yyyy-MM-dd HH:mm}`
By default all times use UTC, only limited number of time zones supported
"""))
.AddComponents(lastPage, nextPage)
.AddComponents(saveEdit, abort);
errorMsg = null;
msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false);
(txt, btn) = await interact.WaitForMessageOrButtonAsync(msg, ctx.User, InteractTimeout).ConfigureAwait(false);
if (btn != null)
{
if (btn.Id == abort.CustomId)
return (false, msg);
if (btn.Id == saveEdit.CustomId)
return (true, msg);
if (btn.Id == lastPage.CustomId)
goto step4;
}
else if (txt != null)
{
if (!TimeParser.TryParse(txt.Content, out var newTime))
{
errorMsg = $"Couldn't parse `{txt.Content}` as a start date and time";
goto step1;
}
if (newTime < DateTime.UtcNow && evt.End == default)
errorMsg = "Specified time is in the past, are you sure it is correct?";
var duration = evt.End - evt.Start;
evt.Start = newTime.Ticks;
evt.End = evt.Start + duration;
evt.Year = newTime.Year;
}
else
return (false, msg);
step2:
// step 2: get the new duration
saveEdit.SetEnabled(evt.IsComplete());
messageBuilder = new DiscordMessageBuilder()
.WithContent("Please specify a new **event duration**")
.WithEmbed(FormatEvent(evt, errorMsg, 2).WithDescription("Example: `2d 1h 15m`, or `2.1:00`"))
.AddComponents(previousPage, nextPage)
.AddComponents(saveEdit, abort);
errorMsg = null;
msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false);
(txt, btn) = await interact.WaitForMessageOrButtonAsync(msg, ctx.User, InteractTimeout).ConfigureAwait(false);
if (btn != null)
{
if (btn.Id == abort.CustomId)
return (false, msg);
if (btn.Id == saveEdit.CustomId)
return (true, msg);
if (btn.Id == previousPage.CustomId)
goto step1;
if (skipEventNameStep)
goto step4;
}
else if (txt != null)
{
var newLength = await TryParseTimeSpanAsync(ctx, txt.Content, false).ConfigureAwait(false);
if (!newLength.HasValue)
{
errorMsg = $"Couldn't parse `{txt.Content}` as a duration";
goto step2;
}
evt.End = (evt.Start.AsUtc() + newLength.Value).Ticks;
}
else
return (false, msg);
step3:
// step 3: get the new event name
saveEdit.SetEnabled(evt.IsComplete());
trash.SetDisabled(string.IsNullOrEmpty(evt.EventName));
messageBuilder = new DiscordMessageBuilder()
.WithContent("Please specify a new **event name**")
.WithEmbed(FormatEvent(evt, errorMsg, 3))
.AddComponents(previousPage, nextPage, trash)
.AddComponents(saveEdit, abort);
errorMsg = null;
msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false);
(txt, btn) = await interact.WaitForMessageOrButtonAsync(msg, ctx.User, InteractTimeout).ConfigureAwait(false);
if (btn != null)
{
if (btn.Id == abort.CustomId)
return (false, msg);
if (btn.Id == saveEdit.CustomId)
return (true, msg);
if (btn.Id == previousPage.CustomId)
goto step2;
if (btn.Id == trash.CustomId)
evt.EventName = null;
}
else if (txt != null)
evt.EventName = string.IsNullOrWhiteSpace(txt.Content) || txt.Content == "-" ? null : txt.Content;
else
return (false, msg);
step4:
// step 4: get the new schedule entry name
saveEdit.SetEnabled(evt.IsComplete());
messageBuilder = new DiscordMessageBuilder()
.WithContent("Please specify a new **schedule entry title**")
.WithEmbed(FormatEvent(evt, errorMsg, 4))
.AddComponents(previousPage, firstPage)
.AddComponents(saveEdit, abort);
errorMsg = null;
msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false);
(txt, btn) = await interact.WaitForMessageOrButtonAsync(msg, ctx.User, InteractTimeout).ConfigureAwait(false);
if (btn != null)
{
if (btn.Id == abort.CustomId)
return (false, msg);
if (btn.Id == saveEdit.CustomId)
return (true, msg);
if (btn.Id == firstPage.CustomId)
goto step1;
if (btn.Id == previousPage.CustomId)
{
if (skipEventNameStep)
goto step2;
goto step3;
}
}
else if (txt != null)
{
if (string.IsNullOrEmpty(txt.Content))
{
errorMsg = "Entry title cannot be empty";
goto step4;
}
evt.Name = txt.Content;
}
else
return (false, msg);
step5:
// step 5: confirm
if (errorMsg == null && !evt.IsComplete())
errorMsg = "Some required properties are not defined";
saveEdit.SetEnabled(evt.IsComplete());
messageBuilder = new DiscordMessageBuilder()
.WithContent("Does this look good? (y/n)")
.WithEmbed(FormatEvent(evt, errorMsg))
.AddComponents(previousPage, firstPage)
.AddComponents(saveEdit, abort);
errorMsg = null;
msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, messageBuilder).ConfigureAwait(false);
(txt, btn) = await interact.WaitForMessageOrButtonAsync(msg, ctx.User, InteractTimeout).ConfigureAwait(false);
if (btn != null)
{
if (btn.Id == abort.CustomId)
return (false, msg);
if (btn.Id == saveEdit.CustomId)
return (true, msg);
if (btn.Id == previousPage.CustomId)
goto step4;
if (btn.Id == firstPage.CustomId)
goto step1;
}
else if (!string.IsNullOrEmpty(txt?.Content))
{
if (!evt.IsComplete())
goto step5;
switch (txt.Content.ToLowerInvariant())
{
case "yes":
case "y":
case "✅":
case "☑":
case "✔":
case "👌":
case "👍":
return (true, msg);
case "no":
case "n":
case "❎":
case "❌":
case "👎":
return (false, msg);
default:
errorMsg = "I don't know what you mean, so I'll just abort";
goto step5;
}
}
else
{
return (false, msg);
}
return (false, msg);
}
private static string? NameWithoutLink(string? name)
{
if (string.IsNullOrEmpty(name))
return name;
var lastPartIdx = name.LastIndexOf(' ');
if (lastPartIdx < 0)
return name;
if (name.Length - lastPartIdx > 5
&& name.Substring(lastPartIdx + 1, 5).ToLowerInvariant() is string lnk
&& (lnk.StartsWith("<http") || lnk.StartsWith("http")))
return name[..lastPartIdx];
return name;
}
private static async Task<string?> FuzzyMatchEventName(BotDb db, string? eventName)
{
var knownEventNames = await db.EventSchedule.Select(e => e.EventName).Distinct().ToListAsync().ConfigureAwait(false);
var (score, name) = knownEventNames.Select(n => (score: eventName.GetFuzzyCoefficientCached(n), name: n)).OrderByDescending(t => t.score).FirstOrDefault();
return score > 0.8 ? name : eventName;
}
private static async Task<string?> FuzzyMatchEntryName(BotDb db, string? eventName)
{
var now = DateTime.UtcNow.Ticks;
var knownNames = await db.EventSchedule.Where(e => e.End > now).Select(e => e.Name).ToListAsync().ConfigureAwait(false);
var (score, name) = knownNames.Select(n => (score: eventName.GetFuzzyCoefficientCached(NameWithoutLink(n)), name: n)).OrderByDescending(t => t.score).FirstOrDefault();
return score > 0.5 ? name : eventName;
}
private static async Task<TimeSpan?> TryParseTimeSpanAsync(CommandContext ctx, string duration, bool react = true)
{
var d = Duration().Match(duration);
if (!d.Success)
{
if (react)
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Failed to parse `{duration}` as a time", true).ConfigureAwait(false);
return null;
}
_ = int.TryParse(d.Groups["days"].Value, out var days);
_ = int.TryParse(d.Groups["hours"].Value, out var hours);
_ = int.TryParse(d.Groups["mins"].Value, out var mins);
if (days == 0 && hours == 0 && mins == 0)
{
if (react)
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Failed to parse `{duration}` as a time", true).ConfigureAwait(false);
return null;
}
return new TimeSpan(days, hours, mins, 0);
}
private static string FormatCountdown(TimeSpan timeSpan)
{
var result = "";
var days = (int)timeSpan.TotalDays;
if (days > 0)
timeSpan -= TimeSpan.FromDays(days);
var hours = (int)timeSpan.TotalHours;
if (hours > 0)
timeSpan -= TimeSpan.FromHours(hours);
var mins = (int)timeSpan.TotalMinutes;
if (mins > 0)
timeSpan -= TimeSpan.FromMinutes(mins);
var secs = (int)timeSpan.TotalSeconds;
if (days > 0)
result += $"{days} day{(days == 1 ? "" : "s")} ";
if (hours > 0 || days > 0)
result += $"{hours} hour{(hours == 1 ? "" : "s")} ";
if (mins > 0 || hours > 0 || days > 0)
result += $"{mins} minute{(mins == 1 ? "" : "s")} ";
result += $"{secs} second{(secs == 1 ? "" : "s")}";
return result;
}
private static DiscordEmbedBuilder FormatEvent(EventSchedule evt, string? error = null, int highlight = -1)
{
var start = evt.Start.AsUtc();
var field = 1;
var result = new DiscordEmbedBuilder
{
Title = "Schedule entry preview",
Color = string.IsNullOrEmpty(error) ? Config.Colors.Help : Config.Colors.Maintenance,
};
if (!string.IsNullOrEmpty(error))
result.AddField("Entry error", error);
var currentTime = DateTime.UtcNow;
if (evt.Start > currentTime.Ticks)
result.WithFooter($"Starts in {FormatCountdown(evt.Start.AsUtc() - currentTime)}");
else if (evt.End > currentTime.Ticks)
result.WithFooter($"Ends in {FormatCountdown(evt.End.AsUtc() - currentTime)}");
var eventDuration = evt.End.AsUtc() - start;
var durationFormat = eventDuration.TotalDays > 0 ? @"d\d\ h\h\ m\m" : @"h\h\ m\m";
var startWarn = start < DateTime.UtcNow ? "⚠️ " : "";
result
.AddFieldEx(startWarn + "Start time", evt.Start == 0 ? "-" : start.ToString("u"), highlight == field++, true)
.AddFieldEx("Duration", evt.Start == evt.End ? "-" : eventDuration.ToString(durationFormat), highlight == field++, true)
.AddFieldEx("Event name", string.IsNullOrEmpty(evt.EventName) ? "-" : evt.EventName, highlight == field++, true)
.AddFieldEx("Schedule entry title", string.IsNullOrEmpty(evt.Name) ? "-" : evt.Name, highlight == field++, true);
#if DEBUG
result.WithFooter("Test bot instance");
#endif
return result;
}
}