Discord API: 완벽 개발자 가이드 (2026)
코드 예시를 통해 처음부터 직접 Discord 봇과 연동 기능을 구축해 보세요
Hypereal로 구축 시작하기
단일 API를 통해 Kling, Flux, Sora, Veo 등에 액세스하세요. 무료 크레딧으로 시작하고 수백만으로 확장하세요.
신용카드 불필요 • 10만 명 이상의 개발자 • 엔터프라이즈 지원
Discord API: 2026년판 개발자 가이드 완벽 정리
Discord는 월간 활성 사용자 수(MAU)가 2억 명을 넘어서며, 게임 커뮤니티, 개발자 그룹, 콘텐츠 크리에이터의 팬덤, 그리고 최근에는 비즈니스 팀에 이르기까지 지배적인 플랫폼으로 자리 잡고 있습니다. Discord API를 사용하면 운영 자동화, 음악 재생, 게임 실행, 외부 서비스 연동, 풍부한 인터랙티브 경험을 제공하는 봇을 구축할 수 있습니다.
이 가이드에서는 설정부터 이벤트 처리, 슬래시 커맨드(Slash Commands), 메시지 컴포넌트, 그리고 배포까지 Discord 봇을 처음부터 구축하는 과정을 단계별로 안내합니다.
사전 요구 사항
시작하기 전에 다음이 필요합니다:
- Discord 계정
- 관리자 권한이 있는 Discord 서버 (테스트용)
- Node.js 18+ 또는 Python 3.10+
- 기초적인 프로그래밍 지식
1단계: 봇 애플리케이션 생성하기
- Discord Developer Portal에 접속합니다.
- "New Application"을 클릭하고 이름을 입력합니다.
- 왼쪽 사이드바에서 "Bot" 섹션으로 이동합니다.
- "Reset Token"을 클릭하여 봇 토큰을 생성합니다. 이 토큰을 안전하게 저장하세요. 한 번만 확인할 수 있습니다.
- "Privileged Gateway Intents" 항목에서 다음을 활성화합니다:
- Message Content Intent (봇이 메시지 내용을 읽어야 하는 경우)
- Server Members Intent (봇이 서버 멤버 데이터가 필요한 경우)
- Presence Intent (봇이 사용자의 상태를 추적해야 하는 경우)
2단계: 서버에 봇 초대하기
- "OAuth2" 섹션의 "URL Generator"로 이동합니다.
- "Scopes"에서
bot과applications.commands를 선택합니다. - "Bot Permissions"에서 봇에 필요한 권한을 선택합니다:
| 권한 (Permission) | 필요한 경우 |
|---|---|
| Send Messages | 거의 대부분의 경우 |
| Read Message History | 과거 메시지에 반응할 때 |
| Manage Messages | 운영 관리 (메시지 삭제 등) |
| Embed Links | 풍부한 임베드 메시지를 보낼 때 |
| Attach Files | 이미지나 파일을 전송할 때 |
| Add Reactions | 이모지 반응 기반 상호작용 |
| Manage Roles | 역할 부여 봇 |
| Kick/Ban Members | 관리용 봇 |
| Use Slash Commands | 현대적인 커맨드 인터페이스 사용 시 |
- 생성된 URL을 복사하여 브라우저에 붙여넣고 봇을 서버에 초대합니다.
3단계: 프로젝트 설정 (JavaScript)
프로젝트 초기화:
mkdir my-discord-bot && cd my-discord-bot
npm init -y
npm install discord.js dotenv
환경 변수 파일 생성:
# .env
DISCORD_TOKEN=your_bot_token_here
CLIENT_ID=your_application_id_here
GUILD_ID=your_test_server_id_here
봇 파일 작성:
// index.js
const { Client, GatewayIntentBits, Events } = require('discord.js');
require('dotenv').config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
client.once(Events.ClientReady, (readyClient) => {
console.log(`Bot is online as ${readyClient.user.tag}`);
});
client.on(Events.MessageCreate, (message) => {
// 봇이 보낸 메시지는 무시
if (message.author.bot) return;
if (message.content === '!ping') {
message.reply(`Pong! Latency: ${client.ws.ping}ms`);
}
});
client.login(process.env.DISCORD_TOKEN);
봇 실행:
node index.js
3단계 (대안): Python으로 설정하기
mkdir my-discord-bot && cd my-discord-bot
python -m venv venv
source venv/bin/activate
pip install discord.py python-dotenv
# bot.py
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f"Bot is online as {bot.user}")
@bot.command()
async def ping(ctx):
await ctx.reply(f"Pong! Latency: {round(bot.latency * 1000)}ms")
bot.run(os.getenv("DISCORD_TOKEN"))
python bot.py
4단계: 슬래시 커맨드 등록
슬래시 커맨드는 Discord 봇과 상호작용하는 현대적인 방식입니다. 사용자가 /를 입력할 때 커맨드 메뉴에 나타납니다.
JavaScript (discord.js):
// deploy-commands.js
const { REST, Routes, SlashCommandBuilder } = require('discord.js');
require('dotenv').config();
const commands = [
new SlashCommandBuilder()
.setName('ping')
.setDescription('봇의 지연 시간을 확인합니다'),
new SlashCommandBuilder()
.setName('userinfo')
.setDescription('사용자 정보를 가져옵니다')
.addUserOption(option =>
option.setName('user')
.setDescription('조회할 사용자')
.setRequired(false)
),
new SlashCommandBuilder()
.setName('poll')
.setDescription('간단한 투표를 만듭니다')
.addStringOption(option =>
option.setName('question')
.setDescription('투표 질문')
.setRequired(true)
),
].map(command => command.toJSON());
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
console.log('슬래시 커맨드 등록 중...');
await rest.put(
Routes.applicationGuildCommands(
process.env.CLIENT_ID,
process.env.GUILD_ID
),
{ body: commands },
);
console.log('슬래시 커맨드 등록 완료.');
} catch (error) {
console.error(error);
}
})();
봇에서 슬래시 커맨드 처리하기:
// index.js에 추가
const { EmbedBuilder } = require('discord.js');
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply(`Pong! Latency: ${client.ws.ping}ms`);
}
if (interaction.commandName === 'userinfo') {
const user = interaction.options.getUser('user') || interaction.user;
const member = await interaction.guild.members.fetch(user.id);
const embed = new EmbedBuilder()
.setTitle(user.username)
.setThumbnail(user.displayAvatarURL({ size: 256 }))
.addFields(
{ name: 'ID', value: user.id, inline: true },
{ name: '서버 가입일', value: member.joinedAt.toDateString(), inline: true },
{ name: '계정 생성일', value: user.createdAt.toDateString(), inline: true },
{ name: '역할', value: member.roles.cache.map(r => r.name).join(', ') }
)
.setColor(0x5865F2);
await interaction.reply({ embeds: [embed] });
}
if (interaction.commandName === 'poll') {
const question = interaction.options.getString('question');
const pollMessage = await interaction.reply({
content: `**투표:** ${question}`,
fetchReply: true,
});
await pollMessage.react('👍');
await pollMessage.react('👎');
}
});
5단계: 인터랙티브 컴포넌트 추가
Discord는 풍부한 상호작용을 위해 버튼, 선택 메뉴, 모달 등을 지원합니다.
const {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
StringSelectMenuBuilder,
} = require('discord.js');
// 버튼 예시
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.commandName === 'ticket') {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('create_ticket')
.setLabel('지원 티켓 생성')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('close_ticket')
.setLabel('티켓 닫기')
.setStyle(ButtonStyle.Danger),
);
await interaction.reply({
content: '도움이 필요하신가요? 지원 티켓을 생성하세요:',
components: [row],
});
}
// 버튼 클릭 처리
if (interaction.isButton()) {
if (interaction.customId === 'create_ticket') {
await interaction.reply({
content: '티켓이 생성되었습니다! 곧 담당자가 안내해 드리겠습니다.',
ephemeral: true,
});
}
}
});
Discord API Rate Limits (속도 제한)
Discord는 엄격한 속도 제한을 적용합니다. 이를 이해해야 봇이 차단되는 것을 방지할 수 있습니다.
| 엔드포인트 유형 | 속도 제한 |
|---|---|
| Global (전역) | 초당 50회 요청 |
| Per route (경로별) | 가변적 (X-RateLimit-* 헤더 확인) |
| 메시지 전송 (채널당) | 5초당 5개 메시지 |
| 대용량 삭제 (Bulk) | 1초당 1회 요청 |
| 서버 멤버 조회 (Fetch) | 10초당 10회 요청 |
| 반응 추가 (Reaction) | 0.25초당 1회 |
응답의 속도 제한 헤더 예시:
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 4
X-RateLimit-Reset: 1738886400.000
X-RateLimit-Bucket: abc123
discord.js와 discord.py는 내장된 큐 시스템을 통해 속도 제한을 자동으로 처리합니다. REST API를 직접 사용하는 경우, 429 응답이 오면 지수 백오프(exponential backoff)를 구현해야 합니다.
6단계: 봇 배포하기
옵션 1: VPS (권장)
VPS 제공업체(DigitalOcean, Hetzner, Linode 등)를 통해 배포하고 프로세스 매니저를 사합니다.
# PM2 설치
npm install -g pm2
# 봇 시작
pm2 start index.js --name "discord-bot"
# 크래시 및 재부팅 시 자동 재시작 설정
pm2 startup
pm2 save
옵션 2: Railway 또는 Render
서버리스 방식의 배포:
# railway.toml
[build]
builder = "nixpacks"
[deploy]
startCommand = "node index.js"
GitHub에 푸시하고 Railway에 연결하여 자동 배포를 구성합니다.
옵션 3: Docker
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
CMD ["node", "index.js"]
docker build -t discord-bot .
docker run -d --env-file .env --name discord-bot discord-bot
일반적인 봇 패턴
| 패턴 | 설명 | 활용 사례 |
|---|---|---|
| 커뮤니티 관리 | 자동 삭제, 경고, 뮤트, 차단 | 커뮤니티 운영 |
| 환영 인사 | 신규 멤버 인사, 역할 부여 | 온보딩 |
| 반응 역할 | 이모지 반응에 따른 역할 부여 | 자가 역할 선택 |
| 로그 기록 | 수정, 삭제, 가입/퇴장 추적 | 감사 로그(Audit trail) |
| 음악 | 음성 채널에서 오디오 재생 | 엔터테인먼트 |
| 이코노미 | 가상 화폐, 상점, 순위표 | 참여 유도 |
| AI 채팅 | 자연스러운 대화를 위한 LLM 연동 | 고객지원, 재미 |
결론
Discord API는 성숙하고 문서화가 잘 되어 있으며, 우수한 커뮤니티 라이브러리들의 지원을 받고 있습니다. 단순한 관리용 봇부터 복잡한 인터랙티브 경험에 이르기까지, 슬래시 커맨드, 메시지 컴포넌트, 이벤트 기반 아키텍처의 조합은 필요한 모든 기능을 제공합니다.
커스텀 아바타 생성, 커뮤니티용 비디오 콘텐츠 제작 또는 AI 음성 기능 추가와 같이 AI 생성 미디어 기능이 필요한 봇의 경우, Hypereal AI에서 제공하는 이미지 생성, 비디오 제작, 말하는 아바타, 목소리 클로닝 등의 합리적인 종량제 API를 Discord 봇에 직접 연동할 수 있습니다.
