-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbotV3.py
More file actions
executable file
·491 lines (436 loc) · 23.3 KB
/
Copy pathbotV3.py
File metadata and controls
executable file
·491 lines (436 loc) · 23.3 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
import discord
from discord import app_commands
from discord.ext import commands, tasks
import random
import os
import json
from pathlib import Path
import qrcode
from datetime import datetime, time
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("TOKEN")
# ──────────────────────────────────────────────
# Setup
# ──────────────────────────────────────────────
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
tree = bot.tree
BASE_DIR = Path(__file__).resolve().parent
QR_DIR = BASE_DIR / "Generated_QRCodes"
QR_DIR.mkdir(exist_ok=True)
CODES_JSON = BASE_DIR / "codes.json"
CODES_TXT = BASE_DIR / "codes.txt"
BLACKLIST = {"52680070", "20966973", "51690273", "03854069", "02488471", "80144618", "02276578"}
pending_codes = {}
ADMIN_ROLE_ID = 1229073109592703076
SELFTESTER_ID = 1351536969175531552
NOTIFY_CHANNEL_ID = 1351538365568122920
# ──────────────────────────────────────────────
# Exercise data
# ──────────────────────────────────────────────
chapitres = {
"1-Suites et recurrence": [28, 43],
"2-Limites de fonctions": [62, 77],
"3-Fonctions cosinus et sinus": [90, 103],
"4-Continuité": [120, 133],
"5-Derivation et convexite": [152, 165],
"6-Fonction logarithme neperien": [182, 197],
"7-Primitives et equations differentielles": [216, 233],
"8-Calcul integral": [252, 269],
"9-Vecteurs droites et plans de espace": [290, 303],
"10-Produit_scalaire et plans de espace": [316, 331],
"11-Denombrement": [346, 359],
"12-Succession epreuves independantes et loi binomiale": [380, 397],
"13-Variables_aleatoires_concentration_et_loi_des_grands_nombres": [416, 433],
"BAC-Sujets_type": [444, 459],
}
exercices_manuel_complet = {
# --- BLOC 1 ---
13: [1, 6], 17: [1, 4], 19: [5, 8], 21: [9, 12], 23: [13, 16],
25: [17, 20], 26: [21, 22], 27: [23, 24], 29: [25, 36], 30: [37, 52],
31: [53, 70], 32: [71, 89], 33: [90, 100], 34: [101, 110], 35: [111, 120],
36: [121, 127], 37: [128, 134], 41: [143, 146], 42: [147, 153], 49: [1, 4],
55: [1, 2], 57: [7, 11], 67: [66, 70], 68: [71, 85], 69: [102, 102],
70: [103, 104], 77: [146, 148], 93: [40, 49], 94: [50, 53], 95: [67, 71],
97: [76, 77], 98: [78, 82], 102: [94, 101], 104: [102, 105],
# --- BLOC 2 ---
109: [1, 5], 113: [1, 2], 115: [3, 6], 117: [7, 8], 118: [9, 10],
119: [11, 12], 121: [13, 19], 122: [20, 28], 123: [29, 39], 124: [40, 46],
125: [47, 53], 126: [54, 55], 127: [56, 60], 128: [61, 63], 130: [64, 70],
131: [71, 76], 132: [77, 82], 133: [83, 86], 137: [1, 5], 149: [17, 20],
150: [21, 22], 157: [71, 86], 158: [87, 103], 159: [104, 110], 160: [111, 116],
162: [117, 126], 163: [127, 131], 164: [132, 149], 175: [5, 8], 179: [15, 16],
180: [17, 18], 181: [19, 20], 183: [21, 28], 184: [29, 48], 185: [49, 62],
186: [63, 70], 187: [71, 79], 189: [80, 82], 190: [83, 88], 191: [89, 92],
192: [93, 98], 194: [99, 105], 195: [106, 109], 196: [110, 117],
200: [118, 122], 201: [123, 128], 208: [4, 5],
# --- BLOC 3 ---
209: [6, 9], 211: [10, 13], 212: [14, 17], 213: [18, 19], 214: [20, 21],
215: [22, 27], 217: [28, 36], 218: [37, 47], 219: [48, 58], 220: [59, 69],
221: [70, 75], 222: [76, 86], 223: [87, 92], 224: [93, 100], 225: [101, 105],
226: [106, 107], 228: [108, 115], 229: [116, 121], 230: [122, 125], 231: [126, 128],
232: [129, 135], 233: [136, 141], 234: [1, 1], 235: [2, 2], 236: [3, 3],
237: [4, 4],
# --- BLOC 4 ---
314: [9, 10], 315: [11, 14], 317: [15, 21], 318: [22, 31], 319: [32, 45],
320: [46, 54], 321: [55, 63], 322: [64, 70], 323: [71, 77], 324: [78, 83],
326: [84, 93], 327: [94, 98], 328: [99, 104], 329: [105, 110], 330: [111, 112],
331: [113, 116], 332: [1, 2], 333: [3, 4], 335: [1, 4], 336: [1, 3],
339: [1, 4], 341: [5, 8], 343: [9, 16], 346: [18, 25], 347: [26, 29],
348: [30, 48], 349: [49, 56], 350: [57, 62], 351: [63, 64], 352: [65, 80],
353: [81, 84], 354: [85, 92], 356: [93, 99], 357: [100, 111], 358: [112, 128],
359: [129, 134], 360: [1, 2], 365: [1, 4], 371: [6, 7], 373: [8, 9],
375: [10, 12], 377: [13, 14], 378: [15, 16], 379: [17, 20], 381: [21, 27],
382: [28, 48], 383: [49, 53], 385: [64, 69], 386: [70, 74], 387: [75, 79],
389: [93, 99], 390: [100, 102], 395: [129, 132], 397: [140, 141], 398: [142, 145],
# --- BLOC 5 ---
419: [47, 57], 420: [58, 73], 421: [74, 80], 422: [81, 87], 423: [88, 93],
424: [94, 99], 425: [100, 106], 426: [107, 112], 427: [113, 123], 428: [124, 127],
430: [128, 136], 431: [137, 140], 432: [141, 147], 433: [148, 154], 434: [1, 1],
435: [2, 2], 436: [3, 3], 437: [4, 4], 444: [1, 1], 445: [2, 3], 446: [4, 4],
447: [1, 1], 448: [2, 3], 449: [4, 4], 450: [1, 2], 451: [3, 3], 452: [4, 4],
453: [1, 2], 454: [3, 4], 455: [5, 5], 456: [1, 2], 457: [3, 3], 458: [4, 5],
}
# ──────────────────────────────────────────────
# Exercise helper
# ──────────────────────────────────────────────
def pick_exercise(pool: dict) -> tuple[int, int]:
"""Return (exercise_number, page) from the given pool."""
page = random.choice(list(pool.keys()))
exo = random.randint(pool[page][0], pool[page][1])
return exo, page
def make_exo_embed(exo: int, page: int, requester: discord.User | discord.Member | None = None) -> discord.Embed:
url = f"https://manuel.sesamath.net/numerique/index.php?ouvrage=mstsspe_2020&page_gauche={page}"
embed = discord.Embed(
title="📚 Nouvel exercice",
description=f"**Exercice {exo}** — page **{page}**",
colour=discord.Colour.blurple(),
url=url,
)
embed.set_footer(text=f"Demandé par {requester}" if requester else "Tirage automatique quotidien")
return embed
# ──────────────────────────────────────────────
# Interactive View (Reroll + Ping role)
# ──────────────────────────────────────────────
# Set this to the role ID you want pinged when users click "Ping role"
#STUDY_ROLE_ID = 1501893232357937255 # <-- replace with your study/révision role ID
class ExoView(discord.ui.View):
"""Persistent view attached to every exercise message."""
def __init__(self, pool: dict = None, *, timeout: float | None = 120): # pool is now optional
super().__init__(timeout=timeout)
self.pool = pool or exercices_manuel_complet # fallback to full book
# ── Reroll ────────────────────────────────
@discord.ui.button(label="🔁 Reroll", style=discord.ButtonStyle.primary)
async def reroll(self, interaction: discord.Interaction, button: discord.ui.Button):
exo, page = pick_exercise(self.pool)
embed = make_exo_embed(exo, page, interaction.user)
embed.set_footer(text=f"🔁 Reroll par {interaction.user} — {datetime.utcnow().strftime('%H:%M:%S')}") # forces refresh
await interaction.response.edit_message(embed=embed, view=self)
# ── Ping study role ────────────────────────
@discord.ui.button(label="📣 Ping", style=discord.ButtonStyle.secondary)
async def ping_role(self, interaction: discord.Interaction, button: discord.ui.Button):
role = interaction.guild.get_role(STUDY_ROLE_ID) if STUDY_ROLE_ID else None
mention = role.mention if role else "*(no study role configured)*"
await interaction.response.send_message(
f"{mention} Un nouvel exercice vous attend ! 👆",
allowed_mentions=discord.AllowedMentions(roles=True),
)
# Disable buttons when the view times out
async def on_timeout(self):
for child in self.children:
child.disabled = True
# ──────────────────────────────────────────────
# /exo slash command
# ──────────────────────────────────────────────
POOL_CHOICES = [
app_commands.Choice(name="Manuel complet", value="complet"),
app_commands.Choice(name="Tous les chapitres", value="chapitres"),
app_commands.Choice(name="1 - Suites et récurrence", value="1"),
app_commands.Choice(name="2 - Limites de fonctions", value="2"),
app_commands.Choice(name="3 - Fonctions cosinus et sinus", value="3"),
app_commands.Choice(name="4 - Continuité", value="4"),
app_commands.Choice(name="5 - Dérivation et convexité", value="5"),
app_commands.Choice(name="6 - Fonction logarithme népérien", value="6"),
app_commands.Choice(name="7 - Primitives et équations différentielles", value="7"),
app_commands.Choice(name="8 - Calcul intégral", value="8"),
app_commands.Choice(name="9 - Vecteurs, droites et plans", value="9"),
app_commands.Choice(name="10 - Produit scalaire et plans", value="10"),
app_commands.Choice(name="11 - Dénombrement", value="11"),
app_commands.Choice(name="12 - Loi binomiale", value="12"),
app_commands.Choice(name="13 - Variables aléatoires", value="13"),
app_commands.Choice(name="BAC - Sujets type", value="BAC"),
]
@tree.command(name="exo", description="Tire un exercice aléatoire du manuel")
@app_commands.describe(pool="Choisir le pool d'exercices (défaut : manuel complet)")
@app_commands.choices(pool=POOL_CHOICES)
async def exo_command(interaction: discord.Interaction, pool: app_commands.Choice[str] = None):
# Mapping numéro → clé dans chapitres
chapitre_keys = {str(i+1): k for i, k in enumerate(chapitres.keys()) if not k.startswith("BAC")}
chapitre_keys["BAC"] = "BAC-Sujets_type"
def build_chapter_pool(page_range: list) -> dict:
start, end = page_range
return {p: v for p, v in exercices_manuel_complet.items() if start <= p <= end}
pools = {
"complet": exercices_manuel_complet,
"chapitres": exercices_manuel_complet,
}
# Ajoute chaque chapitre individuellement
for val, key in chapitre_keys.items():
pools[val] = build_chapter_pool(chapitres[key])
chosen_pool = pools.get(pool.value if pool else "complet", exercices_manuel_complet)
exo, page = pick_exercise(chosen_pool)
embed = make_exo_embed(exo, page, interaction.user)
view = ExoView(chosen_pool)
await interaction.response.send_message(embed=embed, view=view)
# ──────────────────────────────────────────────
# Daily exercise scheduler
# ──────────────────────────────────────────────
DAILY_CHANNEL_ID = 1502250179430973440 # <-- channel where the daily exercise is posted
#DAILY_TIME = time(7, 30) # <-- 7:30 UTC — change to your preferred time
DAILY_POOL = exercices_manuel_complet # change to chapitres_vus / chapitres_a_faire if you prefer
DAILY_ROLE_ID = 1501893232357937255 # <-- role to ping in the daily message (0 = no ping)
#@tasks.loop(time=DAILY_TIME)
async def daily_exo():
channel = bot.get_channel(DAILY_CHANNEL_ID)
if channel is None:
print(f"[daily_exo] Channel {DAILY_CHANNEL_ID} not found.")
return
exo, page = pick_exercise(DAILY_POOL)
embed = make_exo_embed(exo, page)
embed.title = "📅 Exercice du jour"
view = ExoView(DAILY_POOL, timeout=None) # no timeout for the daily post
role = channel.guild.get_role(DAILY_ROLE_ID) if DAILY_ROLE_ID else None
content = role.mention if role else None
await channel.send(
content=content,
embed=embed,
view=view,
allowed_mentions=discord.AllowedMentions(roles=True),
)
@daily_exo.before_loop
async def before_daily():
await bot.wait_until_ready()
# ──────────────────────────────────────────────
# JSON / TXT helpers (unchanged from your original)
# ──────────────────────────────────────────────
def load_json():
if CODES_JSON.exists():
with open(CODES_JSON, "r", encoding="utf-8") as f:
return json.load(f)
return {}
def save_json(data):
with open(CODES_JSON, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
def append_to_txt(code: str):
codes_set = set()
if CODES_TXT.exists():
with open(CODES_TXT, "r", encoding="utf-8") as f:
codes_set = set(line.strip() for line in f if line.strip())
if code not in codes_set:
with open(CODES_TXT, "a", encoding="utf-8") as f:
f.write(code + "\n")
# ──────────────────────────────────────────────
# QR helpers (unchanged from your original)
# ──────────────────────────────────────────────
def generate_unique_code():
data = load_json()
existing = set(data.keys()) | BLACKLIST
while True:
code = str(random.randint(0, 99999999)).zfill(8)
if code not in existing:
return code
def generate_qr(code: str):
img = qrcode.make(code)
path = QR_DIR / f"{code}.png"
img.save(path)
return path
# ──────────────────────────────────────────────
# Events
# ──────────────────────────────────────────────
@bot.event
async def on_ready():
await tree.sync()
daily_exo.start() # start the daily scheduler when the bot comes online
print(f"✅ {bot.user} is online | slash commands synced | daily task started.")
# ──────────────────────────────────────────────
# /qr command (unchanged from your original)
# ──────────────────────────────────────────────
@tree.command(name="qr", description="Generate a new QR code")
async def qr(interaction: discord.Interaction):
await interaction.response.send_message("Generating QR code...", ephemeral=True)
code = generate_unique_code()
qr_path = generate_qr(code)
now = datetime.utcnow().isoformat()
data = load_json()
data[code] = {
"generated_at": now,
"last_reaction": None,
"category": "waiting",
"created_by": interaction.user.id,
}
save_json(data)
append_to_txt(code)
msg = await interaction.channel.send(
file=discord.File(qr_path),
content=(
f"**QR Code Generated!**\n"
f"Code: `{code}`\n"
f"Generated by: {interaction.user.mention}\n"
f"React with ✅ if working or ❌ if not."
),
)
pending_codes[msg.id] = {"code": code, "user_id": interaction.user.id}
await msg.add_reaction("✅")
await msg.add_reaction("❌")
# ──────────────────────────────────────────────
# /list, /edit_code, /shutdown (unchanged)
# ──────────────────────────────────────────────
LIST_CATEGORIES = ["working", "not_working", "waiting"]
async def category_autocomplete(interaction: discord.Interaction, current: str):
return [app_commands.Choice(name=c, value=c) for c in LIST_CATEGORIES if current.lower() in c.lower()][:25]
async def code_autocomplete(interaction: discord.Interaction, current: str):
data = load_json()
return [app_commands.Choice(name=c, value=c) for c in data.keys() if current in c][:25]
@tree.command(name="list", description="List codes by name, date range, category, or creator")
@app_commands.describe(code="Optional: search by code", start_date="Optional: start date YYYY-MM-DD",
end_date="Optional: end date YYYY-MM-DD", category="Optional: filter by category",
creator="Optional: filter by creator username")
@app_commands.autocomplete(code=code_autocomplete, category=category_autocomplete)
async def list_codes(interaction: discord.Interaction, code: str = None, start_date: str = None,
end_date: str = None, category: str = None, creator: str = None):
data = load_json()
if not data:
await interaction.response.send_message("No codes available.", ephemeral=True)
return
filtered = []
for c, info in data.items():
if code and code not in c: continue
if category and info.get("category") != category: continue
gen_date = info.get("generated_at", "")[:10]
if start_date and gen_date < start_date: continue
if end_date and gen_date > end_date: continue
if creator:
cid = info.get("created_by")
member = interaction.guild.get_member(cid) if cid else None
if not member or creator.lower() not in member.name.lower():
continue
filtered.append((c, info))
if not filtered:
await interaction.response.send_message("No codes match your filters.", ephemeral=True)
return
filtered.sort(key=lambda x: x[1]["generated_at"], reverse=True)
lines = []
for c, info in filtered[:25]:
status = info.get("category", "unknown")
date = info.get("generated_at", "n/a")[:19].replace("T", " ")
cid = info.get("created_by")
name = "Unknown"
if cid:
m = interaction.guild.get_member(cid)
if m:
name = f"{m.name}#{m.discriminator}"
lines.append(f"`{c}` | {status} | {date} | {name}")
await interaction.response.send_message(f"**Filtered Codes**\n```{'chr(10)'.join(lines)}```", ephemeral=True)
@tree.command(name="edit_code", description="Modify a code in JSON and TXT (admin only)")
@app_commands.describe(code="The 8-digit code to modify", category="Set the code category",
status="Optional: last reaction status")
@app_commands.autocomplete(code=code_autocomplete)
async def edit_code(interaction: discord.Interaction, code: str, category: str, status: str = None):
if not any(r.id == ADMIN_ROLE_ID for r in interaction.user.roles):
await interaction.response.send_message("❌ Admin role required.", ephemeral=True)
return
data = load_json()
if code not in data:
await interaction.response.send_message(f"❌ Code `{code}` not found.", ephemeral=True)
return
if category not in ["working", "not_working", "waiting"]:
await interaction.response.send_message("❌ Invalid category.", ephemeral=True)
return
data[code]["category"] = category
if status:
data[code]["last_reaction"] = {
"status": status,
"by": f"{interaction.user.name}#{interaction.user.discriminator}",
"at": datetime.utcnow().isoformat(),
}
save_json(data)
append_to_txt(code)
await interaction.response.send_message(f"✅ Code `{code}` updated.", ephemeral=True)
@tree.command(name="shutdown", description="Shutdown the bot (admin only)")
async def shutdown(interaction: discord.Interaction):
if not any(r.id == ADMIN_ROLE_ID for r in interaction.user.roles):
await interaction.response.send_message("❌ Admin role required.", ephemeral=True)
return
data = load_json()
now = datetime.utcnow().isoformat()
for entry in pending_codes.values():
c = entry["code"]
if c not in data:
data[c] = {"generated_at": now, "last_reaction": {"status": "shutdown_backup", "by": "system", "at": now}, "category": "waiting"}
append_to_txt(c)
save_json(data)
channel = bot.get_channel(NOTIFY_CHANNEL_ID)
if channel:
await channel.send("⚠️ Bot is shutting down. Pending codes saved.")
await interaction.response.send_message("✅ Bot is shutting down...", ephemeral=True)
await bot.close()
# ──────────────────────────────────────────────
# Reaction events (unchanged)
# ──────────────────────────────────────────────
@bot.event
async def on_reaction_add(reaction, user):
if user.bot:
return
msg_id = reaction.message.id
emoji = str(reaction.emoji)
if msg_id not in pending_codes:
return
entry = pending_codes[msg_id]
if user.id != entry["user_id"]:
return
code = entry["code"]
data = load_json()
if code not in data:
return
last = data[code].get("last_reaction")
last_status = last["status"] if last and last["by"] == f"{user.name}#{user.discriminator}" else None
opposite = None
if emoji == "✅":
opposite = "❌"
data[code]["category"] = "working"
elif emoji == "❌":
opposite = "✅"
data[code]["category"] = "not_working"
else:
return
if last_status == opposite:
await reaction.message.remove_reaction(opposite, user)
data[code]["last_reaction"] = {"status": emoji, "by": f"{user.name}#{user.discriminator}", "at": datetime.utcnow().isoformat()}
save_json(data)
append_to_txt(code)
await reaction.message.channel.send(f"Code `{code}` marked as **{data[code]['category']}** by {user.mention}.")
@bot.event
async def on_reaction_remove(reaction, user):
if user.bot:
return
msg_id = reaction.message.id
if msg_id not in pending_codes:
return
entry = pending_codes[msg_id]
if user.id != entry["user_id"]:
return
code = entry["code"]
data = load_json()
if code not in data:
return
last = data[code].get("last_reaction")
if last and last["by"] == f"{user.name}#{user.discriminator}" and str(reaction.emoji) == last["status"]:
data[code]["category"] = "waiting"
data[code]["last_reaction"] = {"status": "removed", "by": f"{user.name}#{user.discriminator}", "at": datetime.utcnow().isoformat()}
save_json(data)
await reaction.message.channel.send(f"Code `{code}` reset to waiting by {user.mention}.")
# ──────────────────────────────────────────────
# Run
# ──────────────────────────────────────────────
bot.run(TOKEN)