-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
22225 lines (19251 loc) · 954 KB
/
index.js
File metadata and controls
22225 lines (19251 loc) · 954 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
require('dotenv').config();
const { Telegraf, Markup } = require('telegraf');
const https = require('https');
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const { exec, execFile, spawn } = require('child_process');
const telegramSafe = require('./telegramSafe');
const { throttleWithConfig, settings: rateLimiterSettings } = require('./rateLimiter');
const { parsePromoAmount, normalizePromoAudience } = require('./promo-message');
// =========================
// Config
// =========================
const BOT_TOKEN = process.env.BOT_TOKEN || process.env.TELEGRAM_BOT_TOKEN;
const ADMIN_IDS = (process.env.ADMIN_IDS || '')
.split(',')
.map((id) => id.trim())
.filter(Boolean)
.map((id) => Number(id));
// Affiliate source tag — all bot users come via GambleCodez
const AFFILIATE_SOURCE = process.env.AFFILIATE_SOURCE || 'GambleCodez';
if (!BOT_TOKEN) {
throw new Error('Missing BOT_TOKEN (or TELEGRAM_BOT_TOKEN) in environment variables.');
}
// Startup env var validation — warn on missing optional-but-important vars
if (!ADMIN_IDS || ADMIN_IDS.length === 0) {
console.error('[WARN] ADMIN_IDS is empty — no admins configured. Admin commands will be inaccessible.');
}
if (!process.env.TELEGRAM_CHANNEL_ID && !process.env.ANNOUNCE_CHANNEL) {
console.warn('[WARN] TELEGRAM_CHANNEL_ID not set — channel announcements will be disabled.');
}
if (!process.env.TELEGRAM_GROUP_ID) {
console.warn('[WARN] TELEGRAM_GROUP_ID not set — group-linked Content Drops will be disabled.');
}
// Safe URL schemes allowed in unwrapped/validated links
const SAFE_URL_SCHEMES = new Set(['https:', 'http:', 'tg:', 'ton:']);
const UNSAFE_URL_SCHEMES = /^(javascript|data|file|intent|chrome-extension|about|blob):/i;
function unwrapTelegramUrl(url) {
const raw = String(url || '').trim();
if (!raw) return '';
try {
const parsed = new URL(raw);
const host = parsed.hostname.toLowerCase();
// Normalize t.me / telegram.me redirects
if (host === 't.me' || host === 'www.t.me' || host === 'telegram.me' || host === 'www.telegram.me') {
const embedded = parsed.searchParams.get('url');
if (embedded) {
// Validate the embedded URL scheme before returning
try {
const inner = new URL(embedded);
if (UNSAFE_URL_SCHEMES.test(inner.protocol) || !SAFE_URL_SCHEMES.has(inner.protocol)) return '';
return embedded;
} catch (_) { return ''; }
}
}
// Validate the scheme of the raw URL itself
if (UNSAFE_URL_SCHEMES.test(parsed.protocol) || !SAFE_URL_SCHEMES.has(parsed.protocol)) return '';
} catch (_) { return ''; } // never return raw unvalidated input on parse failure
return raw;
}
function getDiscordLink(url) {
const candidate = unwrapTelegramUrl(url);
if (!candidate) return null; // not configured
try {
const parsed = new URL(candidate);
const host = parsed.hostname.toLowerCase();
if ((host === 'discord.com' || host === 'www.discord.com' || host === 'discord.gg' || host === 'www.discord.gg')
&& parsed.protocol === 'https:') {
return `${parsed.protocol}//${parsed.host}${parsed.pathname}${parsed.search}${parsed.hash}`;
}
} catch (_) { /* ignore */ }
return null; // return null — not a valid discord link and no fallback hardcoded
}
function getBrowserLink(route = 'play') {
// External browser links — always open in the device browser, never inside Telegram
const map = {
play: 'https://www.runewager.com/r/GambleCodez',
profile: 'https://www.runewager.com/profile',
claim: 'https://www.runewager.com/affiliate',
affiliate: 'https://www.runewager.com/affiliate',
discord: LINKS ? LINKS.rwDiscordJoin : 'https://discord.gg/runewagers',
};
return map[route] || map.play;
}
function getWebAppLink(route = 'play') {
const map = { play: LINKS.miniAppPlay, profile: LINKS.miniAppProfile, claim: LINKS.miniAppClaim };
return map[route] || LINKS.miniAppPlay;
}
function getStartAppLink(route = 'play') {
// Sanitize route: only alphanumeric, /, - characters allowed; reject whitespace/control chars
const safeRoute = /^[\w/-]{1,64}$/.test(String(route || '')) ? String(route) : 'home';
return `${LINKS.miniAppPlay}?startapp=${encodeURIComponent(safeRoute)}`;
}
function getPlayLink(user, route = 'play') {
// Read from user.settings.playMode; fall back to legacy user.playMode for migrating users
const rawMode = (user && user.settings && user.settings.playMode)
|| (user && user.playMode)
|| 'miniapp';
const mode = (rawMode === 'browser' || rawMode === 'miniapp') ? rawMode : 'miniapp';
return mode === 'browser' ? getBrowserLink(route) : getStartAppLink(route);
}
const LINKS = {
// External browser links — always open outside Telegram
runewagerSignup: 'https://www.runewager.com/r/GambleCodez',
promoInput: 'https://www.runewager.com/affiliate',
runewagerProfile: 'https://www.runewager.com/profile',
// Discord links — always external browser, no Discord API used
rwDiscordSupport: getDiscordLink(process.env.RW_DISCORD_SUPPORT || 'https://discord.com/channels/1100486422395355197/1249182067296567338'),
rwDiscordJoin: getDiscordLink(process.env.RW_DISCORD_JOIN || 'https://discord.gg/runewagers'),
rwDiscordLink: getDiscordLink(process.env.RW_DISCORD_LINK || 'https://discord.com/channels/1100486422395355197/1249181934811349052'),
// Telegram channels/groups — external links
gczChannel: process.env.TELEGRAM_CHANNEL_LINK || 'https://t.me/GambleCodezDrops',
gczGroup: process.env.TELEGRAM_GROUP_LINK || 'https://t.me/GambleCodezPrizeHub',
gczXCom: process.env.GCZ_X_URL || 'https://x.com/GambleCodez',
// Mini App links — always open INSIDE Telegram
miniAppPlay: process.env.MINI_APP_PLAY_URL || 'https://t.me/RuneWager_bot/Play',
miniAppProfile: process.env.MINI_APP_PROFILE_URL || 'https://t.me/RuneWager_bot/profile',
miniAppClaim: process.env.MINI_APP_CLAIM_URL || 'https://t.me/RuneWager_bot/claim',
};
const DEFAULT_BONUS_RULE = `Wager 3,000 SC in any rolling 7-day period → 30 SC bonus (once per account). Need help? Contact @GambleCodez on Telegram or open a support ticket: ${LINKS.rwDiscordSupport}`;
const PROMO_STATUS = { ACTIVE: 'active', PAUSED: 'paused', DELETED: 'deleted' };
const PROMO_REQUIREMENT = {
NEW_USER_ONLY: 'new_user_only',
EXISTING_USER: 'existing_user',
EXISTING_USER_WITH_WAGER: 'existing_user_with_wager_requirement',
};
// Channel username (or chat_id) for admin announcements via /announce
const TELEGRAM_CHANNEL_ID = process.env.TELEGRAM_CHANNEL_ID || process.env.ANNOUNCE_CHANNEL || '';
const TELEGRAM_GROUP_ID = process.env.TELEGRAM_GROUP_ID || '';
const ANNOUNCE_CHANNEL = TELEGRAM_CHANNEL_ID;
const BOT_PRIVACY_MODE = String(process.env.BOT_PRIVACY_MODE || process.env.BOTPRIVACYMODE || '').trim().toLowerCase();
// Group chat_id for automatic Helpful Tooltips
const TIPS_GROUP = process.env.TIPS_GROUP || TELEGRAM_GROUP_ID || '';
// ── Images ─────────────────────────────────────────────────────────────────
// Images live in /images/ next to index.js.
// If HOSTED_*_URL env vars are set they take priority (CDN / public URL).
// Otherwise the bot streams the local PNG directly to Telegram.
const IMG_DIR = path.join(__dirname, 'images');
const IMG_DISCORD_CODE = process.env.DISCORD_CODE_GENERATION_IMAGE_URL || path.join(IMG_DIR, 'discord_code_generation.png');
const IMG_DISCORD_VERIFY = process.env.DISCORD_VERIFY_IMAGE_URL || path.join(IMG_DIR, 'discord_verify.png');
const IMG_PROMO_ENTRY = process.env.PROMO_ENTRY_IMAGE_URL || path.join(IMG_DIR, 'promo_entry.png');
// Legacy single-var alias kept for any direct references below.
const PROMO_ENTRY_IMAGE_URL = IMG_PROMO_ENTRY;
// Intro GIF shown on /start for new (unconfirmed) users
const IMG_INTRO_GIF = process.env.INTRO_GIF_URL || path.join(IMG_DIR, 'runewager_intro.gif');
/**
* Send a photo from either a public HTTPS URL or a local file path.
* Falls back to a plain text reply if the image cannot be sent.
* @param {object} ctx - Telegraf context
* @param {string} imgSrc - HTTPS URL or absolute local file path
* @param {string} caption - message text to attach
* @param {object} extra - Telegraf extra (e.g. keyboard markup)
*/
async function sendPhoto(ctx, imgSrc, caption, extra = {}) {
try {
const isUrl = imgSrc.startsWith('https://') || imgSrc.startsWith('http://');
const safeImgPath = isUrl ? null : validateSafePath(imgSrc, IMG_DIR);
const source = isUrl ? imgSrc : { source: fs.createReadStream(safeImgPath) };
await ctx.replyWithPhoto(source, { caption, ...extra });
} catch (e) {
logEvent('warn', 'sendPhoto failed, falling back to text', { imgSrc, error: e.message });
await ctx.reply(caption, extra);
}
}
/**
* Send an animation/GIF (intro hero).
* Falls back to a plain text reply if the animation cannot be sent.
*/
async function sendIntroGif(ctx, caption, extra = {}) {
try {
const isUrl = IMG_INTRO_GIF.startsWith('https://') || IMG_INTRO_GIF.startsWith('http://');
const safeGifPath = isUrl ? null : validateSafePath(IMG_INTRO_GIF, IMG_DIR);
const source = isUrl ? IMG_INTRO_GIF : { source: fs.createReadStream(safeGifPath) };
await ctx.replyWithAnimation(source, { caption, ...extra });
} catch (e) {
logEvent('warn', 'sendIntroGif failed, falling back to text', { error: e.message });
await ctx.reply(caption, extra);
}
}
const COPY = {
intro:
'👋 Welcome to Runewager! This platform uses SC (Sweepstakes Coins) for prize-based play and instant crypto prize redemption. No gambling language, no real-money wagering, and no deposit claims. Runewager is 100% FREE to play and accepts players worldwide.',
ageGate:
'<b>🌍 Runewager is 100% free to play and accepts players worldwide.</b>\n\n'
+ 'No real-money wagering. No deposits. No gambling. Just sweepstakes-style SC (Sweepstakes Coin) fun with instant crypto prize redemption.\n\n'
+ 'Before continuing, please confirm you are 18+ and eligible to participate in sweepstakes-style prize activities in your region.',
prizeExplanation:
'Great! Here\'s how Runewager works:\n'
+ '• SC = Sweepstakes Coins used for prize redemption\n'
+ '• 100% free to play — no deposits, no real-money wagering\n'
+ '• Accepts players worldwide 🌍\n'
+ '• Prize redemption is instant crypto\n'
+ '• Promo code names and SC amounts are always pulled from the active promo data\n'
+ '• Sign up under GambleCodez to unlock all rewards and giveaways',
// Discord web-link step is shown here as an EXTERNAL link only.
// Runewager's own Discord bot handles the actual code confirmation — our Telegram bot does nothing.
accountSetup:
'Let\'s set up your Runewager account:\n\n'
+ '1️⃣ Sign up under GambleCodez (browser link below)\n'
+ '2️⃣ Join the official Runewager Discord server (browser link below)\n'
+ '3️⃣ Open your Runewager profile → tap Generate Code (Mini App button below)\n'
+ '4️⃣ Copy the code shown\n'
+ '5️⃣ Open the Discord code-link channel (browser link below) and paste your code\n'
+ ' Runewager\'s Discord bot confirms automatically\n'
+ '6️⃣ Tap "Done — I Pasted My Code" below',
accountReady: '✅ Account confirmed! Use the menu below to continue.',
};
const bot = new Telegraf(BOT_TOKEN);
// Patch bot.telegram methods to route through the global rate limiter.
// Because ctx.telegram IS bot.telegram (same object reference in Telegraf v4),
// this single call covers ctx.reply(), ctx.answerCbQuery(), ctx.editMessageText(),
// ctx.telegram.sendMessage(), and every direct bot.telegram.*() call in this file.
// Must be called BEFORE any bot.use() middleware so the patch is always in effect.
telegramSafe.init(bot);
// Callback-query hygiene middleware: if a callback handler sends a new reply,
// remove the source callback card first so menus do not stack.
bot.use(async (ctx, next) => {
if (!ctx.callbackQuery) return next();
if (isGroupChat(ctx)) {
if (!isBotAuthoredGroupCallback(ctx)) return;
if (!isAllowedGroupCallback(ctx.callbackQuery.data)) {
await ctx.answerCbQuery().catch(() => {});
await ctx.reply('This action can only be completed in DM. Tap below to continue.', {
...buildOpenBotKeyboard(ctx),
disable_notification: true,
}).catch(() => {});
return;
}
}
let cleared = false;
const clearSource = async () => {
if (cleared) return;
try { await ctx.deleteMessage(); } catch (_) { /* stale/missing is fine */ }
cleared = true;
};
const wrapReply = (fn) => async (...args) => {
await clearSource();
return fn(...args);
};
ctx.reply = wrapReply(ctx.reply.bind(ctx));
if (ctx.replyWithPhoto) ctx.replyWithPhoto = wrapReply(ctx.replyWithPhoto.bind(ctx));
if (ctx.replyWithAnimation) ctx.replyWithAnimation = wrapReply(ctx.replyWithAnimation.bind(ctx));
return next();
});
// =========================
// Global Telegraf error handler
// Catches any unhandled error thrown inside a bot.command() or bot.action() handler.
// Without this, async handler errors are silently swallowed by Telegraf.
// =========================
bot.catch((err, ctx) => {
const userId = ctx && ctx.from ? ctx.from.id : 'unknown';
const updateType = ctx && ctx.updateType ? ctx.updateType : 'unknown';
logEvent('error', 'Unhandled bot handler error', { userId, updateType, error: err && err.message ? err.message : String(err) });
if (ctx && ctx.callbackQuery && typeof ctx.answerCbQuery === 'function') {
ctx.answerCbQuery('Something went wrong.').catch(() => {});
}
if (ctx && typeof ctx.reply === 'function' && !isGroupChat(ctx)) {
ctx.reply('<b>⚠️ A handler error occurred.</b>\nThe action was logged and the bot recovered.', {
parse_mode: 'HTML',
...buildMainMenuKeyboard(),
}).catch(() => {});
}
});
// =========================
// Group Command Guard Middleware
// Commands sent in group/supergroup chats are intercepted and redirected to DM,
// unless the command has its own group-specific handling (link, giveaway, admin, etc.)
// =========================
/**
* Authoritative command access metadata.
* audience: user | admin | both
* surface: bot_only | group_only | both
*/
const COMMAND_ACCESS = Object.freeze({
start: { audience: 'user', surface: 'bot_only' },
menu: { audience: 'user', surface: 'bot_only' },
help: { audience: 'user', surface: 'bot_only' },
commands: { audience: 'user', surface: 'bot_only' },
settings: { audience: 'user', surface: 'bot_only' },
language: { audience: 'user', surface: 'bot_only' },
linkuser: { audience: 'user', surface: 'both' },
linkusername: { audience: 'user', surface: 'both' },
walkthrough: { audience: 'user', surface: 'bot_only' },
admin: { audience: 'admin', surface: 'both' },
ai_mirror: { audience: 'admin', surface: 'bot_only' },
ai_replay: { audience: 'admin', surface: 'bot_only' },
ai_fixit: { audience: 'admin', surface: 'bot_only' },
ai_storm: { audience: 'admin', surface: 'bot_only' },
ai_architect: { audience: 'admin', surface: 'bot_only' },
ai_sniffer: { audience: 'admin', surface: 'bot_only' },
ai_sandbox: { audience: 'admin', surface: 'bot_only' },
ai_guardian: { audience: 'admin', surface: 'bot_only' },
ai_autopilot: { audience: 'admin', surface: 'bot_only' },
ai_audit_targeted: { audience: 'admin', surface: 'bot_only' },
sshv: { audience: 'admin', surface: 'bot_only' },
qa_on: { audience: 'admin', surface: 'bot_only' },
qa_off: { audience: 'admin', surface: 'bot_only' },
qa_mode: { audience: 'admin', surface: 'bot_only' },
qa_status: { audience: 'admin', surface: 'bot_only' },
a: { audience: 'admin', surface: 'bot_only' },
announce: { audience: 'admin', surface: 'bot_only' },
giveaway: { audience: 'both', surface: 'both' },
start_giveaway: { audience: 'admin', surface: 'both' },
cancel: { audience: 'both', surface: 'bot_only' },
wager30_admin: { audience: 'admin', surface: 'bot_only' },
admin_backup: { audience: 'admin', surface: 'bot_only' },
deploy: { audience: 'admin', surface: 'bot_only' },
whois: { audience: 'admin', surface: 'bot_only' },
bonusstatus: { audience: 'admin', surface: 'bot_only' },
refreshuser: { audience: 'admin', surface: 'bot_only' },
health: { audience: 'admin', surface: 'bot_only' },
admin_notify: { audience: 'admin', surface: 'bot_only' },
deploy_status: { audience: 'admin', surface: 'bot_only' },
logs: { audience: 'admin', surface: 'bot_only' },
version: { audience: 'admin', surface: 'bot_only' },
resolvebug: { audience: 'admin', surface: 'bot_only' },
exportbugs: { audience: 'admin', surface: 'bot_only' },
bonus: { audience: 'user', surface: 'bot_only' },
startapp: { audience: 'user', surface: 'bot_only' },
claim_history: { audience: 'user', surface: 'bot_only' },
profile: { audience: 'user', surface: 'bot_only' },
leaderboard: { audience: 'user', surface: 'bot_only' },
leaderboard_weekly: { audience: 'user', surface: 'bot_only' },
boost_referrals: { audience: 'admin', surface: 'bot_only' },
status: { audience: 'user', surface: 'bot_only' },
referral: { audience: 'user', surface: 'bot_only' },
on: { audience: 'admin', surface: 'bot_only' },
off: { audience: 'admin', surface: 'bot_only' },
bugreport: { audience: 'user', surface: 'bot_only' },
bugreports: { audience: 'admin', surface: 'bot_only' },
play: { audience: 'user', surface: 'bot_only' },
signup: { audience: 'user', surface: 'bot_only' },
affiliate: { audience: 'user', surface: 'bot_only' },
discord: { audience: 'user', surface: 'bot_only' },
promo: { audience: 'user', surface: 'bot_only' },
setpromo: { audience: 'admin', surface: 'bot_only' },
join: { audience: 'user', surface: 'group_only' },
pmapprove: { audience: 'admin', surface: 'bot_only' },
pmdeny: { audience: 'admin', surface: 'bot_only' },
tips: { audience: 'admin', surface: 'bot_only' },
t: { audience: 'admin', surface: 'bot_only' },
tp: { audience: 'admin', surface: 'bot_only' },
tiplist: { audience: 'admin', surface: 'bot_only' },
tipadd: { audience: 'admin', surface: 'bot_only' },
tipremove: { audience: 'admin', surface: 'bot_only' },
tipedit: { audience: 'admin', surface: 'bot_only' },
tiptoggle: { audience: 'admin', surface: 'bot_only' },
tiptest: { audience: 'admin', surface: 'bot_only' },
tipsettings: { audience: 'admin', surface: 'bot_only' },
testall: { audience: 'admin', surface: 'bot_only' },
testall_debug: { audience: 'admin', surface: 'bot_only' },
testgiveaway: { audience: 'admin', surface: 'bot_only' },
gw_pause: { audience: 'admin', surface: 'bot_only' },
gw_resume: { audience: 'admin', surface: 'bot_only' },
scan_eligibility: { audience: 'admin', surface: 'bot_only' },
funnel: { audience: 'admin', surface: 'bot_only' },
broadcast_retry: { audience: 'admin', surface: 'bot_only' },
broadcast_failed: { audience: 'admin', surface: 'bot_only' },
pick_winner: { audience: 'admin', surface: 'bot_only' },
register_chat: { audience: 'admin', surface: 'both' },
verify_bot_setup: { audience: 'admin', surface: 'both' },
approve_group: { audience: 'admin', surface: 'both' },
unapprove_group: { audience: 'admin', surface: 'both' },
list_groups: { audience: 'admin', surface: 'both' },
admin_log: { audience: 'admin', surface: 'bot_only' },
promo_cooldown: { audience: 'admin', surface: 'bot_only' },
discord_stats: { audience: 'admin', surface: 'bot_only' },
gw_graphic: { audience: 'admin', surface: 'bot_only' },
stuck: { audience: 'user', surface: 'bot_only' },
fixaccount: { audience: 'user', surface: 'bot_only' },
discord_confirm: { audience: 'user', surface: 'bot_only' },
mygiveaways: { audience: 'user', surface: 'bot_only' },
checkin: { audience: 'user', surface: 'both' },
top: { audience: 'user', surface: 'bot_only' },
boostmeter: { audience: 'user', surface: 'bot_only' },
eligible: { audience: 'user', surface: 'bot_only' },
gwhistory: { audience: 'user', surface: 'bot_only' },
promocheck: { audience: 'user', surface: 'bot_only' },
support: { audience: 'user', surface: 'bot_only' },
supportchat: { audience: 'user', surface: 'bot_only' },
bug: { audience: 'user', surface: 'bot_only' },
claim: { audience: 'user', surface: 'bot_only' },
});
/**
* Complete set of commands this bot handles.
* Any command NOT in this list is silently ignored in groups (could belong to another bot).
*/
const BOT_KNOWN_COMMANDS = new Set(Object.keys(COMMAND_ACCESS));
const GROUP_DM_ONLY_COMMANDS = new Set(
Object.entries(COMMAND_ACCESS)
.filter(([, access]) => access.surface === 'bot_only')
.map(([command]) => command),
);
const GROUP_SAFE_CALLBACK_PATTERNS = [
/^gw_/,
/^tgw_/,
/^gwiz_/,
/^group_link_/,
/^admin_gw_/,
/^admin_sys_group_linking$/,
/^confirm_yes_username$/,
/^confirm_no_username$/,
/^cancel_link$/,
/^page_noop$/,
];
function getCommandAccess(command) {
return COMMAND_ACCESS[String(command || '').toLowerCase()] || null;
}
function isGroupChat(ctx) {
const type = ctx && ctx.chat ? ctx.chat.type : '';
return type === 'group' || type === 'supergroup';
}
function buildOpenBotKeyboard(ctx) {
const botUsername = ctx?.botInfo?.username || 'RuneWager_bot';
return buildInlineKeyboard([[Markup.button.url('Open Bot', `https://t.me/${botUsername}`)]]);
}
const LINK_USERNAME_USAGE_HTML = [
'🔗 Link User',
'Use <code>/linkuser YourUsername</code>',
'or <code>/linkusername YourUsername</code>',
'Example: <code>/linkuser GambleCodez</code>',
].join('\n');
const LINK_USERNAME_TOOLTIP_HTML = [
'<b>🔗 Link User</b>',
'Connect your Runewager account.',
'Use <code>/linkuser YourUsername</code>',
'or <code>/linkusername YourUsername</code>.',
'Example: <code>/linkuser GambleCodez</code>',
].join('\n');
const LINK_USERNAME_MISSING_HTML = [
'<b>⚠️ Missing Username</b>',
'Please include your Runewager username.',
'',
'<b>Example:</b>',
'<code>/linkuser GambleCodez</code>',
].join('\n');
async function sendDmRedirect(ctx) {
if (!ctx || typeof ctx.reply !== 'function') return;
await ctx.reply('This action can only be completed in DM. Tap below to continue.', {
...buildOpenBotKeyboard(ctx),
reply_to_message_id: ctx.message?.message_id,
disable_notification: true,
}).catch(() => {});
}
function isBotAuthoredGroupCallback(ctx) {
const message = ctx?.callbackQuery?.message;
if (!message || !isGroupChat(ctx)) return true;
const botId = Number(ctx?.botInfo?.id || 0);
const authorId = Number(message.from?.id || 0);
return Number.isFinite(botId) && botId > 0 && authorId === botId;
}
function isAllowedGroupCallback(data) {
const callbackData = String(data || '');
return GROUP_SAFE_CALLBACK_PATTERNS.some((pattern) => pattern.test(callbackData));
}
function commandAllowedInChat(command, chatType) {
const access = getCommandAccess(command);
if (!access) return false;
if (chatType === 'group' || chatType === 'supergroup') {
return access.surface === 'both' || access.surface === 'group_only';
}
return access.surface === 'both' || access.surface === 'bot_only';
}
bot.use(async (ctx, next) => {
const chatType = ctx.chat && ctx.chat.type;
if (chatType !== 'group' && chatType !== 'supergroup') return next();
if (!ctx.message || !ctx.message.text) return;
const text = ctx.message.text;
if (!text.startsWith('/')) return;
// Extract command name and optional @mention (e.g. "/warn@otherbot" → "warn", "otherbot")
const cmdToken = text.slice(1).split(/\s/)[0]; // "warn@otherbot" or "warn"
const atIdx = cmdToken.indexOf('@');
const rawCmd = (atIdx === -1 ? cmdToken : cmdToken.slice(0, atIdx)).toLowerCase();
const mentionedBot = atIdx === -1 ? '' : cmdToken.slice(atIdx + 1).toLowerCase();
// If the command targets a specific bot that is not us, ignore it entirely
const ourUsername = (ctx.botInfo?.username || '').toLowerCase();
if (mentionedBot && mentionedBot !== ourUsername) return;
// If we don't own this command, ignore it (prevents responding to other bots' commands)
if (!BOT_KNOWN_COMMANDS.has(rawCmd)) return;
const access = getCommandAccess(rawCmd);
if (access && access.audience === 'admin' && !isAdmin(ctx)) return;
const allowedInChat = commandAllowedInChat(rawCmd, chatType);
logEvent('info', 'Group command received', {
command: rawCmd,
chatId: ctx.chat && ctx.chat.id ? ctx.chat.id : null,
chatType,
fromId: ctx.from && ctx.from.id ? ctx.from.id : null,
allowedInChat,
});
if (GROUP_DM_ONLY_COMMANDS.has(rawCmd)) {
await sendDmRedirect(ctx);
return;
}
if (allowedInChat) return next();
// Redirect only commands that are bot-only in group context
const botUsername = ctx.botInfo && ctx.botInfo.username ? ctx.botInfo.username : '';
const dmUrl = botUsername ? `https://t.me/${botUsername}?start=menu` : null;
const keyboard = dmUrl
? buildInlineKeyboard([[Markup.button.url('Open Bot', dmUrl)]])
: buildInlineKeyboard([]);
await ctx.reply('This action can only be completed in DM. Tap below to continue.', {
...keyboard,
reply_to_message_id: ctx.message.message_id,
disable_notification: true,
}).catch(() => {});
logEvent('info', 'Group command redirected to DM', {
command: rawCmd,
chatId: ctx.chat && ctx.chat.id ? ctx.chat.id : null,
fromId: ctx.from && ctx.from.id ? ctx.from.id : null,
});
// Do not call next() — suppress the group command from running
});
// =========================
// Interaction Debug Middleware
// Passively observes every command, callback, and text message during an active
// testall_debug session. Does NOT alter bot behavior — only wraps reply methods
// to detect whether the handler responded, then logs the event.
// =========================
bot.use(async (ctx, next) => {
if (!interactionDebugStore.active) return next();
// Only track DM interactions from the operator
if (!ctx.from || ctx.from.id !== interactionDebugStore.operatorId) return next();
const event = {
ts: Date.now(),
type: null,
command: null,
callbackData: null,
text: null,
userId: ctx.from.id,
chatId: ctx.chat ? ctx.chat.id : null,
chatType: ctx.chat ? ctx.chat.type : null,
responded: false,
buttons: [],
error: null,
durationMs: null,
};
if (ctx.updateType === 'message' && ctx.message && ctx.message.text && ctx.message.text.startsWith('/')) {
event.type = 'command';
const raw = ctx.message.text.split(/\s+/)[0].replace('/', '').split('@')[0].toLowerCase();
event.command = raw;
} else if (ctx.updateType === 'callback_query') {
event.type = 'callback';
event.callbackData = (ctx.callbackQuery && ctx.callbackQuery.data) || '';
} else if (ctx.updateType === 'message' && ctx.message && ctx.message.text) {
event.type = 'text';
event.text = ctx.message.text.slice(0, 80);
} else {
return next();
}
// Wrap ctx.reply to detect response + capture buttons
const origReply = ctx.reply.bind(ctx);
ctx.reply = async function (...args) {
event.responded = true;
const extra = args[1] || {};
const btns = extractCallbackDataFromKeyboard(extra);
event.buttons.push(...btns);
return origReply(...args);
};
// Wrap ctx.editMessageText to detect edits
if (typeof ctx.editMessageText === 'function') {
const origEdit = ctx.editMessageText.bind(ctx);
ctx.editMessageText = async function (...args) {
event.responded = true;
const opts = args[2] || {};
const btns = extractCallbackDataFromKeyboard(opts);
event.buttons.push(...btns);
return origEdit(...args);
};
}
// Wrap ctx.answerCbQuery — confirms the handler fired for callback events
if (typeof ctx.answerCbQuery === 'function') {
const origAcq = ctx.answerCbQuery.bind(ctx);
ctx.answerCbQuery = async function (...args) {
event.responded = true;
return origAcq(...args);
};
}
// Snapshot menu/tooltip state before the handler runs so we can detect
// messages that should have been cleaned up but weren't.
const snapUser = getUser(ctx);
const snapTooltipId = snapUser ? snapUser.lastTooltipMsgId : null;
const snapMenuId = snapUser ? snapUser.lastMenuMsgId : null;
const snapMenuChatId = snapUser ? snapUser.lastMenuChatId : null;
const t0 = Date.now();
try {
await next();
} catch (e) {
event.error = e.message;
}
event.durationMs = Date.now() - t0;
// Classify issues
event.issues = [];
if (!event.responded) {
event.issues.push('no_response');
}
if (event.error) {
event.issues.push('handler_error');
}
// Dead-end: responded but no navigation buttons (back/menu/cancel) found
if (event.responded && event.buttons.length > 0) {
const navPatterns = ['menu', 'back', 'return', 'cancel', 'dashboard', 'main', 'admin', 'close'];
const hasNav = event.buttons.some((b) => navPatterns.some((p) => b.toLowerCase().includes(p)));
if (!hasNav) event.issues.push('possible_dead_end');
}
// Orphaned tooltip: a tooltip message existed before the handler ran and
// still exists after — the handler responded but didn't clean it up.
const afterUser = getUser(ctx);
if (event.responded && snapTooltipId && afterUser && afterUser.lastTooltipMsgId === snapTooltipId) {
event.issues.push('orphaned_tooltip');
}
// Menu stack: a tracked menu from before the handler still points at a
// different message after the handler ran — suggests a new menu was sent
// without deleting the old one.
if (
event.responded
&& snapMenuId
&& afterUser
&& afterUser.lastMenuMsgId
&& afterUser.lastMenuMsgId !== snapMenuId
&& afterUser.lastMenuChatId === snapMenuChatId
) {
event.issues.push('possible_menu_stack');
}
interactionDebugStore.events.push(event);
});
function appendAiLog(moduleName, entry) {
const key = String(moduleName || 'general');
if (!aiToolStore.logs.has(key)) aiToolStore.logs.set(key, []);
const bucket = aiToolStore.logs.get(key);
bucket.push({ ts: Date.now(), ...entry });
if (bucket.length > AI_LOG_LIMIT) bucket.splice(0, bucket.length - AI_LOG_LIMIT);
}
function rememberReplayEvent(userId, event) {
const key = Number(userId);
if (!Number.isFinite(key)) return;
if (!userReplayStore.has(key)) userReplayStore.set(key, []);
const bucket = userReplayStore.get(key);
bucket.push({ ts: Date.now(), ...event });
if (bucket.length > USER_REPLAY_LIMIT) bucket.splice(0, bucket.length - USER_REPLAY_LIMIT);
}
bot.use(async (ctx, next) => {
const userId = ctx && ctx.from ? Number(ctx.from.id) : null;
if (!userId) return next();
if (ctx.updateType === 'message' && ctx.message && typeof ctx.message.text === 'string') {
rememberReplayEvent(userId, {
type: ctx.message.text.startsWith('/') ? 'command' : 'message',
text: ctx.message.text.slice(0, 400),
});
} else if (ctx.updateType === 'callback_query') {
rememberReplayEvent(userId, {
type: 'callback',
callbackData: (ctx.callbackQuery && ctx.callbackQuery.data) || '',
});
}
let answeredCallback = false;
let emittedResponse = false;
const outboundButtons = [];
if (typeof ctx.reply === 'function') {
const originalReply = ctx.reply.bind(ctx);
ctx.reply = async (...args) => {
emittedResponse = true;
outboundButtons.push(...extractCallbackDataFromKeyboard(args[1] || {}));
const sent = await originalReply(...args);
rememberReplayEvent(userId, {
type: 'bot_reply',
text: String(args[0] || '').slice(0, 800),
});
return sent;
};
}
if (typeof ctx.editMessageText === 'function') {
const originalEdit = ctx.editMessageText.bind(ctx);
ctx.editMessageText = async (...args) => {
emittedResponse = true;
outboundButtons.push(...extractCallbackDataFromKeyboard(args[2] || {}));
const sent = await originalEdit(...args);
rememberReplayEvent(userId, {
type: 'bot_edit',
text: String(args[0] || '').slice(0, 800),
});
return sent;
};
}
if (typeof ctx.answerCbQuery === 'function') {
const originalAck = ctx.answerCbQuery.bind(ctx);
ctx.answerCbQuery = async (...args) => {
answeredCallback = true;
emittedResponse = true;
rememberReplayEvent(userId, {
type: 'callback_ack',
text: String(args[0] || '').slice(0, 200),
});
return originalAck(...args);
};
}
await next();
if (!aiToolStore.sniffer.active || ctx.updateType !== 'callback_query') return;
const issues = [];
if (!answeredCallback) issues.push('missing_answerCbQuery');
if (!emittedResponse) issues.push('silent_callback');
if (emittedResponse && outboundButtons.length > 0) {
const hasNav = outboundButtons.some((id) => /(back|home|menu)/i.test(id));
if (!hasNav) issues.push('menu_stack_stall_risk');
}
if (!issues.length) return;
const entry = {
ts: Date.now(),
userId,
callbackData: (ctx.callbackQuery && ctx.callbackQuery.data) || '',
issues,
};
aiToolStore.sniffer.feed.push(entry);
if (aiToolStore.sniffer.feed.length > 500) {
aiToolStore.sniffer.feed.splice(0, aiToolStore.sniffer.feed.length - 500);
}
appendAiLog('sniffer', entry);
});
// =========================
// State (DB-ready interfaces)
// =========================
const userStore = new Map();
const promoStore = {
bonusRule: DEFAULT_BONUS_RULE,
bugreports: [],
logs: [],
};
const promoManagerStore = {
nextPromoId: 1,
nextClaimId: 1,
promos: [],
claims: [],
eligibilityFailures: [],
};
// Legacy compatibility placeholders (promo logic now lives in promoManagerStore only)
const PROMO_AUDIENCE = { NEW_USER: 'new_user', EXISTING_USER: 'existing_user' };
const PROMO_REQUIREMENT_TYPE = { WAGER: 'wager', NO_REQUIREMENT: 'no_requirement' };
const promoCodeStore = { nextId: 1, codes: [] };
const giveawayStore = {
running: new Map(),
history: new Map(),
counter: 1,
};
// =========================
// Interaction Debug Store — tracks manual operator testing sessions
// =========================
const interactionDebugStore = {
active: false,
operatorId: null,
startedAt: null,
stoppedAt: null,
events: [], // interaction event objects appended during session
lastReportPath: null, // path to last generated report
};
const aiToolStore = {
logs: new Map(),
reports: new Map(),
settings: new Map(),
replaySessions: new Map(),
continueAs: new Map(),
sniffer: {
active: true,
feed: [],
lastSummary: null,
},
pendingPatch: new Map(),
};
const userReplayStore = new Map();
const AI_LOG_LIMIT = 100;
const USER_REPLAY_LIMIT = 120;
// =========================
// Tips Store — rotating silent group posts
// Source of truth: data/tooltips.json (populated by generate_tooltips.sh)
// =========================
const PROMO_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
const promoRuntimeCache = {
active_new_user_promo: { value: null, fetchedAt: 0, signature: null },
active_existing_user_promo: { value: null, fetchedAt: 0, signature: null },
};
function getPromoCacheKeyForAudience(audience) {
return normalizePromoAudience(audience) === 'existing_user'
? 'active_existing_user_promo'
: 'active_new_user_promo';
}
function normalizePromoManagerAudience(promo) {
if (!promo || typeof promo !== 'object') return 'new_user';
if (promo.requirement_type === PROMO_REQUIREMENT.EXISTING_USER || promo.requirement_type === PROMO_REQUIREMENT.EXISTING_USER_WITH_WAGER) return 'existing_user';
if (promo.existing_user_only) return 'existing_user';
return 'new_user';
}
function getPromoAmountValue(promo) {
return parsePromoAmount(
promo && (promo.amount ?? promo.amountSC ?? promo.bonus_amount_sc ?? promo.description ?? promo.notes),
);
}
function buildActivePromoRecord(promo, source = 'promo_manager_store') {
if (!promo) return null;
const audience = normalizePromoManagerAudience(promo);
return {
promo_id: Number(promo.promo_id) || Number(promo.id) || 0,
code: String(promo.code_or_link || promo.code || '').trim(),
amount: getPromoAmountValue(promo),
audience,
status: String(promo.status || PROMO_STATUS.ACTIVE).trim().toLowerCase(),
created_at: Number(promo.created_at || promo.createdAt) || Date.now(),
updated_at: Number(promo.updated_at || promo.updatedAt) || Date.now(),
priority: Number(promo.priority) || 0,
description: String(promo.description || promo.notes || '').trim(),
casino_base_url: String(promo.casino_base_url || '').trim(),
name: String(promo.name || `Promo #${promo.promo_id || promo.id || '0'}`).trim(),
source,
};
}
function selectActivePromoForAudience(audience) {
const normalizedAudience = normalizePromoAudience(audience);
const primary = promoManagerStore.promos
.map((promo) => buildActivePromoRecord(promo, 'promo_manager_store'))
.filter((promo) => promo && promo.status === PROMO_STATUS.ACTIVE && promo.audience === normalizedAudience && promo.code)
.sort((a, b) => (Number(b.priority) || 0) - (Number(a.priority) || 0)
|| (Number(b.created_at) || 0) - (Number(a.created_at) || 0)
|| (Number(b.promo_id) || 0) - (Number(a.promo_id) || 0))[0] || null;
if (primary) return primary;
const legacyCode = promoCodeStore.codes
.filter((promo) => {
const legacyAudience = normalizePromoAudience(promo.audience === PROMO_AUDIENCE.EXISTING_USER ? 'existing_user' : 'new_user');
return promo.active !== false && legacyAudience === normalizedAudience && String(promo.code || '').trim();
})
.sort((a, b) => (Number(b.priority) || 0) - (Number(a.priority) || 0)
|| (Number(b.createdAt) || 0) - (Number(a.createdAt) || 0)
|| (Number(b.id) || 0) - (Number(a.id) || 0))[0];
if (legacyCode) {
logEvent('warn', 'Active promo fallback: using legacy promoCodeStore', { audience: normalizedAudience, codeId: legacyCode.id });
return buildActivePromoRecord({
promo_id: legacyCode.id,
code_or_link: legacyCode.code,
amountSC: legacyCode.amountSC,
description: legacyCode.notes,
requirement_type: legacyCode.audience === PROMO_AUDIENCE.EXISTING_USER ? PROMO_REQUIREMENT.EXISTING_USER : PROMO_REQUIREMENT.NEW_USER_ONLY,
status: PROMO_STATUS.ACTIVE,
created_at: legacyCode.createdAt || Date.now(),
updated_at: legacyCode.updatedAt || Date.now(),
name: legacyCode.label || `Promo #${legacyCode.id}`,
}, 'promo_code_store');
}
if (normalizedAudience === 'new_user' && String(promoStore.code || '').trim()) {
logEvent('warn', 'Active promo fallback: using legacy promoStore', { audience: normalizedAudience });
return buildActivePromoRecord({
promo_id: 0,
code_or_link: promoStore.code,
amountSC: promoStore.amountSC,
description: promoStore.bonusRule,
requirement_type: PROMO_REQUIREMENT.NEW_USER_ONLY,
status: PROMO_STATUS.ACTIVE,
created_at: Date.now(),
updated_at: Date.now(),
name: 'Legacy Promo',
}, 'promo_store');
}
return null;
}
function refreshActivePromoCache(audience, reason = 'refresh') {
const normalizedAudience = normalizePromoAudience(audience);
const cacheKey = getPromoCacheKeyForAudience(normalizedAudience);
const cache = promoRuntimeCache[cacheKey];
const previousSignature = cache.signature;
const promo = selectActivePromoForAudience(normalizedAudience);
cache.value = promo;
cache.fetchedAt = Date.now();
cache.signature = promo ? `${promo.promo_id}:${promo.code}:${promo.amount || ''}:${promo.updated_at}:${promo.source}` : 'none';
logEvent('info', 'Promo cache refreshed', { cacheKey, audience: normalizedAudience, reason, promoId: promo && promo.promo_id, code: promo && promo.code, amount: promo && promo.amount });
if (previousSignature && previousSignature !== cache.signature) {
logEvent('info', 'Promo changed', { cacheKey, audience: normalizedAudience, previousSignature, nextSignature: cache.signature, reason });
}
if (!promo) {
logEvent('warn', 'Promo fallback: no active promo found', { cacheKey, audience: normalizedAudience, reason });
}
return promo;
}
function invalidateActivePromoCache(audience = null, reason = 'manual') {
const audiences = audience ? [normalizePromoAudience(audience)] : ['new_user', 'existing_user'];
for (const itemAudience of audiences) {
const cacheKey = getPromoCacheKeyForAudience(itemAudience);
promoRuntimeCache[cacheKey].value = null;
promoRuntimeCache[cacheKey].fetchedAt = 0;
promoRuntimeCache[cacheKey].signature = null;
logEvent('info', 'Promo cache invalidated', { cacheKey, audience: itemAudience, reason });
}
}
function getActivePromoForAudience(audience, { forceRefresh = false } = {}) {
const normalizedAudience = normalizePromoAudience(audience);
const cacheKey = getPromoCacheKeyForAudience(normalizedAudience);
const cache = promoRuntimeCache[cacheKey];
if (!forceRefresh && cache.fetchedAt && (Date.now() - cache.fetchedAt) < PROMO_CACHE_TTL_MS) {
return cache.value;
}
return refreshActivePromoCache(normalizedAudience, forceRefresh ? 'force_refresh' : 'cache_miss');
}
function getPromoForUser(user, options = {}) {
return getActivePromoForAudience(user && user.claimedPromo ? 'existing_user' : 'new_user', options);
}
function getActiveNewUserPromoCode() {
const promo = getActivePromoForAudience('new_user');
return promo ? promo.code : null;
}