首页 > 解决方案 > Discordjs如何在记录发送的消息或附件之前设置延迟?

问题描述

因此,当我记录发送到特定服务器的每条消息时,我的 Discord 日志记录机器人不断达到速率限制,我想知道如何让它在消息发送后几秒钟记录发送的消息,这样它就不会达到速率限制,这里是代码:

client.on('message', message => {

    if (message.author.bot) return;
    if (message.channel.type === 'dm') return;

    const channel = client.users.cache.get('256916902939590656');

    if(channel) {
        if (message.attachments.size > 0) {
            const Attachment = (message.attachments).array();
            Attachment.forEach(function(attachment) {
                const deletedMessageEmbed = new MessageEmbed()
                    .setColor('#cc5500')
                    .setAuthor(message.author.tag, message.author.avatarURL({ format: 'png', dynamic: true }))
                    .setTitle('Attachment Content')
                    .setURL(attachment.url)
                    .addField('Author', `${message.author}`)
                    .addField('Server', `${message.guild.name}`)
                    .addField('Name', `${attachment.name}`)
                    .setImage(attachment.proxyURL)
                    .addField('Channel', `<#${message.channel.id}>  #${message.channel.name}`)
                    .setFooter(`Message ID: ${message.id}`)
                    .setTimestamp();
                try {
                    client.users.cache.get('256916902939590656').send(deletedMessageEmbed);
                }
                catch (err) {
                    message.channel.send('No logs channel found. Please make sure I have access to it and make sure the channel name is called logs');
                }
            });
        }
        else {

            const messageContent = new MessageEmbed()
                .setColor('#cc5500')
                .setURL(message.url)
                .setAuthor(message.author.tag, message.author.avatarURL({ format: 'png', dynamic: true }))
                .setTitle('Message Content')
                .addField('Author', `${message.author}`)
                .addField('Server', `${message.guild.name}`)
                .addField('Channel', `<#${message.channel.id}>  #${message.channel.name}`)
                .setDescription(message.content)
                .setFooter(`Message ID: ${message.id}`)
                .setTimestamp();
            try {
                client.users.cache.get('256916902939590656').send(messageContent);
            }
            catch (err) {
                message.channel.send('No logs channel found. Please make sure I have access to it and make sure the channel name is called logs');
            }
        }
    }
});

上面的代码发送一个嵌入的附件或发送的消息: Sent Message Example Sent Attachment Example

我希望机器人在特定的设定时间后发送发送的图像或附件,这样它就不会一次全部发送并达到速率限制。

标签: javascriptdiscorddiscord.js

解决方案


const wait = (ms) => new Promise(resolve => setTimeout(resolve,ms));

在一个async函数中

await wait(5000)//waits 5 secons

或使用then()

wait(5000).then(()=>{
  //do something...
})

推荐阅读