본문으로 바로가기

2. DiscordJS 기본 코드 리뷰 (bot.js, kick.js)

category Study/DiscordJS 2022. 1. 26. 06:58
반응형

1. bot.js

const fs = require("fs");
const { Client, Collection, Intents } = require("discord.js");
const { token } = require("./config.json");

파일 시스템에 접근할 수 있도록 Fs 라이브러리를 불러옵니다.

Client - Client 객체 생성용

Collection - 명령어 셋 객체 생성용

Intents - Pre-defined Websocket events

Source: DiscordJS

token은 config.json 파일 내의 token을 불러옵니다.

const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.commands = new Collection();
const commandFiles = fs
    .readdirSync("./commands")
    .filter((file) => file.endsWith(".js"));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.data.name, command);
}

Client - Intents.FLAGS.GUILDS를 intents로 하는 Client 객체를 생성합니다.

client.commands를 빈 Collection Function으로 선언합니다.

Commands 폴더 내에 있는 파일들을 불러와 명령어 셋에 추가합니다.

client.once("ready", () => {
    console.log("Ready!");
});

client.on("interactionCreate", async (interaction) => {
    if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        return interaction.reply({
            content: "There was an error while executing this command!",
            ephemeral: true,
        });
    }
});

client.login(token);

Client가 처음 실행되었을 때 log를 출력합니다.

명령어 실행을 받는 Listener와 비슷한? 비동기 함수를 선언합니다.

token으로 Client에 로그인합니다.

2. kick.js

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
	data: new SlashCommandBuilder()
		.setName('kick')
		.setDescription('Select a member and kick them (but not really).')
		.addUserOption(option => option.setName('target').setDescription('The member to kick')),
	async execute(interaction) {
		const user = interaction.options.getUser('target');
		return interaction.reply({ content: `You wanted to kick: ${user.username}`, ephemeral: true });
	},
};

SlashCommandBuilder - 명령어 관련 기본 틀

Kick 명령어의 이름과 Description, Option을 추가합니다.

명령어 입력을 처리하는 비동기 함수를 설정합니다.

반응형