Discord.js: Checking Bot Permissions - javascript

This is probably a nub question, but I can't seem to figure it out. I'm trying to make my bot check if it has a permission, and send a message if does not. I'm guessing it like this code to check it a member has a permission:
message.member.hasPermission("MUTE_MEMBERS")
Is it like that to get a bots permissions? Any help would be appreciated!

message.member gets the GuildMember object of the author who sent the message. Looks like you actually want to get the GuildMember object of the client instead. You can do this by doing <Client>.guild.me and then call .hasPermission(...) on this.

If you want to check if the bot has a permission you can do something like:
if(message.guild.me.hasPermission("MUTE_MEMBERS"))
console.log("I can mute members!!")
else
console.log("I CAN'T mute members!")
F.M.

message.guild.me.hasPermission("MUTE_MEMBERS")

In discord.js V13 you can check for permissions this way:
if (message.member.permissions.has("MUTE_MEMBERS")){
// ....
} else {
//....
}

if(!message.member.hasPermission("PERMISSION") return message.channel.send("You don't have permission to use this command")
Embeds:
const embed = new MessageEmbed()
.setTitle("No Permission")
.setDescription("You don't have permission to use this command")
if(!message.member.hasPermission("PERMISSION") return message.channel.send(embed)

Related

When a user mentions the owner the bot should say you're not allowed

I am trying to make it when a user is tagged (eg. MyNameJeff#0001), the bot will automatically respond with you're not allowed to mention them and delete their message.
I tried searching for an event that could handle this but haven't found anything useful so far.
You can check if the collection message.mentions.users includes the guild owner's ID with the has() method. A simple if (message.mentions.users.has(message.guild.ownerId)) will work for you:
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (message.mentions.users.has(message.guild.ownerId)) {
message.channel.send('You are not allowed to mention the owner!');
message.delete();
}
});

Self Permission Check

How do I check if the bot (Self) has permissions to send messages and make it an if statement? Im using discord js and I've seen forums like member.roles.cache has, but none cover the bot itself, so how do I check that?
As Elitezen said, you can get GuildMember object using Guild#me but to check if your bot can send messages for example in guild where the command was executed you have to use this:
if(message.guild.me.permissions.has("SEND_MESSAGES")) { // check if bot has SEND_MESSAGES permission
// your code
}
You can use Guild#me to get the client's GuildMember object in that guild.
// guild = message.guild or any guild object
if (guild.me.roles.cache.has(...)) {
}
Update: in Discord.JS V14 you now have to use guild.members.me

How to send a message to another Discord server on a specific channel? [duplicate]

I'm failing to achieve something very simple. I can't send a message to a specific channel. I've browsed trough the documentation and similar threads on stack overflow.
client.channels.get().send()
does NOT work.
It is not a function.
I also do not see it as a method on the Channel class on the official documentation yet every thread I've found so far has told me to use that.
I managed to have the bot reply to a message by listening for a message and then using message.reply() but I don't want that. I want my bot to say something in a specific channel in client.on('ready')
What am I missing?
You didn't provide any code that you already tested so I will give you the code for your ready event that will work!
client.on('ready', client => {
client.channels.get('CHANNEL ID').send('Hello here!');
})
Be careful that your channel id a string.
Let me know if it worked, thank you!
2020 Jun 13 Edit:
A Discord.js update requires the cache member of channels before the get method.
If your modules are legacy the above would still work. My recent solution works changing the send line as follows.
client.channels.cache.get('CHANNEL ID').send('Hello here!')
If you are using TypeScript, you will need to cast the channel in order to use the TextChannel.send(message) method without compiler errors.
import { TextChannel } from 'discord.js';
( client.channels.cache.get('CHANNEL ID') as TextChannel ).send('Hello here!')
for v12 it would be the following:
client.on('messageCreate', message => {
client.channels.cache.get('CHANNEL ID').send('Hello here!');
})
edit: I changed it to log a message.
This will work for the newest version of node.js msg.guild.channels.cache.find(i => i.name === 'announcements').send(annEmbed)
This should work
client.channels.fetch('CHANNEL_ID')
.then(channel=>channel.send('booyah!'))
Here's how I send a message to a specific channel every time a message is deleted. This is helpful if you'd like to send the message without a channel ID.
client.on("messageDelete", (messageDelete) => {
const channel = messageDelete.guild.channels.find(ch => ch.name === 'channel name here');
channel.send(`The message : "${messageDelete.content}" by ${messageDelete.author} was deleted. Their ID is ${messageDelete.author.id}`);
});
Make sure to define it if you're not using messageDelete.

Not having an argument shuts off my discord bot

If I don't define a person to ban, it shuts my bot off.
ERROR: TypeError: Cannot read property 'displayName' of undefined
if (msg.member.roles.cache.has()) {
let user = msg.mentions.members.first();
msg.channel.send(`🔨│ Banned #${user.displayName}!`);
user.ban();
}
Yes, if you don't give a mention, then it will generate an error and the bot will crash.
You should make a return statement where you prevent this from happening.
if (msg.member.roles.cache.has('BAN_MEMBERS')) {
let member = msg.mentions.members.first();
// prevents from not mentionning
if (!member) return msg.channel.send(`Give a user to ban !`);
// If the code continues, then there is a mention
try {
user.ban();
msg.channel.send(`🔨│ Banned #${member.user.displayName}!`);
} catch (err) {
msg.channel.send('I cannot ban this member !');
}
} else msg.channel.send('You do not have the permission to do this');
So I fixed many problems :
First, if you want the name of a member you'll have to use the user object. So you can't use member.displayName but member.user.username
Second, you need to prevent that if the bot can't ban the member. If for example, the member is an administrator or the owner of the server
Last, what you asked for, if there is no mention in the message, it will send a message telling you that you didn't pass a member to ban
I suggest you check out some tutorials like the discord.js guide

Sending private messages to user

I'm using the discord.js library and node.js to create a Discord bot that facilitates poker. It is functional except the hands are shown to everyone, and I need to loop through the players and send them a DM with their hand.
bot.on("message", message => {
message.channel.sendMessage("string");
});
This is the code that sends a message to the channel when any user sends a message. I need the bot to reply in a private channel; I've seen dmChannel, but I do not understand how to use it. I have the username of the member that I want to send a message to.
An example would be appreciated.
Edit:
After looking around for a user object, I found that I can get all of the users using the .users property of the client (bot). I will try using the user.sendMessage("string") method soon.
In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author as your client. (you can replace author as mentioned user in a message or something, etc)
Hence, the answer is: message.author.send("Your message here.")
I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.
To send a message to a user you first need to obtain a User instance.
Obtaining a User instance
use the message.author property of a message the user sent .
call client.users.fetch with the user's id
Once you got a user instance you can send the message with .send
Examples
client.on('message', (msg) => {
if (!msg.author.bot) msg.author.send('ok ' + msg.author.id);
});
client.users.fetch('487904509670337509', false).then((user) => {
user.send('hello world');
});
The above answers work fine too, but I've found you can usually just use message.author.send("blah blah") instead of message.author.sendMessage("blah blah").
-EDIT- : This is because the sendMessage command is outdated as of v12 in Discord Js
.send tends to work better for me in general than .sendMessage, which sometimes runs into problems.
Hope that helps a teeny bit!
If your looking to type up the message and then your bot will send it to the user, here is the code. It also has a role restriction on it :)
case 'dm':
mentiondm = message.mentions.users.first();
message.channel.bulkDelete(1);
if (!message.member.roles.cache.some(role => role.name === "Owner")) return message.channel.send('Beep Boing: This command is way too powerful for you to use!');
if (mentiondm == null) return message.reply('Beep Boing: No user to send message to!');
mentionMessage = message.content.slice(3);
mentiondm.send(mentionMessage);
console.log('Message Sent!')
break;
Just an FYI for v12 it's now
client.users.fetch('487904509670337509', false).then((user) => {
user.send('heloo');
});
where '487904509670337509' is an id number.
If you want to send the message to a predetermined person, such as yourself, you can set it so that the channel it would be messaging to would be their (your) own userID. So for instance, if you're using the discord bot tutorials from Digital Trends, where it says "to: ", you would continue with their (or your) userID. For instance, with how that specific code is set up, you could do "to: userID", and it would message that person. Or, if you want the bot to message you any time someone uses a specific command, you could do "to: '12345678890'", the numbers being a filler for the actual userID. Hope this helps!
This is pretty simple here is an example
Add your command code here like:
if (cmd === `!dm`) {
let dUser =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if (!dUser) return message.channel.send("Can't find user!");
if (!message.member.hasPermission('ADMINISTRATOR'))
return message.reply("You can't you that command!");
let dMessage = args.join(' ').slice(22);
if (dMessage.length < 1) return message.reply('You must supply a message!');
dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);
message.author.send(
`${message.author} You have sent your message to ${dUser}`
);
}
Make the code say if (msg.content === ('trigger') msg.author.send('text')}

Categories