【问题标题】:UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty messageUnhandledPromiseRejectionWarning:DiscordAPIError:无法发送空消息
【发布时间】:2021-05-05 03:36:42
【问题描述】:

我在从 fetch 向 Discord 频道发送消息时遇到问题。

我正在从 REST API 获取时间序列数据。然后,如果 Discord 用户键入命令,我想发送此数据。

代码:

require("dotenv").config();
const fetch = require("node-fetch");
const { Client } = require("discord.js");
const PREFIX = "!";

const getPrice = async (ticker) => {
    let result = "test";
    const request = await fetch(
      `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${ticker}&interval=5min&apikey=${process.env.API_KEY}`
    );
    const response = await request.json();
    const data = await response;
    const obj = await data["Time Series (5min)"];
    result = obj[Object.keys(obj)[0]];
    return result;
};

client.on("message", (message) => {
    if (message.author.bot) return;
    if (message.content.startsWith(PREFIX)) {
      const [command, ...args] = message.content
        .trim()
        .substring(PREFIX.length)
        .split(/\s+/);
      const result = getPrice(`${command.toUpperCase()}`);
      message.channel.send(result);
    }
});

我收到以下错误:

UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message

如果您查看以下代码并将其替换为console.log - 它可以工作。例如

原创

message.channel.send(result);

替换为

console.log(result)

然后就可以了:

{
  '1. open': '119.0200',
  '2. high': '119.0200',
  '3. low': '119.0200',
  '4. close': '119.0200',
  '5. volume': '302'
}

我怀疑它与 Promises 有关系,也许我的理解还没有达到标准,但我一遍又一遍地阅读文档,无法理解它。

我认为result 为空的原因是因为在堆栈中调用该方法时,fetch 还没有返回数据,它会尝试发送空数据。

我如何确保message.channel.send 在被调用之前等待我的提取完成?

【问题讨论】:

    标签: javascript node.js discord.js es6-promise


    【解决方案1】:

    getPrice 是一个返回承诺的异步函数。您需要等待结果才能发送:

    client.on("message", async (message) => {
        if (message.author.bot) return;
        if (message.content.startsWith(PREFIX)) {
          const [command, ...args] = message.content
            .trim()
            .substring(PREFIX.length)
            .split(/\s+/);
          const result = await getPrice(`${command.toUpperCase()}`);
          message.channel.send(result);
        }
    });
    

    【讨论】:

    • 感谢您的回复!虽然,我相信(根据我的理解) getPrice 解决了承诺并返回结果。我已经实施了你的建议,但仍然遇到同样的错误
    • 这很奇怪。不过,异步函数总是返回一个 Promise。
    • 好的,所以我设法解决了它 - 主要来自您的建议。所以,你是对的。我需要在 getPrice 完成之前等待。此外,message.channel.send 方法需要一个字符串,所以我将结果放在模板文字中。再次感谢!
    • “我相信...... getPrice 会兑现承诺” @kenwilde 不像你想的那样。 await 很神奇,您可以在其中编写 let value = await promise 之类的代码,而在内部编写 promise.then(value => ...)async function总是返回一个 Promise。
    • 感谢@Thomas 的更正,我现在明白了。简单地调用 async 函数不会解决它,您需要使用另一个 await 来 .. 等待它。谢谢!
    猜你喜欢
    • 2020-01-25
    • 2021-12-15
    • 2020-12-20
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2021-06-25
    相关资源
    最近更新 更多