디스코드 봇 특화 설정
슬래시 명령어 개발 및 등록
접두사 기반 명령어 대신 디스코드 표준인 슬래시 명령어(/)를 등록하고 배포하는 방법을 알아봅니다.
예전에 자주 쓰이던 텍스트 접두사 명령어(!도움말 등) 대신, 현재는 디스코드 공식 표준인 슬래시 명령어(/도움말)를 사용하는 것이 권장됩니다.
글로벌 명령어 vs 길드(특정 서버) 명령어
슬래시 명령어를 등록할 때 배포 범위에 따라 반영 속도에 큰 차이가 있습니다.
- 글로벌 명령어 (Global Commands):
- 봇이 참여해 있는 모든 서버에 적용되는 명령어입니다.
- 디스코드 전역 캐시 정책으로 인해, 등록 스크립트를 실행한 후 사용자 화면에 나타나기까지 최대 1시간 정도의 지연 시간이 발생할 수 있습니다.
- 길드 명령어 (Guild Commands):
- 특정 테스트 서버(Guild ID)에만 등록하는 명령어입니다.
- 등록 즉시 수 초 내에 클라이언트에 바로 반영됩니다.
- 권장 팁: 개발 및 로컬 테스트 단계에서는 테스트 길드에 명령어를 등록해 빠르게 확인하고, 개발이 완료된 후 글로벌 명령어로 전환하는 것이 편리합니다.
Node.js (discord.js v14) 등록 스크립트 예제
별도의 배포 스크립트(deploy-commands.js)를 두고 명령어를 등록하는 방식입니다.
const { REST, Routes, SlashCommandBuilder } = require('discord.js');
require('dotenv').config();
// 등록할 명령어 목록 정의
const commands = [
new SlashCommandBuilder()
.setName('핑')
.setDescription('봇의 반응 속도를 테스트합니다.'),
new SlashCommandBuilder()
.setName('정보')
.setDescription('디스호스트 컨테이너 정보를 출력합니다.')
].map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
console.log('Log: 슬래시 명령어 등록을 시작합니다...');
// 테스트 서버 Guild ID를 지정해 즉시 등록합니다.
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
{ body: commands }
);
console.log('Log: 테스트 서버에 명령어가 즉시 배포되었습니다.');
} catch (error) {
console.error(error);
}
})();Python (discord.py v2) 등록 예제
discord.py에서는 봇의 setup_hook 안에서 커맨드 트리를 동기화(sync())하여 실행 시점에 바로 등록할 수 있습니다.
import discord
from discord.ext import commands
class MyBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
super().__init__(command_prefix="!", intents=intents)
async def setup_hook(self):
# 봇 구동 시 특정 테스트 길드에 명령어를 즉시 동기화합니다.
guild = discord.Object(id=123456789012345) # 본인의 테스트 서버 ID 입력
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
print("Log: 테스트 서버 슬래시 명령어 동기화 완료")
bot = MyBot()
@bot.tree.command(name="ping", description="반응 속도 체크")
async def ping(interaction: discord.Interaction):
await interaction.response.send_message("pong!")
bot.run("DISCORD_TOKEN")