Files
main.py
requirements.txt
Code
2 167
main.py
import logging
import os
import secrets
import string
import discord
from discord import app_commands
from discord.ext import commands
logger = logging.getLogger("user_sniper")
USERNAME_CHARACTERS = string.ascii_lowercase + string.digits + "_"
CANDIDATES_PER_REQUEST = 10
class UserSniperBot(commands.Bot):
def __init__(self, authorized_user_id: int) -> None:
super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.none())
self.authorized_user_id = authorized_user_id
self.seen_candidates: set[str] = set()
self.candidates_generated = 0
async def setup_hook(self) -> None:
try:
synced = await self.tree.sync()
logger.info("Synced %d application command(s).", len(synced))
except discord.HTTPException:
logger.exception("Could not sync application commands.")
def create_bot(authorized_user_id: int) -> UserSniperBot:
bot = UserSniperBot(authorized_user_id)
async def is_authorized(interaction: discord.Interaction) -> bool:
return interaction.user.id == bot.authorized_user_id
@bot.tree.command(
name="sniper",
description="Generate short username ideas (availability is not checked).",
)
@app_commands.choices(
length=[
app_commands.Choice(name="Triple (3 characters)", value=3),
app_commands.Choice(name="Quad (4 characters)", value=4),
]
)
@app_commands.check(is_authorized)
async def sniper(interaction: discord.Interaction, length: app_commands.Choice[int]) -> None:
candidates = generate_candidates(bot, length.value)
if not candidates:
await interaction.response.send_message(
f"No unused {length.value}-character candidates remain in this session. "
"Availability was not checked.",
ephemeral=True,
)
return
formatted = "\n".join(f"`{candidate}`" for candidate in candidates)
await interaction.response.send_message(
"**Username availability cannot be checked through Discord's supported API.**\n"
"These are random candidate ideas only; none were checked or confirmed available. "
"Verify any candidate yourself in Discord's official username settings. "
"This command does not run a background search or send unverified DMs.\n\n"
f"**{length.value}-character candidates:**\n{formatted}",
ephemeral=True,
)
@bot.tree.command(name="status", description="Show candidate generation and availability-check status.")
@app_commands.check(is_authorized)
async def status(interaction: discord.Interaction) -> None:
await interaction.response.send_message(
"No availability search is running. Discord's supported API does not provide "
"availability checks for arbitrary usernames.\n"
f"Candidate ideas generated this session: {bot.candidates_generated}\n"
"Availability checks performed: 0.",
ephemeral=True,
)
@bot.tree.command(name="stop", description="Stop an active username search, if one exists.")
@app_commands.check(is_authorized)
async def stop(interaction: discord.Interaction) -> None:
await interaction.response.send_message(
"There is no active search to stop. This bot only generates one-time candidate ideas; "
"it does not check availability or run background tasks.",
ephemeral=True,
)
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
if isinstance(error, app_commands.CheckFailure):
message = "You are not authorized to use this bot."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
return
logger.error(
"Application command failed.",
exc_info=(type(error), error, error.__traceback__),
)
message = "The command failed unexpectedly. Please try again later."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
return bot
def generate_candidates(bot: UserSniperBot, length: int) -> list[str]:
candidates: list[str] = []
total_candidates = len(USERNAME_CHARACTERS) ** length
already_generated = sum(len(candidate) == length for candidate in bot.seen_candidates)
target_count = min(CANDIDATES_PER_REQUEST, total_candidates - already_generated)
while len(candidates) < target_count:
candidate = "".join(secrets.choice(USERNAME_CHARACTERS) for _ in range(length))
if candidate in bot.seen_candidates:
continue
bot.seen_candidates.add(candidate)
candidates.append(candidate)
bot.candidates_generated += len(candidates)
return candidates
def load_configuration() -> tuple[str, int]:
token = os.getenv("DISCORD_TOKEN", "").strip()
authorized_user_id = os.getenv("AUTHORIZED_USER_ID", "").strip()
if not token:
raise RuntimeError("Set the DISCORD_TOKEN environment variable.")
if not authorized_user_id:
raise RuntimeError("Set the AUTHORIZED_USER_ID environment variable.")
try:
user_id = int(authorized_user_id)
except ValueError as exc:
raise RuntimeError("AUTHORIZED_USER_ID must be your numeric Discord user ID.") from exc
if user_id <= 0:
raise RuntimeError("AUTHORIZED_USER_ID must be a positive numeric Discord user ID.")
return token, user_id
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
try:
token, authorized_user_id = load_configuration()
except RuntimeError as exc:
logger.error("%s", exc)
raise SystemExit(1) from exc
bot = create_bot(authorized_user_id)
try:
bot.run(token, log_handler=None)
except discord.LoginFailure:
logger.error("Discord rejected the bot token. Check DISCORD_TOKEN.")
raise SystemExit(1)
if __name__ == "__main__":
main()