How to send a message if user has the permission - node.js

Okay so, im trying to make an announce command that makes the bot say what the user asks it to write,
the command is working fine but the main problem is that i dont want users that are not moderators/admins to use this command i tried to use if (user.hasPermission("KICK_MEMBERS") but i simply don't know how to implement this into my code, (here it is)
const Discord = require('discord.js');
module.exports = {
name: 'announce',
description: "announce",
execute(message, args){
const developerEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`failed to send message`)
.setAuthor('♥Aiko♥', 'https://i.imgur.com/1q9zMpX.png')
.setDescription('please mention the channel first(if this promblem persists contact the developer)')
.setTimestamp()
.setFooter(`©Revenge#7005 | Requested by ${message.author.tag}.`);
if(message.mentions.channels.size === 0) {
message.channel.send(developerEmbed);
}
else {
let targetChannel = message.mentions.channels.first();
const args = message.content.split(" ").slice(2);
let userMessage = args.join(" ");
targetChannel.send(userMessage);
message.delete();
}
}
}
so yeah, any ideas how to make the bot check for the permission and then send the message if the user has it?
i'm pretty new to coding and this bot is my first bigger project so sorry if this question seems stupid

Make sure to use message.member in place of user, and you should implement it at the beginning of your code.
module.exports = {
name: 'announce',
description: "announce",
execute(message, args) {
if (!message.member.hasPermisson('KICK_MEMBERS')) // if member doesn't have permissions
return message.channel.send('Insufficient Permissions');
// rest of your code...

Related

Discord bot ban and kick commands not working properly

I am working on a discord bot and want to make it able to ban and kick the users which I mention, the issue is that even if it does say that the user I mentioned was banned successfully, it really wasn't. How can I fix this?
kick.js
name: 'kick',
description: "`Executing this command will kick the given user.`",
execute(message, args){
const target = message.mentions.users.first();
if(target){
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.kick();
message.channel.send("**The given user has been kicked.**");
}else{
message.channel.send("`You have to specify who you want to kick!`");
}
}
}
ban.js
name: 'ban',
description: "`Executing this command will ban the given user.`",
execute(message, args){
const target = message.mentions.users.first();
if(target){
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.ban();
message.channel.send("**The given user has been banned.**");
}else{
message.channel.send("`You have to specify who you want to banned!`");
}
}
}
You can put the messages just before the kick/ban, so that the user is available for the client:
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.kick();
message.channel.send("**The given user has been kicked.**");
becomes
const memberTarget = message.guild.members.cache.get(target.id);
message.channel.send("** <#"+ target.id + "> has been kicked.**");
memberTarget.kick();

Discord.js get user by nickname

I'm having a hard time figuring out
Is is possible to find a user by his or her nickname via the discord.js npm package.
How can I query a user by his or her nickname?
i've tried several things but nothing returns the nickname and I can't quite figure out how their documentation works.
So far I haven't been able to tell how to do it.
I've done as so in my code.
const { Client } = require('discord.js')
const discordClient = new Client()
discordClient.on('message', message => {
if (message.author.bot) return
if (message.content.startsWith('!gpwarn')) {
// The command is something like '!gpwarn thomas'.
// If his nick name is thomas but his username is john it doesn't work.
})
Yes, and it's pretty simple. Do this:
const user = client.users.cache.find(user => user.username == "The user's name");
Reference:
UserManager
To meet your exact requirements you would search the guild members cache for the provided nickname. However, I personally would suggest using either a direct tag or a UserID for this, as multiple people can have the same nickname in the server.
const U = message.guild.members.cache.find(E => E.nickname === 'NICKNAME')
Getting by Tag:
const U = message.mentions.members.first()
Getting by ID:
const U = message.guild.members.cache.find(U => U.id === 'IDHERE')
First you need to identify the nickname argument, you can do this by splitting, slicing, and joining message.content.
Next I recommend you fetch all of the GuildMembers from the guild using GuildMemberManager#fetch(), This way you don't run into the error of a member being uncached.
Handle the promise using async/await and use Collection#find() to return the member.
const { Client } = require('discord.js')
const discordClient = new Client()
discordClient.on('message', async message => {
if (message.author.bot) return
if (message.content.startsWith('!gpwarn')) {
// Returns all of the text after !gpwarn
const query = message.content.split(' ').slice(1).join(' ').toLowerCase()
const members = await message.guild.members.fetch()
const memberToWarn = members.find(m => m.nickname.toLowerCase() === query)
if (!memberToWarn) // No member found error
console.log(memberToWarn) // [GuildMember]
}
})

Mentioning users in embed

I'm currently making a hug command.
Im trying to make my bot mention the the user that used to command and the one that the user mentioned while using the command, my main problem is the bot sends the '#user has hugged #user' outside of the embed,
here is the code that im using
const messages = ["https://media.tenor.com/images/c6f27ebfd8657a83794329468c27197f/tenor.gif"]
module.exports = {
name: 'embed',
description: "hug embed",
execute(message, args){
const randomMessage = messages[Math.floor(Math.random() * messages.length)]
const hugged = message.mentions.users.first();
const reply = message.reply(`has hugged! <#${hugged.id}>`);
if(!hugged) return message.reply('please mention who you want to hug');
let embeddedHug = new Discord.MessageEmbed()
.setDescription(reply)
.setImage(randomMessage)
message.channel.send(embeddedHug);
}
}
Any suggestions why the bot sends it ouside of the embed?
You are not doing it correctly.
message.reply() is used to send a normal message and automatically mention the author on the beginning of the message.
This is what you want.
const hugged = message.mentions.users.first();
const embedMessage = `<#!${message.author.id}> has hugged <#!${hugged.id}>`;
let embeddedHug = new Discord.MessageEmbed()
.setDescription(embedMessage)
.setImage(randomMessage)
message.channel.send(embeddedHug);

(Discord.js) how too tag the bot itself

okay , hey there.
Im trying too ping/tag the bot itself in Discord.js.
soo when a user ping the bot in a command that it replies with an error message i defined myself.
thats what i have so far :
async run(message, args)
{
let huggeduser = message.mentions.users.first()
let auser = message.author
if(huggeduser == message.author) {
message.channel.send(`${auser} , you cant hug yourself!`)
return;
}
if(client.bot = huggeduser) { //(Note) How too tag the bot as it self like : (huggeduser == <the string too tag the bot>) {
message.channel.send("You cant meeeee hug!")
return;
}
the rest of the code works fine.
just the code-part of the with the (note)
i would love if someone can help me on that. ive been trying it myself for 2 days now.
Thanks.
Use double equal signs for checking equality. Also, checking the entire user objects is inefficient, just check their IDs.
Additionally, based on your error in the comments, and the name of this function, I'm assuming this is in a different file and you have a line like this at the top:
const client = new Discord.Client();
So in this context, client is not your logged-in bot user, it's an empty, not logged in bot that doesn't know who it is. You should get the client from the message object:
async run(message, args)
{
let huggeduser = message.mentions.users.first()
let auser = message.author
if(!huggeduser) return; //message for if no user was mentioned?
if(huggeduser.id == auser.id) {
message.channel.send(`${auser} , you cant hug yourself!`)
return;
} else if(huggeduser.id == message.client.user.id) {
message.channel.send("You cant meeeee hug!")
return;
}
//rest of code

I keep getting an error in discord.js "discord is not defined" OR I get no response from the bot. Not even an error/

I am coding a discord bot using discord.js.
FOR SOME REASON it says Discord not defined error or the bot has no response. Please could you help me? I have never had this error before. Here's the code.
I have include this command in the same main.js file:
if(cmd === `${prefix}help`){
reporthelp = "Report a user. Requires a channel named `reports`to work!";
kickhelp = "Kick a user from the server. Requires a channel named `incidents` to work; you must have the manage messages permission.";
banhelp = "Ban a user from the server. Requires a channel named `incidents` to qork; toy need the BAN MEMBERS permission to use this command!";
warnhelp = "**COMMAND COMING SOON!**";
requiredperms = "**Embed Links, channel named `incidents`; channel named `reports`; channel named `suggestions`; Kick Members, Ban Members, Manage Roles, Manage Members.**"
helpEmbed = new Discord.RichEmbed()
.setDescription(" 💬 **__Help Is Here!__** 💬")
.setColor("#936285")
.addField("**/report #user <reason>**", reporthelp)
.addField("**(COMING SOON)** /warn #user <reason>", warnhelp)
.addField("**/kick #user <reason>**", kickhelp)
.addField("**/ban #user <reason>**", banhelp)
.addField("**/mytag**", "Shows you **your** discoord username#discrim and your user ID. Requires Embed Links permission.")
.addField("**/invite**", "Get a linkto incite meto our server, and an invite link to my suppoer server")
.addField("**/owner**", "see who currently owns the bot")
.addField("**/git**", "**SOURCE CODE AVAILIBLE SOON**")
.addField("**/token**", "View the bot's super secret bot token!")
.addField("**/serverinfo**", "displays some basic server information!")
.addField("**/botinfo**", "displays basic bot information!")
.addField("**/ping**", "Get the bot to respond with `pong` ")
.addField("**/hosting**", "Bot finds a good website for bot/web hosting")
.addField("**/quotes**", "bot responds with some lovely quotes!")
.addField("**__Required Permissions__**", requiredperms)
// .addField("**COMING SOON!**/suggest <suggestion>", "suggest something. Requires channel named `suggestions`")
.setTimestamp()
.setFooter("Use /invite to invite me to your server!")
return message.channel.send({embed: helpEmbed});
}
This is how I've defined everything:
const botconfig = require("./botconfig.json");
const tokenfile = require("./token.json");
const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
bot.on("ready", async () => {
console.log(`${bot.user.username} is active in ${bot.guilds.size} servers!`);
bot.user.setActivity("rewriteing main.js...", {type: "WATCHING"});
//bot.user.setGame("Lookin' out for ya!");
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
const prefix = botconfig.prefix;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
const bicon = bot.user.displayAvatarURL;
I either get no response/error, or I get the error discord is not defined.
I'm also very new here, sorry If I didn't ask a question clearly...
The code is correct, but I had redfined discord in a different part of the file....
my advice would be to alays read the code over again!

Resources