Discord.js:如果输入不是已知命令,我如何捕获这种情况?



当用户输入一个不存在的命令时,我试图抓住这种情况,但是我不知道确切的位置和如何做到这一点。我以这样一种方式构建了我的discord bot,它有一个事件处理程序和一个命令处理程序。

我的事件:

function reqEvent(event) {
return require(`../events/${event}`);
}
module.exports = bot => {
bot.on('ready', function() { reqEvent('ready') (bot); });
};

ready事件:

const fs = require('fs');
const path = require('path');
const { commandHandler } = require('../config.json');
module.exports = client => {
client.user.setActivity('Diener');
const commandBase = require(`../handlers/${commandHandler}`);
const readCommands = (dir) => {
// TODO: Find a better solution to determine the project folder
const __dirname = 'C:\Users\marce\Documents\Discord-Test-Bot';
// Read out all command files
const files = fs.readdirSync(path.join(__dirname, dir));
// Loop through all the files in ./commands
for (const file of files) {
// Get the status of 'file' (is it a file or directory?)
const stat = fs.lstatSync(path.join(__dirname, dir, file));
// If the 'file' is a directory, call the 'readCommands' function
// again with the path of the subdirectory
if (stat.isDirectory()) {
readCommands(path.join(dir, file));
}
// If the 'file' is not the commandHandler itself, get all the
// commandOptions of that file
else if (file !== commandHandler) {
const commandOption = require(path.join(__dirname, dir, file));
// Call the commandHandler and pass the commandOptions and
// the client
commandBase(client, commandOption);
}
}
};
readCommands('commands');
console.log(`${client.user.username} is online`);

最后是commandHandler:

const { prefix } = require('../config.json');
const validatePermissions = (permissions) => {
const validPermissions = [
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'ADMINISTRATOR',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS',
];
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`);
}
}
};
module.exports = (client, commandOptions) => {
let {
commands,
aliases,
expectedArgs = '',
permissionError = 'You do not have permission to run this command.',
minArgs = 0,
maxArgs = null,
permissions = [],
requiredRoles = [],
execute,
} = commandOptions;
// TODO: Handle aliases => seperate them into a extra option
// Ensure the command and aliases are in an array
if (typeof commands === 'string') {
commands = [commands];
}
console.log(`Registering command "${commands[0]}"`);
// Ensure the permissions are in an array and are all valid
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions];
}
validatePermissions(permissions);
}
// Listen for messages
client.on('message', (message) => {
const { member, content, guild } = message;
if (message.author.bot) return;
for (const alias of commands) {
const command = `${prefix}${alias.toLowerCase()}`;
if (!content.toLowerCase().startsWith(`${prefix}`)) return;
if (content.toLowerCase() != command || !content.toLowerCase().startsWith(`${command} `))
return message.reply('Unknown command!');
console.log('Geht weiter');
// A command has been ran
// Ensure the user has the required permissions
for (const permission of permissions) {
if (!member.hasPermission(permission)) {
message.reply(permissionError);
return;
}
}
// Ensure the user has the required roles
for (const requiredRole of requiredRoles) {
const role = guild.roles.cache.find(
(r) => r.name === requiredRole,
);
if (!role || !member.roles.cache.has(role.id)) {
return message.reply(
`You must have the "${requiredRole}" role to use this command.`,
);
}
}
// Split on any number of spaces
const args = content.split(/[ ]+/);
// Remove the command which is the first index
args.shift();
// Ensure we have the correct number of arguments
if (
args.length < minArgs || (maxArgs !== null && args.length > maxArgs)
) {
return message.reply(
`Incorrect syntax! Use ${prefix}${alias} ${expectedArgs}`,
);
}
// Handle the custom command code
execute(message, args, args.join(' '), client);
return;
}
});
};

我已经尝试通过这行(在commandHandler中)拦截它:

if (content.toLowerCase() != command || !content.toLowerCase().startsWith(`${command} `)) 
return message.reply('Unknown command');

然而,问题是错误消息被发送了几次,甚至当命令实际存在时,因为commandHandler被'ready'事件调用的次数与命令的次数一样多。换句话说,如果我的bot中总共有10个命令,则调用commandHandler 10次,每次它都会检查消息是否为有效命令。那么我该如何拦截这个案子呢?

这个命令/事件处理程序的问题是,如果您有太多的命令,您将得到一个警告,因为它为每个命令创建了一个侦听器。

试试Codelyon的命令/eventhandler V2(在YouTube上搜索)

您只需要列出所有命令并与foreach循环进行比较。我不知道你用的是什么文件结构,但大多数情况下是这样的:

// Where "command" is the command performed by the
// user and "commands" is an array with all avaliable
// commands (if you have each command in a different
// file you can generate the array with node "fs" package)
var valid = false; //Define a "valid" bool variable with default false value
foreach(cmd in commands){ //If any element of commands is equal to "command" set "valid" to true
if(command == cmd) valid = true;
}
if(!valid){ // If not valid raply to the user
message.reply("That's not a valid command!");
}
else{
// Existing command, do what you want
}

相关内容

最新更新