javascript 从机器人 Discord.js 获取机器人消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47951918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:43:03  来源:igfitidea点击:

Fetch bot messages from bots Discord.js

javascriptnode.jsbotsdiscorddiscord.js

提问by qtt qtt

I am trying to make a bot that fetches previous bot messages in the channel and then deletes them. I have this code currently that deletes all messages in the channel when !clearMessagesis entered:

我正在尝试制作一个机器人来获取频道中以前的机器人消息,然后删除它们。我目前有此代码,可在!clearMessages输入时删除频道中的所有消息:

if (message.channel.type == 'text') {
    message.channel.fetchMessages().then(messages => {
        message.channel.bulkDelete(messages);
        messagesDeleted = messages.array().length; // number of messages deleted

        // Logging the number of messages deleted on both the channel and console.
        message.channel.send("Deletion of messages successful. Total messages deleted: "+messagesDeleted);
        console.log('Deletion of messages successful. Total messages deleted: '+messagesDeleted)
    }).catch(err => {
        console.log('Error while doing Bulk Delete');
        console.log(err);
    });
}

I would like the bot to only fetch messages from all bot messages in that channel, and then delete those messages.

我希望机器人只从该频道中的所有机器人消息中获取消息,然后删除这些消息。

How would I do this?

我该怎么做?

回答by André Dion

Each Messagehas an authorpropertythat represents a User. Each Userhas a botpropertythat indicates if the user is a bot.

每个Message都有一个表示的author属性User。每个User都有一个bot属性来指示用户是否是机器人。

Using that information, we can filter out messages that are not bot messages with messages.filter(msg => msg.author.bot):

使用该信息,我们可以过滤掉不是机器人消息的消息messages.filter(msg => msg.author.bot)

if (message.channel.type == 'text') {
    message.channel.fetchMessages().then(messages => {
        const botMessages = messages.filter(msg => msg.author.bot);
        message.channel.bulkDelete(botMessages);
        messagesDeleted = botMessages.array().length; // number of messages deleted

        // Logging the number of messages deleted on both the channel and console.
        message.channel.send("Deletion of messages successful. Total messages deleted: " + messagesDeleted);
        console.log('Deletion of messages successful. Total messages deleted: ' + messagesDeleted)
    }).catch(err => {
        console.log('Error while doing Bulk Delete');
        console.log(err);
    });
}