如何在现有discord.js命令结构中让机器人@提及命令发送者回复
实现方案
完全可以在你当前的代码结构上实现该功能,按以下步骤调整即可:
步骤1:调整主入口的命令匹配逻辑(修改main/index.js)
你现有代码只匹配了cmd命令,可以选择两种调整方式:
- 方案A:改成通用匹配逻辑,后续加新命令不需要重复写判断,替换你原来的
if(command === 'cmd')代码段即可:
if (client.commands.has(command)) { client.commands.get(command).execute(message, args); }
- 方案B:只临时加hello命令的匹配,不需要修改原有逻辑:
if(command === 'cmd'){ client.commands.get('cmd').execute(message, args); } // 新增hello命令匹配规则 if(command === 'hello'){ client.commands.get('hello').execute(message, args); }
步骤2:新建hello命令文件
和cmd.js同目录下新建hello.js,写入以下内容:
module.exports = { name: 'hello', description: '向发送命令的用户打招呼', execute(message, args){ // message.author就是发送命令的用户对象,直接放入发送内容会自动转为@提及效果 message.channel.send(`Hello, ${message.author}`); } }
效果验证
重启机器人后,用户发送!hello,机器人就会自动回复Hello, @对应用户名,和你要求的效果完全一致。
如果不想新增命令,想直接用现有cmd命令实现该效果,直接修改cmd.js的execute方法即可:
execute(message, args){ message.channel.send(`Hello, ${message.author}`); }
调整后用户发送!cmd就会触发对应的回复效果。
内容的提问来源于stack exchange,提问作者asher
相关产品推荐
相关产品推荐

