【问题标题】:My Discord bot sends messages in a weird way我的 Discord 机器人以一种奇怪的方式发送消息
【发布时间】:2021-05-14 04:14:59
【问题描述】:

我目前正在开发一个跟踪 Steam 价格并将其发送到聊天的 Discord 机器人。我为它编写了这段代码:

setInterval(() => {
  const currentDate = new Date();
  var yourchannel = client.channels.cache.get('[CHANNEL ID]');
  fetch('https://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=Operation%20Breakout%20Weapon%20Case&currency=6', )
    .then(res => res.text())
    .then(text => yourchannel.send(`Breakout case price on ${currentDate.toLocaleDateString(`pl-PL`)} is ${text}`))

  }, 1000 * 60 * 60 * 24);
});

我希望我的机器人发送消息 “[date] 的分包价格为 [price]。” 例如 “2021 年 2 月 10 日的分包价格为 5.94zł” em>,但它会发送这个:

Breakout case price on 10.02.2021 is {"success":true,"lowest_price":"5,92zł","volume":"13,807","median_price":"6,01zł"}

【问题讨论】:

  • ...`是 ${text.lowest_price}``

标签: javascript node.js discord.js node-fetch


【解决方案1】:

这是因为您发送了从 fetch 返回的整个对象。您只需要发送该对象的属性(如json.lowest_price)。您还需要确保您parse the body text as JSON。您需要使用res.json() 而不是res.text()

if (message.content === 'lowest_price') {
  fetch(
    'https://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=Operation%20Breakout%20Weapon%20Case&currency=6',
  )
    .then((res) => res.json())
    .then((json) =>
      message.channel.send(
        `Breakout case price on ${new Date().toLocaleDateString('pl-PL')} is ${
          json.lowest_price
        }`,
      ),
    )
    .catch((error) => {
      console.log(error);
      message.channel.send('Oops, there was an error fetching the price');
    });
}

查看basics of objects on MDN

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2021-08-19
    • 2021-01-08
    • 2020-11-23
    • 2021-04-19
    • 2022-01-23
    • 2021-02-22
    • 2019-09-12
    • 2021-10-29
    相关资源
    最近更新 更多