n8n에서 Discord 메시지를 수신하는 자동화 봇
n8n에서 Discord 메시지를 수신하는 자동화 봇
n8n에서 Discord 메시지를 수신하는 자동화 봇 만들기
Discord에서 수신한 메시지를 n8n 워크플로우로 자동 전송하는 방법을 정리 사용자가 Discord 채널에 메시지를 입력할 때마다 n8n으로 해당 메시지를 받아 다양한 자동화를 수행할 수 있습니다.
📌 준비 사항
- n8n 설치 및 실행 중 (
http://localhost:5678
또는 배포 환경) - Discord 봇 생성 및 토큰 발급
- Node.js 실행 환경
- (선택) 외부 접근을 위해
ngrok
설치
1. Discord 봇 생성 및 권한 설정
봇 생성하기
Discord Developer Portal 에 접속하고 새 애플리케이션 생성
→ 원하는 봇 이름 입력
→ 봇 생성
을 선택합니다.
send-to-n8n
이름으로 application을 위와 같이 생성했습니다. 생성한 application을 클릭하면 다양한 설정이 가능합니다.
Token 및 Permission 설정
application을 선택하고 좌측의 Bot
을 선택하여 TOKEN
을 생성합니다. n8n에서 메세지를 webhook으로 받기 위해 사용됩니다.
Discord의 기본 설정으로는메세지를 볼수 없기 때문에 MESSAGE CONTENT INTENT
옵션을 활성화 합니다. 이 기능이 enable되어 있어야 bot이 메세지를 볼 수 있습니다.
Send Messages
, Read Message History
, View Channels
선택해서 Bot이 메세지를 보내기 위한 permission을 선택합니다.
생성된 봇은 Installation
메뉴의 Install Link
를 통해서 설치할 수 있습니다.
이 링크를 봇을 추가할 채널에 입력해서 봇을 설치합니다.
2. n8n에서 Webhook 워크플로우 만들기
n8n 실행 후 새 워크플로우 생성
Webhook
노드 추가- Method:
POST
- Path: 예:
/discord-message
- Method:
Webhook 노드를 선택하고 “Listen for Test Event” 클릭
우측 상단에서
Test URL
을 복사 예:
http://localhost:5678/webhook/discord-message
외부에서 접속할 경우, ngrok
등을 사용해 HTTPS 주소 생성 가능합니다.
3. Discord 메시지를 수신하는 bot.js
작성
Discord 봇을 작성하려면 discord.js
라이브러리가 필요합니다. 아래 명령으로 라이브러리를 설치합니다.
.js npm install discord
n8n Webhook에 데이터를 전송하려면 axios 라이브러리도 설치해야 합니다. axios는 JavaScript에서 HTTP 요청을 쉽게 처리할 수 있게 해주는 Promise 기반 라이브러리입니다. 서버와 클라이언트 간에 데이터를 주고받을 때 사용됩니다.
npm install axios
이 코드는 Discord 봇을 실행하고, 수신된 메시지를 콘솔에 출력한 뒤, n8n Webhook으로 메시지 데이터를 전송하는 역할을 합니다.
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');
const client = new Client({
intents: [
.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits,
];력
})
const DISCORD_TOKEN = '여기에_봇_토큰_입력';
const N8N_WEBHOOK_URL = '웹훅 주소 입력';
.on('ready', () => {
clientconsole.log(`✅ 로그인 성공: ${client.user.tag}`);
;
})
.on('messageCreate', async (message) => {
clientif (message.author.bot) return;
console.log(`📥 수신된 메시지: ${message.content}`);
console.log(`👤 작성자: ${message.author.username}`);
console.log(`#️⃣ 채널: ${message.channel.name}`);
try {
await axios.post(N8N_WEBHOOK_URL, {
content: message.content,
author: message.author.username,
channel: message.channel.name,
timestamp: message.createdAt,
;
})
console.log('✅ n8n Webhook으로 전송 완료');
catch (err) {
} console.error('❌ Webhook 전송 실패:', err.message);
};
})
.login(DISCORD_TOKEN); client
🔍 코드 분석
1. 필요한 모듈 불러오기
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');
- discord.js: Discord API와 상호작용하는 라이브러리
- axios: HTTP 요청을 보내기 위한 라이브러리 (n8n Webhook 호출용)
필요한 모듈을 불러옵니다.
2. 클라이언트 설정
const client = new Client({
intents: [
.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits,
]; })
- Discord 봇이 어떤 이벤트에 반응할지를 설정
- Guilds: 서버 관련 이벤트 수신
- GuildMessages: 메시지 생성 이벤트 수신
- MessageContent: 메시지 텍스트(message.content) 접근 권한 부여 (필수!)
토큰과 Webhook URL 설정
const DISCORD_TOKEN = '여기에_봇_토큰_입력';
const N8N_WEBHOOK_URL = '웹훅 주소 입력';
- DISCORD_TOKEN: Discord 개발자 포털에서 발급받은 봇 토큰
- N8N_WEBHOOK_URL: 메시지를 전달할 n8n Webhook 주소
메세지 수신처리
.on('messageCreate', async (message) => {
clientif (message.author.bot) return;
- 사용자가 메시지를 입력할 때마다 실행
- message.author.bot 체크로 봇 자신의 메시지는 무시
n8n Webhook으로 메세지 전송
try {
await axios.post(N8N_WEBHOOK_URL, {
content: message.content,
author: message.author.username,
channel: message.channel.name,
timestamp: message.createdAt,
;
})
console.log('✅ n8n Webhook으로 전송 완료');
catch (err) {
} console.error('❌ Webhook 전송 실패:', err.message);
}
- 메시지 내용을 JSON 형식으로 Webhook에 POST
- 성공/실패 여부를 콘솔에 출력
봇 로그인
.login(DISCORD_TOKEN); client
- 위에서 설정한 토큰을 사용해 Discord 서버에 로그인
4. bot.js
실행
node bot.js
Discord에서 아무 채널에 메시지를 보내보면, n8n 콘솔에서 해당 메시지를 수신하는 로그가 뜨고, Webhook 데이터가 도착합니다.
5. n8n에서 받은 메시지 처리
Webhook 다음 단계에 원하는 노드를 연결하여:
- Slack으로 메시지 전송
- Google Sheets에 기록
- 이메일 자동 알림 발송 등
다양한 자동화를 이어붙일 수 있습니다.
❗ 에러 해결 팁
에러 메시지 | 원인 | 해결 방법 |
---|---|---|
Unsupported protocol localhost: |
http:// 누락 |
http://localhost:5678/... 형식으로 수정 |
write EPROTO ... wrong version number |
HTTPS로 요청했으나 실제는 HTTP | https://localhost → http://localhost 로 변경 |
status code 404 |
Webhook 경로가 잘못되었거나 워크플로우가 비활성화됨 | 워크플로우에서 “Listen for Test Event” 클릭 or “Activate” |
✅ 마무리
이 방식은 Discord의 자유로운 대화를 n8n으로 바로 연결하여 알림, 데이터 저장, 자동 응답 등 실시간 자동화를 구현할 수 있는 매우 유용한 방법입니다.
카테고리 다른 글
Date | Title | Author |
---|---|---|
May 3, 2025 | n8n의 Merge 노드 |