我正在尝试创建一个机器人,它会将晚安回“晚安”作为辅助命令,但我不知道如何执行没有前缀的单个命令。我找到了一篇关于此问题的帖子,其中有一个很好的答案并应用了它,但现在我遇到了不同的问题。
这是我的 bot.js
主文件:
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = 'm!';
const fs = require('fs');
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('Meonkl is Online!');
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: "online", //You can show online, idle....
});
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command == 'ping'){
client.commands.get('pong').execute(message, args);
}else if(message.content.toLowerCase() == 'goodnight'){
client.commands.get('goodnight').execute(message, args);
}
console.log(message.member, message, args);
});
client.login('');
我怀疑问题出在这一行,if(!message.content.startsWith(prefix) || message.author.bot) return;
,但我无法将其取出并破坏我的常规命令。
我不确定该怎么做,或者是否有干净的解决方案。
答案 0 :(得分:0)
如果传入的消息不是以 if(!message.content.startsWith(prefix) || message.author.bot) return
开头,则消息处理函数 (prefix
) 的第一行不会让您执行任何其他操作。您可以删除 !message.content.startsWith(prefix)
部分:
client.on('message', message => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('pong').execute(message, args);
} else if(message.content.toLowerCase() === 'goodnight') {
client.commands.get('goodnight').execute(message, args);
}
});
或者你可以让一些不带前缀的命令通过;只需使用一个数组来存储这些并检查消息是否包含在此数组中。检查以下代码段:
client.on('message', (message) => {
if (message.author.bot) return;
const unprefixedCommands = ['goodnight', 'morning'];
const isUnprefixedCommand = unprefixedCommands.includes(message.content.toLowerCase());
if (!isUnprefixedCommand && !message.content.startsWith(prefix)) return;
let args;
let command;
if (isUnprefixedCommand) {
// don't remove the prefix from the message
// although it will be an array with the command only
// not sure how you want to use it :)
args = message.content.split(/ +/);
// the command is the message content itself
// this way both "!goodnight" and "goodnight" will work
command = message.content.toLowerCase();
} else {
// it's the same as before
args = message.content.slice(prefix.length).split(/ +/);
command = args.shift().toLowerCase();
}
if (command === 'ping') {
client.commands.get('pong').execute(message, args);
} else if (command === 'goodnight') {
client.commands.get('goodnight').execute(message, args);
}
});