.qr.g
📎 1 file 2,164 chars
📄
pasted-code-1792377184808.txt
txt 49 lines
▶
I want you to build a complete Discord bot in Python using discord.py, with all the code in a working main.py file.

Project Name: User Sniper

1. Slash Command

Create a /sniper slash command that displays two options:

* Triple: Search for 3-character usernames.
* Quad: Search for 4-character usernames.

2. Username Search

* After selecting an option, the bot should start generating and checking usernames.
* Use only officially supported and permitted methods to verify username availability.
* If a username is confirmed to be available, send it to my Discord DMs immediately.
* Include the username, its length, the discovery time, and its verification status.
* Avoid duplicate results and continue searching until I stop it.

3. Additional Commands

* /stop — Stop the active search.
* /status — Show whether the search is running and how many usernames have been checked.

4. Reliability

* Use asynchronous tasks so the bot remains responsive.
* Handle network errors, Discord API errors, rate limits, and failed DMs properly.
* Prevent duplicate searches and duplicate notifications.
* Keep the code organized, readable, and easy to maintain.

5. Security

* Use a regular Discord bot account created through the Discord Developer Portal.
* Never use a user token or self-bot.
* Store the bot token in an environment variable or Replit Secrets.
* Restrict commands to my authorized Discord user ID.

6. Testing and Delivery

* Provide the complete main.py file, not incomplete snippets.
* Include a requirements.txt file if needed.
* Explain exactly how to configure and run the bot on Replit.
* Review the code for syntax errors, missing imports, invalid commands, and compatibility issues.
* Test all components that can reasonably be tested before delivering the final code.

Important: Do not invent a Discord API endpoint or claim that username availability checking works if the official API does not support it. If continuous availability checking is not officially supported, explain the limitation and implement the closest permitted alternative.

I want a real, functional project—not a mockup, pseudocode, or code that only looks complete.
Kodari AI
KodariOct 19 at 2:36 am 1
UserSniper
User Sniper is a Discord bot that monitors username availability for 3 and 4 character usernames. It provides a /sniper slash command with Triple and Quad options, generating and checking usernames asynchronously. Available usernames are sent to the authorized user's DMs with details like length, discovery time, and verification status. Additional /stop and /status commands control the search process. The bot handles rate limits, network errors, and duplicate prevention while maintaining responsiveness through async tasks. Security is enforced via environment variable token storage and user ID authorization.
  1. Add a complete discord.py bot with /sniper, /status, and /stop, restricted to one configured Discord user.

  2. Since Discord has no supported API for checking arbitrary username availability, make /sniper generate clearly labeled, unverified candidates instead of claiming availability.

  3. Add the dependency; include Replit setup and be explicit about what cannot be tested without credentials.

Created main.py and requirements.txt.

Discord does not provide a supported API for checking arbitrary usernames, so /sniper generates 10 random candidate ideas and clearly labels them unverified. It does not run a background search or send DMs claiming a name is available. /status reports zero availability checks; /stop reports that no search is running. All commands are restricted to the configured Discord user ID.

Run it on Replit

  1. Add both files to your Replit project.

  2. In Replit Secrets, set DISCORD_TOKEN to your bot token and AUTHORIZED_USER_ID to your numeric Discord user ID. Enable Developer Mode in Discord to copy your ID.

  3. In the Discord Developer Portal, create the bot and invite it to your server with the bot and applications.commands scopes. No privileged intents are needed.

  4. Install dependencies with pip install -r requirements.txt, then run python main.py (or use the Replit Run button configured to run that command).

  5. Use /sniper and choose Triple or Quad. Global slash commands can take a while to appear after syncing.

I reviewed the code, but couldn’t run a live Discord test without bot credentials or a Replit environment.

Kodari can make mistakes. Review important code before using.
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()