-
kick-off-bot(2) / ping-pong프로젝트/Kick-off-bot 2021. 12. 30. 10:31
모든 프로그래밍 언어에 Hello World 명령어가 있듯이 디스코드 봇에는 ping-pong이라는 예제가 있다. 아마 간단한 통신이나 상호작용에 대한 기본적인 예제에서 ping-pong을 사용하지 않을까 한다.
그렇지만 가장 먼저 해야하는 것은 나의 봇에 명령어를 심는 과정이 필요하다. 그래야 상호작용이 가능하기 때문이다. 아래는 원하는 명령어를 봇에 등록하는 과정이다.
const { SlashCommandBuilder } = require('@discordjs/builders'); const { REST } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v9'); const { clientId, guildId, token } = require('./config.json'); const commands = [ new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'), ] .map(command => command.toJSON()); const rest = new REST({ version: '9' }).setToken(token); rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands }) .then(() => console.log('Successfully registered application commands.')) .catch(console.error);
슬래시(/)를 사용하여 커맨드라는 배열에 명령어를 등록한다. 저 상태는 /ping이라는 명령어로 등록되게 된다. 그리고 rest 통신을 위해 json형식으로 바꿔주고 client id와 guild id를 같이 실어서 put한다. 만약 에러가 난다면 id나 오타이지 않을까 싶다.
나같은 경우는 세개의 명령어를 등록했고 /team 같은 경우는 각 팀에 분배될 인원을 사용자가 정해야했기에 a와 b라는 두 개의 인자 값을 받도록 설정했다.
그다음부터는 실제로 상호작용하는 코드를 작성하면 된다.
client.on('interactionCreate', async interaction => { // isCommand인지 유효성 체크 if (!interaction.isCommand()) return; // interaction에서 commandName를 가져옴. const { commandName } = interaction; // commandName이 'ping'일 때 if (commandName === 'ping') { // 해당 채널에 'Pong!'이란 메세지를 보낸다. await interaction.reply('Pong!'); } }); client.login(token);
명령어를 사용한다는 것은 봇과 interaction 한다는 것이다. interactionCreate이란 상호작용에 대해 작업을 처리할 수 있는 여러개의 옵션 중 하나이다. 일단 기본적으로 통신을 기반으로 하기 때문에 async / await를 사용해야한다. 그리고 항상 까먹지말고 동작 제일 마지막 부분에는 login를 써주어야한다. 이렇게 작성하고 js를 실행해보면 명령어가 잘 돌아갈 것이다.
만약 /를 썼을 때 아무것도 뜨지 않는다면 명령어가 등록이 안된 것이다. 등록 부분에서 성공 로그가 떴는지 확인해봐야할 것이다.
728x90반응형LIST'프로젝트 > Kick-off-bot' 카테고리의 다른 글
kick-off-bot(3) - develop (0) 2022.01.06 kick-off-bot(1) (0) 2021.12.21 무엇을 먼저 알아야할까? (0) 2021.12.19 디스코드 봇을 만들어달라고? (0) 2021.12.13