DiscordJS Commando v12.5 ticket指令报Cannot read property 'on' of null错误
报错原因
- 你对Commando v12.5框架的
Command.run()方法参数定义存在错误,该方法原生仅接收3个参数:触发命令的消息对象、解析后的参数数组、模式匹配返回值,你代码中额外定义的第四个client参数不存在,实际传入registerEvent函数的值为null,调用null.on()就触发了对应类型错误。 - Commando的所有命令实例本身已挂载客户端对象,可直接通过
this.client获取,不需要从run方法参数中传递。
修复方案
核心修改点
- 删除run方法中多余的第四个
client参数 - 调用
registerEvent时传入this.client而非不存在的参数变量
修复后完整代码
const Commando = require('discord.js-commando') const Discord = require('discord.js') const channelId = '873769980729106442' const thumbsup = '👍' const thumbsdown = '👎' let registered = false const registerEvent = client => { if (registered) { return } registered = true client.on('messageReactionAdd', (reaction, user) => { if (user.bot) { return } const { message } = reaction if (message.channel.id === channelId) { message.delete() } }) } module.exports = class TicketCommand extends Commando.Command { constructor(client) { super(client, { name: 'ticket', group: 'misc', memberName: 'ticket', description: 'Sends a suggestion to the staff', // 补充参数配置,避免原生参数解析错误 args: [ { key: 'content', prompt: '请输入你要提交的ticket内容', type: 'string' } ] }) } run(userMessage, { content }) { const { guild, member } = userMessage const syntax = `${guild.commandPrefix}ticket <Message>` registerEvent(this.client) const channel = guild.channels.cache.get(channelId) const newTicketEmbed = new Discord.MessageEmbed() .setAuthor(userMessage.author.username) .setTitle('SUCCESS\n\nCreated a new ticket: ') .setDescription(`"${content}"`) .setFooter(`Click the ${thumbsup} icon to delete this message.`) .setColor('#1be730') channel.send(newTicketEmbed).then(ticketMessage => { ticketMessage.react(thumbsup).then(() => { ticketMessage.react(thumbsdown) }) const replyEmbed = new Discord.MessageEmbed() .setTitle('SUCCESS') .setDescription(`<@${member.id}> Your ticket has been created!\n\n**${content}**`) .setFooter('While the community votes, expect a reply from staff soon!') .setColor('#1be730') userMessage.channel.send(replyEmbed).then((newMessage) => { newMessage.react(thumbsup).then(() => { newMessage.react(thumbsdown) }) }) userMessage.delete() }) } }
补充说明:你当前把messageReactionAdd事件的注册逻辑放在命令首次执行时触发,更规范的做法是直接在机器人入口文件客户端初始化完成后注册该事件,避免和命令逻辑耦合。
内容的提问来源于stack exchange,提问作者PrezOfTheUnitedIdiots
相关产品推荐
相关产品推荐

