dooltr

ช่วยรันบอทดิสคอร์ดให้หน่อย

Kodari AI
KodariSep 16 at 1:10 pm 1
DiscordBotRunner
A Discord bot management system that runs and controls Discord bots using discord.py. It provides commands to start, stop, restart, and monitor bot instances. The bot supports multiple bot configurations, logs activity, and handles errors gracefully. It includes a command prefix system, event handlers for member joins and messages, and a modular cog structure for extensibility. The system tracks uptime, manages permissions, and offers administrative controls for bot lifecycle management.

สร้างโปรเจกต์บอท Discord ให้แล้ว พร้อมคำสั่ง /ping

ไฟล์ที่สร้าง:

  • bot.py

  • requirements.txt

  • .env.example

  • .gitignore

วิธีรัน:

Shell
python -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate
pip install -r requirements.txt
cp .env.example .env

แก้ไฟล์ .env:

Env
DISCORD_TOKEN=โทเคนบอทของคุณ

จากนั้นรัน:

Shell
python bot.py

ตอนนี้ยังรันบอทจริงไม่ได้จนกว่าจะใส่ DISCORD_TOKEN จาก Discord Developer Portal ก่อน.

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