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
'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 |