-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
1206 lines (1017 loc) · 44.6 KB
/
worker.js
File metadata and controls
1206 lines (1017 loc) · 44.6 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
const botToken='xxxxxx';
const CACHE_TTL = 3600000;
const inMemoryKV = {
async get(key) {
const v = _inMemoryKVStore.get(key);
return typeof v === 'undefined' ? null : v;
},
async put(key, value) {
_inMemoryKVStore.set(key, value);
return;
}
};
const RESET_HOUR = 8; // 8 AM
function getCurrentDateKey(now = new Date()) {
const d = new Date(now);
if (d.getHours() < RESET_HOUR) {
d.setDate(d.getDate() - 1);
}
return d.toISOString().split('T')[0];
}
// Achievement definitions
const ACHIEVEMENTS = {
FIRST_BLOOD: { name: "First Blood", desc: "Solve your first problem", emoji: "🩸" },
STREAK_7: { name: "Week Warrior", desc: "7-day solving streak", emoji: "🔥" },
RATING_100: { name: "Centurion", desc: "Solve 100 problems", emoji: "💯" },
ALL_TAGS: { name: "Jack of All Trades", desc: "Solve problems from 10 different tags", emoji: "🎭" },
RATING_1600: { name: "Expert", desc: "Solve a 1600+ rated problem", emoji: "⭐" },
DAILY_CHAMP: { name: "Daily Champion", desc: "Complete daily challenge", emoji: "🏆" }
};
// Command descriptions (kept mostly for reference)
const COMMANDS = {
"/start": "Start the bot",
"/stats": "View your solving statistics",
"/contest": "Upcoming contests",
"/goal": "Set daily goals",
"/challenge": "Daily challenge",
"/compare": "Compare with friends",
"/browse": "Browse problems interactively",
"/reminder": "Set contest reminders",
"/achievements": "View your achievements",
"/help": "Show all commands",
"/history": "Your problem history"
};
let problemsCache = { data: null, timestamp: 0 };
let contestsCache = { data: null, timestamp: 0 };
function getDifficultyText(rating) {
if (!rating) return "Unknown";
if (rating < 1000) return "Very Easy";
if (rating < 1400) return "Easy";
if (rating < 1800) return "Medium";
if (rating < 2200) return "Hard";
return "Very Hard";
}
function createKeyboard(buttonRows) {
return { inline_keyboard: buttonRows };
}
// Telegram API sendMessage wrapper
async function sendMessage(chatId, text, botToken, replyMarkup = null, parseMode = null) {
const payload = { chat_id: chatId, text };
if (replyMarkup) payload.reply_markup = replyMarkup;
if (parseMode) payload.parse_mode = parseMode;
try {
const res = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const json = await res.json();
if (!res.ok) {
console.error('Telegram API error', json);
return false;
}
return true;
} catch (err) {
console.error('sendMessage error', err);
return false;
}
}
async function fetchCFProblems() {
const now = Date.now();
if (problemsCache.data && (now - problemsCache.timestamp) < CACHE_TTL) {
return problemsCache.data;
}
try {
const res = await fetch('https://codeforces.com/api/problemset.problems');
const json = await res.json();
if (json.status !== 'OK') {
throw new Error('Codeforces API returned non-OK');
}
problemsCache.data = json.result.problems;
problemsCache.timestamp = now;
return problemsCache.data;
} catch (err) {
console.error('fetchCFProblems error', err);
return problemsCache.data || [];
}
}
async function getProblemsWithSmartCache() {
try {
const problems = await fetchCFProblems();
return problems || [];
} catch (err) {
console.error('getProblemsWithSmartCache error', err);
return [];
}
}
async function fetchContests() {
const now = Date.now();
if (contestsCache.data && (now - contestsCache.timestamp) < CACHE_TTL) {
return contestsCache.data;
}
try {
const res = await fetch('https://codeforces.com/api/contest.list');
const json = await res.json();
if (json.status === 'OK') {
contestsCache.data = json.result;
contestsCache.timestamp = now;
return contestsCache.data;
}
return contestsCache.data || [];
} catch (err) {
console.error('fetchContests error', err);
return contestsCache.data || [];
}
}
function filterProblems(problems, mode, rating = null, tag = null, indexLetter = null, count = 5, options = {}) {
let filtered = Array.isArray(problems) ? [...problems] : [];
if (mode === 'rating') {
filtered = filtered.filter(p => p.rating === rating);
} else if (mode === 'tag') {
filtered = filtered.filter(p => tag && p.tags && p.tags.some(t => t.toLowerCase() === tag.toLowerCase()));
} else if (mode === 'index') {
filtered = filtered.filter(p => p.index === indexLetter);
} else if (mode === 'rating_tag') {
filtered = filtered.filter(p =>
p.rating === rating &&
tag && p.tags && p.tags.some(t => t.toLowerCase() === tag.toLowerCase())
);
} else if (mode === 'random') {
const minRating = options.minRating || 800;
const maxRating = options.maxRating || 3500;
filtered = filtered.filter(p => p.rating >= minRating && p.rating <= maxRating);
} else if (mode === 'recent_contest') {
// Simple heuristic to pick relatively recent contests/problems
const sixMonthsAgo = Date.now() - 180 * 24 * 60 * 60 * 1000;
filtered = filtered.filter(p => p.contestId && p.contestId > 1000);
}
filtered = filtered.filter(p => p && p.contestId && p.index);
// Shuffle
for (let i = filtered.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[filtered[i], filtered[j]] = [filtered[j], filtered[i]];
}
return filtered.slice(0, count);
}
async function dbGetUser(chatId, KV) {
try {
const raw = await KV.get(`user:${chatId}`);
return raw ? JSON.parse(raw) : null;
} catch (err) {
console.error('dbGetUser error', err);
return null;
}
}
async function dbUpsertUser(chatId, updates, KV) {
try {
const existingRaw = await KV.get(`user:${chatId}`);
const existing = existingRaw ? JSON.parse(existingRaw) : {};
const merged = { ...existing, ...updates, chat_id: chatId };
await KV.put(`user:${chatId}`, JSON.stringify(merged));
return merged;
} catch (err) {
console.error('dbUpsertUser error', err);
return null;
}
}
async function dbAddHistory(chatId, problem, KV) {
try {
const historyItem = {
chat_id: chatId,
contestId: problem.contestId,
problem_index: problem.index,
name: problem.name,
rating: problem.rating,
tags: problem.tags || [],
ts: new Date().toISOString()
};
const userHistoryKey = `user_history:${chatId}`;
const raw = await KV.get(userHistoryKey);
let list = raw ? JSON.parse(raw) : [];
list.unshift(historyItem);
if (list.length > 50) list = list.slice(0, 50);
await KV.put(userHistoryKey, JSON.stringify(list));
await checkAchievements(chatId, KV);
} catch (err) {
console.error('dbAddHistory error', err);
}
}
async function dbGetHistory(chatId, limit = 10, KV) {
try {
const raw = await KV.get(`user_history:${chatId}`);
if (!raw) return [];
const list = JSON.parse(raw);
return list.slice(0, limit);
} catch (err) {
console.error('dbGetHistory error', err);
return [];
}
}
async function dbGetAllHistory(chatId, KV) {
try {
const raw = await KV.get(`user_history:${chatId}`);
return raw ? JSON.parse(raw) : [];
} catch (err) {
console.error('dbGetAllHistory error', err);
return [];
}
}
async function getUserStats(chatId, KV, botToken) {
const history = await dbGetAllHistory(chatId, KV);
if (!history || history.length === 0) {
return sendMessage(chatId, "No problems solved yet! Start with /start", botToken);
}
const solvedByRating = {};
const solvedByTag = {};
let totalRating = 0;
let maxRating = 0;
let ratedCount = 0;
history.forEach(p => {
const ratingKey = p.rating || 'Unknown';
solvedByRating[ratingKey] = (solvedByRating[ratingKey] || 0) + 1;
p.tags?.forEach(t => { solvedByTag[t] = (solvedByTag[t] || 0) + 1; });
if (p.rating) { totalRating += p.rating; maxRating = Math.max(maxRating, p.rating); ratedCount++; }
});
const averageRating = ratedCount ? Math.round(totalRating / ratedCount) : 0;
let statsMsg = "📊 *Your Statistics:*\n\n";
statsMsg += `✅ Total Solved: *${history.length}* problems\n`;
statsMsg += `⭐ Average Rating: *${averageRating || 'N/A'}*\n`;
statsMsg += `🏆 Highest Rated: *${maxRating || 'N/A'}*\n\n`;
statsMsg += "📈 By Rating:\n";
Object.keys(solvedByRating)
.sort((a, b) => {
if (a === 'Unknown') return 1;
if (b === 'Unknown') return -1;
return a - b;
})
.forEach(rating => {
const count = solvedByRating[rating];
const percentage = ((count / history.length) * 100).toFixed(1);
const bar = "█".repeat(Math.round(percentage / 10));
statsMsg += `${rating}: ${bar} ${count} (${percentage}%)\n`;
});
const topTags = Object.entries(solvedByTag).sort(([, a], [, b]) => b - a).slice(0, 5);
if (topTags.length > 0) {
statsMsg += "\n🏷️ Top Tags:\n";
topTags.forEach(([tag, count]) => { statsMsg += `• ${tag}: ${count}\n`; });
}
return sendMessage(chatId, statsMsg, botToken, null, "Markdown");
}
// Contests
async function getUpcomingContests(chatId, botToken) {
try {
const contests = await fetchContests();
const upcoming = (contests || []).filter(c => c.phase === 'BEFORE').slice(0, 8);
if (upcoming.length === 0) {
return sendMessage(chatId, "No upcoming contests found.", botToken);
}
let msg = "🗓️ *Upcoming Contests:*\n\n";
upcoming.forEach(contest => {
const startTime = new Date(contest.startTimeSeconds * 1000);
const timeUntilMs = contest.startTimeSeconds * 1000 - Date.now();
const days = Math.floor(timeUntilMs / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeUntilMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
msg += `🏆 [${contest.name}](https://codeforces.com/contest/${contest.id})\n`;
msg += `⏰ ${startTime.toLocaleDateString()} ${startTime.toLocaleTimeString()}\n`;
msg += `⏳ Starts in ${days}d ${hours}h\n\n`;
});
const keyboard = createKeyboard([
[{ text: "🔔 Set Reminder", callback_data: "set_reminder" }],
[{ text: "📚 Practice Problems", callback_data: "practice_for_contest" }]
]);
return sendMessage(chatId, msg, botToken, keyboard, "Markdown");
} catch (err) {
console.error('getUpcomingContests error', err);
return sendMessage(chatId, "❌ Failed to fetch contests", botToken);
}
}
// Goals
async function setDailyGoal(chatId, count, KV, botToken) {
const parsed = parseInt(count, 10);
const goalObj = {
target: parsed,
startDate: new Date().toISOString(),
current: 0,
streak: 0
};
await KV.put(`goal:${chatId}`, JSON.stringify(goalObj));
return sendMessage(chatId, `🎯 Daily goal set: ${parsed} problems per day!`, botToken);
}
async function checkGoalProgress(chatId, KV, botToken) {
const raw = await KV.get(`goal:${chatId}`);
if (!raw) return sendMessage(chatId, "No goal set. Use /goal <number> to set a daily goal.", botToken);
const goal = JSON.parse(raw);
const today = new Date().toDateString();
const history = await dbGetAllHistory(chatId, KV);
const todayProblems = history.filter(p => new Date(p.ts).toDateString() === today);
goal.current = todayProblems.length;
const progress = Math.min(100, Math.round((goal.current / goal.target) * 100 || 0));
const filled = Math.floor(progress / 10);
const progressBar = "█".repeat(filled) + "░".repeat(10 - filled);
let msg = `🎯 *Daily Goal Progress*\n\n`;
msg += `Target: ${goal.target} problems\n`;
msg += `Solved today: ${goal.current} problems\n\n`;
msg += `Progress: ${progressBar} ${progress}%\n\n`;
if (goal.current >= goal.target) {
msg += "🎉 *Goal completed!* Amazing work!";
goal.streak = (goal.streak || 0) + 1;
if (goal.streak > 1) msg += `\n🔥 Streak: ${goal.streak} days!`;
} else {
msg += `Keep going! ${Math.max(0, goal.target - goal.current)} more to go.`;
}
await KV.put(`goal:${chatId}`, JSON.stringify(goal));
return sendMessage(chatId, msg, botToken, null, "Markdown");
}
// Daily Challenge
async function startDailyChallenge(chatId, KV, botToken) {
const today = getCurrentDateKey();
const challengeKey = `challenge:${today}`;
try {
let raw = await KV.get(challengeKey);
let challenge;
if (!raw) {
const problems = await fetchCFProblems();
if (!problems || problems.length === 0) {
return sendMessage(chatId, "❌ Cannot generate challenge - Codeforces API is unavailable. Try again later.", botToken);
}
const easy = filterProblems(problems, 'rating', 800, null, null, 1);
const medium = filterProblems(problems, 'rating', 1200, null, null, 1);
const hard = filterProblems(problems, 'rating', 1600, null, null, 1);
let challengeProblems = [...easy, ...medium, ...hard].filter(Boolean);
if (challengeProblems.length === 0) {
challengeProblems = filterProblems(problems, 'random', null, null, null, 3);
}
challenge = { problems: challengeProblems, participants: {}, date: today };
await KV.put(challengeKey, JSON.stringify(challenge));
console.log(`Created new daily challenge with ${challengeProblems.length} problems`);
} else {
challenge = JSON.parse(raw);
}
const participant = challenge.participants[chatId];
if (participant) {
let statusMsg = "🎲 *Today's Challenge Problems*\n\n";
statusMsg += "📋 **Your Current Progress:**\n";
statusMsg += `Solved: ${participant.solved?.length || 0}/${challenge.problems.length} problems\n\n`;
challenge.problems.forEach((p, index) => {
const link = `https://codeforces.com/problemset/problem/${p.contestId}/${p.index}`;
const isSolved = participant.solved?.includes(`${p.contestId}${p.index}`);
statusMsg += `${isSolved ? '✅' : '◻️'} ${index + 1}. [${p.name}](${link})\n`;
statusMsg += ` Rating: ${p.rating || '?'}⭐ | ${getDifficultyText(p.rating)}\n\n`;
});
if (participant.completed) {
statusMsg += "🎉 *CHALLENGE COMPLETED!* 🏆\nYou've earned the Daily Champion achievement!\n\n";
} else {
statusMsg += "💡 **Keep going!** Solve all problems to complete the challenge.\n\n";
}
const keyboard = createKeyboard([
[{ text: "🔄 Check Progress", callback_data: "refresh_challenge" }],
[{ text: "📊 View Stats", callback_data: "challenge_stats" }],
[{ text: "🎯 New Problems", callback_data: "get_new_problems" }]
]);
return sendMessage(chatId, statusMsg, botToken, keyboard, "Markdown");
}
// New user invitation
let msg = "🎲 *Daily Challenge - Ready to Join!*\n\n";
msg += `Solve ${challenge.problems.length} problems of varying difficulty:\n\n`;
challenge.problems.forEach((p, idx) => {
const link = `https://codeforces.com/problemset/problem/${p.contestId}/${p.index}`;
msg += `${idx + 1}. [${p.name}](${link})\n`;
msg += ` Rating: ${p.rating || '?'}⭐ | ${getDifficultyText(p.rating)}\n\n`;
});
msg += "**Rewards:**\n";
msg += "✅ Complete all → 🏆 Daily Champion achievement\n";
msg += "✅ Track progress and streaks\n";
msg += "✅ Compare with other participants\n";
const keyboard = createKeyboard([
[{ text: "🎯 Join Challenge", callback_data: "join_challenge" }],
[{ text: "👀 View Problems Only", callback_data: "view_challenge_problems" }]
]);
return sendMessage(chatId, msg, botToken, keyboard, "Markdown");
} catch (err) {
console.error('startDailyChallenge error', err);
return sendMessage(chatId, "❌ Error loading daily challenge. Please try again.", botToken);
}
}
// Achievement system
async function checkAchievements(chatId, KV) {
try {
const user = await dbGetUser(chatId, KV) || {};
const history = await dbGetAllHistory(chatId, KV);
if (!history || history.length === 0) return;
const achievements = user.achievements || {};
const newAchievements = [];
if (history.length >= 1 && !achievements.FIRST_BLOOD) newAchievements.push('FIRST_BLOOD');
if (history.length >= 100 && !achievements.RATING_100) newAchievements.push('RATING_100');
if (!achievements.RATING_1600 && history.some(p => p.rating >= 1600)) newAchievements.push('RATING_1600');
const uniqueTags = new Set();
history.forEach(p => p.tags?.forEach(t => uniqueTags.add(t)));
if (uniqueTags.size >= 10 && !achievements.ALL_TAGS) newAchievements.push('ALL_TAGS');
if (newAchievements.length > 0) {
// Unlock achievements (we don't have botToken here; unlocking will only update DB;
// notification will be sent by caller that has botToken (we call unlockAchievements with botToken below))
const unlocked = { ...(achievements || {}) };
newAchievements.forEach(k => {
unlocked[k] = { unlocked: new Date().toISOString(), ...ACHIEVEMENTS[k] };
});
await dbUpsertUser(chatId, { achievements: unlocked }, KV);
}
} catch (err) {
console.error('checkAchievements error', err);
}
}
async function unlockAchievements(chatId, achievementKeys, KV, botToken) {
try {
const user = await dbGetUser(chatId, KV) || {};
const achievements = user.achievements || {};
achievementKeys.forEach(key => {
achievements[key] = { unlocked: new Date().toISOString(), ...ACHIEVEMENTS[key] };
});
await dbUpsertUser(chatId, { achievements }, KV);
// Send notifications
for (const key of achievementKeys) {
const achievement = ACHIEVEMENTS[key];
const msg = `🎉 *Achievement Unlocked!*\n\n${achievement.emoji} *${achievement.name}*\n${achievement.desc}`;
await sendMessage(chatId, msg, botToken, null, "Markdown");
}
} catch (err) {
console.error('unlockAchievements error', err);
}
}
// Daily Notification System
let dailyNotificationSent = {}; // Track if daily problems were sent today
// Function to send daily problems to a user
async function sendDailyProblems(chatId, KV, botToken) {
const today = getCurrentDateKey();
// Check if already sent today (based on reset-hour day key)
if (dailyNotificationSent[chatId] === today) {
return; // Already sent today
}
try {
const todaysProblems = await getOrCreateTodaysProblems(chatId, KV, false);
if (!todaysProblems || todaysProblems.length === 0) {
console.log('Cannot send daily problems - CF API unavailable or no problems generated');
return;
}
let message = `📅 *Today's Recommended Problems* 🚀\n\n`;
message += `Here are your daily practice problems to keep you sharp:\n\n`;
todaysProblems.forEach((p, index) => {
const link = `https://codeforces.com/problemset/problem/${p.contestId}/${p.index}`;
message += `${index + 1}. [${p.name}](${link})\n`;
message += ` Rating: ${p.rating}⭐ | ${getDifficultyText(p.rating)}\n`;
message += ` Tags: ${p.tags?.slice(0, 3).join(', ') || 'None'}\n\n`;
});
message += `💡 *Tip:* Try to solve at least one problem daily to maintain consistency!\n`;
message += `✅ Solving these will count towards your daily goals.`;
const keyboard = createKeyboard([
[{ text: "🎯 Set Daily Goal", callback_data: "set_goal_menu" }],
[{ text: "🏆 Join Daily Challenge", callback_data: "daily_challenge" }],
[{ text: "📊 View Progress", callback_data: "show_stats" }]
]);
await sendMessage(chatId, message, botToken, keyboard, "Markdown");
// Mark as sent for today (worker-local cache)
dailyNotificationSent[chatId] = today;
console.log(`✅ Daily problems sent to ${chatId}`);
} catch (error) {
console.error('Error sending daily problems:', error);
}
}
// Function to check and send daily problems to all active users
async function sendDailyProblemsToAllUsers(KV, botToken) {
try {
console.log('🔄 Starting daily problem distribution...');
const activeUsers = await getAllActiveUsers(KV);
if (activeUsers.length === 0) {
console.log('No active users found for daily problems');
return;
}
console.log(`Sending daily problems to ${activeUsers.length} users`);
for (let i = 0; i < activeUsers.length; i++) {
const chatId = activeUsers[i];
await sendDailyProblems(chatId, KV, botToken);
if (i < activeUsers.length - 1) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
console.log('✅ Daily problem distribution completed');
} catch (error) {
console.error('Error in daily problem distribution:', error);
}
}
async function getAllActiveUsers(KV) {
const users = [];
const userList = await KV.get('active_users');
if (userList) {
return JSON.parse(userList);
}
return users;
}
async function getOrCreateTodaysProblems(chatId, KV, force = false) {
const today = getCurrentDateKey();
const key = `todays_problems:${today}:${chatId}`;
try {
if (!KV) {
console.error('getOrCreateTodaysProblems: KV binding is not provided');
return [];
}
if (!force) {
const raw = await KV.get(key);
console.log(`getOrCreateTodaysProblems: KV.get(${key}) returned length:`, raw ? raw.length : 0);
if (raw) {
try {
const stored = JSON.parse(raw);
if (Array.isArray(stored) && stored.length > 0) return stored;
} catch (e) {
console.warn('Failed to parse stored todays problems, regenerating', e);
}
}
}
const problems = await getProblemsWithSmartCache();
if (!problems || problems.length === 0) return [];
const p1200 = filterProblems(problems, 'rating', 1200, null, null, 1);
const p1300 = filterProblems(problems, 'rating', 1300, null, null, 1);
const p1400 = filterProblems(problems, 'rating', 1400, null, null, 1);
let todays = [...p1200, ...p1300, ...p1400].filter(Boolean);
if (todays.length === 0) {
todays = filterProblems(problems, 'random', null, null, null, 3, { minRating: 1100, maxRating: 1500 });
}
const toStore = todays.map(p => ({ contestId: p.contestId, index: p.index, name: p.name, rating: p.rating, tags: p.tags || [] }));
await KV.put(key, JSON.stringify(toStore));
console.log(`getOrCreateTodaysProblems: Stored ${toStore.length} problems at key ${key}`);
return toStore;
} catch (err) {
console.error('getOrCreateTodaysProblems error', err);
return [];
}
}
async function trackActiveUser(chatId, KV) {
try {
const userListKey = 'active_users';
let activeUsers = await KV.get(userListKey);
if (activeUsers) {
activeUsers = JSON.parse(activeUsers);
} else {
activeUsers = [];
}
if (!activeUsers.includes(chatId)) {
activeUsers.push(chatId);
await KV.put(userListKey, JSON.stringify(activeUsers));
}
await KV.put(`user_activity:${chatId}`, Date.now().toString());
} catch (error) {
console.error('Error tracking active user:', error);
}
}
// Manual command to get today's problems
async function sendTodaysProblems(chatId, KV, botToken, force = false) {
const today = getCurrentDateKey();
try {
const todaysProblems = await getOrCreateTodaysProblems(chatId, KV, force);
if (!todaysProblems || todaysProblems.length === 0) {
return sendMessage(chatId,
"❌ Cannot fetch problems right now. Codeforces API might be temporarily unavailable.\n\nTry again in a few minutes!",
botToken
);
}
let message = `📅 *Today's Practice Problems* 🎯\n\n`;
message += `Here are your recommended problems for today:\n\n`;
todaysProblems.forEach((p, index) => {
const link = `https://codeforces.com/problemset/problem/${p.contestId}/${p.index}`;
message += `**${index + 1}. ${p.rating}⭐ Challenge**\n`;
message += `[${p.name}](${link})\n`;
message += `Tags: ${p.tags?.slice(0, 3).join(', ') || 'None'}\n\n`;
});
message += `🔥 *Progression Path:*\n`;
message += `• 1200⭐: Foundation building\n`;
message += `• 1300⭐: Skill development\n`;
message += `• 1400⭐: Advanced concepts\n\n`;
message += `💪 Complete all three for maximum growth!`;
const keyboard = createKeyboard([
[{ text: "✅ Mark as Started", callback_data: "start_todays_problems" }],
[{ text: "🔄 Get Different Problems", callback_data: "refresh_todays_problems" }],
[{ text: "📊 Track Progress", callback_data: "show_stats" }]
]);
dailyNotificationSent[chatId] = today;
return sendMessage(chatId, message, botToken, keyboard, "Markdown");
} catch (error) {
console.error('Error sending today problems:', error);
return sendMessage(chatId,
"❌ Error fetching today's problems. Please try again later.",
botToken
);
}
}
async function showAchievements(chatId, KV, botToken) {
const user = await dbGetUser(chatId, KV) || {};
const achievements = user.achievements || {};
const allKeys = Object.keys(ACHIEVEMENTS);
let msg = "🏆 *Your Achievements*\n\n";
allKeys.forEach(key => {
const achievement = ACHIEVEMENTS[key];
const unlocked = achievements[key];
if (unlocked) {
const date = new Date(unlocked.unlocked).toLocaleDateString();
msg += `✅ ${achievement.emoji} *${achievement.name}*\n ${achievement.desc}\n 🗓️ ${date}\n\n`;
} else {
msg += `🔒 ${achievement.emoji} ${achievement.name}\n ${achievement.desc}\n\n`;
}
});
msg += `📊 Total: ${Object.keys(achievements || {}).length}/${allKeys.length} unlocked`;
return sendMessage(chatId, msg, botToken, null, "Markdown");
}
// Problem browsing and sending
async function browseProblems(chatId, page = 0, KV, botToken) {
const problems = await fetchCFProblems();
const pageSize = 5;
const start = page * pageSize;
const pageProblems = problems.slice(start, start + pageSize);
if (!pageProblems || pageProblems.length === 0) {
return sendMessage(chatId, "No more problems to show!", botToken);
}
let msg = `🔍 *Browse Problems* (Page ${page + 1})\n\n`;
pageProblems.forEach((p, index) => {
msg += `${index + 1}. [${p.name}](https://codeforces.com/problemset/problem/${p.contestId}/${p.index})\n`;
msg += ` Rating: ${p.rating || '?'} | Index: ${p.index}\n`;
msg += ` Tags: ${p.tags?.slice(0, 3).join(', ') || 'None'}\n\n`;
});
const keyboardRows = pageProblems.map((p) => ([
{ text: `${p.index} - ${p.name.substring(0, 20)}...`, callback_data: `problem_${p.contestId}_${p.index}` }
]));
const navRow = [];
if (page > 0) navRow.push({ text: "⬅️ Previous", callback_data: `browse_${page - 1}` });
navRow.push({ text: "Next ➡️", callback_data: `browse_${page + 1}` });
keyboardRows.push(navRow);
keyboardRows.push([{ text: "🏠 Main Menu", callback_data: "main_menu" }]);
const keyboard = createKeyboard(keyboardRows);
return sendMessage(chatId, msg, botToken, keyboard, "Markdown");
}
async function sendProblems(chatId, problems, KV, botToken) {
if (!problems || problems.length === 0) {
return sendMessage(chatId, "❌ No problems found for your filters.", botToken);
}
for (const p of problems) {
const link = `https://codeforces.com/problemset/problem/${p.contestId}/${p.index}`;
const name = p.name;
const rating = p.rating || "?";
const tags = p.tags ? p.tags.slice(0, 3).join(", ") : "";
await sendMessage(chatId, `[${name}](${link}) — ${rating}⭐ (${tags})`, botToken, null, "Markdown");
await dbAddHistory(chatId, p, KV);
}
const keyboard = createKeyboard([
[{ text: "🔄 More Problems", callback_data: "main_menu" }],
[{ text: "📊 View Stats", callback_data: "show_stats" }]
]);
return sendMessage(chatId, "✅ Problems sent! Keep up the great work! 🚀", botToken, keyboard);
}
// Help & main menu
async function showHelp(chatId, botToken) {
let helpMsg = "🤖 *Codeforces Bot - Complete Guide*\n\n";
helpMsg += "*🎯 Basic Commands:*\n";
helpMsg += "/start - Start the bot and choose mode\n";
helpMsg += "/help - Show this help message\n";
helpMsg += "/history - Your recent problem history\n\n";
helpMsg += "*📊 Analytics Commands:*\n";
helpMsg += "/stats - Detailed solving statistics\n";
helpMsg += "/achievements - View your achievements\n\n";
helpMsg += "*🏆 Contest & Goals:*\n";
helpMsg += "/contest - Upcoming contests\n";
helpMsg += "/goal <number> - Set daily goal\n";
helpMsg += "/challenge - Daily challenge\n\n";
helpMsg += "*🔍 Exploration:*\n";
helpMsg += "/browse - Browse problems interactively\n";
helpMsg += "/compare - Compare with friends (coming soon)\n\n";
helpMsg += "*💡 Pro Tips:*\n";
helpMsg += "• Use buttons for quick navigation\n";
helpMsg += "• Set daily goals for consistency\n";
helpMsg += "• Join daily challenges for motivation\n";
helpMsg += "• Check /stats to track progress\n";
const keyboard = createKeyboard([
[{ text: "🎯 Start Solving", callback_data: "mode_rating" }],
[{ text: "📊 View Stats", callback_data: "show_stats" }],
[{ text: "🏆 Daily Challenge", callback_data: "daily_challenge" }],
[{ text: "🗓️ Upcoming Contests", callback_data: "upcoming_contests" }]
]);
return sendMessage(chatId, helpMsg, botToken, keyboard, "Markdown");
}
async function showMainMenu(chatId, KV, botToken) {
const user = await dbGetUser(chatId, KV);
const history = await dbGetAllHistory(chatId, KV);
const solvedCount = (history || []).length;
let msg = "🤖 *Codeforces Bot - Main Menu*\n\n";
msg += `✅ Problems Solved: *${solvedCount}*\n`;
const goalRaw = await KV.get(`goal:${chatId}`);
if (goalRaw) {
const goal = JSON.parse(goalRaw);
msg += `🎯 Daily Goal: *${goal.current || 0}/${goal.target || 0}*\n`;
}
msg += "\nChoose an option below:";
const keyboard = createKeyboard([
[
{ text: "🎯 By Rating", callback_data: "mode_rating" },
{ text: "🏷️ By Tag", callback_data: "mode_tag" }
],
[
{ text: "🔤 By Index", callback_data: "mode_index" },
{ text: "⭐ Rating+Tag", callback_data: "mode_rating_tag" }
],
[
{ text: "📊 Statistics", callback_data: "show_stats" },
{ text: "🏆 Achievements", callback_data: "show_achievements" }
],
[
{ text: "🎲 Daily Challenge", callback_data: "daily_challenge" },
{ text: "🗓️ Contests", callback_data: "upcoming_contests" }
],
[
{ text: "🔍 Browse", callback_data: "browse_0" },
{ text: "🎯 Set Goal", callback_data: "set_goal_menu" }
],
[{ text: "ℹ️ Help", callback_data: "show_help" }]
]);
return sendMessage(chatId, msg, botToken, keyboard, "Markdown");
}
async function handleStart(chatId, KV, botToken) {
await dbUpsertUser(chatId, {
step: null,
mode: null,
rating: null,
tag: null,
index_letter: null,
count: null,
joined_date: new Date().toISOString()
}, KV);
await trackActiveUser(chatId, KV);
return showMainMenu(chatId, KV, botToken);
}
// Get fresh problems (used by callbacks)
async function getNewProblems(chatId, KV, botToken) {
try {
const problems = await fetchCFProblems();
if (!problems || problems.length === 0) {
return sendMessage(chatId, "⚠️ Codeforces API unavailable. Try again later.", botToken);
}
const easy = filterProblems(problems, 'rating', 800, null, null, 1);
const medium = filterProblems(problems, 'rating', 1200, null, null, 1);
const hard = filterProblems(problems, 'rating', 1600, null, null, 1);
const selected = [...easy, ...medium, ...hard].filter(Boolean);
if (selected.length === 0) {
return sendMessage(chatId, "⚠️ Couldn’t find new problems right now.", botToken);
}
let msg = "🎯 *Fresh Problem Set for You*\n\n";
selected.forEach((p, idx) => {
const link = `https://codeforces.com/problemset/problem/${p.contestId}/${p.index}`;
msg += `${idx + 1}. [${p.name}](${link})\n`;
msg += ` Rating: ${p.rating || '?'}⭐ | ${getDifficultyText(p.rating)}\n\n`;
});
msg += "💡 Try solving these to boost your skills!";
return sendMessage(chatId, msg, botToken, null, "Markdown");
} catch (err) {
console.error('getNewProblems error', err);
return sendMessage(chatId, "❌ Failed to fetch new problems.", botToken);
}
}
async function showChallengeStats(chatId, KV, botToken) {
try {
const today = getCurrentDateKey();
const data = await KV.get(`challenge:${today}`);
if (!data) return sendMessage(chatId, "⚠️ No active challenge found for today.", botToken);
const challenge = JSON.parse(data);
const participants = Object.keys(challenge.participants || {});
if (participants.length === 0) return sendMessage(chatId, "📊 No one has joined today’s challenge yet!", botToken);
let completedCount = 0;
for (const id in challenge.participants) {
if (challenge.participants[id].completed) completedCount++;
}
const msg =
`📈 *Today's Challenge Stats*\n\n` +
`👥 Total Participants: ${participants.length}\n` +
`🏆 Completed: ${completedCount}\n` +
`🔥 Completion Rate: ${((completedCount / participants.length) * 100).toFixed(1)}%\n\n` +
`Keep solving to climb the leaderboard! 💪`;
return sendMessage(chatId, msg, botToken, null, "Markdown");
} catch (err) {
console.error('showChallengeStats error', err);
return sendMessage(chatId, "❌ Failed to fetch challenge stats.", botToken);
}
}
async function handleCallback(callbackData, chatId, KV, botToken) {
console.log(`Handling callback: ${callbackData} for chat ${chatId}`);
if (callbackData.startsWith('mode_')) {
const mode = callbackData.split('_')[1];
await dbUpsertUser(chatId, { mode, step: null }, KV);
if (mode === 'rating') {
await dbUpsertUser(chatId, { step: 'await_rating' }, KV);
return sendMessage(chatId, "Enter rating (e.g., 1200):", botToken);
} else if (mode === 'tag') {
await dbUpsertUser(chatId, { step: 'await_tag' }, KV);
return sendMessage(chatId, "Enter tag (e.g., dp, greedy, math):", botToken);
} else if (mode === 'index') {
await dbUpsertUser(chatId, { step: 'await_index' }, KV);
return sendMessage(chatId, "Enter index letter (e.g., A, B, C):", botToken);
} else if (mode === 'rating_tag') {
await dbUpsertUser(chatId, { step: 'await_rating_tag_rating' }, KV);
return sendMessage(chatId, "Enter rating first (e.g., 1300):", botToken);
}
} else if (callbackData === 'show_stats') {
return getUserStats(chatId, KV, botToken);
} else if (callbackData === 'show_achievements') {
return showAchievements(chatId, KV, botToken);
} else if (callbackData === 'upcoming_contests') {
return getUpcomingContests(chatId, botToken);
} else if (callbackData === 'daily_challenge') {
return startDailyChallenge(chatId, KV, botToken);
} else if (callbackData === 'challenge_stats' || callbackData === 'show_challenge_stats') {
return showChallengeStats(chatId, KV, botToken);
} else if (callbackData === 'get_new_problems' || callbackData === 'get_new_problems') {
return getNewProblems(chatId, KV, botToken);
} else if (callbackData === 'show_help') {
return showHelp(chatId, botToken);
} else if (callbackData === 'main_menu') {
return showMainMenu(chatId, KV, botToken);
} else if (callbackData.startsWith('browse_')) {
const page = parseInt(callbackData.split('_')[1], 10) || 0;
return browseProblems(chatId, page, KV, botToken);
} else if (callbackData === 'set_goal_menu') {
const keyboard = createKeyboard([
[{ text: "1 Problem", callback_data: "set_goal_1" }],
[{ text: "3 Problems", callback_data: "set_goal_3" }],
[{ text: "5 Problems", callback_data: "set_goal_5" }],
[{ text: "Custom Goal", callback_data: "set_goal_custom" }]