forked from TheCodeVerseHub/Eigen-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodebuddy_quiz.py
More file actions
430 lines (369 loc) · 17.6 KB
/
codebuddy_quiz.py
File metadata and controls
430 lines (369 loc) · 17.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
import discord
from discord.ext import commands, tasks
from discord import app_commands
import random
import os
from typing import cast
from utils.codebuddy_database import (
increment_user_score,
reset_user_streak,
get_leaderboard,
get_user_stats,
get_user_rank,
get_score_gap,
increment_quest_quiz_count,
use_streak_freeze
)
from utils.codingquestions import get_random_question
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 = None
self.current_answer = None
self.current_message = None
self.question_active = False
self.ignored_users = set()
self.bonus_active = False
async def cog_load(self):
self.post_question_loop.start()
async def cog_unload(self):
self.post_question_loop.cancel()
@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
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=" Coding Quiz",
description=f"**{self.current_question}**\n\n{options_text}",
color=discord.Color.blurple()
)
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
# Richtige Antwort
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}")
# Update daily quest progress
try:
quest_completed = await increment_quest_quiz_count(user_id)
if quest_completed:
# Notify user about quest completion
try:
quest_embed = discord.Embed(
title="Daily Quest Completed!",
description=f"{message.author.mention} You completed your daily quest!\n\n**Rewards Earned:**\n• 1 Streak Freeze\n• 1 Bonus Hint\n\nUse `?inventory` to check your rewards!",
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()
# Falsche Antwort
else:
self.ignored_users.add(user_id)
try:
await message.add_reaction("❌")
except Exception:
pass
# Try to use streak freeze first
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:
# Streak was protected!
try:
freeze_embed = discord.Embed(
title="Streak Freeze Activated!",
description=f"{message.author.mention} Wrong answer, but your **Streak Freeze** protected your streak!\n\nYour 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:
# No freeze available, reset streak
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="codeleaderboard", description="Show the top players with the most correct answers.")
async def leaderboard(self, interaction: discord.Interaction):
try:
# Immediate simple response first
embed = discord.Embed(
title=" Code Leaderboard",
description="Loading leaderboard...",
color=discord.Color.gold()
)
await interaction.response.send_message(embed=embed)
# Now get the actual data
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 discord.NotFound:
pass
except Exception:
pass
return
desc = ""
medals = ["1.", "2.", "3."]
for i, (user_id, score, streak, best) in enumerate(lb, 1):
# Use cached user data only for speed
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())
# Add timeout protection for edit operation
try:
await interaction.edit_original_response(embed=final_embed)
except discord.NotFound:
pass
except Exception:
pass
except discord.NotFound:
pass # Interaction already expired
except Exception as e:
print(f"[Unexpected error in leaderboard command]: {e}")
try:
if not interaction.response.is_done():
await interaction.response.send_message("Failed to load the leaderboard. Please try again in a moment.", ephemeral=True)
else:
try:
await interaction.edit_original_response(content="Failed to load the leaderboard. Please try again in a moment.")
except discord.NotFound:
pass
except Exception:
pass
@commands.command(name="codeleaderboard", aliases=["clb"])
async def codeleaderboard_prefix(self, ctx):
"""Show the top players with the most correct answers."""
try:
# Immediate simple response first
embed = discord.Embed(
title=" Code Leaderboard",
description="Loading leaderboard...",
color=discord.Color.gold()
)
msg = await ctx.send(embed=embed)
# Now get the actual data
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):
# Use cached user data only for speed
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("Failed to load the leaderboard. Please try again in a moment.")
@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("Failed to load your stats. Please try again in a moment.", ephemeral=True)
return
# Haupt-Embed
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)
# Footer mit Punkte-Differenz
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("Failed to load your stats. Please try again in a moment.", ephemeral=True)
except Exception:
pass
@commands.command(name="codestats", aliases=["cst"])
async def codestats_prefix(self, ctx):
"""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("Failed to load your stats. Please try again in a moment.")
return
# Haupt-Embed
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)
# Footer mit Punkte-Differenz
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("Failed to load your stats. Please try again in a moment.")
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}")