我开始使用discord.js 编写一个discord 机器人。我还遵循他们提供的指南,直到完成“事件处理”:https://discordjs.guide/creating-your-bot/event-handling.html#reading-event-files
我编写了第一个事件,当有人加入服务器时,我希望机器人在频道中写入欢迎消息。 这是我的代码:
欢迎.js
const { Events } = require('discord.js');
module.exports = {
name: Events.GuildMemberAdd,
once: true,
execute(client, member) {
const channelID = '1194723491551912079';
const channel = client.channels.cache.get(channelID);
const message = `Welcome <@${member}>!`;
channel.send(message);
},
};
指南中的斜杠命令(用户、ping 和服务器)正在运行,ClientReady 事件也正在运行。在搜索了一些解决方案并且对js不熟悉之后,我不知道该怎么办。 感谢您提前的帮助。
编辑:我的index.js:
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
// command handling
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
// event handling
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));
}
}
client.login(token);
您可以使用“guildMemberAdd”事件。
// I'll assume you've already imported the Client class and defined it
client.on("guildMemberAdd", async (member) => {
let channelId; // Add your desired channel Id here
let channel = member.guild.channels.cache.get(channelId);
let message = `Welcome <@${member.id}>`;
await channel.send(message);
});