Fetch bot messages from bots Discord.js

℡╲_俬逩灬. 提交于 2019-12-24 20:46:01

问题


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.

How would I do this?


回答1:


Each Message has an author property that represents a User. Each User has a bot property that indicates if the user is a 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);
    });
}


来源:https://stackoverflow.com/questions/47951918/fetch-bot-messages-from-bots-discord-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!