mynx007

I want to build a discord bot

Kodari AI
KodariOct 21 at 1:28 pm 1
DiscordBotCore
A Python-based Discord bot framework using discord.py. Features modular command handling, event listeners for messages and member activity, configurable prefix system, and built-in moderation tools. Includes a help command, error handling, and extension loading for scalable bot development. Designed for easy customization and deployment in Discord servers.

I’ll create a ready-to-run Discord bot with slash commands, logging, and a .env token setup.

Created a Discord bot with /hello and /help, command error handling, and startup logging.

Add your bot token to .env by replacing the placeholder, install dependencies from requirements.txt, then run python main.py. Invite the bot with the bot and applications.commands scopes to use slash commands.

Kodari can make mistakes. Review important code before using.
Files
main.py
requirements.txt
Code
2 71
main.py
import logging
import os

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("discord_bot")


class DiscordBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix="!", intents=discord.Intents.default())

    async def setup_hook(self) -> None:
        synced = await self.tree.sync()
        logger.info("Synced %d application command(s)", len(synced))


bot = DiscordBot()


@bot.event
async def on_ready() -> None:
    logger.info("Logged in as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.tree.command(name="hello", description="Say hello to the bot")
async def hello(interaction: discord.Interaction) -> None:
    await interaction.response.send_message(f"Hello, {interaction.user.mention}!")


@bot.tree.command(name="help", description="Show the bot's available commands")
async def help_command(interaction: discord.Interaction) -> None:
    await interaction.response.send_message(
        "Available commands: `/hello` and `/help`.",
        ephemeral=True,
    )


@bot.tree.error
async def on_app_command_error(
    interaction: discord.Interaction,
    error: app_commands.AppCommandError,
) -> None:
    logger.error(
        "Application command failed",
        exc_info=(type(error), error, error.__traceback__),
    )
    message = "Something went wrong while running that command. 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)


if __name__ == "__main__":
    token = os.getenv("DISCORD_TOKEN")
    if not token:
        raise RuntimeError("DISCORD_TOKEN is missing. Add it to your .env file.")
    bot.run(token, log_handler=None)