친구들과 게임을 하거나 소통을 할 때 자주 사용하는 DISCORD 봇을 만들려고 한다.
물론 오늘은 기본 환경세팅과 간단한 코드만 작성하였지만, 향후 시리즈에 다양한 기능을 넣어보며 포스팅을 이어갈 생각이다.
1-1. node.js(본인은 예전에 세팅해둔 v18.16.0 사용)
1-2. discord 어플리케이션
1-3. 디스코드 개발자 홈페이지(https://discord.com/developers/applications)
2-1. 홈페이지 접속 후 로그인 -> New Application 클릭
2-2. 봇 명칭 작성 -> 체크박스 선택 -> Create 클릭
2-3. 나온 화면(General Information)에서 Bot이름 작성, Bot 이미지 등록 -> Save Change
[참고로 내가 작성한건 Bot 생성 시 기본적인 것들만 설명]
2-4.왼쪽의 Bot 메뉴로 진입 -> Reset Token으로 발급(최초 1회 발급이니 잘 저장) -> 하단의 권한 체크
2-5. 왼쪽의 OAuth2 메뉴로 진입 -> 하단의 Bot 체크박스 선택 -> 최하단의 URL 을 복사해서 인터넷 주소창에 복붙하면 내 Discrod 서버로 초대 가능
3-1. 기본 프로젝트 파일 구조
3-2. config.json (2-4에서 저장한 Token을 JSON 에 저장)
3-3. index.js 작성
const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, GatewayIntentBits, Partials } = require('discord.js'); const { token } = require('./config.json'); const prefix = '!'; const client = new Client({ intents: [ GatewayIntentBits.DirectMessages, GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], partials: [Partials.Channel], }); client.commands = new Collection(); // 명령어 로드 const foldersPath = path.join(__dirname, 'commands'); const commandFolders = fs.readdirSync(foldersPath); for (const folder of commandFolders) { const commandsPath = path.join(foldersPath, folder); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); client.commands.set(command.name, command); } } console.log(client.commands.map(c => c.name).join(', ') + ' 명령어가 로드됨.'); // 준비 client.on('ready', () => console.log(`${client.user.tag} 에 로그인됨`)); // 메세지 client.on('messageCreate', msg => { console.log("client mgs => " + msg.content) if (msg.author.bot) return; if (!msg.content.startsWith(prefix)) return; if (msg.content.slice(0, prefix.length) !== prefix) return; const args = msg.content.slice(prefix.length).trim().split(/ +/g); const command = args.shift().toLowerCase(); let cmd = client.commands.get(command); if (cmd) cmd.run(client, msg, args); }) client.login(token);
3-4. 사용자 command에 따른 응답 js 작성
다음과 같이 사용자 Command에 따라 봇의 응답을 확인할 수 있다.