繁体   English   中英

成功加载某些内容后,是否可以延迟发送Discord消息?

[英]Is there a way to delay sending a Discord message after something has successfully loaded?

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

我已经尝试使事件函数异步并等待图像var的创建,我还尝试在giphyRandom函数之后创建一个promise,但这似乎并不能解决我的问题。

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!"));

});

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

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;
        });
  };

只需返回Promise,异步/等待将处理其余部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM