ساخت بات دیسکورد با Node.js و پایتون
آموزش ساخت اولین بات دیسکورد با Node.js و discord.js و نمونهی پایتون: ساخت اپلیکیشن، دریافت توکن، دعوت بات، ثبت دستور اسلش، اجرای دائم و نکات امنیتی.
بات دیسکورد برنامهای است که با اکانتی مخصوص وارد سرور میشود و کارهایی مثل خوشآمدگویی، موزیک و مدیریت را انجام میدهد. در این آموزش یک بات با دستور /ping میسازیم، با Node.js (نسخهی ۱۸ به بالا) و کتابخانهی discord.js.
مرحله ۱: ساخت اپلیکیشن و توکن
- به Discord Developer Portal (
discord.com/developers/applications) بروید و New Application را بزنید. - از منوی Bot، دکمهی Reset Token را بزنید و توکن را فقط برای خودتان نگه دارید؛ دوباره نشان داده نمیشود.
- در General Information مقدار Application ID را کپی کنید؛ همان Client ID است.
مرحله ۲: دعوت بات به سرور
در بخش OAuth2 و URL Generator، scopeهای bot و applications.commands را انتخاب کنید، دسترسیهای لازم را تیک بزنید (برای شروع Send Messages کافی است) و لینک ساختهشده را باز کنید تا بات را به سرور خود اضافه کنید. همیشه فقط حداقل دسترسی لازم را بدهید.
مرحله ۳: پروژهی Node.js
mkdir my-bot
cd my-bot
npm init -y
npm install discord.js dotenv
فایل .env بسازید و مقدارها را بنویسید:
DISCORD_TOKEN=توکن-بات
CLIENT_ID=آیدی-اپلیکیشن
GUILD_ID=آیدی-سرور
آیدی سرور را با روشن کردن Developer Mode در تنظیمات دیسکورد و کلیک راست روی سرور (Copy Server ID) میگیرید.
مرحله ۴: ثبت دستور اسلش
فایل deploy-commands.js:
require('dotenv').config();
const { REST, Routes, SlashCommandBuilder } = require('discord.js');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with Pong!').toJSON(),
];
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID), { body: commands })
.then(() => console.log('Commands registered'))
.catch(console.error);
مرحله ۵: کد اصلی بات
فایل index.js:
require('dotenv').config();
const { Client, GatewayIntentBits, Events } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, (c) => {
console.log(`Logged in as ${c.user.tag}`);
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
client.login(process.env.DISCORD_TOKEN);
اول node deploy-commands.js و بعد node index.js را اجرا کنید. در سرور /ping را بنویسید و پاسخ بات را ببینید.
نسخهی پایتون (discord.py)
با pip install -U discord.py نصب کنید و این کد را اجرا کنید (توکن را در متغیر محیطی DISCORD_TOKEN بگذارید):
import os
import discord
from discord import app_commands
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
@tree.command(name="ping", description="Replies with Pong!")
async def ping(interaction: discord.Interaction):
await interaction.response.send_message("Pong!")
@client.event
async def on_ready():
await tree.sync()
print(f"Logged in as {client.user}")
client.run(os.environ["DISCORD_TOKEN"])
اجرای دائم بات
اگر بات روی کامپیوتر شخصی اجرا شود، با خاموش شدن سیستم از دسترس خارج میشود. برای اجرای ۲۴ ساعته از یک سرور مجازی VPS استفاده کنید و بات را با ابزاری مثل PM2 نگه دارید:
npm install -g pm2
pm2 start index.js --name my-bot
pm2 save
برای سرور تیماسپیک هم روش مشابهی با رباتهای تیماسپیک وجود دارد.