1

所以,我试图创建一个 RichEmbed 消息,它应该在用户离开 Discord 之后立即执行。在这个 RichEmbed 中应该是一个来自 giphy 的随机 GIF,它是我使用这个节点模块在 getGiphyPic() 函数中创建的:https ://github.com/risan/giphy-random 当这个事件被执行时,嵌入在没有 .setImage() 的情况下发送。我尝试过执行 console.log,在成功创建 URL 之前,似乎正在发送消息。

我已经尝试使事件函数异步并等待创建图像变量,我还尝试在 giphyRandom 函数之后创建一个承诺,但这似乎并没有解决我的问题。

const Discord = require('discord.js');
const { token, giphyToken } = require('./config.json');
const client = new Discord.Client();
const giphyRandom = require("giphy-random");
  function getGiphyPic() {
    (async () => {

        await giphyRandom(giphyToken, {
            tag: "fail",
            rating: "pg-13"
        }).then(resp => {
            let { data } = resp;

            console.log('Created GiphyURL: ' + JSON.stringify(data.image_url))
            return JSON.stringify(data.image_url);
        });
    })();
};
client.on('guildMemberRemove', async function (member) {

    var logChannel = client.channels.get('60370230389694091');
    if (!logChannel) return;
    var image = await getGiphyPic();
    var  embed = new Discord.RichEmbed()
        .setColor(0xc62828)
        .setAuthor('Someone has left the Server!', member.user.avatarURL);
        .setImage(image);
    logChannel.send(embed).then(message => console.log("Sent message!"));

});
4

1 回答 1

0

你可以使用提供给你的承诺......

const Discord = require('discord.js');
const { token, giphyToken } = require('./config.json');
const client = new Discord.Client();
const giphyRandom = require("giphy-random");
  function getGiphyPic() {
    return giphyRandom(giphyToken, {
        tag: "fail",
        rating: "pg-13"
    }).then(resp => {
        let { data } = resp;
        console.log('Created GiphyURL: ' + JSON.stringify(data.image_url))
        return data.image_url; // give correct response
    });
};
client.on('guildMemberRemove', function (member) {

    var logChannel = client.channels.get('60370230389694091');
    if (!logChannel) return;
    getGiphyPic().then(image => {
      var  embed = new Discord.RichEmbed()
          .setColor(0xc62828)
          .setAuthor('Someone has left the Server!', member.user.avatarURL);
          .setImage(image);
      logChannel.send(embed).then(message => console.log("Sent message!"));
    });
});

async / await 对于复杂的流控制很有用,但在这里似乎不需要,如果你想使用它,你就太复杂了:

  function getGiphyPic() {
    return giphyRandom(giphyToken, {
            tag: "fail",
            rating: "pg-13"
        }).then(resp => {
            let { data } = resp;

            console.log('Created GiphyURL: ' + JSON.stringify(data.image_url))
            return data.image_url;
        });
  };

只需返回承诺,async / await 将处理其余的。

于 2019-07-26T15:53:34.837 回答