초기설정을 해보자.
https://discord.com/developers/applications
Discord Developer Portal — API Docs for Bots and Developers
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
discord.com
여기서 우리가 해야할건
1. 토큰 받고 저장하기
프로젝트 내에 특정 json이나 원하는 파일형식으로 저장시킨다.
https://discordjs.guide/creating-your-bot/#using-config-json
discord.js Guide
Imagine a guide... that explores the many possibilities for your discord.js bot.
discordjs.guide
2. gateway intents를 설정하기
다 ON해줬다. 일종의 권한 설정이다.
https://discordjs.guide/popular-topics/intents.html#privileged-intents
discord.js Guide
Imagine a guide... that explores the many possibilities for your discord.js bot.
discordjs.guide
3. 코드 작성
import Discord from 'discord.js';
const { Client, GatewayIntentBits } = Discord;
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
]
});
discord bot 용 클라이언트 인스턴스를 초기화한다.
초기화할 때 2번에서 설정한걸 코드로 작성해준다. 이 글을 작성할 시점에서 discrod js가 V14로 업데이트 됐는데,
GatewayIntentBits를 import해주고 사용한다.
4. 봇 출격 준비
client.once('ready', () => {
# 코드 작성
});
client.login(저장해둔 토큰);
client.once는 봇이 서버에 로그인됐을 때 딱 한번만 실행된다.
일종의 시작이다.
'ready'이벤트는 봇을 이용가능하게(봇이 준비됐음을 알리는) 만드는 이벤트이다.
여기서 우린
1. 봇이 서버에 성공적으로 로그인됐는지 알려줌
2. 초기 작업을 함
3. 서버에 명령어를 등록함
4. 봇의 상태를 변경함 등등을 할 수 있다.
client.once('ready', () => {
// 등록된 모든 guild(서버)를 돌면서
client.guilds.cache.forEach((guild) => {
// 명령어들을 guild(서버)에 등록함
commands.forEach((command) => {
guild.commands.create(command)
.then((command) => console.log(`Command registered in guild ${guild.name}: ${command.name}`))
.catch((error) => console.error(`Failed to register command in guild ${guild.name}:`, error));
})
});
// 서버에 성공적으로 봇이 접속됐는지를 알려줌
console.log(`Logged in as ${client.user.tag}`);
});
나의 경우엔 이렇게 작성했다. (서버에 등록하는게 굳이 필요한진 모르겠다. 난 특정 기능을 수정하면서 적용했는데 없었을 때도 동작은 했다.)
5. 테스트용 서버 만들고 봇을 불러오기
디버그를하거나 봇을 테스트하기 위해 직접 서버에 봇을 불러와야한다.
scopes에서 우리는 bot을 만들 것이므로 bot을 체크해준다.
그러면 bot의 권한을 설정해주는 창이 나온다. (필요없는걸 체크해도 서버에 초대할때 또 설정가능하다.)
권한을 설정해주고 generated url에 뜬 링크를 복사하고 주소창에 붙여넣기한다.
서버를 선택하고 봇을 초대한다.
'개발' 카테고리의 다른 글
React로 스크롤 기반 인터랙티브 웹 만들기 2 인터랙션 (3) | 2023.10.17 |
---|---|
React로 스크롤 기반 인터랙티브 웹 만들기 1 목적, 레이아웃 (0) | 2023.10.15 |
Redux와 Redux ToolKit사용하기 (1) | 2023.08.17 |
discord js 로 간단한 봇 개발하기 3. client.on (1) | 2023.06.10 |
discord js로 간단한 봇 개발하기.0 개요 (0) | 2023.06.09 |