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)