Files
.gitignore
bot.py
Dockerfile
README.md
requirements.txt
Code
5 117
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")
class DiscordBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix="!", intents=intents)
async def setup_hook(self) -> None:
synced_commands = await self.tree.sync()
logger.info("ซิงก์คำสั่งแล้ว %d คำสั่ง", len(synced_commands))
bot = DiscordBot()
@bot.event
async def on_ready() -> None:
if bot.user is not None:
logger.info("บอทออนไลน์แล้ว: %s (%s)", bot.user, bot.user.id)
@bot.tree.command(name="ping", description="ตรวจสอบว่าบอทออนไลน์อยู่หรือไม่")
async def ping(interaction: discord.Interaction) -> None:
latency = round(bot.latency * 1000)
await interaction.response.send_message(f"Pong! 🟢 {latency} ms")
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
logger.error("เกิดข้อผิดพลาดในคำสั่ง: %s", error, 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)
def main() -> None:
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("กรุณากำหนด DISCORD_TOKEN ในไฟล์ .env")
bot.run(token, log_handler=None)
if __name__ == "__main__":
main()