discord.js commando运行感谢命令时报Invalid left-hand side in assignment错误
问题解决方案
核心错误根源
你遇到的ReferenceError: Invalid left-hand side in assignment错误完全由语法错误导致:
- 计算时间差的代码行错误使用了赋值运算符:
// 错误写法 const diff = now.getTime() = then.getTime()
你本意是计算两个时间戳的差值,应该用减法运算符-,这里连续使用=会被解析为要把then.getTime()的结果赋值给now.getTime()的返回值,而函数返回值是不可被赋值的左值,因此直接抛出该错误。
其他需要修正的隐性错误
你粘贴的代码里还有几个转义和拼写问题,需要同步修正才能正常运行:
- 代码中的逻辑与运算符被转义为
&&,需要改回原生&& - 小于等于运算符被转义为
<=,需要改回原生<= - 成功消息的描述文本中
<@${targetId}缺少闭合的>符号,会导致用户提及渲染异常
修正后的完整命令代码
const Commando = require('discord.js-commando') const Discord = require('discord.js') const thanksSchema = require('@schemas/thanks-schema') module.exports = class ThanksCommand extends Commando.Command { constructor(client) { super(client, { name: 'thanks', group: 'thanks', memberName: 'thanks', description: 'Thanks a staff member for their help', }) } async run(message) { const target = message.mentions.users.first() if (!target) { const noPingThanksEmbed = new Discord.MessageEmbed() .setTitle('ERROR: Invalid user provided') .setDescription('Please tag a valid user') .setColor('#ff0000') message.channel.send(noPingThanksEmbed) return } const { guild } = message const guildId = guild.id const targetId = target.id const authorId = message.author.id const now = new Date() if (targetId === authorId) { const thankSelfEmbed = new Discord.MessageEmbed() .setTitle('ERROR: Invalid user provided') .setDescription('You cannot thank yourself') .setFooter('LOL YOU THOUGHT') .setColor('#ff0000') message.channel.send(thankSelfEmbed) return } const authorData = await thanksSchema.findOne({ userId: authorId, guildId, }) if (authorData && authorData.lastGave) { const then = new Date(authorData.lastGave) const diff = now.getTime() - then.getTime() const diffHours = Math.round(diff / (1000 * 60 * 60)) const hours = 24 if (diffHours <= hours) { const cooldownThankEmbed = new Discord.MessageEmbed() .setTitle('ERROR: User on cooldown') .setDescription(`You have already thanked someone within the last ${hours} hours`) .setColor('#ff0000') message.channel.send(cooldownThankEmbed) return } } await thanksSchema.findOneAndUpdate({ userId: authorId, guildId, }, { userId: authorId, guildId, lastGave: now, }, { upsert: true, }) const result = await thanksSchema.findOneAndUpdate({ userId: targetId, guildId, }, { userId: targetId, guildId, $inc: { received: 1, } }, { upsert: true, new: true, }) const amount = result.received const thanksEmbed = new Discord.MessageEmbed() .setTitle('SUCCESS') .setDescription(`<@${authorId}> has thanked <@${targetId}>! They now have ${amount} thanks`) .setColor('#1be730') message.channel.send(thanksEmbed) } }
补充说明
Discord.js Commando框架会默认捕获命令执行时的运行时错误,不会将错误抛出到全局服务端控制台,因此你看不到控制台报错,只有命令执行流程被中断,修改后重启机器人即可正常使用该命令。
内容的提问来源于stack exchange,提问作者PrezOfTheUnitedIdiots
相关产品推荐
相关产品推荐

