๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Bot/Discord Bot

discord.js bot ๋งŒ๋“ค๊ธฐ (2) - Events

๋ฐ˜์‘ํ˜•

 

Event handling

 

 

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

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

client.once('ready', c => {
	console.log(`Ready! Logged in as ${c.user.tag}`);
});

client.on('interactionCreate', interaction => {
	console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
});

client.login(token);

 

 

events ํด๋”๋ฅผ ๋งŒ๋“ค์ž.

index.js ์— ์žˆ๋Š” ์ด๋ฒคํŠธ ์ฝ”๋“œ๋ฅผ events/ready.js, events/interactionCreate.js ํŒŒ์ผ๋กœ ์˜ฎ๊ธฐ์ž.

 

 

events/ready.js

module.exports = {
	name: 'ready',
	once: true,
	execute(client) {
		console.log(`Ready! Logged in as ${client.user.tag}`);
	},
};

once ์†์„ฑ์€ boolean ์ด๊ณ  ์ด๋ฒคํŠธ๊ฐ€ ํ•œ๋ฒˆ ์‹คํ–‰๋˜๋Š”์ง€๋ฅผ ๋ช…์‹œํ•œ๋‹ค.

execute ํ•จ์ˆ˜๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•  ๋•Œ๋งˆ๋‹ค ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ์— ์˜ํ•ด ํ˜ธ์ถœ๋˜๋Š” ์ด๋ฒคํŠธ ๋กœ์ง์„ ์œ„ํ•œ ๊ฒƒ์ด๋‹ค.

 

 

 

events/interactionCreate.js

module.exports = {
	name: 'interactionCreate',
	execute(interaction) {
		console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
	},
};

 

 

eventFiles = ['ready.js', 'interactionCreate.js'] 

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

const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
	const filePath = path.join(eventsPath, file);
	const event = require(filePath);
	if (event.once) {
		client.once(event.name, (...args) => event.execute(...args));
	} else {
		client.on(event.name, (...args) => event.execute(...args));
	}
}

 

discord.js ์—์„œ Client ํด๋ž˜์Šค๋Š” EventEmitter ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๋Š”๋‹ค.

๋”ฐ๋ผ์„œ client ๊ฐ์ฒด๋Š” ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ๋“ค์„ ๋“ฑ๋กํ• ์ˆ˜ ์žˆ๋Š” .on() ํ•˜๊ณ  .once() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•จ.

์ด ๋ฉ”์†Œ๋“œ๋Š” ๋‘ ์ธ์ž๋ฅผ ๊ฐ€์ง€๋Š”๋ฐ event name ํ•˜๊ณ  callback function ์ด๋‹ค.

 

 

https://discordjs.guide/creating-your-bot/event-handling.html#individual-event-files

 

discord.js Guide

Imagine a guide... that explores the many possibilities for your discord.js bot.

discordjs.guide

 

 

 

 

 

๋ฐ˜์‘ํ˜•

'Bot > Discord Bot' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Discord.py] Bookmarks  (0) 2022.08.01
discord.js bot ๋งŒ๋“ค๊ธฐ (3) - Interactions  (0) 2022.07.13
discord.js bot ๋งŒ๋“ค๊ธฐ (1)  (0) 2022.07.13