-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
731 lines (631 loc) · 26.7 KB
/
main.py
File metadata and controls
731 lines (631 loc) · 26.7 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
"""
Group & Role Management Discord Bot
Author & Contributions:
------------------------
Author: Victor Sandi
Contributors:
Description:
------------
This bot helps server admins rapidly provision "group-style" structures
for courses, labs, or projects. Given a category and a channel base name,
it can create:
• A category (if missing)
• N channels (e.g., group-1..group-N or group-a..group-z)
• Matching roles tied to the category (e.g., "Lab 1 1", "Lab 1 2", ...)
It also posts interactive dropdown menus (role selectors) so members can
assign themselves exactly one role within a set. Finally, it supports a
confirmation-based deletion workflow that removes a category, its channels,
related roles, and previously-posted selector messages.
Key commands:
• ?create_groups <category> <channel_base> <mode:number|letter> <amount>
• ?roledrop <#channel_or_name> <category>
• ?delete <category> (with confirmation UI)
Configuration:
--------------
• private.json must contain:
{
"token": "DISCORD_BOT_TOKEN",
"allowed_ids": [123456789012345678]
}
Logging:
--------
• Rotating logs to bot.log (up to ~5MB, 3 backups)
• Detailed command start/end lines with durations
• Startup summary of joined guilds
"""
import discord
from discord.ext import commands
from discord import ui
import json
import math
import os
import logging
from logging.handlers import RotatingFileHandler
import time
from typing import List
# ----------------------------
# Load config
# ----------------------------
with open("private.json", "r", encoding="utf-8") as f:
data = json.load(f)
TOKEN = data.get("token", "")
allowed_list = data.get("allowed_ids", [])
if TOKEN == "":
print("No Token")
raise SystemExit
# ----------------------------
# Logging setup
# ----------------------------
LOG_DIR = "."
LOG_FILE = os.path.join(LOG_DIR, "bot.log")
logger = logging.getLogger("groupbot")
logger.setLevel(logging.INFO)
# Console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# Rotating file handler (prevents unbounded log growth)
fh = RotatingFileHandler(LOG_FILE, maxBytes=5_000_000, backupCount=3, encoding="utf-8")
fh.setLevel(logging.INFO)
fmt = logging.Formatter(
"[%(asctime)s] %(levelname)s %(name)s :: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
ch.setFormatter(fmt)
fh.setFormatter(fmt)
logger.addHandler(ch)
logger.addHandler(fh)
def tag_user(u: discord.abc.User) -> str:
"""Return a human-readable tag for a user including ID."""
return f"{str(u)} ({u.id})"
def tag_guild(g: discord.Guild) -> str:
"""Return a human-readable tag for a guild including ID."""
return f"{g.name} ({g.id})"
def tag_channel(c):
"""Return a human-readable tag for a channel including guild and channel IDs."""
if c is None:
return "N/A"
g = c.guild.name if hasattr(c, "guild") and c.guild else "DM"
return f"{g} / #{getattr(c, 'name', 'unknown')} ({getattr(c, 'id', 'n/a')})"
# ----------------------------
# Bot setup
# ----------------------------
intents = discord.Intents.default()
# Privileged intents required for role assignment UI and message content
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='?', intents=intents)
# Remove the default help so we can supply a domain-specific version
bot.remove_command("help")
# Persistent storage of roledrop messages we post (so they can be deleted later)
ROLE_DROPS_DB = "roledrops.json"
def _load_db() -> dict:
"""
Load roledrop message metadata from disk.
Returns:
dict: Mapping guild_id -> list of message records with:
{ "message_id": int, "channel_id": int, "label": str }
"""
if not os.path.exists(ROLE_DROPS_DB):
return {}
with open(ROLE_DROPS_DB, "r", encoding="utf-8") as f:
try:
return json.load(f)
except Exception:
# Corrupt/empty file; start fresh
return {}
def _save_db(db: dict) -> None:
"""Persist roledrop message metadata to disk."""
with open(ROLE_DROPS_DB, "w", encoding="utf-8") as f:
json.dump(db, f, indent=2)
# ----------------------------
# Helpers
# ----------------------------
def number_tokens(n: int) -> List[str]:
"""
Generate numeric tokens "1".."n" as strings.
Args:
n (int): Number of tokens to generate.
Returns:
List[str]: ["1", "2", ..., str(n)]
"""
return [str(i) for i in range(1, n + 1)]
def letter_tokens(n: int) -> List[str]:
"""
Generate alphabetic tokens in a sequence similar to spreadsheet columns,
but lowercase: a..z, aa..az, ba..bz, ...
Args:
n (int): Number of tokens to generate.
Returns:
List[str]: e.g., ["a", "b", ..., "z", "aa", "ab", ...]
"""
tokens = []
i = 0
# Loop until we have n tokens. Base-26 rollover with "a".."z".
while len(tokens) < n:
x = i
s = ""
# Convert integer index to "alphabetic base-26" string.
while True:
s = chr(ord('a') + (x % 26)) + s
x = x // 26 - 1
if x < 0:
break
tokens.append(s)
i += 1
return tokens
def make_role_names(category_name: str, mode: str, amount: int) -> List[str]:
"""
Create role names bound to a category with sequential tokens.
E.g. category "Lab 1", mode "number", amount 3 -> ["Lab 1 1", "Lab 1 2", "Lab 1 3"]
Args:
category_name (str): Category display name (e.g., "Lab 1" or "Lab_1").
mode (str): "number" or "letter" (case-insensitive).
amount (int): How many roles/groups to create.
Returns:
List[str]: Role names of form "<category_name> <token>"
"""
category_clean = category_name.replace("_", " ").strip()
if mode.lower() in ("number", "numbers", "num"):
toks = number_tokens(amount)
elif mode.lower() in ("letter", "letters", "alpha"):
toks = letter_tokens(amount)
else:
raise ValueError("mode must be 'number' or 'letter'")
return [f"{category_clean} {t}" for t in toks]
def find_roles_by_prefix(guild: discord.Guild, prefix_str: str) -> List[discord.Role]:
"""
Find roles whose names begin with "<prefix> " (note the trailing space),
case-insensitive. The trailing space ensures tighter matching on the label.
Args:
guild (discord.Guild): Guild to search.
prefix_str (str): Prefix string (usually category name).
Returns:
List[discord.Role]: Matching roles.
"""
prefix_clean = prefix_str.replace("_", " ").strip().lower() + " "
roles = [r for r in guild.roles if r.name.lower().startswith(prefix_clean)]
return roles
async def get_or_create_role(guild: discord.Guild, name: str) -> discord.Role:
"""
Get an existing role by name, or create it if missing.
Args:
guild (discord.Guild): Guild to operate in.
name (str): Exact role name.
Returns:
discord.Role: Existing or newly created role.
"""
role = discord.utils.get(guild.roles, name=name)
if role is None:
role = await guild.create_role(name=name)
return role
# ----------------------------
# Dropdown Menu (Role Selector)
# ----------------------------
class Select(ui.Select):
"""
Single-select dropdown listing group roles for a category.
Behavior:
• Selecting a role removes any other role from the same category prefix.
• Then it adds the selected role to the user.
• Ephemeral confirmation is sent to avoid channel noise.
"""
def __init__(self, role_ids: List[int], role_names: List[str], label: str):
"""
Args:
role_ids (List[int]): IDs of roles in the current page.
role_names (List[str]): Display names parallel to role_ids.
label (str): Category label for UX text (e.g., "Lab 1").
"""
options = [
discord.SelectOption(label=role_names[i], value=str(role_ids[i]))
for i in range(len(role_ids))
]
super().__init__(
placeholder=f"Select your {label} group…",
options=options,
max_values=1,
custom_id="role-select" # Stable ID for persistent view wiring
)
async def callback(self, interaction: discord.Interaction) -> None:
"""
On select:
• Remove any existing role from the same category prefix.
• Add the new role.
• Reply ephemerally with the result.
"""
t0 = time.monotonic()
chosen_role = None
try:
chosen_role = discord.utils.get(interaction.guild.roles, id=int(self.values[0]))
if chosen_role is None:
await interaction.response.send_message("That role no longer exists.", ephemeral=True)
return
# Compute category prefix from role name: "<category> <token>" -> "<category>"
name = chosen_role.name
role_label = name.rsplit(" ", 1)[0] if " " in name else name
prefix = f"{role_label} ".lower()
user_role_ids = {r.id for r in interaction.user.roles}
removed_any = False
# Remove user's other roles within same category set
for r in interaction.guild.roles:
if r.name.lower().startswith(prefix) and r.id in user_role_ids:
await interaction.user.remove_roles(r)
removed_any = True
# Assign the chosen role
await interaction.user.add_roles(chosen_role)
msg = (f"Selected <@&{chosen_role.id}> and removed your other **{role_label}** role(s)."
if removed_any else f"Selected <@&{chosen_role.id}>.")
await interaction.response.send_message(msg, ephemeral=True)
finally:
dt = (time.monotonic() - t0) * 1000
logger.info(
f"ROLE-SELECT by {tag_user(interaction.user)} in {tag_guild(interaction.guild)} "
f"-> role {chosen_role.name if chosen_role else 'N/A'} ({dt:.1f} ms)"
)
class SelectView(ui.View):
"""
Persistent view wrapper for the Select dropdown. The bot re-registers
this view on startup so previously-posted menus continue to function.
"""
def __init__(self, role_ids: List[int], role_names: List[str], label: str):
super().__init__(timeout=None)
self.add_item(Select(role_ids, role_names, label))
# ----------------------------
# Ready
# ----------------------------
@bot.event
async def on_ready() -> None:
"""
Startup hook:
• Logs bot identity and intent configuration.
• Lists connected guilds with basic stats.
• Re-registers the empty SelectView so existing menus stay active.
"""
logger.info(f"Logged in as {bot.user} (ID: {bot.user.id})")
logger.info(f"Intents: members={intents.members} message_content={intents.message_content}")
if bot.guilds:
logger.info("Connected guilds:")
for g in bot.guilds:
try:
logger.info(f" - {tag_guild(g)} | members≈{g.member_count} | channels={len(g.channels)}")
except Exception:
logger.info(f" - {tag_guild(g)}")
else:
logger.info("No guilds joined yet.")
# Register a "blank" persistent view so previously-sent components keep working
bot.add_view(SelectView([], [], ""))
# ----------------------------
# Commands
# ----------------------------
def _is_allowed(ctx) -> bool:
"""
Return True if invoker is authorized to run admin commands.
Policy:
• IDs listed in private.json -> allowed_ids
• OR guild Administrator permission
"""
return ctx.author.id in allowed_list or ctx.author.guild_permissions.administrator
@bot.command(help="Create roles/channels for groups.")
async def create_groups(ctx, ctx_category: str, ctx_channel: str, mode: str, amount: int) -> None:
"""
Create or update a category + N channels + N roles tied to that category.
Args:
ctx_category (str): Category name; underscores converted to spaces. ("Lab_1" -> "Lab 1")
ctx_channel (str): Base name for channels; underscores become hyphens for neatness.
mode (str): "number" or "letter" for sequence type.
amount (int): How many groups to create.
Side effects:
• Creates missing category.
• Creates/updates text channels with role-based visibility.
• Creates missing roles named "<category> <token>".
Example:
?create_groups Lab_1 group number 5
"""
t0 = time.monotonic()
logger.info(f"START create_groups by {tag_user(ctx.author)} in {tag_guild(ctx.guild)} "
f"args=({ctx_category} {ctx_channel} {mode} {amount})")
try:
if not _is_allowed(ctx):
await ctx.send("ERROR: Unauthorized User")
logger.info("END create_groups -> unauthorized")
return
guild = ctx.guild
category_name = ctx_category.replace("_", " ").strip()
channel_base = ctx_channel.replace("_", "-").lower().strip()
# Ensure category exists
category = discord.utils.get(guild.categories, name=category_name)
if category is None:
category = await guild.create_category(category_name)
# Build roles & channels in lock-step so each token has a role + channel
role_names = make_role_names(category_name, mode, amount)
for role_name in role_names:
role = await get_or_create_role(guild, role_name)
token = role_name.rsplit(" ", 1)[1] # Extract "1" from "Lab 1 1", etc.
chan_name = f"{channel_base}-{token}".lower()
text_chan = discord.utils.get(category.text_channels, name=chan_name)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True),
role: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
if text_chan is None:
await guild.create_text_channel(chan_name, category=category, overwrites=overwrites)
else:
await text_chan.edit(overwrites=overwrites)
# Provide a ready-to-copy roledrop command for convenience
await ctx.send(
f"Created/updated **{amount}** groups in category **{category_name}**.\n\n"
f"If you want to create roledrops for this, enter:\n"
f"`?roledrop <#channel_name> {ctx_category}`"
)
logger.info("END create_groups -> success")
except Exception as e:
logger.exception("END create_groups -> FAILED")
await ctx.send(f"⚠️ Error creating groups: `{e}`")
finally:
dt = (time.monotonic() - t0) * 1000
logger.info(f"create_groups duration {dt:.1f} ms")
@bot.command(help="Post role dropdowns for a category.")
async def roledrop(ctx, channel: str, category_name: str) -> None:
"""
Post one or more dropdown menus listing all roles tied to a category.
Args:
channel (str): Channel mention (e.g., <#12345>) or channel name.
category_name (str): Category; underscores become spaces for matching.
Behavior:
• Sorts roles alphabetically by name for consistent UX.
• Posts multiple dropdowns if >25 roles (Discord select limit).
• Persists message IDs to disk for future cleanup on deletion.
"""
t0 = time.monotonic()
logger.info(f"START roledrop by {tag_user(ctx.author)} in {tag_guild(ctx.guild)} "
f"args=({channel} {category_name})")
try:
# Resolve text channel target from mention or name
if channel.startswith("<#") and channel.endswith(">"):
ch_id = int(channel[2:-1])
target = bot.get_channel(ch_id)
else:
target = discord.utils.get(ctx.guild.channels, name=channel)
if target is None or not isinstance(target, discord.TextChannel):
await ctx.send("That text channel does not exist.")
logger.info("END roledrop -> no channel")
return
category_clean = category_name.replace("_", " ").strip()
# Collect all roles for this category prefix and sort for top-to-bottom UX
roles = sorted(find_roles_by_prefix(ctx.guild, category_clean), key=lambda r: r.name.lower())
if not roles:
await ctx.send(f"No roles found for category **{category_clean}**.")
logger.info("END roledrop -> no roles")
return
role_ids = [r.id for r in roles]
role_names = [r.name for r in roles]
# Load DB and record posted messages so we can delete them later
db = _load_db()
gkey = str(ctx.guild.id)
if gkey not in db:
db[gkey] = []
async def post_chunk(ids, names, suffix=""):
view = SelectView(ids, names, category_clean)
msg = await target.send(f"Select group for **{category_clean}**{suffix}", view=view)
db[gkey].append({
"message_id": msg.id,
"channel_id": target.id,
"label": category_clean
})
# First batch up to 25, then any needed overflow batches
await post_chunk(role_ids[:25], role_names[:25])
runoffs = math.floor(len(role_ids) / 25)
for amount in range(runoffs):
i = (amount + 1) * 25
await post_chunk(role_ids[i:i+25], role_names[i:i+25], " (Overflow)")
_save_db(db)
await ctx.send(f"Posted selector(s) for **{category_clean}** in {target.mention}.")
logger.info("END roledrop -> success")
except Exception as e:
logger.exception("END roledrop -> FAILED")
await ctx.send(f"⚠️ Error posting roledrop: `{e}`")
finally:
dt = (time.monotonic() - t0) * 1000
logger.info(f"roledrop duration {dt:.1f} ms")
# ----------------------------
# Delete with confirmation
# ----------------------------
class ConfirmDeleteView(ui.View):
"""
Two-button confirmation view to prevent accidental destructive actions.
Interactions:
• Only the original command invoker may confirm/cancel (interaction_check).
• On confirm: defers immediately (prevents 3s timeout), deletes roles,
channels, the category, and any stored roledrop messages, then edits
the original channel message and removes the ephemeral response.
• On cancel: clears the UI and posts a clean "cancelled" message in-channel.
"""
def __init__(self, category_name: str, author_id: int):
"""
Args:
category_name (str): Category to delete (underscores allowed).
author_id (int): User ID authorized to press these buttons.
"""
super().__init__(timeout=30)
self.category_name = category_name
self.author_id = author_id
async def interaction_check(self, interaction: discord.Interaction) -> bool:
"""
Restrict interactions to the command invoker.
Returns:
bool: True if allowed; otherwise an ephemeral warning is sent.
"""
allowed = interaction.user.id == self.author_id
if not allowed:
await interaction.response.send_message("Only the command invoker can use these buttons.", ephemeral=True)
return allowed
@ui.button(label="✅ Confirm Delete", style=discord.ButtonStyle.danger)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
"""
Execute the full deletion flow after a positive confirmation:
1) Defer immediately to acknowledge the component interaction.
2) Delete related roles, channels, category, and roledrop messages.
3) Edit the original channel message with a concise completion summary.
4) Remove the ephemeral deferred response to avoid duplicate messages.
"""
t0 = time.monotonic()
logger.info(f"START delete/confirm by {tag_user(interaction.user)} in {tag_guild(interaction.guild)} "
f"category={self.category_name}")
# Defer and display a spinner; we will remove the ephemeral response at the end
await interaction.response.defer(thinking=True)
guild = interaction.guild
category_clean = self.category_name.replace("_", " ").strip()
# Delete roles tied to this category
roles = find_roles_by_prefix(guild, category_clean)
deleted_roles = 0
for r in roles:
try:
await r.delete(reason=f"delete by {interaction.user}")
deleted_roles += 1
except Exception as e:
# Log but continue; we want best-effort cleanup
logger.warning(f"Role delete failed: {r.name} :: {e}")
# Delete channels and category
deleted_channels = 0
category_obj = discord.utils.get(guild.categories, name=category_clean)
if category_obj:
# Make a stable copy; channel list mutates as we delete
for ch in list(category_obj.channels):
try:
await ch.delete(reason=f"delete by {interaction.user}")
deleted_channels += 1
except Exception as e:
logger.warning(f"Channel delete failed: {tag_channel(ch)} :: {e}")
try:
await category_obj.delete(reason=f"delete by {interaction.user}")
except Exception as e:
logger.warning(f"Category delete failed: {category_clean} :: {e}")
# Delete previously posted roledrop selector messages
db = _load_db()
gkey = str(guild.id)
removed_msgs = 0
kept = []
if gkey in db:
for entry in db[gkey]:
if entry.get("label") == category_clean:
ch = guild.get_channel(entry["channel_id"])
if ch:
try:
msg = await ch.fetch_message(entry["message_id"])
await msg.delete()
removed_msgs += 1
except Exception as e:
removed_msgs += 1
logger.warning(f"Roledrop delete failed: message_id={entry.get('message_id')} :: {e}")
else:
kept.append(entry)
db[gkey] = kept
_save_db(db)
# 1) Edit the channel message (remove buttons + show final result)
try:
await interaction.message.edit(
content=(f"Deleted category **{category_clean}**, {deleted_channels} channels, "
f"{deleted_roles} roles, and {removed_msgs} roledrop messages."),
view=None
)
except Exception as e:
logger.warning(f"Failed to edit original confirmation message: {e}")
# 2) Remove ephemeral deferred response so only one line remains in-channel
try:
await interaction.delete_original_response()
except Exception:
# If it's already gone or not deletable, ignore.
pass
dt = (time.monotonic() - t0) * 1000
logger.info(f"END delete/confirm -> success ({dt:.1f} ms)")
@ui.button(label="❌ Cancel", style=discord.ButtonStyle.secondary)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
"""
Cancel deletion:
• Acknowledge the click quickly.
• Replace the channel message with a clean cancellation note.
• Remove ephemeral ack to avoid duplication.
"""
t0 = time.monotonic()
try:
await interaction.response.defer() # quick ack; no spinner
await interaction.message.edit(content="❌ Deletion cancelled.", view=None)
try:
await interaction.delete_original_response()
except Exception:
pass
finally:
dt = (time.monotonic() - t0) * 1000
logger.info(f"delete/cancel by {tag_user(interaction.user)} in {tag_guild(interaction.guild)} "
f"-> cancelled ({dt:.1f} ms)")
@bot.command(name="delete", help="Delete a category, its channels, and related roles & roledrops (with confirmation).")
async def delete_category(ctx, category_name: str) -> None:
"""
Prompt for confirmation to delete a whole category set.
Args:
category_name (str): Category to delete; underscores become spaces.
Behavior:
• Sends a channel message with a confirmation button view.
• Only the invoker can confirm/cancel.
"""
t0 = time.monotonic()
logger.info(f"START delete (prompt) by {tag_user(ctx.author)} in {tag_guild(ctx.guild)} "
f"args=({category_name})")
try:
if not _is_allowed(ctx):
await ctx.send("ERROR: Unauthorized User")
logger.info("END delete (prompt) -> unauthorized")
return
await ctx.send(
f"⚠ Are you sure you want to delete category **{category_name.replace('_', ' ')}** and all related data?",
view=ConfirmDeleteView(category_name, ctx.author.id)
)
logger.info("END delete (prompt) -> asked for confirmation")
except Exception as e:
logger.exception("END delete (prompt) -> FAILED")
await ctx.send(f"⚠️ Error preparing delete: `{e}`")
finally:
dt = (time.monotonic() - t0) * 1000
logger.info(f"delete (prompt) duration {dt:.1f} ms")
# ----------------------------
# Custom help command
# ----------------------------
@bot.command(name="help")
async def custom_help(ctx) -> None:
"""
Domain-specific help with concise examples tailored to this bot’s workflow.
Replaces the default discord.py help for clarity.
"""
t0 = time.monotonic()
logger.info(f"START help by {tag_user(ctx.author)} in {tag_guild(ctx.guild)}")
try:
help_text = """
**📜 Bot Commands Help**
**?create_groups <category> <channel_base> <mode:number|letter> <amount>**
Create a category, channels, and roles.
Example:
`?create_groups Lab_1 group number 5`
→ Creates "Lab 1" category, `group-1`..`group-5` channels,
and roles `Lab 1 1`..`Lab 1 5`.
**?roledrop <#channel_or_name> <category>**
Post dropdowns for all roles in a category.
Example:
`?roledrop #announcements Lab_1`
**?delete <category>**
Deletes the category, its channels, roles, and roledrop messages **after confirmation**.
Example:
`?delete Lab_1`
Notes:
- Use `_` instead of spaces in names.
- Only IDs in `private.json`'s `allowed_ids` can create/delete.
"""
await ctx.send(help_text)
logger.info("END help -> success")
except Exception:
logger.exception("END help -> FAILED")
finally:
dt = (time.monotonic() - t0) * 1000
logger.info(f"help duration {dt:.1f} ms")
# Entrypoint
bot.run(TOKEN)