-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGiveawayBot.cs
More file actions
9626 lines (8547 loc) · 469 KB
/
GiveawayBot.cs
File metadata and controls
9626 lines (8547 loc) · 469 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
// Suppress "modernization" suggestions to maintain compatibility with Streamer.bot's internal compiler
// Streamer.bot uses .NET Framework 4.8 / C# 7.3
// CI Verification Trigger environment)
#pragma warning disable IDE0028 // Simplify collection initialization
#pragma warning disable IDE0300 // Use collection expression
#pragma warning disable IDE0301 // Use collection expression
#pragma warning disable IDE0090 // 'new' expression can be simplified
#pragma warning disable IDE0290 // Use primary constructor
#pragma warning disable IDE0055 // Fix formatting
#pragma warning disable IDE0034 // Simplify default expression
#pragma warning disable IDE0001 // Simplify name
#pragma warning disable IDE0074 // Use compound assignment
#pragma warning disable IDE0063 // 'using' statement can be simplified
#pragma warning disable IDE1006 // Naming styles
#pragma warning disable CA1825 // Avoid zero-length array allocations
#pragma warning disable RCS1077 // Optimize LINQ
#pragma warning disable RCS1036 // Optimize LINQ
#pragma warning disable RCS1079 // Throwing exceptions in finally
#pragma warning disable CS8603 // Possible null reference return
#pragma warning disable CS8601 // Possible null reference assignment
#pragma warning disable CS8618 // Non-nullable property initialization
#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member
#pragma warning disable CS8604 // Possible null reference argument
#pragma warning disable CS8602 // Dereference of a possibly null reference
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type
#pragma warning disable CS8605 // Unboxing a possibly null value
#pragma warning disable IDE0017 // Simplify object initialization
#pragma warning disable IDE0019 // Use pattern matching
#pragma warning disable IDE0078 // Use pattern matching
#pragma warning disable IDE0083 // Use pattern matching
// Streamer.bot specific / C# 7.3 Limits
#pragma warning disable CA1850 // Prefer static 'HashData' over 'ComputeHash' (.NET 5+)
#pragma warning disable CA2249 // Consider using 'string.Contains' with char (.NET Core 2.1+)
#pragma warning disable IDE0066 // Convert switch statement to expression (C# 8.0)
#pragma warning disable CA1854 // Prefer 'TryGetValue' (Keep simple)
#pragma warning disable CA1836 // Prefer 'IsEmpty' over 'Count' (Compatibility)
#pragma warning disable IDE0059 // Unnecessary assignment (Regex discard)
#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable IDE0028 // Duplicate suppression (just in case)
// css_ref System.Net.Http.dll
// css_ref Newtonsoft.Json.dll
// css_ref System.Core.dll
// css_ref System.Xml.Linq.dll
// css_ref Microsoft.CSharp.dll
#region Imports & Assembly Attributes
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
#endregion
// UNCONDITIONAL SUPPRESSION for Streamer.bot (Legacy C# Environment) - Required for valid compilation
#pragma warning disable IDE0028 // Simplify collection initialization
#pragma warning disable IDE0300 // Use collection expression
#pragma warning disable IDE0301 // Use collection expression
#pragma warning disable IDE0090 // 'new' expression can be simplified
#pragma warning disable IDE0290 // Use primary constructor
#pragma warning disable IDE0055 // Fix formatting
#pragma warning disable IDE0034 // Simplify default expression
#pragma warning disable IDE0001 // Simplify name
#pragma warning disable IDE1006 // Naming styles
#pragma warning disable CA1825 // Avoid zero-length array allocations
#pragma warning disable RCS1077 // Optimize LINQ
#pragma warning disable RCS1036 // Optimize LINQ
#pragma warning disable RCS1079 // Throwing exceptions in finally
#pragma warning disable CS8603 // Possible null reference return
#pragma warning disable CS8601 // Possible null reference assignment
#pragma warning disable CS8618 // Non-nullable property initialization
#pragma warning disable CS8604 // Possible null reference argument
#pragma warning disable CS8602 // Dereference of a possibly null reference
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type
#pragma warning disable CS8605 // Unboxing a possibly null value
#pragma warning disable IDE0017 // Simplify object initialization
#pragma warning disable IDE0019 // Use pattern matching
#pragma warning disable IDE0078 // Use pattern matching
#pragma warning disable IDE0083 // Use pattern matching
#if EXTERNAL_EDITOR || GIVEAWAY_TESTS
namespace StreamerBot
{
#pragma warning disable IDE0028 // Simplify collection initialization
#pragma warning disable IDE0300 // Use collection expression
#pragma warning disable IDE0301 // Use collection expression
#pragma warning disable IDE0090 // 'new' expression can be simplified
#pragma warning disable IDE0290 // Use primary constructor
#pragma warning disable IDE0055 // Fix formatting
#pragma warning disable IDE0034 // Simplify default expression
#pragma warning disable IDE0001 // Simplify name
#pragma warning disable IDE1006 // Naming styles
#pragma warning disable CA1825 // Avoid zero-length array allocations
#pragma warning disable RCS1077 // Optimize LINQ
#pragma warning disable RCS1036 // Optimize LINQ
#pragma warning disable RCS1079 // Throwing exceptions in finally
#pragma warning disable CS8603 // Possible null reference return
#pragma warning disable CS8601 // Possible null reference assignment
#pragma warning disable CS8618 // Non-nullable property initialization
#pragma warning disable CS8604 // Possible null reference argument
#pragma warning disable CS8602 // Dereference of a possibly null reference
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type
#pragma warning disable CS8605 // Unboxing a possibly null value
#pragma warning disable IDE0017 // Simplify object initialization
#pragma warning disable IDE0019 // Use pattern matching
#pragma warning disable IDE0078 // Use pattern matching
#pragma warning disable IDE0083 // Use pattern matching
#endif
#region Interfaces
/// <summary>
/// Interface wrapper for Streamer.bot's `CPH` object.
/// Allows us to mock the CPH interaction for unit testing outside of Streamer.bot.
/// This abstraction is crucial for maintaining testability and decoupling the bot logic from the runtime environment.
/// </summary>
public interface IGiveawayCPH
{
// Logging Methods
/// <summary>Logs an informational message to the Streamer.bot log.</summary>
void LogInfo(string message);
/// <summary>Logs a warning message to the Streamer.bot log.</summary>
void LogWarn(string message);
/// <summary>Logs a debug message to the Streamer.bot log (requires verbose logging).</summary>
void LogDebug(string message);
/// <summary>Logs an error message to the Streamer.bot log.</summary>
void LogError(string message);
/// <summary>Logs a trace message for deep debugging.</summary>
void LogTrace(string message);
/// <summary>Logs a verbose message.</summary>
void LogVerbose(string message);
/// <summary>Logs a fatal error message, typically indicating a crash or critical failure.</summary>
void LogFatal(string message);
// Argument Handling
/// <summary>
/// Attempts to retrieving an argument from the action's argument dictionary.
/// </summary>
/// <typeparam name="T">The expected type of the argument.</typeparam>
/// <param name="argName">The key name of the argument.</param>
/// <param name="value">The output value if found.</param>
/// <returns>True if found and successfully converted, otherwise false.</returns>
bool TryGetArg<T>(string argName, out T value);
// Variable Management
/// <summary>Retrieves a global variable from Streamer.bot's persistent store.</summary>
T GetGlobalVar<T>(string varName, bool persisted = true);
/// <summary>Sets a global variable in Streamer.bot's persistent store.</summary>
void SetGlobalVar(string varName, object value, bool persisted = true);
/// <summary>Retrieves a user-specific variable.</summary>
T GetUserVar<T>(string userId, string varName, bool persisted = true);
/// <summary>Sets a user-specific variable.</summary>
void SetUserVar(string userId, string varName, object value, bool persisted = true);
/// <summary>Gets a list of all global variable names (used for cleanup).</summary>
List<string> GetGlobalVarNames(bool persisted = true);
/// <summary>Removes a global variable from the store.</summary>
void UnsetGlobalVar(string varName, bool persisted = true);
// Platform Actions
/// <summary>Sends a chat message to the active platform (Twitch/YouTube/Kick).</summary>
void SendMessage(string message, bool bot = true);
/// <summary>Sends a chat message specifically to YouTube.</summary>
void SendYouTubeMessage(string message);
/// <summary>Sends a chat message specifically to Kick.</summary>
void SendKickMessage(string message);
/// <summary>Replies to a specific message on Twitch.</summary>
void TwitchReplyToMessage(string message, string replyId, bool useBot = true, bool fallback = true);
// State Checks
/// <summary>Checks if the Twitch broadcaster is live.</summary>
bool IsTwitchLive();
/// <summary>Checks if the YouTube broadcaster is live.</summary>
bool IsYouTubeLive();
/// <summary>Checks if the Kick broadcaster is live.</summary>
bool IsKickLive();
// User Status
/// <summary>Checks if a user is following the channel on Twitch.</summary>
bool TwitchIsUserFollower(string userId);
/// <summary>Checks if a user is subscribed to the channel on Twitch.</summary>
bool TwitchIsUserSubscriber(string userId);
// OBS Integration
/// <summary>Updates a browser source URL in OBS via Streamer.bot.</summary>
void ObsSetBrowserSource(string scene, string source, string url);
// UI & Core
/// <summary>Shows a Windows toast notification via Streamer.bot.</summary>
void ShowToastNotification(string title, string message);
/// <summary>Executes another Streamer.bot action by name.</summary>
bool RunAction(string actionName, bool runImmediately = true);
/// <summary>Gets the event trigger type.</summary>
object GetEventType();
// Internal
/// <summary>Access to the internal file logger instance.</summary>
FileLogger Logger { get; set; }
}
#endregion
/*
* Streamer.bot Giveaway Bot
*
* Target Environment: Streamer.bot Execute C# Code Action
* Compatibility: .NET Framework 4.8 / C# 7.3
*
* Description:
* A comprehensive giveaway management system for Streamer.bot.
* Features include multi-profile support, anti-loop protection,
* Bidirectional Config Sync (Mirror Mode), Separate Game Name Dumps,
* Wheel of Names integration, OBS control, and robust logging/persistence.
*
* Rules & constraints:
* - Must reside in a single file for CPHInline copy/paste deployment.
* - Must NOT use C# 8.0+ features (e.g. file-scoped namespaces, records).
* - Must handle CPH interaction via reflection or direct calls safely.
*/
/*--------------------------------------------*/
#region GiveawayBotHostBase
#if EXTERNAL_EDITOR || GIVEAWAY_TESTS
// Base class validation to ensure editor compatibility without external references
public class GiveawayBotHostBase
{
public dynamic CPH { get; set; }
// Mock args for editor support
public Dictionary<string, object> args { get; set; } = new Dictionary<string, object>();
}
public class GiveawayBot : GiveawayBotHostBase
#else
public class CPHInline
#endif
#endregion
/*--------------------------------------------*/
#region GiveawayBot Main Class
{
// Singleton instance to maintain state across multiple executions of the Execute() method
private static GiveawayManager _manager;
// Lock object to ensure thread-safe initialization of the singleton
private static readonly object _initLock = new object();
// Identity Constants
private const string ActionName = "Giveaway Bot";
public const string Version = GiveawayManager.Version;
/// <summary>
/// Entry point for the Streamer.bot Action.
/// This method is called every time the action is triggered.
/// It ensures the manager is initialized and then processes the current trigger.
/// </summary>
public bool Execute()
{
var adapter = new CPHAdapter(CPH, args);
// Restore logger from singleton if it exists
if (_manager != null)
{
adapter.Logger = _manager.Logger;
// Force reset the thread-local logging flag in case a Previous execution on this thread hung
FileLogger.ResetLoggingFlag();
}
// Safe RunMode check to avoid re-entrancy during the very first LogTrace
string runMode = "Unknown";
try { runMode = ConfigLoader.GetRunMode(adapter); } catch { }
adapter.LogTrace($"[GiveawayBot] [Execute] >>> Entry point triggered. RunMode: {runMode}");
try
{
EnsureInitialized(adapter);
// Pass the CPH adapter to ensure the Logger and state persist correctly
return _manager.ProcessTrigger(adapter).GetAwaiter().GetResult();
}
catch (Exception ex)
{
adapter.LogFatal($"[GiveawayBot] [Execute] Unhandled exception in root: {ex.Message}");
// Fallback direct bot log if adapter fails
try { CPH.LogError($"[GiveawayBot] [Execute] FATAL CRASH: {ex.Message}"); } catch { }
return false;
}
finally
{
adapter.LogTrace("[GiveawayBot] [Execute] <<< Exit point reached.");
}
}
private static void EnsureInitialized(CPHAdapter adapter)
{
if (_manager != null) return;
lock (_initLock)
{
if (_manager != null) return;
adapter.LogDebug("[GiveawayBot] [EnsureInitialized] Initializing Giveaway Manager singleton...");
_manager = new GiveawayManager
{
Logger = new FileLogger()
};
adapter.Logger = _manager.Logger;
adapter.LogVerbose("[GiveawayBot] [EnsureInitialized] FileLogger initialized and attached to CPH adapter.");
_manager.Initialize(adapter);
adapter.LogInfo("[GiveawayBot] [EnsureInitialized] Giveaway System initialized successfully.");
}
}
}
#endregion
#region Localization
/// <summary>
/// Static Localization Helper.
/// Manages default strings and user overrides from config.
/// </summary>
public static class Loc
{
private static readonly Dictionary<string, string> _defaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
// Entries
{ "EntryAccepted", "Entry accepted! Total tickets: {0} ({1})" }, // {0}=Tickets, {1}=Luck
{ "EntryAccepted_NoLuck", "Entry accepted! Total tickets: {0}" },
{ "EntryRejected_MaxEntries", "You have reached the maximum number of entries." },
{ "EntryRejected_TooNew", "Your account is too new to join this giveaway." },
{ "EntryRejected_LowEntropy", "Entry rejected by anti-bot protection." },
{ "EntryRejected_Blacklisted", "You are not allowed to join this giveaway." },
{ "EntryRejected_NotFollower", "Sorry, you must be a follower to join this giveaway!" },
{ "EntryRejected_NotSubscriber", "Sorry, you must be a subscriber to join this giveaway!" },
{ "EntryRejected_GiveawayClosed", "The giveaway is currently closed." },
// Toasts & UI
{ "ToastTitle", "Giveaway Bot" },
{ "ToastTitle_Security", "Giveaway Bot - Security" },
{ "ToastMsg_NewEntry", "New Entry: {0}" },
{ "ToastMsg_Rejected_Pattern", "Entry Rejected: {0} (Username Pattern)" },
{ "EntryRejected_GW2Pattern", "Sorry @{0}, please include your Guild Wars 2 account name (Format: Name.1234)" },
{ "ToastMsg_Rejected_Age", "Entry Rejected: {0} (Account Too New)" },
{ "ToastMsg_SpamDetected", "⚠ SPAM DETECTED: {0} (Rate Limit)" },
{ "ToastMsg_Opened", "Giveaway '{0}' is OPEN!" },
{ "ToastMsg_Closed", "Giveaway '{0}' is CLOSED!" },
{ "ToastMsg_Winner", "Winner: {0}!" },
// Draw
{ "WinnerSelected", "🎉 Congratulations @{0}! You have won the giveaway!" },
{ "WinnerDrawn_Log", "Winner drawn: {0} (Tickets: {1})" },
// State
{ "GiveawayOpened", "🎟 The giveaway for '{0}' is now OPEN! Type !enter to join." },
{ "GiveawayOpened_NoProfile", "🎟 The giveaway is now OPEN! Type !enter to join." },
{ "GiveawayClosed", "🚫 The giveaway is now CLOSED! No more entries accepted." },
{ "GiveawayFull", "🚫 The giveaway is FULL! No more entries accepted." },
{ "TimerUpdated", "⏳ Time limit updated! Ends in {0}." },
// Update Service
{ "Update_CheckFailed", "❌ Failed to fetch release info." },
{ "Update_Checking", "🔄 Checking GitHub for updates..." },
{ "Update_Available", "⬇ Update Available: {0}" },
{ "Update_Downloaded", "✅ Update {0} downloaded to updates/{1}" },
{ "Update_FailedDownload", "❌ Failed to download update" },
{ "Update_UpToDate", "✅ You are on the latest version ({0})." },
{ "Update_ErrorTitle", "Update Error" },
{ "Update_ErrorUnexpected", "❌ Unexpected error." },
// Errors
{ "Error_Loop", "Loop detected. Setup error." },
{ "Error_System", "A system error occurred." },
{ "Error_NoPermission", "You do not have permission to use this command." }
};
public static IEnumerable<string> Keys => _defaults.Keys;
/// <summary>
/// Common toast title localization key. Use this constant instead of hardcoding "ToastTitle" string.
/// </summary>
public const string ToastTitle = "ToastTitle";
/// <summary>
/// Gets a localized string for the specified key, with optional formatting arguments.
/// Uses global custom strings and defaults (no profile-specific override).
/// </summary>
/// <param name="key">Localization key to retrieve</param>
/// <param name="args">Optional formatting arguments for placeholders like {0}, {1}, etc.</param>
/// <returns>Formatted localized string</returns>
public static string Get(string key, params object[] args)
{
return Get(key, null, args);
}
/// <summary>
/// Gets a global localized string, explicitly bypassing profile-specific overrides.
/// Use this for system messages (like update notifications) that should always use
/// the same text regardless of which giveaway profile is active.
/// </summary>
/// <param name="key">Localization key to retrieve</param>
/// <param name="args">Optional formatting arguments for placeholders like {0}, {1}, etc.</param>
/// <returns>Formatted localized string from global custom strings or defaults</returns>
public static string GetGlobal(string key, params object[] args)
{
return Get(key, null, args);
}
/// <summary>
/// Gets a localized string with optional profile-specific override support.
/// Resolution order: profile messages → global custom strings → defaults.
/// </summary>
/// <param name="key">Localization key to retrieve</param>
/// <param name="profileName">Optional profile name for profile-specific message lookup</param>
/// <param name="args">Optional formatting arguments for placeholders like {0}, {1}, etc.</param>
/// <returns>Formatted localized string</returns>
public static string Get(string key, string profileName, params object[] args)
{
string template = null;
// Try Profile Overrides
if (!string.IsNullOrEmpty(profileName) && GiveawayManager.GlobalConfig != null)
{
if (GiveawayManager.GlobalConfig.Profiles.TryGetValue(profileName, out var profile) && profile.Messages != null)
{
if (profile.Messages.TryGetValue(key, out var profileStr))
{
template = profileStr;
}
}
}
// Try Global Custom Strings
if (template == null && GiveawayManager.GlobalConfig?.Globals?.CustomStrings != null)
{
if (GiveawayManager.GlobalConfig.Globals.CustomStrings.TryGetValue(key, out var overrideStr))
{
template = overrideStr;
}
}
// Try Default Dictionary
if (template == null && _defaults.TryGetValue(key, out var defStr))
{
template = defStr;
}
// Fallback
if (template == null) return $"[{key}]";
// Randomize (Pick variant if | or , exists)
template = GiveawayManager.PickRandomMessage(template);
// Format
if (args != null && args.Length > 0)
{
try { return string.Format(template, args); }
catch { return template; } // Fail safe
}
return template;
}
}
#endregion
#region Metrics System
/// <summary>
/// Represents aggregated metrics data across all giveaway profiles.
/// </summary>
public class MetricsContainer
{
// Giveaway Analytics Metrics
/// <summary>Total entries across all profiles.</summary>
public long EntriesTotal { get; set; }
/// <summary>Total wins across all profiles.</summary>
public long WinsTotal { get; set; }
/// <summary>Total draws executed across all profiles.</summary>
public long DrawsTotal { get; set; }
/// <summary>Per-profile metrics breakdown.</summary>
public Dictionary<string, ProfileMetrics> Profiles { get; set; }
// Legacy Diagnostic Metrics (for backward compatibility)
public Dictionary<string, long> GlobalMetrics { get; set; } = new Dictionary<string, long>();
public Dictionary<string, UserMetricSet> UserMetrics { get; set; } = new Dictionary<string, UserMetricSet>();
public DateTime LastUpdated { get; set; }
// Enhanced metrics for Phase 9 monitoring
/// <summary>Current size of the message ID deduplication cache</summary>
public int MessageIdCacheSize { get; set; }
/// <summary>Count of message ID cleanup operations performed</summary>
public int MessageIdCleanupCount { get; set; }
/// <summary>Total count of loop detections across all layers</summary>
public int LoopDetectedCount { get; set; }
/// <summary>Count of loops detected via message ID deduplication</summary>
public int LoopDetectedByMsgId { get; set; }
/// <summary>Count of loops detected via invisible token check</summary>
public int LoopDetectedByToken { get; set; }
/// <summary>Count of loops detected via bot source flag</summary>
public int LoopDetectedByBotFlag { get; set; }
/// <summary>Count of configuration reloads</summary>
public int ConfigReloadCount { get; set; }
/// <summary>Count of file I/O errors</summary>
public int FileIOErrors { get; set; }
// Phase 10 additional metrics
/// <summary>Total time spent processing entries (milliseconds)</summary>
public long TotalEntryProcessingMs { get; set; }
/// <summary>Count of entries processed (for average calculation)</summary>
public int EntriesProcessedCount { get; set; }
/// <summary>Count of winner draw attempts</summary>
public int WinnerDrawAttempts { get; set; }
/// <summary>Count of successful winner draws</summary>
public int WinnerDrawSuccesses { get; set; }
/// <summary>Total time for Wheel API calls (milliseconds)</summary>
public long WheelApiTotalMs { get; set; }
/// <summary>Count of Wheel API calls (for average latency calculation)</summary>
public int WheelApiCalls { get; set; }
// Error & Diagnostic Metrics
public int ApiErrors { get; set; }
public int WheelApiErrors { get; set; }
public int WheelApiInvalidKeys { get; set; }
public int WheelApiTimeouts { get; set; }
public int WheelApiNetworkErrors { get; set; }
public MetricsContainer()
{
Profiles = new Dictionary<string, ProfileMetrics>();
GlobalMetrics = new Dictionary<string, long>();
UserMetrics = new Dictionary<string, UserMetricSet>();
}
/// <summary>Serializes metrics to JSON string.</summary>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Loads aggregated metrics from global variables.
/// </summary>
public static MetricsContainer FromGlobalVars(CPHAdapter adapter)
{
var container = new MetricsContainer();
container.EntriesTotal = adapter.GetGlobalVar<long>("Giveaway Global Metrics EntriesTotal", true);
container.WinsTotal = adapter.GetGlobalVar<long>("Giveaway Global Metrics WinsTotal", true);
container.DrawsTotal = adapter.GetGlobalVar<long>("Giveaway Global Metrics DrawsTotal", true);
return container;
}
}
/// <summary>
/// Metrics for a specific giveaway profile.
/// </summary>
public class ProfileMetrics
{
/// <summary>Profile name.</summary>
public string ProfileName { get; set; }
/// <summary>Total entries for this profile.</summary>
public long Entries { get; set; }
/// <summary>Total wins for this profile.</summary>
public long Wins { get; set; }
/// <summary>Total draws for this profile.</summary>
public long Draws { get; set; }
}
/// <summary>
/// Metrics for a specific user.
/// </summary>
public class UserMetrics
{
/// <summary>User ID.</summary>
public string UserId { get; set; }
/// <summary>Total entries across all giveaways.</summary>
public long EntriesTotal { get; set; }
/// <summary>Total wins across all giveaways.</summary>
public long WinsTotal { get; set; }
}
/// <summary>
/// Service for tracking and aggregating giveaway metrics.
/// Provides cross-profile analytics and per-user statistics.
/// </summary>
public class MetricsService
{
/// <summary>
/// Gets aggregated metrics across all profiles.
/// </summary>
public MetricsContainer GetGlobalMetrics(CPHAdapter adapter)
{
adapter.LogDebug("[MetricsService] [GetGlobalMetrics] Fetching global metrics...");
return MetricsContainer.FromGlobalVars(adapter);
}
/// <summary>
/// Gets metrics for a specific profile.
/// </summary>
public ProfileMetrics GetProfileMetrics(string profileName, CPHAdapter adapter)
{
adapter.LogDebug($"[MetricsService] [GetProfileMetrics] Fetching metrics for profile '{profileName}'...");
var metrics = new ProfileMetrics();
metrics.ProfileName = profileName;
metrics.Entries = adapter.GetGlobalVar<long>($"Giveaway Profile {profileName} Metrics Entries", true);
metrics.Wins = adapter.GetGlobalVar<long>($"Giveaway Profile {profileName} Metrics Wins", true);
metrics.Draws = adapter.GetGlobalVar<long>($"Giveaway Profile {profileName} Metrics Draws", true);
return metrics;
}
/// <summary>
/// Gets metrics for a specific user.
/// </summary>
public UserMetrics GetUserMetrics(string userId, CPHAdapter adapter)
{
adapter.LogDebug($"[MetricsService] [GetUserMetrics] Fetching metrics for user '{userId}'...");
var metrics = new UserMetrics();
metrics.UserId = userId;
metrics.EntriesTotal = adapter.GetUserVar<long>(userId, "Giveaway User Metrics EntriesTotal", true);
metrics.WinsTotal = adapter.GetUserVar<long>(userId, "Giveaway User Metrics WinsTotal", true);
return metrics;
}
/// <summary>
/// Records an entry for a user in a specific profile.
/// </summary>
public void RecordEntry(string profileName, string userId, CPHAdapter adapter)
{
adapter.LogTrace($"[MetricsService] [RecordEntry] Recording entry for user '{userId}' in profile '{profileName}'");
// Global metrics
long globalEntries = adapter.GetGlobalVar<long>("Giveaway Global Metrics EntriesTotal", true);
adapter.SetGlobalVar("Giveaway Global Metrics EntriesTotal", globalEntries + 1, true);
// Profile metrics
string profileKey = $"Giveaway Profile {profileName} Metrics Entries";
long profileEntries = adapter.GetGlobalVar<long>(profileKey, true);
adapter.SetGlobalVar(profileKey, profileEntries + 1, true);
// User metrics
long userEntries = adapter.GetUserVar<long>(userId, "Giveaway User Metrics EntriesTotal", true);
adapter.SetUserVar(userId, "Giveaway User Metrics EntriesTotal", userEntries + 1, true);
}
/// <summary>
/// Records a win for a user in a specific profile.
/// </summary>
public void RecordWin(string profileName, string userId, CPHAdapter adapter)
{
adapter.LogTrace($"[MetricsService] [RecordWin] Recording win for user '{userId}' in profile '{profileName}'");
// Global metrics
long globalWins = adapter.GetGlobalVar<long>("Giveaway Global Metrics WinsTotal", true);
adapter.SetGlobalVar("Giveaway Global Metrics WinsTotal", globalWins + 1, true);
// Profile metrics
string profileKey = $"Giveaway Profile {profileName} Metrics Wins";
long profileWins = adapter.GetGlobalVar<long>(profileKey, true);
adapter.SetGlobalVar(profileKey, profileWins + 1, true);
// User metrics
long userWins = adapter.GetUserVar<long>(userId, "Giveaway User Metrics WinsTotal", true);
adapter.SetUserVar(userId, "Giveaway User Metrics WinsTotal", userWins + 1, true);
}
/// <summary>
/// Records a draw execution for a specific profile.
/// </summary>
public void RecordDraw(string profileName, CPHAdapter adapter)
{
adapter.LogTrace($"[MetricsService] [RecordDraw] Recording draw for profile '{profileName}'");
// Global metrics
long globalDraws = adapter.GetGlobalVar<long>("Giveaway Global Metrics DrawsTotal", true);
adapter.SetGlobalVar("Giveaway Global Metrics DrawsTotal", globalDraws + 1, true);
// Profile metrics
string profileKey = $"Giveaway Profile {profileName} Metrics Draws";
long profileDraws = adapter.GetGlobalVar<long>(profileKey, true);
adapter.SetGlobalVar(profileKey, profileDraws + 1, true);
}
/// <summary>
/// Legacy diagnostic metric set for a user (backward compatibility).
/// </summary>
public class UserMetricSet
{
public Dictionary<string, long> Metrics { get; set; } = new Dictionary<string, long>();
}
private readonly string _path;
/// <summary>
/// Initializes file path for diagnostic metrics persistence.
/// </summary>
public MetricsService()
{
_path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Giveaway Bot", "data", "metrics.json");
}
/// <summary>
/// Saves diagnostic metrics data to JSON file.
/// </summary>
public void SaveMetrics(CPHAdapter adapter, MetricsContainer metrics)
{
try
{
string stateDir = Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(stateDir) && !Directory.Exists(stateDir)) Directory.CreateDirectory(stateDir);
var json = JsonConvert.SerializeObject(metrics, Formatting.Indented);
File.WriteAllText(_path, json);
adapter.LogTrace($"[MetricsService] [SaveMetrics] Metrics successfully saved to disk: {_path}");
}
catch (Exception ex)
{
adapter.LogError($"[MetricsService] [SaveMetrics] Failed to save metrics: {ex.Message}");
}
}
/// <summary>
/// Loads diagnostic metrics data from JSON file.
/// </summary>
public MetricsContainer LoadMetrics(CPHAdapter adapter)
{
try
{
if (!File.Exists(_path)) return new MetricsContainer();
var json = File.ReadAllText(_path);
var metrics = JsonConvert.DeserializeObject<MetricsContainer>(json);
return metrics ?? new MetricsContainer();
}
catch (Exception ex)
{
adapter.LogError($"[MetricsService] [LoadMetrics] Failed to load metrics: {ex.Message}");
return new MetricsContainer();
}
}
}
#endregion
#region Event Bus
/// <summary>
/// Base interface for all giveaway events.
/// </summary>
public interface IGiveawayEvent
{
/// <summary>CPH adapter context for this event.</summary>
CPHAdapter Adapter { get; }
/// <summary>Profile name associated with this event.</summary>
string ProfileName { get; }
/// <summary>Timestamp when the event was created.</summary>
DateTime Timestamp { get; }
}
/// <summary>
/// Event Bus interface for decoupled communication.
/// </summary>
public interface IEventBus
{
/// <summary>
/// Subscribes a handler to a specific event type.
/// </summary>
/// <typeparam name="T">The event type to subscribe to.</typeparam>
/// <param name="handler">The action to execute when the event is published.</param>
void Subscribe<T>(Action<T> handler) where T : IGiveawayEvent;
/// <summary>
/// Unsubscribes a handler from a specific event type.
/// </summary>
/// <typeparam name="T">The event type to unsubscribe from.</typeparam>
/// <param name="handler">The handler to remove.</param>
void Unsubscribe<T>(Action<T> handler) where T : IGiveawayEvent;
/// <summary>
/// Publishes an event to all subscribed handlers.
/// </summary>
/// <typeparam name="T">The event type.</typeparam>
/// <param name="evt">The event instance to publish.</param>
void Publish<T>(T evt) where T : IGiveawayEvent;
}
/// <summary>
/// Thread-safe Event Bus implementation for pub/sub event handling.
/// Isolates handler exceptions to prevent cascading failures.
/// </summary>
public class EventBus : IEventBus
{
private readonly Dictionary<Type, List<Delegate>> _subscribers;
private readonly object _lock = new object();
public EventBus()
{
_subscribers = new Dictionary<Type, List<Delegate>>();
}
public void Subscribe<T>(Action<T> handler) where T : IGiveawayEvent
{
if (handler == null) throw new ArgumentNullException(nameof(handler));
lock (_lock)
{
var eventType = typeof(T);
if (!_subscribers.ContainsKey(eventType))
{
_subscribers[eventType] = new List<Delegate>();
}
_subscribers[eventType].Add(handler);
}
}
public void Unsubscribe<T>(Action<T> handler) where T : IGiveawayEvent
{
if (handler == null) throw new ArgumentNullException(nameof(handler));
lock (_lock)
{
var eventType = typeof(T);
if (_subscribers.ContainsKey(eventType))
{
_subscribers[eventType].Remove(handler);
if (_subscribers[eventType].Count == 0)
{
_subscribers.Remove(eventType);
}
}
}
}
public void Publish<T>(T evt) where T : IGiveawayEvent
{
if (evt == null) throw new ArgumentNullException(nameof(evt));
List<Delegate> handlers;
lock (_lock)
{
var eventType = typeof(T);
if (!_subscribers.ContainsKey(eventType))
{
return; // No subscribers
}
// Create a copy to avoid modification during iteration
handlers = new List<Delegate>(_subscribers[eventType]);
}
// Invoke handlers outside the lock to avoid deadlocks
foreach (var handler in handlers)
{
try
{
((Action<T>)handler)(evt);
}
catch (Exception ex)
{
// Isolate exceptions - log but don't propagate
evt.Adapter.LogError($"[EventBus] Handler exception for {typeof(T).Name}: {ex.Message}");
}
}
}
}
// =====================================================================
// EVENT TYPE DEFINITIONS
// =====================================================================
/// <summary>
/// Event published when a giveaway is started/opened.
/// </summary>
public class GiveawayStartedEvent : IGiveawayEvent
{
public CPHAdapter Adapter { get; private set; }
public string ProfileName { get; private set; }
public DateTime Timestamp { get; private set; }
public GiveawayState State { get; private set; }
public GiveawayStartedEvent(CPHAdapter adapter, string profileName, GiveawayState state)
{
Adapter = adapter;
ProfileName = profileName;
State = state;
Timestamp = DateTime.Now;
}
}
/// <summary>
/// Event published when a giveaway is ended/closed.
/// </summary>
public class GiveawayEndedEvent : IGiveawayEvent
{
public CPHAdapter Adapter { get; private set; }
public string ProfileName { get; private set; }
public DateTime Timestamp { get; private set; }
public GiveawayState State { get; private set; }
public GiveawayEndedEvent(CPHAdapter adapter, string profileName, GiveawayState state)
{
Adapter = adapter;
ProfileName = profileName;
State = state;
Timestamp = DateTime.Now;
}
}
/// <summary>
/// Event published when a winner is drawn.
/// </summary>
public class WinnerDrawnEvent : IGiveawayEvent
{
public CPHAdapter Adapter { get; private set; }
public string ProfileName { get; private set; }
public DateTime Timestamp { get; private set; }
public GiveawayState State { get; private set; }
public string WinnerName { get; private set; }
public string WinnerId { get; private set; }
public string Platform { get; private set; }
public WinnerDrawnEvent(CPHAdapter adapter, string profileName, GiveawayState state, string winnerName, string winnerId, string platform)
{
Adapter = adapter;
ProfileName = profileName;
State = state;
WinnerName = winnerName;
WinnerId = winnerId;
Platform = platform;
Timestamp = DateTime.Now;
}
}
/// <summary>
/// Event published when Wheel of Names URL is ready.
/// </summary>
public class WheelReadyEvent : IGiveawayEvent
{
public CPHAdapter Adapter { get; private set; }
public string ProfileName { get; private set; }
public DateTime Timestamp { get; private set; }
public GiveawayState State { get; private set; }
public string WheelUrl { get; private set; }
public string Platform { get; private set; }
public WheelReadyEvent(CPHAdapter adapter, string profileName, GiveawayState state, string wheelUrl, string platform)
{
Adapter = adapter;
ProfileName = profileName;
State = state;
WheelUrl = wheelUrl;
Platform = platform;
Timestamp = DateTime.Now;
}
}
/// <summary>
/// Event published when an entry is successfully accepted.
/// </summary>
public class EntryAcceptedEvent : IGiveawayEvent
{
public CPHAdapter Adapter { get; private set; }
public string ProfileName { get; private set; }
public DateTime Timestamp { get; private set; }
public string UserId { get; private set; }
public string UserName { get; private set; }
public int TicketCount { get; private set; }
public string Platform { get; private set; }
public string MessageId { get; private set; }
public EntryAcceptedEvent(CPHAdapter adapter, string profileName, string userId, string userName, int ticketCount, string platform, string messageId)
{
Adapter = adapter;
ProfileName = profileName;
UserId = userId;
UserName = userName;
TicketCount = ticketCount;
Platform = platform;
MessageId = messageId;
Timestamp = DateTime.Now;
}
}
/// <summary>
/// Event published when an entry is rejected.
/// </summary>
public class EntryRejectedEvent : IGiveawayEvent
{
public CPHAdapter Adapter { get; private set; }
public string ProfileName { get; private set; }
public DateTime Timestamp { get; private set; }
public string UserId { get; private set; }
public string UserName { get; private set; }
public string Reason { get; private set; }
public EntryRejectedEvent(CPHAdapter adapter, string profileName, string userId, string userName, string reason)
{
Adapter = adapter;
ProfileName = profileName;
UserId = userId;
UserName = userName;
Reason = reason;
Timestamp = DateTime.Now;
}
}
/// <summary>
/// Event requesting a toast notification.
/// </summary>
public class ToastNotificationEvent : IGiveawayEvent
{
public CPHAdapter Adapter { get; private set; }
public string ProfileName { get; private set; }
public DateTime Timestamp { get; private set; }
public string Title { get; private set; }
public string Message { get; private set; }
public ToastNotificationEvent(CPHAdapter adapter, string profileName, string title, string message)
{
Adapter = adapter;
ProfileName = profileName;
Title = title;
Message = message;
Timestamp = DateTime.Now;
}
}
/// <summary>
/// Event requesting a chat broadcast.
/// </summary>
public class ChatMessageEvent : IGiveawayEvent