DeviousDev
DeviousDev

Reputation: 27

Discord.js - How do I remove all messages sent by a bot?

I only want my bot to have a single message, so each time it sends a message, its previous message is deleted. What I'm trying to do is loop through all the messages and see if the ID matches the bot. Here is the command:

if(message.content.startsWith(`${PREFIX}update`)){
    const channel = message.channel
    const messages = await channel.messages.fetch({ limit: 100 });
    messages.forEach(msg => **IF MESSAGE IS SENT BY BOT, DELETE IT**); 
    message.channel.send("update");
}

How do I see if the message is sent by the bot and delete it? I've only seen people deleting a certain number of messages before.

Upvotes: 0

Views: 2511

Answers (1)

Jakye
Jakye

Reputation: 6625

User has a property called bot which will be true/false depending on if the account is a bot or not. You can use that to check if the message you want to delete was sent by a bot.

Moreover, you can use message.author.id to check the ID of the author. (Just in case you want to delete messages by a certain bot.)

Examples:

    if (message.content.startsWith(`${PREFIX}update`)) {
        const Channel = message.channel;
        const Messages = await Channel.messages.fetch({limit: 100});

        Messages.forEach(msg => { // Checking if the message author has a certain ID.
            if (msg.author.id == "ID") msg.delete()
        });

        message.channel.send("Updated");
    };
});
    if (message.content.startsWith(`${PREFIX}update`)) {
        const Channel = message.channel;
        const Messages = await Channel.messages.fetch({limit: 100});

        Messages.forEach(msg => { // Checking if the message author is a bot.
            if (msg.author.bot) msg.delete()
            // This will delete messages from any bot.
        });

        message.channel.send("Updated");
    };

Deleting a message by ID:

const Channel = client.channels.cache.get("ChannelID");
Channel.messages.fetch("MessageID").then(message => message.delete())

Upvotes: 1

Related Questions