【发布时间】:2021-03-02 16:05:14
【问题描述】:
我正在尝试使用 Javascript 对这个 discord 机器人进行编码,我目前正在逐步遵循 discordjs 指南,并且我正在执行与指南完全相同的步骤。现在我正在学习动态命令,似乎我在这个大洞里被困了 4 天。问题是命令处理程序确实检测到命令文件夹中的命令文件,但它只检测到该顺序中的最后一个命令。这是我的主文件夹中的 bot.js 文件中的代码:
const fs = require('fs');
const {prefix, token} = require('./config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
client.commands = new Discord.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.name, command);
}
client.once('ready', () =>{
console.log('Imperial Bot is online!');
});
client.on('message', message => {
console.log(message.content);
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
})
client.login(token);
这是命令文件夹中文件 fun.js 中的代码:
module.exports = {
name: 'avatar',
description: '...',
execute(message, args){
if(!message.mentions.users.size){
message.channel.send(`Poza ta de profil: <${message.author.displayAvatarURL({ format: "png", dynamic: true })}>`)
}
// the array of avatars of the tagged users get put in a constant and shown in the chat.
const avatarList = message.mentions.users.map(user => { //for every user tagged in the message, an avatar of theirs will get shown
return `Avatarul lui ${user.username}: <${user.displayAvatarURL({ format: "png", dynamic: true })}>`;
});
message.channel.send(avatarList);
},
}
module.exports = {
name: 'gaymeter',
description: '...',
execute(message, args){
let gen = Math.floor(Math.random()*100 + 1);
let tagged = message.mentions.users.first();
if(!args[0]){
message.channel.send(`Esti ${gen}% gay!`);
} else {
message.channel.send(`${tagged.username} este ${gen}% gay! :gay_pride_flag: `);
}
}
}
module.exports = {
name: 'delete',
description: '...',
execute(message, args){
let checkINT = parseInt(args[0]);
let amount = args[0];
if(isNaN(checkINT) || !args[0]){
message.channel.send("Trebuie precizat un numar.");
} else if(amount < 2 || amount > 99){
message.channel.send("Limita de mesaje care pot fii sterse este intre 2 si 99.");
} else {
message.channel.bulkDelete(amount, true);
message.reply(`sterse ${amount} mesaje!`).catch(err => {
console.error(err);
message.channel.send('Eroare! Nu au putut fii sterse mesajele.');
});
}
},
}
如果我运行机器人,它检测到的唯一命令是删除命令,它是该文件中的最后一个命令。我的问题是如何安排或修复代码,以便所有 module.exports 在那个 fun.js 文件中工作,而不仅仅是那个 delete 命令?我必须在一个模块导出中只放一个命令并为每个命令制作单独的文件吗?
【问题讨论】:
标签: javascript discord.js dom-events