-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcodebuddy_leaderboard.py
More file actions
388 lines (329 loc) · 16.6 KB
/
codebuddy_leaderboard.py
File metadata and controls
388 lines (329 loc) · 16.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
import discord
from discord.ext import commands, tasks
from discord import app_commands
import datetime
import asyncio
from utils.codebuddy_database import get_weekly_leaderboard, get_streak_leaderboard, reset_weekly_leaderboard, get_current_week
class CodeBuddyLeaderboardCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.weekly_reset.start() # Start the weekly reset task
def cog_unload(self):
self.weekly_reset.cancel()
@tasks.loop(time=datetime.time(hour=0, minute=0)) # Run daily at midnight
async def weekly_reset(self):
"""Check if it's Monday and reset weekly leaderboard if needed."""
today = datetime.date.today()
if today.weekday() == 0: # Monday = 0
await reset_weekly_leaderboard()
print(" Weekly leaderboard reset for new week")
@weekly_reset.before_loop
async def before_weekly_reset(self):
await self.bot.wait_until_ready()
@app_commands.command(name="codeweek", description="Show the weekly coding leaderboard")
async def codeweek(self, interaction: discord.Interaction):
"""Display the weekly leaderboard."""
try:
# Immediate simple response first
embed = discord.Embed(
title="Weekly Coding Leaderboard",
description="Loading weekly leaderboard...",
color=0x00ff00
)
await interaction.response.send_message(embed=embed)
# Now get the actual data with timeout protection
try:
weekly_data = await asyncio.wait_for(get_weekly_leaderboard(10), timeout=10.0)
week_start, week_end = get_current_week()
weekly_list = list(weekly_data) if weekly_data else []
except asyncio.TimeoutError:
await interaction.edit_original_response(content=" Database query timed out. Please try again.")
return
if not weekly_list:
updated_embed = discord.Embed(
title="Weekly Coding Leaderboard",
description="No one has scored points this week yet!\nBe the first to solve some coding questions!",
color=0x00ff00
)
updated_embed.set_footer(text=f"Week: {week_start.strftime('%b %d')} - {week_end.strftime('%b %d, %Y')}")
try:
await interaction.edit_original_response(embed=updated_embed)
except discord.NotFound:
pass
except Exception:
pass
return
# Create final leaderboard embed
final_embed = discord.Embed(
title="Weekly Coding Leaderboard",
description=f"Top coders for the week of {week_start.strftime('%b %d')} - {week_end.strftime('%b %d, %Y')}",
color=0x00ff00
)
leaderboard_text = ""
medals = ["1.", "2.", "3."]
# Get usernames efficiently - use cached data only
for i, (user_id, weekly_score) in enumerate(weekly_list):
# Use only cached user data for speed
user = interaction.guild.get_member(user_id) if interaction.guild else None
if not user:
user = self.bot.get_user(user_id)
# If still not found, try to fetch (fallback)
if not user:
try:
user = await self.bot.fetch_user(user_id)
except discord.NotFound:
user = None
except Exception:
user = None
username = user.display_name if user else f"<@{user_id}>"
if i < 3:
medal = medals[i]
else:
medal = f"{i+1:2d}."
leaderboard_text += f"{medal} **{username}** - {weekly_score} points\n"
final_embed.add_field(name=" Rankings", value=leaderboard_text or "No data", inline=False)
final_embed.set_footer(text=" Solve coding questions to climb the weekly leaderboard! Resets every Monday.")
# 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 codeweek command]: {e}")
try:
if not interaction.response.is_done():
await interaction.response.send_message(" An error occurred while fetching the weekly leaderboard.", ephemeral=True)
else:
try:
await interaction.edit_original_response(content=" An error occurred while fetching the weekly leaderboard.")
except discord.NotFound:
pass
except Exception:
pass
@commands.command(name="codeweek", aliases=["cw", "cwlb"], help="Show the weekly coding leaderboard")
async def codeweek_prefix(self, ctx):
"""Display the weekly leaderboard."""
try:
# Immediate simple response first
embed = discord.Embed(
title="Weekly Coding Leaderboard",
description="Loading weekly leaderboard...",
color=0x00ff00
)
msg = await ctx.send(embed=embed)
# Now get the actual data with timeout protection
try:
weekly_data = await asyncio.wait_for(get_weekly_leaderboard(10), timeout=10.0)
week_start, week_end = get_current_week()
weekly_list = list(weekly_data) if weekly_data else []
except asyncio.TimeoutError:
await msg.edit(content=" Database query timed out. Please try again.")
return
if not weekly_list:
updated_embed = discord.Embed(
title="Weekly Coding Leaderboard",
description="No one has scored points this week yet!\nBe the first to solve some coding questions!",
color=0x00ff00
)
updated_embed.set_footer(text=f"Week: {week_start.strftime('%b %d')} - {week_end.strftime('%b %d, %Y')}")
await msg.edit(embed=updated_embed)
return
# Create final leaderboard embed
final_embed = discord.Embed(
title="Weekly Coding Leaderboard",
description=f"Top coders for the week of {week_start.strftime('%b %d')} - {week_end.strftime('%b %d, %Y')}",
color=0x00ff00
)
leaderboard_text = ""
medals = ["1.", "2.", "3."]
# Get usernames efficiently - use cached data only
for i, (user_id, weekly_score) in enumerate(weekly_list):
# Use only cached user data for speed
user = ctx.guild.get_member(user_id) if ctx.guild else None
if not user:
user = self.bot.get_user(user_id)
# If still not found, try to fetch (fallback)
if not user:
try:
user = await self.bot.fetch_user(user_id)
except discord.NotFound:
user = None
except Exception:
user = None
username = user.display_name if user else f"<@{user_id}>"
if i < 3:
medal = medals[i]
else:
medal = f"{i+1:2d}."
leaderboard_text += f"{medal} **{username}** - {weekly_score} points\n"
final_embed.add_field(name=" Rankings", value=leaderboard_text or "No data", inline=False)
final_embed.set_footer(text=" Solve coding questions to climb the weekly leaderboard! Resets every Monday.")
await msg.edit(embed=final_embed)
except Exception as e:
print(f"[Unexpected error in codeweek command]: {e}")
await ctx.send(" An error occurred while fetching the weekly leaderboard.")
@app_commands.command(name="codestreak", description="Show the coding streak leaderboard")
async def codestreak(self, interaction: discord.Interaction):
"""Display the streak leaderboard."""
try:
# Immediate simple response first
embed = discord.Embed(
title=" Coding Streak Leaderboard",
description="Loading streak leaderboard...",
color=0xff6b35
)
await interaction.response.send_message(embed=embed)
# Now get the actual data with timeout protection
try:
streak_data = await asyncio.wait_for(get_streak_leaderboard(10), timeout=10.0)
streak_list = list(streak_data) if streak_data else []
except asyncio.TimeoutError:
await interaction.edit_original_response(content=" Database query timed out. Please try again.")
return
if not streak_list:
updated_embed = discord.Embed(
title=" Coding Streak Leaderboard",
description="No active streaks found!\n Solve any question correctly to start streak. ",
color=0xff6b35
)
try:
await interaction.edit_original_response(embed=updated_embed)
except discord.NotFound:
pass
except Exception:
pass
return
# Create final streak leaderboard embed
final_embed = discord.Embed(
title=" Coding Streak Leaderboard",
description="Top coding streaks (Consecutive correct answers)",
color=0xff6b35
)
leaderboard_text = ""
medals = ["1.", "2.", "3."]
# Get usernames efficiently - use cached data only
for i, (user_id, current_streak, best_streak) in enumerate(streak_list):
# Use only cached user data for speed
user = interaction.guild.get_member(user_id) if interaction.guild else None
if not user:
user = self.bot.get_user(user_id)
# If still not found, try to fetch (fallback)
if not user:
try:
user = await self.bot.fetch_user(user_id)
except discord.NotFound:
user = None
except Exception:
user = None
username = user.display_name if user else f"<@{user_id}>"
if i < 3:
medal = medals[i]
else:
medal = f"{i+1:2d}."
leaderboard_text += f"{medal} **{username}** - {current_streak} questions "
if best_streak > current_streak:
leaderboard_text += f" (Best: {best_streak})"
leaderboard_text += "\n"
final_embed.add_field(name=" Current Streaks", value=leaderboard_text or "No data", inline=False)
final_embed.add_field(
name=" How Streaks Work",
value="• Answer questions correctly in a row to build your streak\n• Giving a wrong answer resets your current streak\n• Your best streak is always remembered!",
inline=False
)
final_embed.set_footer(text="Keep learning and answering questions to build an epic streak!")
# 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 codestreak command]: {e}")
try:
if not interaction.response.is_done():
await interaction.response.send_message(" An error occurred while fetching the streak leaderboard.", ephemeral=True)
else:
try:
await interaction.edit_original_response(content=" An error occurred while fetching the streak leaderboard.")
except discord.NotFound:
pass
except Exception:
pass
@commands.command(name="codestreak", aliases=["cs", "cslb"], help="Show the coding streak leaderboard")
async def codestreak_prefix(self, ctx):
"""Display the streak leaderboard."""
try:
# Immediate simple response first
embed = discord.Embed(
title=" Coding Streak Leaderboard",
description="Loading streak leaderboard...",
color=0xff6b35
)
msg = await ctx.send(embed=embed)
# Now get the actual data with timeout protection
try:
streak_data = await asyncio.wait_for(get_streak_leaderboard(10), timeout=10.0)
streak_list = list(streak_data) if streak_data else []
except asyncio.TimeoutError:
await msg.edit(content=" Database query timed out. Please try again.")
return
if not streak_list:
updated_embed = discord.Embed(
title=" Coding Streak Leaderboard",
description="No active streaks found!\n Solve any question correctly to start streak. ",
color=0xff6b35
)
await msg.edit(embed=updated_embed)
return
# Create final streak leaderboard embed
final_embed = discord.Embed(
title=" Coding Streak Leaderboard",
description="Top coding streaks (Consecutive correct answers)",
color=0xff6b35
)
leaderboard_text = ""
medals = ["1.", "2.", "3."]
# Get usernames efficiently - use cached data only
for i, (user_id, current_streak, best_streak) in enumerate(streak_list):
# Use only cached user data for speed
user = ctx.guild.get_member(user_id) if ctx.guild else None
if not user:
user = self.bot.get_user(user_id)
# If still not found, try to fetch (fallback)
if not user:
try:
user = await self.bot.fetch_user(user_id)
except discord.NotFound:
user = None
except Exception:
user = None
username = user.display_name if user else f"<@{user_id}>"
if i < 3:
medal = medals[i]
else:
medal = f"{i+1:2d}."
leaderboard_text += f"{medal} **{username}** - {current_streak} questions "
if best_streak > current_streak:
leaderboard_text += f" (Best: {best_streak})"
leaderboard_text += "\n"
final_embed.add_field(name=" Current Streaks", value=leaderboard_text or "No data", inline=False)
final_embed.add_field(
name=" How Streaks Work",
value="• Answer questions correctly in a row to build your streak\n• Giving a wrong answer resets your current streak\n• Your best streak is always remembered!",
inline=False
)
final_embed.set_footer(text="Keep learning and answering questions to build an epic streak!")
await msg.edit(embed=final_embed)
except Exception as e:
print(f"[Unexpected error in codestreak command]: {e}")
await ctx.send(" An error occurred while fetching the streak leaderboard.")
async def setup(bot):
"""Setup function to add this cog to the bot."""
await bot.add_cog(CodeBuddyLeaderboardCog(bot))