-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcodebuddy_quiz.py
More file actions
555 lines (487 loc) · 20.8 KB
/
codebuddy_quiz.py
File metadata and controls
555 lines (487 loc) · 20.8 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
import os
import random
from typing import Optional, cast
import discord
from discord import app_commands
from discord.ext import commands, tasks
from utils.codebuddy_database import (
get_leaderboard,
get_score_gap,
get_user_rank,
get_user_stats,
increment_quest_quiz_count,
increment_user_score,
reset_user_streak,
use_streak_freeze,
)
from utils.codingquestions import (
get_available_categories,
get_random_question,
get_random_question_by_category,
)
class CodeBuddyQuizCog(commands.Cog):
def __init__(self, bot: commands.Bot, question_channel_id: int):
self.bot = bot
self.channel_id = question_channel_id
self.current_question: Optional[str] = None
self.current_answer: Optional[str] = None
self.current_message: Optional[discord.Message] = None
self.question_active = False
self.ignored_users = set()
self.bonus_active = False
self.frequency_minutes = 25
async def cog_load(self):
self.post_question_loop.change_interval(minutes=self.frequency_minutes)
self.post_question_loop.start()
async def cog_unload(self):
self.post_question_loop.cancel()
def _build_question_embed(
self, q: dict, title: str = "Coding Quiz"
) -> discord.Embed:
options_letters = ["a", "b", "c"]
options_text = "\n".join(
f"**{letter})** {option}"
for letter, option in zip(options_letters, q["options"])
)
embed = discord.Embed(
title=title,
description=f"**{q['question']}**\n\n{options_text}",
color=discord.Color.blurple(),
)
return embed
@tasks.loop(minutes=25)
async def post_question_loop(self):
try:
if self.question_active and self.current_message:
try:
await self.current_message.delete()
except discord.NotFound:
pass
except Exception as e:
print(f"[Error deleting old message]: {e}")
self._reset_question_state()
channel = self.bot.get_channel(self.channel_id)
if not isinstance(channel, discord.abc.Messageable):
print(
f"[Error] Channel ID {self.channel_id} not found or not messageable."
)
return
channel = cast(discord.abc.Messageable, channel)
try:
q = get_random_question()
self.current_question = q["question"]
self.current_answer = q["correct"]
self.question_active = True
self.ignored_users.clear()
self.bonus_active = random.random() < 0.1
except Exception as e:
print(f"[Error fetching question]: {e}")
return
embed = self._build_question_embed(q)
footer_text = (
"BONUS QUESTION – double points!"
if self.bonus_active
else "Answer with 'a', 'b', or 'c'."
)
lang_name = q.get("language", "General")
embed.set_footer(text=f"{lang_name} • {footer_text}")
try:
self.current_message = await channel.send(embed=embed)
except Exception as e:
print(f"[Error sending question message]: {e}")
except Exception as e:
print(f"[Unexpected error in post_question_loop]: {e}")
def _reset_question_state(self):
self.question_active = False
self.current_question = None
self.current_answer = None
self.current_message = None
self.ignored_users.clear()
self.bonus_active = False
@post_question_loop.before_loop
async def before_post_question(self):
await self.bot.wait_until_ready()
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
try:
if (
message.author.bot
or not self.question_active
or message.channel.id != self.channel_id
):
return
user_id = message.author.id
content = message.content.lower().strip()
if content not in ["a", "b", "c"]:
return
if user_id in self.ignored_users:
return
if content == self.current_answer:
try:
await message.add_reaction("✅")
except Exception:
pass
points = 2 if self.bonus_active else 1
extra_bonus = 0
try:
await increment_user_score(user_id, points)
except Exception as e:
print(f"[Error incrementing user score]: {e}")
try:
quest_completed = await increment_quest_quiz_count(user_id)
if quest_completed:
try:
quest_embed = discord.Embed(
title="Quest Completed!",
description=(
f"{message.author.mention} You completed the **Quiz** quest!\n\n"
"**Rewards Earned:**\n"
"• **0.2** Streak Freeze\n"
"• **0.5** Save\n\n"
"Use `?inventory` to check your items!"
),
color=0x000000,
)
await message.channel.send(embed=quest_embed)
except Exception as e:
print(f"[Error sending quest completion message]: {e}")
except Exception as e:
print(f"[Error updating quest progress]: {e}")
try:
lb = await get_leaderboard(100)
except Exception as e:
print(f"[Error fetching leaderboard]: {e}")
lb = []
streak = 0
for uid, score, s, best in lb:
if uid == user_id:
streak = s
try:
if streak == 3:
extra_bonus = 1
await increment_user_score(user_id, extra_bonus)
elif streak == 5:
extra_bonus = 2
await increment_user_score(user_id, extra_bonus)
except Exception as e:
print(f"[Error applying streak bonus]: {e}")
break
total_points = points + extra_bonus
title = f"{streak}x Streak!"
embed = discord.Embed(
title=title,
description=f"{message.author.mention} answered correctly and earned **{total_points} point(s)**!",
color=discord.Color.green(),
)
if extra_bonus > 0:
embed.add_field(
name="Streak Bonus", value=f"+{extra_bonus}", inline=True
)
if self.bonus_active:
embed.set_footer(text="Bonus Question!")
try:
await message.channel.send(embed=embed)
except Exception as e:
print(f"[Error sending success embed]: {e}")
self._reset_question_state()
else:
self.ignored_users.add(user_id)
try:
await message.add_reaction("❌")
except Exception:
pass
freeze_used = False
try:
freeze_used = await use_streak_freeze(user_id)
except Exception as e:
print(f"[Error checking streak freeze]: {e}")
if freeze_used:
try:
freeze_embed = discord.Embed(
title="Streak Freeze Activated!",
description=(
f"{message.author.mention} Wrong answer, but your **Streak Freeze** protected your streak!\n\n"
"Your streak remains intact."
),
color=0x000000,
)
freeze_embed.set_footer(
text="Earn more freezes by completing daily quests!"
)
await message.channel.send(embed=freeze_embed)
except Exception as e:
print(f"[Error sending freeze message]: {e}")
else:
try:
await reset_user_streak(user_id)
except Exception as e:
print(f"[Error resetting user streak]: {e}")
try:
await message.channel.send(
f"{message.author.mention} Wrong answer! Streak reset to 0."
)
except discord.Forbidden:
pass
except Exception as e:
print(f"[Error sending wrong answer message]: {e}")
except Exception as e:
print(f"[Unexpected error in on_message]: {e}")
@app_commands.command(
name="question",
description="Get one practice question by category/language (no points).",
)
@app_commands.describe(
category="Choose category like python, java, javascript, general, system design, etc.",
)
async def question(self, interaction: discord.Interaction, category: str):
try:
q = get_random_question_by_category(category)
if not q:
available = ", ".join(get_available_categories())
await interaction.response.send_message(
f"Invalid category: `{category}`.\nAvailable: {available}",
ephemeral=True,
)
return
embed = self._build_question_embed(q, title="Practice Question")
embed.set_footer(
text=f"{q.get('language', 'General')} • Knowledge mode (no points)"
)
await interaction.response.send_message(embed=embed)
except Exception as e:
print(f"[Unexpected error in /question]: {e}")
if not interaction.response.is_done():
await interaction.response.send_message(
"Could not fetch a practice question right now.",
ephemeral=True,
)
@app_commands.command(
name="frequency",
description="Set CodeBuddy quiz frequency in minutes (1 to 30).",
)
@app_commands.describe(
minutes="How often quiz questions appear in the quiz channel."
)
async def frequency(self, interaction: discord.Interaction, minutes: int):
try:
if not interaction.user.guild_permissions.manage_guild:
await interaction.response.send_message(
"You need `Manage Server` permission to change quiz frequency.",
ephemeral=True,
)
return
if minutes < 1 or minutes > 30:
await interaction.response.send_message(
"Frequency must be between **1** and **30** minutes.",
ephemeral=True,
)
return
self.frequency_minutes = minutes
self.post_question_loop.change_interval(minutes=minutes)
await interaction.response.send_message(
f"CodeBuddy quiz frequency updated to **{minutes} minute(s)**.",
ephemeral=True,
)
except Exception as e:
print(f"[Unexpected error in /frequency]: {e}")
if not interaction.response.is_done():
await interaction.response.send_message(
"Could not update quiz frequency.",
ephemeral=True,
)
@app_commands.command(
name="codeleaderboard",
description="Show the top players with the most correct answers.",
)
async def leaderboard(self, interaction: discord.Interaction):
try:
embed = discord.Embed(
title="Code Leaderboard",
description="Loading leaderboard...",
color=discord.Color.gold(),
)
await interaction.response.send_message(embed=embed)
lb = await get_leaderboard()
if not lb:
updated_embed = discord.Embed(
title="Code Leaderboard",
description="No leaderboard data yet.",
color=discord.Color.gold(),
)
try:
await interaction.edit_original_response(embed=updated_embed)
except Exception:
pass
return
desc = ""
medals = ["1.", "2.", "3."]
for i, (user_id, score, streak, best) in enumerate(lb, 1):
user = (
interaction.guild.get_member(user_id) if interaction.guild else None
)
if not user:
user = self.bot.get_user(user_id)
mention = user.mention if user else f"<@{user_id}>"
medal = medals[i - 1] if i <= len(medals) else f"{i}."
desc += (
f"{medal} {mention} - {score} pts Streak: {streak} (Best: {best})\n"
)
final_embed = discord.Embed(
title="Code Leaderboard",
description=desc,
color=discord.Color.gold(),
)
try:
await interaction.edit_original_response(embed=final_embed)
except Exception:
pass
except Exception as e:
print(f"[Unexpected error in leaderboard command]: {e}")
try:
if not interaction.response.is_done():
await interaction.response.send_message(
"Error fetching leaderboard.", ephemeral=True
)
else:
await interaction.edit_original_response(
content="Error fetching leaderboard."
)
except Exception:
pass
@commands.command(name="codeleaderboard", aliases=["clb"], help="Show the top players with the most correct answers")
async def codeleaderboard_prefix(self, ctx: commands.Context):
"""Show the top players with the most correct answers."""
try:
embed = discord.Embed(
title="Code Leaderboard",
description="Loading leaderboard...",
color=discord.Color.gold(),
)
msg = await ctx.send(embed=embed)
lb = await get_leaderboard()
if not lb:
updated_embed = discord.Embed(
title="Code Leaderboard",
description="No leaderboard data yet.",
color=discord.Color.gold(),
)
await msg.edit(embed=updated_embed)
return
desc = ""
medals = ["1.", "2.", "3."]
for i, (user_id, score, streak, best) in enumerate(lb, 1):
user = ctx.guild.get_member(user_id) if ctx.guild else None
if not user:
user = self.bot.get_user(user_id)
mention = user.mention if user else f"<@{user_id}>"
medal = medals[i - 1] if i <= len(medals) else f"{i}."
desc += (
f"{medal} {mention} - {score} pts Streak: {streak} (Best: {best})\n"
)
final_embed = discord.Embed(
title="Code Leaderboard",
description=desc,
color=discord.Color.gold(),
)
await msg.edit(embed=final_embed)
except Exception as e:
print(f"[Unexpected error in codeleaderboard command]: {e}")
await ctx.send("Error fetching leaderboard.")
@app_commands.command(
name="codestats", description="Show your personal coding quiz stats."
)
async def codestats(self, interaction: discord.Interaction):
try:
user_id = interaction.user.id
try:
score, streak, best = await get_user_stats(user_id)
rank = await get_user_rank(user_id)
gap, higher_id = await get_score_gap(user_id)
except Exception as e:
print(f"[Error fetching user stats]: {e}")
await interaction.response.send_message(
"Error fetching your stats.", ephemeral=True
)
return
embed = discord.Embed(
title=f"{interaction.user.display_name}'s Stats",
color=discord.Color.blurple(),
)
embed.add_field(name="Points", value=str(score), inline=False)
embed.add_field(
name="Streak", value=f"{streak} (current)\n{best} (best)", inline=False
)
embed.add_field(
name="Rank", value=f"#{rank}" if rank else "Unranked", inline=False
)
if gap is not None and higher_id is not None:
try:
higher_user = self.bot.get_user(
higher_id
) or await self.bot.fetch_user(higher_id)
higher_name = (
higher_user.display_name if higher_user else f"User {higher_id}"
)
except Exception:
higher_name = f"User {higher_id}"
embed.set_footer(text=f"{gap} point(s) behind {higher_name}")
else:
embed.set_footer(text="You are at the top!")
await interaction.response.send_message(embed=embed)
except Exception as e:
print(f"[Unexpected error in codestats command]: {e}")
try:
await interaction.response.send_message(
"Error displaying your stats.", ephemeral=True
)
except Exception:
pass
@commands.command(name="codestats", aliases=["cst"], help="Show your personal coding quiz stats")
async def codestats_prefix(self, ctx: commands.Context):
"""Show your personal coding quiz stats."""
try:
user_id = ctx.author.id
try:
score, streak, best = await get_user_stats(user_id)
rank = await get_user_rank(user_id)
gap, higher_id = await get_score_gap(user_id)
except Exception as e:
print(f"[Error fetching user stats]: {e}")
await ctx.send("Error fetching your stats.")
return
embed = discord.Embed(
title=f"{ctx.author.display_name}'s Stats",
color=discord.Color.blurple(),
)
embed.add_field(name="Points", value=str(score), inline=False)
embed.add_field(
name="Streak", value=f"{streak} (current)\n{best} (best)", inline=False
)
embed.add_field(
name="Rank", value=f"#{rank}" if rank else "Unranked", inline=False
)
if gap is not None and higher_id is not None:
try:
higher_user = self.bot.get_user(
higher_id
) or await self.bot.fetch_user(higher_id)
higher_name = (
higher_user.display_name if higher_user else f"User {higher_id}"
)
except Exception:
higher_name = f"User {higher_id}"
embed.set_footer(text=f"{gap} point(s) behind {higher_name}")
else:
embed.set_footer(text="You are at the top!")
await ctx.send(embed=embed)
except Exception as e:
print(f"[Unexpected error in codestats command]: {e}")
await ctx.send("Error displaying your stats.")
async def setup(bot: commands.Bot):
question_channel_id = int(os.getenv("QUESTION_CHANNEL_ID", "0"))
if question_channel_id == 0:
print("[Warning] QUESTION_CHANNEL_ID not set. QuizCog will not work correctly.")
try:
await bot.add_cog(CodeBuddyQuizCog(bot, question_channel_id))
except Exception as e:
print(f"[Error setting up QuizCog]: {e}")