Files
.gitignore
bot.py
requirements.txt
Code
3 70
bot.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")
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is missing from the environment or .env file")
class DiscordBot(commands.Bot):
def __init__(self) -> None:
super().__init__(
command_prefix="!",
intents=discord.Intents.default(),
)
async def setup_hook(self) -> None:
synced_commands = await self.tree.sync()
logger.info("Synced %d application command(s)", len(synced_commands))
bot = DiscordBot()
@bot.event
async def on_ready() -> None:
if bot.user is not None:
logger.info("Logged in as %s (ID: %s)", bot.user, bot.user.id)
@bot.tree.command(name="ping", description="Check whether the bot is online")
async def ping(interaction: discord.Interaction) -> None:
latency_ms = round(bot.latency * 1000)
await interaction.response.send_message(f"Pong! {latency_ms} ms")
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
logger.error("Application command failed", exc_info=error)
message = "เกิดข้อผิดพลาดระหว่างใช้คำสั่ง กรุณาลองใหม่อีกครั้ง"
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
bot.run(token)