Node.js Discord机器人报错:无法读取undefined的属性'17'
错误原因
quotes是数组而非对象,你错误地用quotes.quote访问,这会返回undefined,后续尝试读取[args[1]]就触发了Cannot read properties of undefined错误。args[1]是字符串格式的数字,数组索引需要数字类型,且你的quote项id从1开始,但数组索引从0开始,直接用args[1]作为索引会导致索引不匹配(比如输入1会取到数组第2项)。- 代码未使用命令中的
username参数,不符合你C!send quote (number) (username)的需求。
修复方案
- 修正quote的查找逻辑:通过
id匹配数组中的项,避免索引偏移问题。 - 补充参数有效性校验(比如输入的数字对应的quote是否存在)。
- 加入username参数的使用逻辑(支持@目标用户或输入用户名)。
修复后的代码示例:
const Discord = require('discord.js'); require('dotenv').config(); const client = new Discord.Client(); const quotes = [ { id: "1", quote: "This is quote 1" }, { id: "2", quote: "This is quote 2" }, // 更多Quote项 ]; client.on('message', (msg) => { if (msg.content.startsWith("C!send")) { let messageArray = msg.content.split(" "); let args = messageArray.slice(1); if (!args[0]) { return msg.channel.send("Error, missing argument 1"); } else if (args[0] === "quote") { // 校验参数2是否为有效数字 const quoteId = args[1]; if (!quoteId || isNaN(quoteId)) { return msg.channel.send("Error, argument 2 needs to be a valid number!"); } // 校验参数3是否存在 const targetUsername = args[2]; if (!targetUsername) { return msg.channel.send("Error, missing argument 3"); } // 根据id查找对应的quote const targetQuote = quotes.find(item => item.id === quoteId); if (!targetQuote) { return msg.channel.send(`Error, no quote found with id ${quoteId}`); } // 发送quote并@目标用户(兼容@提及和纯用户名输入) const targetUser = msg.mentions.users.first() || targetUsername; msg.channel.send(`${targetUser}, ${targetQuote.quote}`); } } }); // 记得登录客户端 client.login(process.env.DISCORD_TOKEN);
额外说明
- 使用
Array.find()根据id匹配quote,逻辑更直观,避免数组索引偏移带来的错误。 - 增加了quote不存在的校验,防止发送空内容或报错。
- 兼容两种输入方式:直接@目标用户,或输入纯用户名。
内容的提问来源于stack exchange,提问作者Trader
相关产品推荐
相关产品推荐

