Files
.gitignore
bot.py
requirements.txt
Code
3 266
bot.py
import logging
import os
import secrets
import string
import uuid
from typing import Optional
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("generator_bot")
def get_audit_channel_id() -> Optional[int]:
configured_id = os.getenv("AUDIT_CHANNEL_ID")
if not configured_id:
return None
try:
return int(configured_id)
except ValueError:
logger.error("AUDIT_CHANNEL_ID must be a Discord channel ID.")
return None
class GeneratorBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix="!", intents=intents)
self.commands_synced = False
self.audit_channel_id = get_audit_channel_id()
async def setup_hook(self) -> None:
if not self.commands_synced:
synced_commands = await self.tree.sync()
self.commands_synced = True
logger.info("Synced %d application commands.", len(synced_commands))
await self.audit_log(
f"Commands synced: {len(synced_commands)} application commands."
)
async def on_ready(self) -> None:
if self.user is not None:
logger.info("Logged in as %s (%s).", self.user, self.user.id)
await self.audit_log(f"Bot ready: {self.user} ({self.user.id}).")
async def audit_log(self, message: str) -> None:
logger.info("AUDIT | %s", message)
if self.audit_channel_id is None:
return
channel = self.get_channel(self.audit_channel_id)
if channel is None:
try:
channel = await self.fetch_channel(self.audit_channel_id)
except (discord.HTTPException, discord.NotFound):
logger.error(
"Could not access the configured audit channel (%s).",
self.audit_channel_id,
)
return
if not isinstance(channel, discord.TextChannel):
logger.error("The configured audit channel is not a text channel.")
return
try:
await channel.send(f"[Generator bot audit] {message[:1900]}")
except discord.HTTPException:
logger.exception("Could not send an audit log message.")
bot = GeneratorBot()
generate_group = app_commands.Group(
name="generate",
description="Generate fictional values for testing and creative projects.",
)
def create_password(length: int) -> str:
alphabet = string.ascii_letters + string.digits + "!@#$%^&*()-_=+"
password_characters = [
secrets.choice(string.ascii_lowercase),
secrets.choice(string.ascii_uppercase),
secrets.choice(string.digits),
secrets.choice("!@#$%^&*()-_=+"),
]
password_characters.extend(
secrets.choice(alphabet) for _ in range(length - len(password_characters))
)
secrets.SystemRandom().shuffle(password_characters)
return "".join(password_characters)
def create_username() -> str:
adjectives = (
"Bright",
"Cosmic",
"Frosty",
"Golden",
"Lunar",
"Pixel",
"Quiet",
"Swift",
"Turbo",
"Velvet",
)
nouns = (
"Builder",
"Comet",
"Creator",
"Dragon",
"Explorer",
"Gamer",
"Pilot",
"Ranger",
"Robot",
"Wizard",
)
return f"{secrets.choice(adjectives)}{secrets.choice(nouns)}{secrets.randbelow(10000):04d}"
def create_mock_profile() -> dict[str, str]:
return {
"username": create_username(),
"user_id": str(secrets.randbelow(900_000_000) + 100_000_000),
"profile_id": str(uuid.uuid4()),
"status": secrets.choice(("Active", "Away", "Offline")),
"created_for": "fictional testing data only",
}
async def send_private_result(
interaction: discord.Interaction,
content: str,
) -> None:
await interaction.response.send_message(content, ephemeral=True)
@generate_group.command(
name="password",
description="Generate a secure random password.",
)
@app_commands.describe(length="Password length from 8 to 64 characters.")
async def generate_password(
interaction: discord.Interaction,
length: app_commands.Range[int, 8, 64] = 20,
) -> None:
password = create_password(length)
await send_private_result(
interaction,
f"Generated password:\n```{password}```\n"
"Store it in a password manager and never share it.",
)
await bot.audit_log(
f"/generate password by {interaction.user} ({interaction.user.id}); "
f"length={length}; password value redacted."
)
@generate_group.command(
name="username",
description="Generate a fictional username.",
)
async def generate_username(interaction: discord.Interaction) -> None:
username = create_username()
await send_private_result(
interaction,
f"Generated fictional username:\n```{username}```\n"
"This does not create or reserve an account on any platform.",
)
await bot.audit_log(
f"/generate username by {interaction.user} ({interaction.user.id}); "
f"value={username}."
)
@generate_group.command(
name="uuid",
description="Generate a random UUID.",
)
async def generate_uuid(interaction: discord.Interaction) -> None:
generated_uuid = uuid.uuid4()
await send_private_result(
interaction,
f"Generated UUID:\n```{generated_uuid}```",
)
await bot.audit_log(
f"/generate uuid by {interaction.user} ({interaction.user.id}); "
f"value={generated_uuid}."
)