如何覆盖Discord.js-commando命令参数缺失时的默认提示回复
Discord.js Commando 自定义必填参数缺失提示方案
方案1:单命令自定义参数缺失提示(适合仅修改say命令的场景)
直接在你的命令类中重写onMissingArgs方法即可,该方法会在参数缺失时优先触发,完全覆盖框架默认的提示逻辑。
注意:Commando对必填参数默认会拦截请求,未传必填参数时不会进入run方法,你原有run方法中判断text为空的逻辑已经冗余,可以直接删除。
修改后的完整代码如下:
const { Command } = require('discord.js-commando'); module.exports = class ServerCommand extends Command { constructor(client) { super(client, { name: 'say', aliases: ['s'], group: 'mod', memberName: 'say', description: 'Make the bot speak for you.', userPermissions: ['MANAGE_CHANNELS'], examples: [client.commandPrefix + 'say <text>',client.commandPrefix + 'say hello world'], // 可选:如果你不需要框架多次询问用户补全参数,设置提示次数为0 argsPromptLimit: 0, args: [{ key: 'text', prompt: 'What should the bot say?', type: 'string', }] }) } // 重写参数缺失触发的方法 async onMissingArgs(message, args, missingArg) { // 可根据missingArg.key判断缺失的参数,做多场景适配 return message.say("You didn't specify what the bot should say."); } run(message, { text }) { message.say(text); message.delete(); } }
方案2:全局覆盖所有命令的参数缺失提示
如果需要所有命令都走统一的自定义参数缺失逻辑,可以在客户端初始化后重写基类的onMissingArgs方法,不需要逐个修改命令:
const { CommandoClient, Command } = require('discord.js-commando'); const client = new CommandoClient({ commandPrefix: '!', // 全局关闭参数多次询问提示 argsPromptLimit: 0 }); // 全局重写参数缺失逻辑 Command.prototype.onMissingArgs = async function(message, args, missingArg) { return message.say(`命令 \`${this.name}\` 缺少必填参数:\`${missingArg.key}\`,请检查输入格式。`); };
内容的提问来源于stack exchange,提问作者Salvador Bacci
相关产品推荐
相关产品推荐

