-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
2745 lines (2334 loc) · 118 KB
/
Copy pathProgram.cs
File metadata and controls
2745 lines (2334 loc) · 118 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
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 Discord;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using System.Text.RegularExpressions;
using System.Collections.Concurrent;
using Newtonsoft.Json;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace NoPhishing;
// Response model for Anti-Fish API
public class AntiFishResponse
{
public bool Match { get; set; }
public List<AntiFishMatch>? Matches { get; set; }
}
public class AntiFishMatch
{
public string? Domain { get; set; }
public string? Source { get; set; }
public string? Type { get; set; }
public bool Trust { get; set; }
}
// Response model for Phish.Sinking.Yachts API
public class SinkingYachtsResponse
{
public List<string>? Domains { get; set; }
}
// Domain check result for three-tier validation
public class DomainCheckResult
{
public string Domain { get; set; } = string.Empty;
public bool IsScam { get; set; }
public List<string> DetectionSources { get; set; } = new();
public List<string> Details { get; set; } = new();
}
// Guild settings model for persistent storage
public class GuildSettings
{
public ulong GuildId { get; set; }
public bool DefendingModeActive { get; set; }
public DateTime LastActivated { get; set; }
public string? ActivatedBy { get; set; }
}
// Bot settings container
public class BotSettings
{
public Dictionary<ulong, GuildSettings> Guilds { get; set; } = new();
public DateTime LastUpdated { get; set; } = DateTime.Now;
}
// Database entities
[Table("ScamDomains")]
public class ScamDomain
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(255)]
public string Domain { get; set; } = string.Empty;
[MaxLength(100)]
public string? DetectionSource { get; set; }
public DateTime DateAdded { get; set; } = DateTime.UtcNow;
[MaxLength(500)]
public string? Notes { get; set; }
public bool IsActive { get; set; } = true;
}
[Table("DomainReports")]
public class DomainReport
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(255)]
public string Domain { get; set; } = string.Empty;
[MaxLength(500)]
public string? Reason { get; set; }
public ulong ReportedByUserId { get; set; }
[MaxLength(100)]
public string ReportedByUsername { get; set; } = string.Empty;
public ulong? GuildId { get; set; }
[MaxLength(200)]
public string? GuildName { get; set; }
public DateTime ReportDate { get; set; } = DateTime.UtcNow;
public bool IsProcessed { get; set; } = false;
[MaxLength(1000)]
public string? ProcessingNotes { get; set; }
}
[Table("DomainImportLogs")]
public class DomainImportLog
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Source { get; set; } = string.Empty;
public DateTime ImportDate { get; set; } = DateTime.UtcNow;
public int DomainsImported { get; set; }
public int DomainsSkipped { get; set; }
[MaxLength(1000)]
public string? Notes { get; set; }
}
[Table("WhitelistDomains")]
public class WhitelistDomain
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(255)]
public string Domain { get; set; } = string.Empty;
public ulong? GuildId { get; set; } // null = global whitelist
[MaxLength(200)]
public string? GuildName { get; set; }
public ulong AddedByUserId { get; set; }
[MaxLength(100)]
public string AddedByUsername { get; set; } = string.Empty;
public DateTime DateAdded { get; set; } = DateTime.UtcNow;
[MaxLength(500)]
public string? Reason { get; set; }
public bool IsActive { get; set; } = true;
}
[Table("ServerConfigs")]
public class ServerConfig
{
[Key]
public int Id { get; set; }
public ulong GuildId { get; set; }
[MaxLength(200)]
public string? GuildName { get; set; }
public bool AutoDeleteScamMessages { get; set; } = true;
public bool SendWarningMessages { get; set; } = true;
public bool LogDetections { get; set; } = true;
public ulong? LogChannelId { get; set; }
public bool RequireManualReview { get; set; } = false;
public int ScamThreshold { get; set; } = 1; // How many sources need to detect before action
public DateTime LastUpdated { get; set; } = DateTime.UtcNow;
public ulong? UpdatedByUserId { get; set; }
[MaxLength(100)]
public string? UpdatedByUsername { get; set; }
}
[Table("DetectionLogs")]
public class DetectionLog
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(255)]
public string Domain { get; set; } = string.Empty;
public ulong GuildId { get; set; }
[MaxLength(200)]
public string? GuildName { get; set; }
public ulong UserId { get; set; }
[MaxLength(100)]
public string Username { get; set; } = string.Empty;
public ulong ChannelId { get; set; }
[MaxLength(100)]
public string ChannelName { get; set; } = string.Empty;
public ulong MessageId { get; set; }
[MaxLength(2000)]
public string? MessageContent { get; set; }
[MaxLength(500)]
public string DetectionSources { get; set; } = string.Empty; // JSON array of sources
public DateTime DetectionDate { get; set; } = DateTime.UtcNow;
public bool WasDeleted { get; set; } = false;
public bool WasWarned { get; set; } = false;
[MaxLength(500)]
public string? ActionTaken { get; set; }
}
// Database context
public class NoPhishingDbContext : DbContext
{
public DbSet<ScamDomain> ScamDomains { get; set; }
public DbSet<DomainImportLog> DomainImportLogs { get; set; }
public DbSet<DomainReport> DomainReports { get; set; }
public DbSet<WhitelistDomain> WhitelistDomains { get; set; }
public DbSet<ServerConfig> ServerConfigs { get; set; }
public DbSet<DetectionLog> DetectionLogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=nophishing.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ScamDomain>(entity =>
{
entity.HasIndex(e => e.Domain).IsUnique();
entity.Property(e => e.Domain).IsRequired();
});
modelBuilder.Entity<DomainImportLog>(entity =>
{
entity.Property(e => e.Source).IsRequired();
});
modelBuilder.Entity<DomainReport>(entity =>
{
entity.Property(e => e.Domain).IsRequired();
entity.Property(e => e.ReportedByUsername).IsRequired();
entity.HasIndex(e => e.Domain);
entity.HasIndex(e => e.ReportDate);
});
modelBuilder.Entity<WhitelistDomain>(entity =>
{
entity.Property(e => e.Domain).IsRequired();
entity.Property(e => e.AddedByUsername).IsRequired();
entity.HasIndex(e => e.Domain);
entity.HasIndex(e => e.GuildId);
entity.HasIndex(e => new { e.Domain, e.GuildId }).IsUnique();
});
modelBuilder.Entity<ServerConfig>(entity =>
{
entity.HasIndex(e => e.GuildId).IsUnique();
entity.Property(e => e.GuildId).IsRequired();
});
modelBuilder.Entity<DetectionLog>(entity =>
{
entity.Property(e => e.Domain).IsRequired();
entity.Property(e => e.Username).IsRequired();
entity.Property(e => e.ChannelName).IsRequired();
entity.HasIndex(e => e.Domain);
entity.HasIndex(e => e.GuildId);
entity.HasIndex(e => e.DetectionDate);
});
}
}
class Program
{
private static DiscordSocketClient? _client;
private static readonly ConcurrentDictionary<string, bool> _scamDomainsCache = new();
private static readonly string BotSettingsFile = "bot_settings.json";
private static readonly string ScamLinksUrl = "https://raw.githubusercontent.com/Discord-AntiScam/scam-links/main/list.txt";
private static readonly string AntiFishApiUrl = "https://anti-fish.bitflow.dev/check";
private static readonly string SinkingYachtsApiUrl = "https://phish.sinking.yachts/v2/all";
private static BotSettings _botSettings = new();
private static IConfiguration? _configuration;
private static readonly HttpClient _httpClient = new();
private static readonly ConcurrentDictionary<string, List<(string url, string source)>> _pendingScamReveals = new();
private static readonly SemaphoreSlim _databaseLock = new(1, 1);
private static readonly SemaphoreSlim _settingsLock = new(1, 1);
static async Task Main(string[] args)
{
Console.WriteLine("NoPhishing Discord Bot Starting...");
Console.WriteLine("=====================================");
// Build configuration with user secrets
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddUserSecrets<Program>()
.AddEnvironmentVariables()
.Build();
// Configure HttpClient
_httpClient.DefaultRequestHeaders.Add("User-Agent", "NoPhishing-Discord-Bot/1.0");
_httpClient.Timeout = TimeSpan.FromSeconds(30);
Console.WriteLine("Starting database initialization...");
// Initialize database and load scam domains
await InitializeDatabase();
await LoadScamDomainsFromDatabase();
// Download and update scam domains from GitHub
await UpdateScamDomainsFromGitHub();
// Load bot settings (guild defending mode states)
await LoadBotSettings();
var domainCount = await GetScamDomainCountAsync();
Console.WriteLine($"Database initialization complete - {domainCount} domains loaded");
Console.WriteLine($"Bot settings loaded - {_botSettings.Guilds.Count} guild configurations");
Console.WriteLine("=====================================");
// Configure Discord client with only required intents
var config = new DiscordSocketConfig
{
// Only request the gateway intents we actually use:
// - Guilds: Access guild information and settings
// - GuildMessages: Receive messages in guild channels for scanning
// - DirectMessages: Send developer notifications via DM
// - MessageContent: Read message content to extract URLs
GatewayIntents = GatewayIntents.Guilds |
GatewayIntents.GuildMessages |
GatewayIntents.DirectMessages |
GatewayIntents.MessageContent |
GatewayIntents.DirectMessages
};
_client = new DiscordSocketClient(config);
// Subscribe to events
_client.Log += LogAsync;
_client.Ready += ReadyAsync;
_client.MessageReceived += MessageReceivedAsync;
_client.SlashCommandExecuted += SlashCommandHandler;
_client.ButtonExecuted += ButtonExecutedAsync;
_client.ModalSubmitted += ModalSubmittedAsync;
// Get bot token from configuration (user secrets, then environment variables, then appsettings.json)
var token = _configuration["DiscordBotToken"];
if (string.IsNullOrEmpty(token))
{
Console.WriteLine("😞 Discord bot token not found!");
Console.WriteLine();
Console.WriteLine("Please set the token using one of the following methods:");
Console.WriteLine();
Console.WriteLine("1. User Secrets (Recommended for development):");
Console.WriteLine(" dotnet user-secrets set \"DiscordBotToken\" \"your_bot_token_here\"");
Console.WriteLine(" dotnet user-secrets set \"DeveloperUserId\" \"your_discord_user_id_here\"");
Console.WriteLine();
Console.WriteLine("2. Environment Variable:");
Console.WriteLine(" $env:DiscordBotToken=\"your_bot_token_here\"");
Console.WriteLine(" $env:DeveloperUserId=\"your_discord_user_id_here\"");
Console.WriteLine();
Console.WriteLine("3. appsettings.json file:");
Console.WriteLine(" {");
Console.WriteLine(" \"DiscordBotToken\": \"your_bot_token_here\",");
Console.WriteLine(" \"DeveloperUserId\": \"your_discord_user_id_here\"");
Console.WriteLine(" }");
Console.WriteLine();
Console.WriteLine("Note: User secrets are the most secure option for development!");
Console.WriteLine("Note: DeveloperUserId is optional - reports will be saved to database regardless.");
return;
}
Console.WriteLine("😊 Connecting to Discord...");
// Start the bot
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
Console.WriteLine("😄 Bot initialization complete! Press Ctrl+C to stop.");
// Keep the program running
await Task.Delay(-1);
}
private static async Task<bool> CheckUrlWithAntiFishApi(string url)
{
try
{
var requestData = new { message = url };
var json = JsonConvert.SerializeObject(requestData);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(AntiFishApiUrl, content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<AntiFishResponse>(responseContent);
if (result?.Match == true)
{
Console.WriteLine($"Anti-Fish API detected scam: {url}");
// Check if this domain is not in local database and add it
var domain = ExtractDomainFromUrl(url);
if (!await IsScamDomainAsync(url))
{
Console.WriteLine($"New scam domain detected: {domain}");
_ = Task.Run(() => AddScamDomainToDatabase(domain, "Anti-Fish API"));
}
return true;
}
else
{
return false;
}
}
else
{
Console.WriteLine($"Anti-Fish API error: {response.StatusCode}");
return false;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error checking URL with Anti-Fish API: {ex.Message}");
return false;
}
}
private static async Task<bool> CheckDomainWithSinkingYachtsApi(string domain)
{
try
{
Console.WriteLine($"😊 Checking domain with Phish.Sinking.Yachts API: {domain}");
var response = await _httpClient.GetAsync(SinkingYachtsApiUrl);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SinkingYachtsResponse>(responseContent);
if (result?.Domains != null)
{
// Normalize the domain for comparison
var normalizedDomain = domain.ToLowerInvariant();
// Remove protocol if present
if (normalizedDomain.StartsWith("http://"))
normalizedDomain = normalizedDomain[7..];
else if (normalizedDomain.StartsWith("https://"))
normalizedDomain = normalizedDomain[8..];
else if (normalizedDomain.StartsWith("www."))
normalizedDomain = normalizedDomain[4..];
// Extract domain part only
var domainEnd = normalizedDomain.IndexOfAny(new[] { '/', '?', '#' });
if (domainEnd > 0)
normalizedDomain = normalizedDomain[..domainEnd];
// Check if the domain is in the phishing list
var isPhishing = result.Domains.Any(phishDomain =>
normalizedDomain.Contains(phishDomain.ToLowerInvariant()) ||
phishDomain.ToLowerInvariant().Contains(normalizedDomain));
if (isPhishing)
{
Console.WriteLine($"😱 Phish.Sinking.Yachts API detected scam: {domain}");
// Check if this domain is not in local database and add it
if (!await IsScamDomainAsync(domain))
{
Console.WriteLine($"😳 New scam domain detected by Phish.Sinking.Yachts: {normalizedDomain}");
_ = Task.Run(() => AddScamDomainToDatabase(normalizedDomain, "Phish.Sinking.Yachts"));
}
return true;
}
else
{
Console.WriteLine($"😊 Phish.Sinking.Yachts API: Domain appears safe: {domain}");
return false;
}
}
else
{
Console.WriteLine("😐 Phish.Sinking.Yachts API returned no domains data");
return false;
}
}
else
{
Console.WriteLine($"😞 Phish.Sinking.Yachts API error: {response.StatusCode} {response.ReasonPhrase}");
return false;
}
}
catch (Exception ex)
{
Console.WriteLine($"😞 Error checking domain with Phish.Sinking.Yachts API: {ex.Message}");
return false;
}
}
private static async Task UpdateScamDomainsFromGitHub()
{
try
{
Console.WriteLine("Fetching latest scam links from GitHub...");
var response = await _httpClient.GetAsync(ScamLinksUrl);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrWhiteSpace(content))
{
await ImportDomainsFromGitHub(content);
var lines = content.Split('\n', StringSplitOptions.RemoveEmptyEntries);
var domainCount = lines.Count(line => !string.IsNullOrWhiteSpace(line.Trim()) && !line.Trim().StartsWith("#"));
Console.WriteLine($"Successfully processed {domainCount} domains from GitHub");
}
else
{
Console.WriteLine("GitHub response was empty, keeping existing database");
}
}
else
{
Console.WriteLine($"Failed to fetch scam links from GitHub: {response.StatusCode}");
Console.WriteLine("Will use existing database entries");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error while fetching scam links: {ex.Message}");
Console.WriteLine("Will use existing database entries");
}
}
private static async Task ReadyAsync()
{
Console.WriteLine($"{_client?.CurrentUser} is connected and ready!");
// Set bot status and activity
if (_client != null)
{
await _client.SetStatusAsync(UserStatus.DoNotDisturb);
await _client.SetGameAsync($"{_client.Guilds.Count} guilds!", type: ActivityType.Watching);
Console.WriteLine($"Bot status set to DND with activity: Watching {_client.Guilds.Count} guilds...");
}
var activeGuilds = _botSettings.Guilds.Values.Count(g => g.DefendingModeActive);
// Use cache count for faster startup, database count will be accurate from previous load
var domainCount = _scamDomainsCache.Count;
Console.WriteLine($"Protection Status: {activeGuilds} guild(s) with defending mode active");
Console.WriteLine($"Database Status: {domainCount} scam domains loaded");
Console.WriteLine($"Protection Layers: Local Database + APIs");
Console.WriteLine($"Startup completed at: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
Console.WriteLine("=====================================");
// Register slash commands asynchronously without blocking the gateway
_ = Task.Run(async () =>
{
try
{
// Add a small delay to ensure the bot is fully connected
await Task.Delay(3000);
await RegisterSlashCommands();
}
catch (Exception ex)
{
Console.WriteLine($"Error registering slash commands in background: {ex.Message}");
}
});
}
private static async Task RegisterSlashCommands()
{
try
{
Console.WriteLine("Checking existing slash commands...");
// Get existing commands to avoid re-registering
var existingCommands = new List<string>();
if (_client != null)
{
try
{
var currentCommands = await _client.GetGlobalApplicationCommandsAsync();
existingCommands = currentCommands.Select(c => c.Name).ToList();
if (existingCommands.Count > 0)
{
Console.WriteLine($"Found {existingCommands.Count} existing commands: {string.Join(", ", existingCommands)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"⚠️ Could not fetch existing commands: {ex.Message}");
}
}
Console.WriteLine("Preparing slash commands for registration...");
var commands = new List<SlashCommandBuilder>
{
new SlashCommandBuilder()
.WithName("activate")
.WithDescription("Activate defending mode - bot will scan messages for scam links"),
new SlashCommandBuilder()
.WithName("deactivate")
.WithDescription("Deactivate defending mode - bot will stop scanning messages"),
new SlashCommandBuilder()
.WithName("status")
.WithDescription("Check the current defending mode status"),
new SlashCommandBuilder()
.WithName("update")
.WithDescription("Manually update scam links database from GitHub"),
new SlashCommandBuilder()
.WithName("check")
.WithDescription("Check a domain for scams using three-tier validation")
.AddOption("domain", ApplicationCommandOptionType.String, "The domain to check (e.g., example.com)", isRequired: true),
new SlashCommandBuilder()
.WithName("report")
.WithDescription("Report a potentially malicious domain to the developers"),
new SlashCommandBuilder()
.WithName("whitelist")
.WithDescription("Manage trusted domains that should never be flagged as scams")
.AddOption("action", ApplicationCommandOptionType.String, "Action to perform", isRequired: true, choices: new ApplicationCommandOptionChoiceProperties[]
{
new() { Name = "add", Value = "add" },
new() { Name = "remove", Value = "remove" },
new() { Name = "list", Value = "list" }
})
.AddOption("domain", ApplicationCommandOptionType.String, "Domain to add/remove (not needed for list)", isRequired: false)
.AddOption("reason", ApplicationCommandOptionType.String, "Reason for whitelist action", isRequired: false),
new SlashCommandBuilder()
.WithName("blacklist")
.WithDescription("Manage domains that should be flagged as scams")
.AddOption("action", ApplicationCommandOptionType.String, "Action to perform", isRequired: true, choices: new ApplicationCommandOptionChoiceProperties[]
{
new() { Name = "add", Value = "add" },
new() { Name = "remove", Value = "remove" },
new() { Name = "list", Value = "list" }
})
.AddOption("domain", ApplicationCommandOptionType.String, "Domain to add/remove (not needed for list)", isRequired: false)
.AddOption("reason", ApplicationCommandOptionType.String, "Reason for blacklist action", isRequired: false),
new SlashCommandBuilder()
.WithName("stats")
.WithDescription("Show protection statistics for this server"),
new SlashCommandBuilder()
.WithName("config")
.WithDescription("Manage bot configuration for this server")
.AddOption("setting", ApplicationCommandOptionType.String, "Setting to configure", isRequired: true, choices: new ApplicationCommandOptionChoiceProperties[]
{
new() { Name = "auto_delete", Value = "auto_delete" },
new() { Name = "send_warnings", Value = "send_warnings" },
new() { Name = "log_detections", Value = "log_detections" },
new() { Name = "log_channel", Value = "log_channel" },
new() { Name = "manual_review", Value = "manual_review" },
new() { Name = "scam_threshold", Value = "scam_threshold" },
new() { Name = "show", Value = "show" }
})
.AddOption("value", ApplicationCommandOptionType.String, "New value for the setting", isRequired: false),
new SlashCommandBuilder()
.WithName("history")
.WithDescription("View domain detection history")
.AddOption("domain", ApplicationCommandOptionType.String, "Specific domain to check history for", isRequired: false)
.AddOption("days", ApplicationCommandOptionType.Integer, "Number of days to look back (default: 7)", isRequired: false)
};
if (_client != null)
{
// Filter out commands that are already registered
var commandsToRegister = commands.Where(cmd => !existingCommands.Contains(cmd.Name)).ToList();
if (commandsToRegister.Count == 0)
{
Console.WriteLine("✅ All commands are already registered! No updates needed.");
return;
}
Console.WriteLine($"🔄 Need to register {commandsToRegister.Count} new commands (skipping {commands.Count - commandsToRegister.Count} existing)");
// Register commands sequentially to avoid rate limits
Console.WriteLine($"Registering {commandsToRegister.Count} commands with rate limit protection...");
var successCount = 0;
var failedCommands = new List<string>();
for (int i = 0; i < commandsToRegister.Count; i++)
{
var command = commandsToRegister[i];
try
{
await _client.CreateGlobalApplicationCommandAsync(command.Build());
successCount++;
Console.WriteLine($"✅ Registered command {i + 1}/{commandsToRegister.Count}: /{command.Name}");
// Add delay between commands to respect rate limits (except for the last command)
if (i < commandsToRegister.Count - 1)
{
await Task.Delay(2000); // 2 second delay between each command
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Failed to register command /{command.Name}: {ex.Message}");
failedCommands.Add(command.Name);
// If we hit a rate limit, wait longer before continuing
if (ex.Message.Contains("rate limit") || ex.Message.Contains("timed out"))
{
Console.WriteLine("⏳ Rate limit detected, waiting 5 seconds...");
await Task.Delay(5000);
}
}
}
if (successCount == commandsToRegister.Count)
{
Console.WriteLine($"🎉 Successfully registered all {successCount} new slash commands!");
Console.WriteLine($"📊 Total commands available: {existingCommands.Count + successCount}");
}
else
{
Console.WriteLine($"⚠️ Registered {successCount}/{commandsToRegister.Count} new commands successfully.");
if (failedCommands.Count > 0)
{
Console.WriteLine($"❌ Failed commands: {string.Join(", ", failedCommands)}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Critical error during slash command registration: {ex.Message}");
// Log more details for debugging
if (ex.InnerException != null)
Console.WriteLine($" Inner exception: {ex.InnerException.Message}");
// Check if it's a rate limit issue
if (ex.Message.Contains("rate limit") || ex.Message.Contains("timed out"))
{
Console.WriteLine("⚠️ This appears to be a rate limiting issue.");
Console.WriteLine("💡 The bot will still work with existing commands. New commands will be available after Discord's rate limit resets.");
Console.WriteLine("💡 To avoid this in the future, consider registering commands during off-peak hours.");
}
else
{
Console.WriteLine("⚠️ Command registration failed, but the bot will continue with existing functionality.");
}
}
}
private static async Task MessageReceivedAsync(SocketMessage message)
{
// Ignore messages from bots (including ourselves)
if (message.Author.IsBot)
return;
// Get guild ID for this message
var guildId = (message.Channel as SocketGuildChannel)?.Guild?.Id ?? 0;
// Check if defending mode is active for this guild
if (!IsDefendingModeActive(guildId))
return;
// Check if message contains URLs
var urls = ExtractUrls(message.Content);
if (urls.Any())
{
var scamUrls = new List<(string url, string source)>();
var newDomainsDetected = new List<string>();
foreach (var url in urls)
{
// Extract domain from URL for checking
var domain = ExtractDomainFromUrl(url);
// Check if domain is whitelisted first
if (await IsWhitelistedAsync(domain, guildId))
{
Console.WriteLine($"Skipping whitelisted domain: {domain}");
continue;
}
// First check local database (fastest)
if (await IsScamDomainAsync(url))
{
scamUrls.Add((url, "Local Database"));
}
else
{
// If not found locally, check with both APIs as fallback
// Note: For real-time message scanning, we'll use a lighter approach
// to avoid too much delay. Full three-tier is available via /check command
var isScamFromApi = await CheckUrlWithAntiFishApi(url);
if (isScamFromApi)
{
scamUrls.Add((url, "Anti-Fish API"));
newDomainsDetected.Add($"{domain} (Anti-Fish API)");
}
else
{
// Only check Sinking Yachts if Anti-Fish didn't detect anything
// This prevents excessive API calls during message scanning
var isSinkingYachtsScam = await CheckDomainWithSinkingYachtsApi(domain);
if (isSinkingYachtsScam)
{
scamUrls.Add((url, "Phish.Sinking.Yachts"));
newDomainsDetected.Add($"{domain} (Phish.Sinking.Yachts)");
}
}
}
}
if (scamUrls.Any())
{
// Log newly detected domains
if (newDomainsDetected.Any())
{
Console.WriteLine($"😳 New scam domains detected and added to database:");
foreach (var newDomain in newDomainsDetected)
{
Console.WriteLine($" - {newDomain}");
}
var totalCount = await GetScamDomainCountAsync();
Console.WriteLine($"😊 Database now contains {totalCount} active domains");
}
await HandleScamDetection(message, scamUrls);
}
}
}
private static string ExtractDomainFromUrl(string url)
{
try
{
// Normalize the URL
var normalizedUrl = url.ToLowerInvariant();
// Remove protocol if present
if (normalizedUrl.StartsWith("http://"))
normalizedUrl = normalizedUrl[7..];
else if (normalizedUrl.StartsWith("https://"))
normalizedUrl = normalizedUrl[8..];
else if (normalizedUrl.StartsWith("www."))
normalizedUrl = normalizedUrl[4..];
// Extract domain part
var domainEnd = normalizedUrl.IndexOfAny(new[] { '/', '?', '#' });
if (domainEnd > 0)
normalizedUrl = normalizedUrl[..domainEnd];
return normalizedUrl;
}
catch
{
return url; // Return original if parsing fails
}
}
private static async Task<bool> IsScamDomainAsync(string domain)
{
var normalizedDomain = ExtractDomainFromUrl(domain).ToLowerInvariant();
// Check cache first
if (_scamDomainsCache.ContainsKey(normalizedDomain))
return true;
// Check database if not in cache
try
{
using var context = new NoPhishingDbContext();
var exists = await context.ScamDomains
.AnyAsync(d => d.IsActive && d.Domain.ToLower() == normalizedDomain);
if (exists)
{
_scamDomainsCache[normalizedDomain] = true;
}
return exists;
}
catch (Exception ex)
{
Console.WriteLine($"😞 Error checking domain in database: {ex.Message}");
return false;
}
}
private static async Task AddScamDomainToDatabase(string domain, string detectionSource, string? notes = null)
{
try
{
await _databaseLock.WaitAsync();
var cleanDomain = ExtractDomainFromUrl(domain).ToLowerInvariant();
// Check if already exists in cache
if (_scamDomainsCache.ContainsKey(cleanDomain))
{
return;
}
using var context = new NoPhishingDbContext();
// Check if domain already exists in database
var existingDomain = await context.ScamDomains
.FirstOrDefaultAsync(d => d.Domain.ToLower() == cleanDomain);
if (existingDomain != null)
{
if (!existingDomain.IsActive)
{
// Reactivate if it was deactivated
existingDomain.IsActive = true;
existingDomain.DateAdded = DateTime.UtcNow;
existingDomain.DetectionSource = detectionSource;
existingDomain.Notes = notes;
await context.SaveChangesAsync();
_scamDomainsCache[cleanDomain] = true;
Console.WriteLine($"Reactivated scam domain: {cleanDomain}");
}
return;
}
// Add new domain
var newDomain = new ScamDomain
{
Domain = cleanDomain,
DetectionSource = detectionSource,
DateAdded = DateTime.UtcNow,
Notes = notes,
IsActive = true
};
context.ScamDomains.Add(newDomain);
await context.SaveChangesAsync();
// Add to cache
_scamDomainsCache[cleanDomain] = true;
Console.WriteLine($"Added new scam domain: {cleanDomain} (detected by {detectionSource})");
}
catch (Exception ex)
{
Console.WriteLine($"Error adding domain to database: {ex.Message}");
}
finally
{
_databaseLock.Release();
}