Bulk delete messages by user in Discord.js - javascript

I want to delete all the messages posted by a particular user. So far I have:
async function clear() {
let botMessages;
botMessages = await message.channel.fetch(708292930925756447);
message.channel.bulkDelete(botMessages).then(() => {
message.channel.send("Cleared bot messages").then(msg => msg.delete({timeout: 3000}))
});
}
clear();
There seems to be an issue with passing botMessages to bulkDelete(), it wants an array or collection but apparantly botMessages isn't an array or collection.
How would I give botMessages to bulkDelete, or am I going about this totally wrong?

message.channel.fetch() fetches the channel the message is sent to, not the messages in that channel.
You need to fetch a certain amount of messages and filter it so you're only getting messages sent by your bot then pass them to bulkDelete()
message.channel.messages.fetch({
limit: 100 // Change `100` to however many messages you want to fetch
}).then((messages) => {
const botMessages = [];
messages.filter(m => m.author.id === BOT_ID_HERE).forEach(msg => botMessages.push(msg))
message.channel.bulkDelete(botMessages).then(() => {
message.channel.send("Cleared bot messages").then(msg => msg.delete({
timeout: 3000
}))
});
})

Related

Discord js bot: Cannot send DM to users with specific role

I seem to be having serious trouble sending DM's to all users with a specific role.
Here is my bot code:
bot.on('message', async message => {
members = message.guild.roles.cache.find(role => role.id === "12345678998765").members.map(m => m.user.id);
members.forEach(member_id => {
sleep(5000).then(() => {
message.users.fetch(member_id, false).then((user) => {
user.send("some message");
});
});
});
});
This code gives me the error:
Cannot read properties of null (reading 'roles')
on this line:
members = message.guild.roles.cache.find(role => role.id === ....
However that is not the issue. When I comment out the sleep command to send the message and output the member roles using:
members.forEach(member_id => {
console.log(member_id)
//sleep(5000).then(() => {
// bot.users.fetch(member_id, false).then((user) => {
// user.send("some message");
// });
//});
});
I get a list returned in the console of all the user ID's.. So it must be returning the roles.
How do I send a message to all users with a specific role ID ?? I want to be able to loop through them and put a wait in to reduce the API requests and spam trigger.
To fix your first issue, message.guild will be null in DM. Make sure it isn't DM, or if it has to be, choose a guild with client.guilds.cache.get("id").
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
//...
})
To fix your other issue, you can run GuildMember#send() rather than getting the IDs and fetching the users
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
let members = guild.roles.cache.get("12345678998765").members
// I used .get here because it's getting by ID
members.forEach(member => {
sleep(5000).then(() => member.send("some message"));
});
})
The above code will get all the GuildMembers and loop through every one of them, "sleeping" for 5 seconds (if the sleep parameter is milliseconds) and send the member a DM

Get count of member's messages in channel in discord.js

Is there any way how to count messages of specified user in specified Discord channel in discord.js? When I use:
const countMyMessages = async (channel, member) => {
const messages = await channel.messages.fetch()
const myMessages = message.filter(m => m.author.id === member.id)
console.log(myMessages.size)
}
Only 50 messages are fetched, so I can't count all messages of user. And option limit can have max value 100. /guilds/guild_id/messages/search API on the other hand is not available for bots.
You will need to use a storage system to keep this kind of statistics on Discord.
I recommend you to use SQLite at first (like Enmap npm package).
I can quickly draw a structure for you based on this one.
const Enmap = require("enmap");
client.messages = new Enmap("messages");
client.on("message", message => {
if (message.author.bot) return;
if (message.guild) {
const key = `${message.guild.id}-${message.author.id}`;
client.messages.ensure(key, {
user: message.author.id,
guild: message.guild.id,
messages: 0
});
client.messages.inc(key, "messages");
// Do your stuff here.
console.log(client.messages.get(key, "messages"))
}
});

discord.js removing roles of member who deletes more than one channel recently

I'm kind of new to bot coding so I would like to get some help on this,
So, I wanted my bot to remove all permissions of a member which intends to delete more than 1 channel in 2 minutes interval. I made something like this below;
client.on("channelDelete", async function(channel) {
const channelDeleteId = channel.id;
// finding all channel deletions in the log
channel.guild.fetchAuditLogs({
'type': 'CHANNEL_DELETE'
})
// finding the log entry for this specific channel
.then(logs => logs.entries.find(entry => entry.target.id === channelDeleteId))
.then(entry => {
// getting the author of the deletion
author = entry.executor;
if (author.id === "472911936951156740") return console.log("VoiceMaster Bot has deleted a channel."); // dont mind, it's ok
console.log(`channel ${channel.name} deleted by ${author}`);
let member = channel.guild.members.cache.find(m => m.id === author.id);
let deletedRecently = new Set;
if (deletedRecently.has(member)) {
member.roles.set([]);
//member.ban();
} else {
deletedRecently.add(member);
setTimeout(() => {
deletedRecently.delete(member);
}, 120000);
}
})
.catch(error => console.error(error));
});
When I test it, it sometimes loops 3-4 times and triggers the role removing row.
Problem solved, thx. It was all about my little mistake. Sry for bothering...

How do I fetch the creator of a channel in discord?

bot.on('channelCreate', async channel => {
if (!channel.guild) return;
const fetchedLogs = await channel.guild.fetchAuditLogs({
limit: 1,
type: 'CHANNEL_CREATE',
});
const logbook = channel.guild.channels.cache.get("ChannelID")
const deletionLog = fetchedLogs.entries.first();
if (!deletionLog) return logbook.send(`A channel was updated but no relevant autid logs were found`);
const { executor, user } = deletionLog;
if (user.id) {
logbook.send(`${executor.tag} created a channel`);
} else {
logbook.send(`A channel was created but idk who did.`);
}
});
I am a newbie when it comes to fetching actions through Discord Audit Logs; so I am experimenting and somehow came up with this code. However, when I create a channel, it does not send any messages saying that a channel has been created by #user. I have no idea what my next step will be. All I wanted to do was to know who created the channel.
Discord.JS: v12.2.0
client.on("channelCreate", async channel => {
if (!channel.guild) return false; // This is a DM channel.
const AuditLogFetch = await channel.guild.fetchAuditLogs({limit: 1, type: "CHANNEL_CREATE"}); // Fetching the audot logs.
const LogChannel = client.channels.cache.get("722052103060848664"); // Getting the loggin channel. (Make sure its a TextChannel)
if (!LogChannel) return console.error(`Invalid channel.`); // Checking if the channel exists.
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first(); // Getting the first entry of AuditLogs that was found.
LogChannel.send(`${Entry.executor.tag || "Someone"} created a new channel. | ${channel}`) // Sending the message to the logging channel.
});
If the code I provided is not working, please make sure the bot has access to view AuditLogs.

How to get the last message of a specific channel discordjs

I'm trying to get the last message of a specific channel but I've couldn't do that, I want that if i write a command in another channel (Channel 1) that command gives me the last message of another channel (channel 2).
My code is:
client.on('message', (message)=>{
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')){
message.channel.fetchMessages({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
console.log(lastMessage.content);
})
.catch(console.error);
}
}
});
I cleaned up you code a bit, and added some comments explaining what is happening.
If you have more questions, i would recommend visiting the official Discord.js Discord server.
https://discord.gg/bRCvFy9
client.on('message', message => {
// Check if the message was sent in the channel with the specified id.
// NOTE, this defines the message variable that is going to be used later.
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')) {
// Becuase the message varibable still refers to the command message,
// this method will fetch the last message sent in the same channel as the command message.
message.channel.fetchMessages({ limit: 1 }).then(messages => {
const lastMessage = messages.first()
console.log(lastMessage.content)
}).catch(err => {
console.error(err)
})
}
}
})
If you want to get a message from another channel, you can do something like this.
And use the command start #channel
client.on('message', message => {
// Check if the message was sent in the channel with the specified id.
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')) {
// Get the channel to fetch the message from.
const channelToCheck = message.mentions.channels.first()
// Fetch the last message from the mentioned channel.
channelToCheck.fetchMessages({ limit: 1 }).then(messages => {
const lastMessage = messages.first()
console.log(lastMessage.content)
}).catch(err => {
console.error(err)
})
}
}
})
More about mentioning channels in messages can be found here.
https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=mentions

Categories

Resources