-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBot.cs
More file actions
600 lines (499 loc) · 23.2 KB
/
Bot.cs
File metadata and controls
600 lines (499 loc) · 23.2 KB
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
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using MyDiscordBot.Background;
using MyDiscordBot.Commands;
using MyDiscordBot.Models;
using MyDiscordBot.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
namespace MyDiscordBot
{
public class Bot : IDisposable
{
// --- Lifecycle/guards ---
private volatile bool _didInit = false;
private volatile bool _commandsLoaded = false;
private volatile bool _birthdayLoopStarted = false;
// prevent concurrent birthday checks
private readonly SemaphoreSlim _birthdayCheckGate = new(1, 1);
// dedupe birthday posts per day
private readonly HashSet<string> _birthdaySentToday = new();
private DateTime _lastBirthdayResetDate = DateTime.MinValue;
// --- Services ---
public BotServices Services { get; }
public CreatorStore CreatorStore { get; private set; } = null!;
private readonly HttpClient _http;
public Bot(ReminderService reminderService)
{
_http = new HttpClient();
var triviaApi = new OpenTdbService(_http);
Services = new BotServices(reminderService, triviaApi);
}
// --- Discord client & config ---
public DiscordSocketClient _client = null!;
private string _token = null!;
private string _prefix = "!";
// --- Commands & settings ---
private readonly Dictionary<string, ILegacyCommand> _legacyCommands = new(StringComparer.OrdinalIgnoreCase);
private static Dictionary<ulong, GuildSettings> _guildSettings = new();
private static readonly JsonSerializerOptions CachedJsonSerializerOptions = new() { WriteIndented = true };
// settings persistence (Render disk)
private static readonly string DataDir = ResolveDataDir();
private static readonly string SettingsFile = Path.Combine(DataDir, "guild-settings.json");
private static readonly string BirthdaysFile = Path.Combine(DataDir, "birthdays.json");
private static readonly string CreatorsFile = Path.Combine(DataDir, "creators.json");
private static readonly object _settingsSync = new();
public static Bot BotInstance { get; private set; } = null!;
public DiscordSocketClient GetClient() => _client;
public List<ILegacyCommand> GetAllLegacyCommands() => _legacyCommands.Values.ToList();
public async Task RunAsync()
{
BotInstance = this;
_token = Environment.GetEnvironmentVariable("DISCORD_TOKEN") ?? string.Empty;
if (string.IsNullOrWhiteSpace(_token))
throw new InvalidOperationException("DISCORD_TOKEN env var is missing.");
_prefix = Environment.GetEnvironmentVariable("PREFIX") ?? "!";
_client = new DiscordSocketClient(new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.Guilds
| GatewayIntents.GuildMessages
| GatewayIntents.MessageContent
| GatewayIntents.GuildMembers
| GatewayIntents.GuildMessageReactions
| GatewayIntents.GuildVoiceStates
| GatewayIntents.GuildPresences
});
// wire events
_client.Log += Log;
_client.MessageReceived += HandleMessageAsync;
_client.UserJoined += HandleUserJoinedAsync;
_client.UserLeft += HandleUserLeftAsync;
_client.UserVoiceStateUpdated += HandleVoiceStateAsync;
_client.PresenceUpdated += HandlePresenceUpdatedAsync;
_client.ReactionAdded += HandleReactionAddedAsync;
// visibility for invites
_client.JoinedGuild += g => { Console.WriteLine($"[GUILD] Joined: {g.Name} ({g.Id})"); return Task.CompletedTask; };
_client.LeftGuild += g => { Console.WriteLine($"[GUILD] Left: {g.Name} ({g.Id})"); return Task.CompletedTask; };
// single-run init
_client.Ready += OnClientReadyOnce;
await _client.LoginAsync(TokenType.Bot, _token);
await _client.StartAsync();
// keep alive
await Task.Delay(Timeout.Infinite);
}
// one-time init after gateway is ready
private async Task OnClientReadyOnce()
{
if (_didInit) return;
lock (this)
{
if (_didInit) return;
_didInit = true;
}
_client.Ready -= OnClientReadyOnce;
Console.WriteLine("[READY] init start");
EnsureDataDir();
// ✅ CRITICAL: instantiate CreatorStore ONCE, using the persistent disk path
CreatorStore = new CreatorStore(CreatorsFile);
Console.WriteLine(
$"[creators] using store: {CreatorsFile} " +
$"exists={File.Exists(CreatorsFile)} " +
$"size={(File.Exists(CreatorsFile) ? new FileInfo(CreatorsFile).Length : 0)} bytes"
);
LoadSettings();
Console.WriteLine($"[settings] using file: {SettingsFile}");
LoadLegacyCommandsOnce();
foreach (var guild in _client.Guilds)
{
var settings = GetSettings(guild.Id);
if (!string.IsNullOrEmpty(settings.Nickname))
{
var botUser = guild.GetUser(_client.CurrentUser.Id);
if (botUser != null)
{
try { await botUser.ModifyAsync(p => p.Nickname = settings.Nickname); } catch { }
}
}
LogMessage(guild.Id, $"Connected to guild: {guild.Name} ({guild.Id})", LogCategory.Log);
}
if (!_birthdayLoopStarted)
{
_birthdayLoopStarted = true;
_ = RepeatBirthdayCheck();
}
// ✅ Wire join/leave announcements (your existing hook)
MemberEvents.Wire(_client, Services.GuildSettings, s => Console.WriteLine($"[leave-events] {s}"));
// ✅ Start reminders dispatcher ONCE (and fix Program.BotInstance usage)
// Optional gating; if you already use IS_DISPATCHER=true elsewhere, keep this.
if (string.Equals(Environment.GetEnvironmentVariable("IS_DISPATCHER"), "true", StringComparison.OrdinalIgnoreCase))
{
void Log(string s) => Console.WriteLine($"[reminders] {s}");
ReminderDispatcher.Start(_client, BotInstance.Services.Reminders, Log);
}
Console.WriteLine("[READY] init end");
}
// ---------------- Command pipeline with per-guild debug logging ----------------
private async Task HandleMessageAsync(SocketMessage message)
{
// Ignore bots/system/empty
if (message.Author.IsBot || string.IsNullOrWhiteSpace(message.Content))
return;
// ✅ Intercept free trivia answers like "A", "B", "C", "D"
if (await TriviaCommand.TryHandleFreeAnswerAsync(message))
return;
if (message is not SocketUserMessage userMessage)
return;
int argPos = 0;
if (!userMessage.HasStringPrefix(_prefix, ref argPos))
return;
var content = userMessage.Content.Substring(argPos).Trim();
string commandName;
string argRest = string.Empty;
int firstSpace = content.IndexOf(' ');
if (firstSpace < 0)
{
commandName = content.ToLowerInvariant();
}
else
{
commandName = content.Substring(0, firstSpace).ToLowerInvariant();
argRest = content.Substring(firstSpace + 1);
}
bool debug = DebugOn(message);
var ctx = debug ? FormatContext(message) : string.Empty;
var sw = debug ? Stopwatch.StartNew() : null;
if (!_legacyCommands.TryGetValue(commandName, out var command))
{
if (debug) Console.WriteLine($"[CMD] unknown '{commandName}' args=\"{argRest}\" | {ctx}");
// Route unknowns to 'Other' category for guild logs
var gid = (message.Channel as SocketGuildChannel)?.Guild.Id;
if (gid.HasValue)
LogMessage(gid.Value, $"Unknown command '{commandName}' args=\"{argRest}\"");
return;
}
if (debug) Console.WriteLine($"[CMD] start '{commandName}' args=\"{argRest}\" | {ctx}");
try
{
var args = string.IsNullOrWhiteSpace(argRest)
? Array.Empty<string>()
: argRest.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
await command.ExecuteAsync(message, args);
if (debug && sw is not null)
{
sw.Stop();
Console.WriteLine($"[CMD] ok '{commandName}' {sw.ElapsedMilliseconds}ms | {ctx}");
}
}
catch (Exception ex)
{
if (debug && sw is not null)
{
sw.Stop();
Console.WriteLine($"[CMD] fail '{commandName}' {sw.ElapsedMilliseconds}ms | {ctx}\n{ex}");
}
}
}
private static bool DebugOn(SocketMessage msg)
{
var guildId = (msg.Channel as SocketGuildChannel)?.Guild.Id;
return guildId.HasValue && GetDebugMode(guildId.Value);
}
private static string FormatContext(SocketMessage msg)
{
var guild = (msg.Channel as SocketGuildChannel)?.Guild;
var guildPart = guild is null ? "DM" : $"{guild.Name}({guild.Id})";
var channelName = (msg.Channel as SocketGuildChannel)?.Name ?? "DM";
var channelPart = $"{channelName}({msg.Channel.Id})";
var user = msg.Author;
var userPart = $"{user.Username}#{user.Discriminator}({user.Id})";
return $"guild={guildPart} chan={channelPart} user={userPart}";
}
// ------------------------- Settings persistence -------------------------
private static string ResolveDataDir()
{
var candidates = new[]
{
Environment.GetEnvironmentVariable("DATA_DIR"), // e.g., /data
"/data",
"/var/data",
AppContext.BaseDirectory
};
foreach (var p in candidates)
{
if (string.IsNullOrWhiteSpace(p)) continue;
try { Directory.CreateDirectory(p); return p; } catch { }
}
return AppContext.BaseDirectory;
}
private static void EnsureDataDir()
{
try { Directory.CreateDirectory(DataDir); } catch { }
}
private static void LoadSettings()
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!);
if (!File.Exists(SettingsFile))
{
_guildSettings = new Dictionary<ulong, GuildSettings>();
SafeWrite(SettingsFile, JsonSerializer.Serialize(_guildSettings, CachedJsonSerializerOptions));
Console.WriteLine($"[settings] created new file at {SettingsFile}");
return;
}
var json = File.ReadAllText(SettingsFile);
var data = JsonSerializer.Deserialize<Dictionary<ulong, GuildSettings>>(json)
?? new Dictionary<ulong, GuildSettings>();
// hydrate null collections
foreach (var kv in data)
kv.Value.LogCategories ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
_guildSettings = data;
Console.WriteLine($"[settings] loaded {_guildSettings.Count} guilds from {SettingsFile}");
}
catch (Exception ex)
{
Console.WriteLine($"[settings] load FAILED: {ex.Message}");
_guildSettings = new Dictionary<ulong, GuildSettings>();
}
}
private static void SaveSettings()
{
lock (_settingsSync)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!);
var json = JsonSerializer.Serialize(_guildSettings, CachedJsonSerializerOptions);
SafeWrite(SettingsFile, json);
Console.WriteLine($"[settings] saved {_guildSettings.Count} guilds to {SettingsFile}");
}
catch (Exception ex)
{
Console.WriteLine($"[settings] save FAILED: {ex.Message}");
}
}
}
private static void SafeWrite(string path, string json)
{
var tmp = path + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, path, true);
}
public static void SaveGuildSettings() => SaveSettings();
public static GuildSettings GetSettings(ulong guildId)
{
if (!_guildSettings.ContainsKey(guildId))
_guildSettings[guildId] = new GuildSettings();
return _guildSettings[guildId];
}
public static bool IsLogCategoryEnabled(ulong guildId, LogCategory category)
=> GetSettings(guildId).LogCategories.Contains(category.ToString());
public static bool GetDebugMode(ulong guildId)
=> GetSettings(guildId).DebugEnabled;
public static void SetDebugMode(ulong guildId, bool enabled)
{
GetSettings(guildId).DebugEnabled = enabled;
SaveSettings();
}
public static bool ToggleLogCategory(ulong guildId, LogCategory category)
{
var settings = GetSettings(guildId);
if (settings.LogCategories.Contains(category.ToString()))
settings.LogCategories.Remove(category.ToString());
else
settings.LogCategories.Add(category.ToString());
SaveSettings();
return settings.LogCategories.Contains(category.ToString());
}
private static void LogMessage(ulong guildId, string message, LogCategory category = LogCategory.Other)
{
if (IsLogCategoryEnabled(guildId, category))
Console.WriteLine($"[{category}] {message}");
}
// ----------------------------- Birthdays loop ----------------------------
private async Task CheckBirthdays(Dictionary<string, BirthdayCommand.BirthdayEntry>? birthdayData)
{
var today = DateTime.Today;
var birthdayPath = Path.Combine(AppContext.BaseDirectory, "birthdays.json");
if (!File.Exists(birthdayPath))
{
Console.WriteLine("[BirthdayCheck] No birthdays.json file found.");
return;
}
var birthdayEntries = JsonSerializer.Deserialize<Dictionary<string, BirthdayCommand.BirthdayEntry>>(File.ReadAllText(birthdayPath));
if (birthdayEntries == null)
{
Console.WriteLine("[BirthdayCheck] No valid birthday entries found.");
return;
}
foreach (var (key, entry) in birthdayEntries)
{
var parts = key.Split('-');
if (parts.Length != 2 || !ulong.TryParse(parts[0], out var guildId) || !ulong.TryParse(parts[1], out var userId))
continue;
var guild = _client.GetGuild(guildId);
if (guild == null) continue;
if (entry.Date.Month == today.Month && entry.Date.Day == today.Day)
{
var user = guild.GetUser(userId);
var channel = guild.TextChannels.FirstOrDefault(c =>
guild.CurrentUser.GetPermissions(c).SendMessages &&
(GetSettings(guildId).BirthdayChannelId == 0 || c.Id == GetSettings(guildId).BirthdayChannelId));
if (channel != null)
{
LogMessage(guildId, $"🎉 Birthday match for {entry.Username}", LogCategory.BirthdayCheck);
await channel.SendMessageAsync($"🎉 Happy Birthday {user.Mention}!");
}
else
{
LogMessage(guildId, $"No accessible birthday channel for {entry.Username}", LogCategory.BirthdayCheck);
}
}
else
{
LogMessage(guildId, $"❌ No birthday match today for {entry.Username} ({entry.Date:MM/dd})", LogCategory.BirthdayCheck);
}
}
}
private async Task RepeatBirthdayCheck()
{
while (true)
{
var nextRunLocalMidnight = DateTime.Today.AddDays(1);
var delay = nextRunLocalMidnight - DateTime.Now;
if (delay < TimeSpan.FromSeconds(1)) delay = TimeSpan.FromSeconds(1);
await Task.Delay(delay);
await CheckBirthdaysInternal();
}
}
private async Task CheckBirthdaysInternal()
{
await _birthdayCheckGate.WaitAsync();
try
{
ResetBirthdaySentIfNewDay();
if (!File.Exists(BirthdaysFile))
{
var empty = new Dictionary<string, BirthdayCommand.BirthdayEntry>();
SafeWrite(BirthdaysFile, JsonSerializer.Serialize(empty, CachedJsonSerializerOptions));
return;
}
var json = File.ReadAllText(BirthdaysFile);
var data = JsonSerializer.Deserialize<Dictionary<string, BirthdayCommand.BirthdayEntry>>(json, CachedJsonSerializerOptions);
if (data == null || data.Count == 0) return;
var today = DateTime.Today;
foreach (var kv in data)
{
var key = kv.Key;
var entry = kv.Value;
var parts = key.Split('-');
if (parts.Length != 2 || !ulong.TryParse(parts[0], out var guildId) || !ulong.TryParse(parts[1], out var userId))
continue;
if (entry.Date.Month != today.Month || entry.Date.Day != today.Day) continue;
var guild = _client.GetGuild(guildId);
var user = guild?.GetUser(userId);
var channel = guild?.TextChannels.FirstOrDefault(c =>
guild.CurrentUser.GetPermissions(c).SendMessages &&
(GetSettings(guildId).BirthdayChannelId == 0 || c.Id == GetSettings(guildId).BirthdayChannelId));
if (guild == null || user == null || channel == null) continue;
var sentKey = $"{guildId}:{userId}:{DateTime.UtcNow:yyyy-MM-dd}";
if (_birthdaySentToday.Contains(sentKey)) continue;
await channel.SendMessageAsync($"🎉 Happy Birthday {user.Mention}!");
_birthdaySentToday.Add(sentKey);
}
}
finally
{
_birthdayCheckGate.Release();
}
}
private void ResetBirthdaySentIfNewDay()
{
var today = DateTime.UtcNow.Date;
if (_lastBirthdayResetDate != today)
{
_birthdaySentToday.Clear();
_lastBirthdayResetDate = today;
}
}
// ------------------------------ Other events -----------------------------
private Task HandleUserJoinedAsync(SocketGuildUser user)
{
if (IsLogCategoryEnabled(user.Guild.Id, LogCategory.Register))
Console.WriteLine($"[JOIN] {user.Username} joined {user.Guild.Name}");
return Task.CompletedTask;
}
private Task HandleUserLeftAsync(SocketGuild guild, SocketUser user)
{
if (IsLogCategoryEnabled(guild.Id, LogCategory.Register))
Console.WriteLine($"[LEAVE] {user.Username} left {guild.Name}");
return Task.CompletedTask;
}
private Task HandleVoiceStateAsync(SocketUser user, SocketVoiceState before, SocketVoiceState after)
{
Console.WriteLine($"[VOICE] {user.Username} moved from {before.VoiceChannel?.Name ?? "None"} to {after.VoiceChannel?.Name ?? "None"}");
return Task.CompletedTask;
}
private Task HandlePresenceUpdatedAsync(SocketUser user, SocketPresence before, SocketPresence after)
{
if (user is SocketGuildUser gUser)
{
ulong guildId = gUser.Guild.Id;
if (IsLogCategoryEnabled(guildId, LogCategory.Presence))
Console.WriteLine($"[PRESENCE] {user.Username} went from {before.Status} to {after.Status}");
}
return Task.CompletedTask;
}
private Task HandleReactionAddedAsync(Cacheable<IUserMessage, ulong> cacheable, Cacheable<IMessageChannel, ulong> channel, SocketReaction reaction)
{
if (reaction.User.IsSpecified && reaction.Channel is SocketGuildChannel guildChannel)
{
var guildId = guildChannel.Guild.Id;
if (IsLogCategoryEnabled(guildId, LogCategory.Reaction))
Console.WriteLine($"[REACTION] {reaction.UserId} reacted with {reaction.Emote.Name} in channel {channel.Id}");
}
return Task.CompletedTask;
}
private Task Log(LogMessage msg)
{
// if (msg.Source == "Rest") return Task.CompletedTask; // noisy
Console.WriteLine("[LOG] " + msg.ToString());
return Task.CompletedTask;
}
// --------------------------- Commands discovery --------------------------
private void LoadLegacyCommandsOnce()
{
if (_commandsLoaded) return;
_commandsLoaded = true;
var commandTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(ILegacyCommand).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface);
foreach (var type in commandTypes)
{
if (type.GetCustomAttribute<ObsoleteAttribute>() != null) continue;
if (Activator.CreateInstance(type) is ILegacyCommand instance)
{
_legacyCommands[instance.Name.ToLowerInvariant()] = instance;
}
}
foreach (var g in _client.Guilds)
foreach (var key in _legacyCommands.Keys)
LogMessage(g.Id, $"Loaded legacy command: {_prefix}{key}", LogCategory.Register);
}
public void Dispose()
{
Services?.Dispose();
_http?.Dispose();
_birthdayCheckGate?.Dispose();
}
}
}