如何实现Discord机器人识别特定用户并差异化执行指令?
问题分析与修复方案
原代码的核心问题
- 在
ping指令的execute函数内重复绑定messageCreate事件,每次调用指令都会新增一个监听器,导致逻辑混乱且无法正确触发预期响应 - 条件判断使用了赋值运算符
=而非比较运算符===,属于语法错误 message.author.user.id是错误调用,message.author本身就是User对象,直接访问.id即可
修正后的代码
const { Client, Intents } = require('discord.js'); const { Player, QueryType } = require("discord-player"); const client = new Client({ intents: [Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILDS] }); // 替换为你的实际用户ID const OWNER_ID = '你的用户ID'; module.exports = { name: 'ping', description: "Test command", execute(message, args){ // 直接在指令执行阶段判断发送者身份 if (message.author.id === OWNER_ID) { message.channel.send("identity test 1"); } // 所有用户执行指令都会收到该回复 message.reply('pong!'); } }
扩展优化说明
如果需要给非所有者用户设置不同响应,可以添加else分支:
if (message.author.id === OWNER_ID) { message.channel.send("identity test 1"); } else { message.channel.send("你无权限触发特殊响应"); }
注意确保机器人已正确注册该指令,且拥有对应频道的消息发送权限。
内容的提问来源于stack exchange,提问作者Pedro Silva
相关产品推荐
相关产品推荐

