discord.js make a bot delete a given number of messages - discord.js

I've started creating a discord bot and I've wanted it to start moderating my server. my first command to try was 'mass delete' or 'purge' which deletes the number of messages a user gives.
But I'm pretty new to java and discord.js so I have no idea how to start.
// code here to check if an mod or above
// code to delete a number of message a user gave
}```

For permissions checking, you could simply check for the message author's roles using:
if (!message.member.roles.cache.has(moderator role object)) return;
Overall, you should be looking at the bulkDelete() function that can be found here.
Although, since you don't really know how to really develop bots yet from what you're saying, I won't be telling you the answer to your problem straight ahead. I'd highly recommend learning some JavaScript basics (Also, keep in mind Java != JavaScript) as well as Discord.js basics before you jump head straight into what you want to create.
I'd highly recommend WornOffKeys on YouTube, they're fantastic.

Check user permission first using
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You have no permission to access this command")
check bot permission using
if (!message.guild.me.permissions.has("MANAGE_MESSAGES")) return message.channel.send("This bot have no permission to delete msg!")
return a message when user havnt mention a select message
if (!args[0]) return message.channel.send("no messages have been selected")
then as Bqre said using bulkdelete()
try {
await message.channel.bulkDelete(args[0])
} catch (e) {
console.log(e); //err
}
hope you find it useful!

Related

Discord Autocode reaction reply bot (not reaction role bot)

I have been using autocode.com to create some Discord bots. I have very little programming experience and found autocode to be quite easy. However, I've tried asking a question on autocode's discord that no one seems to understand or is asking.
I am trying to create a bot that replies to reactions--but does not assign roles, but instead, provides a reply--either in thread or a DM to that user who uses that specific emoji reaction.
For example, this is what I am looking to do: if there is a bot message in #channelx, userX will react to that message with a pepperoni emoji and then a pizza bot will reply back with a message either in thread or DM such as, "Hi #userx, your pizza topping has been recorded and will be ready for pickup in 15 minutes, please visit this link.com to track your order".
Autocode has a bot that can react to reactions and assign roles but I can't seem to reverse engineer it give a reply, rather than assign roles.
I appreciate any assistance. Thanks!
What does autocode use? Python or node.js? If python, you can do something like this:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('message'):
await message.channel.send('hi')
If node.js, you can do something like this:
client.on('messageCreate', msg => {
if (msg.content === 'specific message') {
msg.reply(`response text`);
}
});
I was previously a Community Hero at the Autocode Discord server. Try finding another app through this, and if none are available, the thing to do would be looking through the API's. Here's one for messaging in general, here's one for responding, and here's one for dm-ing.
Let's say, for example, I'd be making it reply to a reaction through DM:
The first thing you do is make sure the event trigger is set to message.reaction.add. This is so that the code you will write is triggered whenever a reaction is added.
Make either a switch or if statement to change what happens depending on what reaction triggers the code. In this example, I'll just use an if statement for easy explanation.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
if (context.params.event.emoji.id == '1234567890') {
await lib.discord.users['#0.2.1'].dms.create({
recipient_id: `${context.params.event.member.user.id}`,
content: `Hi <#${context.params.event.member.user.id}>, your pizza topping has been recorded and will be ready for pickup in 15 minutes, please visit this link.com to track your order`
});
}
What this does is check if the thing that triggered this event has the emoji id equaling '1234567890': If it does, then it follows into that if statement, and if it does not, it skips over it.
In the future, please stay patient in the Autocode Discord server; The ones who are helping are also community members, similar to here. You may always ask the same question every now and then.

Checking if message author has specific permissions in Discord.js v16?

I’m making a command that should only be ran by people that can kick or ban, assuming that the role they have is some sort of mod or admin. I’ve only seen answers for previous versions, like .hasPermissions.
what do i do?
As said in this question (self-answered by me), .hasPermission() has been removed. Use .permissions.has() instead
if (message.member.permissions.has("KICK_MEMBERS")) {
// member HAS kick members permissions
}
You can also check multiple permissions at the same time. This is just an example that would probably not be used
if (message.member.permissions.has(["MANAGE_GUILD", "SEND_MESSAGES"])) {
// member HAS *BOTH* permissions to send messages and manage server
}
You can check all the permission flags at the discord.js docs for Permissions.FLAGS
It's really simple
if (message.member.permissions.has('KICK_MEMBERS') || message.member.permissions.has('BAN_MEMBERS')) {
//your code here
}

How to not send bots message edit discord.js

I have a message edit log but I want to stop sending the log if a mobs message was updated, I tried a few codes like
if(bot.oldMessage.content.edit()){
return;
}
It showed and error
cannot read property 'edit' of undefined
I then removed edit then content was undefined. The code for the message update is below.
The Code
module.exports = async (bot, oldMessage, newMessage) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[oldMessage.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
if (oldMessage.content === newMessage.content){
return;
}
let mEmbed = new MessageEmbed()
.setAuthor(oldMessage.author.tag, oldMessage.author.displayAvatarURL({dynamic: true}))
.setColor(cyan)
.setDescription(`**Message Editied in <#${oldMessage.channel.id}>**`)
.addField(`Before`, `${oldMessage.content}`)
.addField(`After`, `${newMessage.content}`)
.setFooter(`UserID: ${oldMessage.author.id}`)
.setTimestamp()
msgChannel.send(mEmbed)
}
How would I stop it from sending the embed if a bots message was updated.
Making a really simple check will resolve this issue. In Discord.js there is a user field that tells you if the user is a bot or not.
In fact, it is really recommended you add this in the "onMessage" part of your code as it stops other bots from using your bot, this is to make sure things are safe and no loopbacks/feedbacks happen, either way, you don't want a malicious bot taking advantage of your bot, which can get your bot in trouble too.
Here is what you want to do;
if (message.author.bot) return;
What this code specifically does is check if the message's author is a bot, if it returns true, it will break the code from running, if it returns a false, the code continues running.
You can do the same if you want to listen to bots ONLY by simply adding a exclamation mark before the message.author.bot like this;
if (!message.author.bot) return;
It is also possible to see what other kinds of information something holds, you can print anything to your console. For example, if you want to view what a message object contains, you can print it into your console with;
console.log(message) // This will show everything within that object.
console.log(message.author) // This will show everything within the author object (like ID's, name, discriminators, avatars, etc.)
Go ahead and explore what you can do!
Happy developing! ^ -^
That is really easy to do. All you need to do is check if the author of the message ist a bot and then return if true. You do that like this
if (oldMessage.author.bot) return;

How can I find the reason for a ban through discord audit logs? (Using Discord.js)

What I'm trying to do is make a log for my bot, (you know, something to record server events as they happen), and I've been doing alright so far, but I just can't seem to figure out how to get the reason for a ban/kick or whatever else can record reasons. I've checked the documentation, and I just can't really figure out what some of the stuff there means. There isn't really code to show off, because I have no clue where to start here, and it's about time I ask somewhere for help.
Edit: I do know where to start, I can find the audit log entry, but I can't get the reason for the entry
You can use guild.fetchAuditLogs()
const guild = client.guilds.cache.get('Guild_ID')
const fetchedBan = await guild.fetchAuditLogs({ user: 'User_ID), type: 'MEMBER_BAN_ADD' })
You can also use message.guild instead of const guild = client.guilds.cache.get('Guild_ID')
To get the reason for the latest ban of that member
const banReason = fetchedBan.entries.first().reason

Changing nickname in discord.js

So I've looked at a fair few forum posts and can't find something fitting my code.
I'm trying to do something like this...
case "setnick":
if (args[1]) {
if (message.guild.me.hasPermission("MANAGE_NICKNAMES")) {
if (message.member.hasPermission("CHANGE_NICKNAME"))
message.member.setNickname(args[1])
else message.channel.send("You do not have the permissions! **(CHANGE_NICKNAME)**")
}
else message.channel.send("The bot does not have the permissions! **(MANAGE_NICKNAMES)**")
}
else message.channel.send("There's no argument to set your nickname too! **Eg. f!setnick NICKNAME**")
break;
So it checks if there is a argument like
f!setnick NICKNAME
Then checks if the bot has permission MANAGE_NICKNAMES
if it doesn't it sends a chat message.
And it then checks for if the user has the permission CHANGE_NICKNAME
so i'm wondering why its not working.
Any reason why?
Have you tried checking if it works on other users besides yourself? Bots can not do administrator commands (like change someone's nickname) if you are higher/the same in the hierarchy than it, and seeing the owner is the ultimate power it is probably returning a permission error.
Try catching it and see what the error is
message.member.setNickname(args[1]).catch(e=>console.log(e))
if it returns DiscordAPIError: Privilege is too low... then my theory is correct. It should work for lower users.
message.member.me doesn't get the bot's user, it gets the user sending the message. Try message.guild.members.find("id", client.user.id).hasPermission("MANAGE_NICKNAMES")

Resources