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

Fetch bot messages from bots Discord.js(从机器人 Discord.js 获取机器人消息)
本文介绍了从机器人 Discord.js 获取机器人消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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 !clearMessages is entered:

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.

我该怎么做?

推荐答案

每个 Message 有一个 author 属性,表示 用户.每个 User 都有一个 bot 属性 表示如果用户是机器人.

Each Message has an author property that represents a User. Each User has a bot property that indicates if the user is a bot.

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

Using that information, we can filter out messages that are not bot messages with 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);
    });
}

这篇关于从机器人 Discord.js 获取机器人消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Discord.js Arguments With Spaces(Discord.js 带空格的参数)
DiscordJS fetching more then 100 messages(DiscordJS 获取超过 100 条消息)
my discord.js bot doesn#39;t reply to a user message even if there isn#39;t any error(即使没有任何错误,我的 discord.js 机器人也不会回复用户消息)
Make a bot wait for some time before continuing the code(在继续代码之前让机器人等待一段时间)
Invalid Form Body in Discord.js ban command(Discord.js 禁止命令中的无效表单正文)
Set Discord Bot Activity to the number of Online users. Discord.js(将 Discord Bot 活动设置为在线用户数.不和谐.js)