1

在此search命令中,for in循环不会将字段添加到嵌入中。当我使用该命令时,我会获得在创建嵌入时定义的名称和描述。但我没有得到我在for in循环中添加的字段。

这是返回的图像,以防万一它有助于回答我的问题:

命令返回的图像

我的search命令代码:

const { MessageEmbed } = require('discord.js')

module.exports = {
    name: 'search',
    description: 'Searches for a song and returns the results.',
  options: [
    {
      name: 'search_term',
      description: 'The song to search for.',
      type: 'STRING',
      required: true
    },
    {
      name: 'limit',
      type: 'INTEGER',
      description: 'Number of results to return.',
      required: true
    },
    {
      name: 'type',
      type: 'STRING',
      description: 'The type of search result.',
      required: true,
      choices: [{
        name: 'Video',
        value: 'video'
      },
      {
        name: 'Playlist',
        value: 'playlist'
      }]
    }
  ],
    async execute(interaction) {
    const query = await interaction.options.getString('search_term')
    const limit = await interaction.options.getInteger('limit')
    const type = await interaction.options.getString('type')

    let type2 = 'x'
    if (type === 'video') type2 = 'Video'
    else if (type === 'playlist') type2 = 'Playlist'

    let results = await interaction.client.distube.search(query, { limit: limit, type: type })

    let embed = new MessageEmbed()
    .setTitle('search')
    .setDescription('Searches for a song and returns the results.')

    for (const result in results) {
      if (result.type === 'video') {
        embed.addFields({
          name :result.name, 
          value: `ID: ${result.id}\nType: ${type2}\nURL: ${result.url}\nViews: ${result.views}\nDuration: ${result.formattedDuration}\nLive: ${result.isLive}`, 
          inline: true})
      }
      else if (result.type === 'playlist') {
        embed.addFields({
          name: result.name, 
          value: `ID: ${result.id}\nType: ${type2}\nURL: ${result.url}\nViews: ${result.views}`,
          inline: true})
      }
    }

    await interaction.reply({embeds: [embed]})
    

    },
};
4

2 回答 2

0

您需要使用embed.addField(...)或将数组传递给embed.addFields([...]).

<MessageEmbed>.addFields()将数组作为输入。

于 2021-09-10T17:17:13.603 回答
0

解决方案:使用for of代替for in

两者的区别:

for...of 语句创建一个循环遍历可迭代对象的循环,包括:内置的String、、Array类似数组的对象(例如,参数或NodeListTypedArray、、、、MapSet

for...in 语句迭代对象的所有可枚举属性,这些属性以字符串为键(忽略以符号为键的),包括继承的可枚举属性。

了解更多信息:

for of: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

for in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

于 2021-09-12T07:54:31.413 回答