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

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을 추가합니다.
명령어 입력을 처리하는 비동기 함수를 설정합니다.
'옛날 글들 > DiscordJS' 카테고리의 다른 글
| The Patch - 게임 패치노트 전용 디스코드 봇 (게임 18종 지원 : FC온라인, 롤, 로스트아크, 배그, 메이플, 발로란트, 오버워치2 지원) (0) | 2022.03.22 | 
|---|---|
| 4. DiscordJS client.on 이벤트 정리 (0) | 2022.02.23 | 
| 3. DiscordJS 슬래시 명령어 설정하기 (0) | 2022.02.23 | 
| 1. DiscordJS 시작하기 - 설치 및 봇 생성 (0) | 2022.01.25 |