我正在try 创建自己的discord机器人(在discord.js v13中).我找到了官方的discord.js guide on this topictheir 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 ,但什么也没找到.非常感谢您的帮助!

推荐答案

正如您在回答中提到的,返回的对象中没有list项.应该是items.此外,您收到了[object Object],因为您隐式地将返回的对象强制为字符串(即console.log(`Console log 3: `+itemSearchResult.body`)).

我回答这个问题的原因是,你可以go 掉这个丑陋的getJSONResponse()函数,使用一个内置的body mixin来简化你的代码:

async execute(interaction) {
  const itemName = interaction.options.getString('item_name');
  const { body } = await request(ITEM_URL + encodeURIComponent(itemName));
  const { items } = await body.json();

  if (!items.length)
    await interaction.reply(`No results found for **${itemName}**.`);

  const [answer] = items;
  const itemEmbed = new MessageEmbed()
    .setColor('#000000')
    .setTitle(answer.name)
    .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] });
},

enter image description here

Javascript相关问答推荐

如何指定1条记录1个表?

可以的.是否可以在不预编译的情况下使用嵌套 Select 器?

Klaro与Angular的集成

使用axios.获取实时服务器时的404响应

提交表格后保留Web表格中的收件箱值?

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

v—自动完成不显示 Select 列表中的所有项目

为什么按钮会随浮动属性一起移动?

使用POST请求时,Req.Body为空

更改预请求脚本中重用的JSON主体变量- Postman

JavaScript是否有多个`unfined`?

MongoDB受困于太多的数据

使用Document.Evaluate() Select 一个包含撇号的HTML元素

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

如何在Reaction中清除输入字段

通过解构/功能组件接收props-prop验证中缺少错误"

如何在Java脚本中并行运行for或任意循环的每次迭代

在将元素追加到DOM之前,createElement()是否会触发回流?混淆abt DocumentFragment行为

限制数组中每个元素的长度,

更改管线时不渲染组件的react