This snippet will delete all messages sent by a user in a specific channel when they leave. To set this snippet up just provide in the envirnment variable the channel you want to delete messages in.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
let channel_id = process.env.DELETE_MESSAGES_CHANNEL;
//Lists 100 messages in the channel
let messages = await lib.discord.channels['@0.3.2'].messages.list({
channel_id,
limit: 100,
});
//Empty array to hold all of the message IDs to delete
let list = [];
//Creates a for loop that checks if a message in the message list was made by the user who left
for (let i = 0; i < messages.length; i++) {
if (messages[i].author.id == context.params.event.user.id) {
//If the message was made by the user it will add the message ID to the list array
list.push(messages[i].id);
}
}
//Checks if the list is empty still
if (list.length == 0) {
//If it is it will return a message to the logs telling you that
console.log(`User has no messages`);
//Checks if the list only has 1 message
} else if (list.length == 1) {
//Only deletes one message (The minimum amount of messages for messages.bulkDelete is 2)
await lib.discord.channels['@0.3.2'].messages.destroy({
message_id: `${list[0]}`,
channel_id,
});
console.log(`User only has 1 message`);
//If the list has 2 or more messages it will delete all of the messages in the list
} else {
//Uses the bulkDelete API to delete all of the messages
await lib.discord.channels['@0.3.2'].messages.bulkDelete({
channel_id,
messages: list,
});
}