用for循环填充RichEmbed

时间:2019-03-20 13:59:07

标签: javascript node.js discord.js

对于Discord机器人,我正在从API提取数据(json)。我正在使用a for循环遍历所有json数据,并希望对发现的每个数据使用.addfield()。不幸的是,这是行不通的。我该如何解决?

这是我当前的代码:

let search = json.search
let richembed = new Discord.RichEmbed()
  .setTitle("Title")
  .setDescription("Description")
  for (i in search) {
    let title = search[i].title
    let snippet = search[i].snippet
    .addField(title, snippet)
  }
  .setTimestamp()
  .setFooter("bot.user.username", bot.user.avatarURL)

这是来自API的示例JSON响应。

"search": [{
    "ns": 0,
    "title": "Monkey",
    "snippet": "text here",
    "timestamp": "2019-03-19T04:18:52Z"
  },
  {
    "ns": 0,
    "title": "The Monkey",
    "snippet": "text here",
    "timestamp": "2018-12-31T14:40:16Z"
  },
  {
    "ns": 0,
    "title": "Monkey see, monkey do",
    "snippet": "text here",
    "timestamp": "2019-01-16T00:12:51Z"
  }]

1 个答案:

答案 0 :(得分:0)

您不能在RichEmbed Builder中执行for循环。您必须像下面的代码那样进行操作:

let search = json.search    
let richembed = new Discord.RichEmbed()
    .setTitle("Title")
    .setDescription("Description")
    .setTimestamp()
    .setFooter("bot.user.username", bot.user.avatarURL);

for (i of search) {
  let title = i.title
  let snippet = i.snippet
  richembed.addField(title, snippet)
}