【发布时间】:2020-12-28 12:13:43
【问题描述】:
开始认为这确实是一个.split() 错误,它适用于我的所有命令,无论有无参数。以为我找到了解决方案,但事实并非如此。这是一个简单的 ping 命令:
这是我的 index.js:
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const featureFiles = fs.readdirSync('./commands/features').filter(file => file.endsWith('.js'));
for (const file of featureFiles) {
const command = require(`./commands/features/${file}`);
client.commands.set(command.name, command);
}
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
//.trim() is removed, see notes below on why
const args = message.content.slice(prefix.length).split(/ +/g);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('That command cannot be used inside a DM');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, client, args);
} catch (error) {
console.error(error);
message.channel.send('Error trying to execute command');
}});
client.login(token);
我删除了 .trim(),因为它正在读取前缀和命令名称之间的空格,这是我不想要的,所以可以在前缀和命令之间使用 100 个空格,它会执行它。这是 !ping 命令:
const {prefix} = require('../../config.json')
module.exports = {
name: 'ping',
description: 'Shows latency',
usage: ' ',
execute(message) {
if (message.content.startsWith(prefix + "ping")) {
var ping = Date.now() - message.createdTimestamp + " ms";
message.channel.send(`${Date.now() - message.createdTimestamp}` + " ms");
}
},
};
解决这个问题的任何方法都很好,因为我只是希望它在我指定的任何参数或命令名称之后 return; 之后仍然使用其他输入执行。我难住了。我想这是由我的 index.js 中的 .split() 引起的。
【问题讨论】:
-
我不太明白你在问什么,你的意思是如果命令没有
args,如果他们用args运行命令,你想@987654329 @? -
相当接近,有些命令有args,比如
if (args[0] === 'test') {do something},如果有人输入!test test arg1 arg2,即使后面有“arg1 arg2”,它仍然会执行“do something”。实际上,我希望它不执行,或者return;如果 if 语句中未指定“arg1”等,而且在整个常规命令(如上面显示的 !ping 示例)中也是如此。希望这会有所帮助,谢谢:) -
啊,我明白了,我会继续回答这个问题
标签: javascript discord.js