我正在try 创建自己的discord机器人(在discord.js v13中).我找到了官方的discord.js guide on this topic和their example code,我正在try 使用/重用那里的代码来构建我自己的机器人.
idea 是在斜杠命令"item"
(so /item: firebrand
)之后获取用户输入,将用户输入传递到URL(允许您从后端/API获取关于该项目的信息),并使用收到的响应填充嵌入的各个字段,这些字段被发送回用户.
我能够传递用户输入并将其添加到URL,URL返回可用链接,但代码在创建嵌入之前中断.我在代码中输入了console.log
条命令,以查看哪里出了问题.
请参见下面代码中console.log
的位置.
- 控制台日志(log)1:
{"items":[{"id":14,"name":"Frost Brand","type":"1-h wpn","constlevel":4,"mainlevel":1,"mpath":"W1","gemcost":"5W","screenshot":"/items/14/screenshot"}],"similarity":-0}
- 控制台日志(log)2:https://dom5api.illwiki.com/items?match=fuzzy&name=frostbrand
- 控制台日志(log)3:
[object Object]
- 控制台日志(log)4:
[object Object]
- 控制台日志(log)5:
undefined
-类型错误:无法读取未定义的属性(读取"length")
我猜我得到了TypeError,因为{ list }
是undefined
.这可能是因为itemSearchResult.body
回复[object Object]
,但我不知道如何解决这个问题.
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
const { request } = require('undici');
const { ITEM_URL, BASE_URL } = require('../utils/utils');
module.exports = {
data: new SlashCommandBuilder()
.setName('item')
.setDescription('Replies with information about an item')
.addStringOption(option => option.setName('item_name').setDescription('Enter the name of the item')),
async execute(interaction) {
async function getJSONResponse(body) {
let fullBody = '';
for await (const data of body) {
fullBody += data.toString();
console.log(`Console log 1: `+fullBody);
}
return JSON.parse(fullBody);
}
const itemName = interaction.options.getString('item_name');
const itemSearchResult = await request(ITEM_URL + encodeURIComponent(itemName));
console.log(`Console log 2: `+ITEM_URL + encodeURIComponent(itemName));
console.log(`Console log 3: `+itemSearchResult.body);
console.log(`Console log 4: `+itemSearchResult.body.toString())
const { list } = await getJSONResponse(itemSearchResult.body);
console.log(`Console log 5: `+list)
if (!list.length) {
await interaction.reply(`No results found for **${itemName}**.`);
}
const [answer] = list;
const itemEmbed = new MessageEmbed()
.setColor('#000000')
.setTitle(answer.name)
.setURL('X')
.setAuthor({ name: 'Author' })
.setDescription('Lot of hassle, but hey, it was working!')
.setImage(BASE_URL + answer.screenshot)
.setTimestamp()
.setFooter({ text: 'A small step for X, a giant leap for X' });
await interaction.reply({ embeds: [itemEmbed] });
},
};
我试图在网上和StackOverflow上搜索错误消息/类似 case ,但什么也没找到.非常感谢您的帮助!