Bot checking if the member has the role - javascript

I have this on my code but when I execute the command twice (the name command, user, and role) it doesn't return this message. It keeps on saying "I added [role name] to [user]"
if (message.guild.members.cache.some(role => role.name)) {
const embed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setDescription(`${message.mentions.users.first()} has that role already!`);
return message.channel.send(embed);
}

Did you save the code? Also, instead of
if (message.guild.members.cache.some(role => role.name))
do
if (message.guild.members.cache.some(role => role.name === 'roleName')) //insert role name.
Hope this helps :)

Related

Discord.js mod bot ban command not working

My discord bot's ban command isn't working and is currently giving me this error. My rols id is 853527575317708820
I don't know what I am doing wrong so please help me out
Here is the command :
Server is ready.
TigerShark Community#3557 Has logged in
(node:204) UnhandledPromiseRejectiontarning: DiscordAPTError: T
AEE RS
user_id: Value "<#!856413967595012127>" is not snowflake.
at RequestHandler.execute (/home/Tunner/TSC/node_modules/di
scoxd. js/src/rest/RequestHandler. js:154:13)
at processTicksAndRejections (internal/process/task
§5:97:5) :!
at async RequestHandler.push (/home/zunner/TSC/node
/discord. js/s1c/rest/RequestHandler. js:39:14)
Here is my code :
module.exports = {
name: 'ban',
description: "Used to ban members from a server",
async execute(client, message, args, Discord) {
if (!(message.member.roles.cache.some(r => r.id === "853527575317708820"))) return
let reason;
const user = await client.users.fetch(args[0])
if (!args[1])
{
reason = "Not specified"
} else {
reason = args[1]
}
const embed = new Discord.MessageEmbed()
.setTitle(`${user.username} was banned!`)
.setDescription(`${user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
message.channel.send(embed)
message.guild.members.ban(user)
}
}
Your command has few issues in it.
The first being that it does not allow banning users with command if the user is mentioned, it only allows banning by user ID. To fix that simply do:
const user = message.mentions.members.first() || await client.users.fetch(args[0])
You should also add check if the user is found, so right after you declare value for user
const user = message.mentions.members.first() || await client.users.fetch(args[0])
if(!user) return message.reply(`No user found`);
Now if you allow banning both mentions and user IDs there might be a different user value. So I recommend editing your embed aswell to something like:
const embed = new Discord.MessageEmbed()
.setTitle(`${user.user.username} was banned!`)
.setDescription(`${user.user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
This should fix majority of your issues, I recommend that if something is undefined in future or you come across any bugs in your code. Do some debugging by sending messages to console console.log(variable) or console.log("This works?")
if you are using discord.js v12 you can do what the other answer said and get the user by mention message.mentions.members.first() but if you are using v13 that wont work anymore
the reason its giving that error is because you need to fetch the user by their id alone, so you can do this client.users.fetch(args[0].replace('<#!', '').replace('>', '')) to remove the <#! and > (mention prefix) from it.

I'm trying to make a set role command and a set channel command. I've attempted to do it but it doesn't work

So what's going on is that I'm trying to make a set role/set channel command for logs and a mute role to mute people with and I'm wondering how to do this. I have looked at the docs and other stackoverflow threads and it still doesn't work.
if(!args[1]) return message.channel.send('Please specify a arg')
let roleName = args.slice(2).join(" ");
var role = message.guild.roles.cache.find(role => role.name === roleName)
if(!role){
message.channel.send("Thats not a role!")
}
if(role){
await GuildConfigSchema.update({ Guild: message.guild.id }, { MuteRole: role })
message.channel.send(`The mute role is now ${role}`)
}
First you can use if(role){ } else { } something like that and second on comments you said when I ping it for your code ping will not work because you use role.name if you want to catch role with ping then use let role = message.mentions.roles.first();

I'm trying to make leave/disconnect VC command for discord bot (js), I'm facing some issues discussed bellow

The code won't work perfectly, i find couple of issues:
When I'm connected to a VC and trying to attempt the command the bot leaves the VC but triggers two functions at a time i.e., General leave funtion and author not in the same channel.
When i give command being outside the VC(bot connected to the VC) the bot responds with function we are not in a same channel funtion., rather i want it to respond with you're not connected to VC
When i give command while being outside VC and bot not connected to VC, it responds nothing and at console i get error:
(node:37) UnhandledPromiseRejectionWarning: TypeError: cannot read property "id" of undefined
Code:
client.on('message', async (message) => {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'leave') {
let authorVoice = message.member.voice;
const embed1 = new discord.MessageEmbed()
.setTitle('🚫`You are not in a Voice Channel!`')
.setColor('RED')
.setTimestamp();
if (!authorVoice.channel) return message.channel.send(embed1);
const embed2 = new discord.MessageEmbed()
.setTitle('⛔`We are not in a same Voice Channel`')
.setColor('YELLOW')
.setTimestamp();
if (authorVoice.channel.id !== client.voice.channel.id)
return message.channel.send(embed2);
const embed = new discord.MessageEmbed()
.setTitle('`Successfully left the Voice Channel`✔')
.setColor('RED')
.setTimestamp();
authorVoice.channel.leave()
message.channel.send(embed);
}
});
Can someone help me fix it?
client.voice doesn't have a channel property. It means that client.voice.channel is undefined. When you try to read the id of it, you receive the error that you "cannot read property "id" of undefined".
You probably want the connections that is a collection of VoiceConnections. A connection does have a channel property but as client.voice.connections is a collection, you need to find the one you need first.
As you only want to check if a channel with the same ID exists, you can use the .some() method. In its callback function you check if any of the connections has the same channel ID as the message author's channel ID. So, instead of if(authorVoice.channel.id !== client.voice.channel.id) you could create a variable that returns a boolean. It returns true if the bot is in the same channel and false otherwise:
const botIsInSameChannel = client.voice.connections.some(
(c) => c.channel.id === authorVoice.channel.id,
);
// bot is not in the same channel
if (!botIsInSameChannel)
return message.channel.send(embed2);
Here is the updated code if anyone watching for:
client.on('message', async message => {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'leave') {
let authorVoice = message.member.voice;
const botIsInSameChannel = client.voice.connections.some(
(c) => c.channel.id === authorVoice.channel.id,
);
const embed1 = new discord.MessageEmbed()
.setTitle(':no_entry_sign: You are not in a Voice Channel!')
.setColor('RED')
.setTimestamp();
if(!authorVoice.channel) return message.channel.send(embed1);
const embed2 = new discord.MessageEmbed()
.setTitle(':no_entry: We are not in a same Voice Channel')
.setColor('YELLOW')
.setTimestamp();
if (!botIsInSameChannel) return message.channel.send(embed2)
const embed = new discord.MessageEmbed()
.setTitle('Successfully left the Voice Channel✔')
.setColor('RED')
.setTimestamp();
authorVoice.channel.leave();
message.channel.send(embed);
}
});

How to fix: roles is not defined (Discord.js)

I'm trying to add a role to a member when they join my server, here is the code I have:
The problem I'm getting is "ReferenceError: roles is not defined" can someone please help me solve this?
client.on("guildMemberAdd", (member) => {
console.log("User " + member.user.username + " has joined the server!");
var role = member.guild.roles.cache.find((role) => role.name === "Javjajjaj");
roles.add(role);
});
The problem is that the roles variable is never defined within your piece of code.
client.on("guildMemberAdd", GuildMember => {
// Logging when a GuildMember enters the Guild.
console.log(`${GuildMember.user.tag} joined ${GuildMember.guild.name}!`);
const Role = GuildMember.guild.roles.cache.find(role => role.name == "Javjajjaj"); // Finding the Role by name in the GuildMember's Guild.
// Checking if the role exists.
if (!Role) return console.error("Couldn't find the role!");
// Trying to add the Role to the GuildMember and catching any error(s).
GuildMember.roles.add(Role).catch(error => console.error(`Couldn't add the Role to the GuildMember. | ${error}`));
});

I am trying to make a guild add message

I am trying to make it so when my bot is added to another server, it will send an embed saying how many servers it's in now and the guild name and also the guild owner. I am also trying to make another embed so it tells me when it leaves a server and tells me when it joined the server first and then when it was removed and the guild name and guild owner. I use discord.js. Could someone help, please? This is my current script:
bot.on("guildCreate", guild => {
const joinserverembed = new Discord.MessageEmbed()
.setTitle("Joined a server!")
.addField("Guild name:", `${guild.name}`)
.addField("Time of join:", `${Discord.Guild.createdTimestamp()}`)
.setColor("GREEN")
.setThumbnail(guild.displayAvatarURL())
if (guilds.channel.id = 740121026683207760) {
channel.send(joinserverembed)
}
guild.channel.send("Thank you for inviting Ultra Bot Premium! Please use up!introduction and up!help for the new perks and more!")
})
bot.on("guildDelete", guild => {
const leftserverembed = new Discord.MessageEmbed()
.setTitle("Left a server!")
.addField("Guild name:", `${guild.name}`)
.addField("Time of removal:", `${createdTimestamp()}`)
.setColor("RED")
.setThumbnail(guild.displayAvatarURL())
if (guilds.channel.id = 740121026683207760) {
channel.send(leftserverembed)
}
})
I have resolved your first issue for you in the code below.
You were doing guild.channel.send(), in this case, guild represents a Discord.Guild however you're using it like it represents an instance of Message, which it does not.
You can use guild.channels.cache.find(x => x.name == 'general').send("Thanks for inviting me to this server¬!") will send a message to a channel named general in that server.
bot.on("guildCreate", (guild) => {
const joinserverembed = new Discord.MessageEmbed()
.setTitle("Joined a server!")
.addField("Guild name:", guild.name)
.addField("Time of join:", Date.now())
.setColor("GREEN")
.setThumbnail(guild.iconURL({ dynamic: true }));
bot.channels.cache.get("740121026683207760").send(joinserverembed);
guild.channels.cache
.filter((c) => c.type === "text")
.random()
.send(
"Thank you for inviting Ultra Bot Premium! Please use up!introduction and up!help for the new perks and more!"
);
});
I filter the channels in the guild, ensuring that they are not categories or voice channels, then send the welcome message to a random one.
As for your second query, you need to use a database, store the Date.now timestamp of when it was added, then once the bot has left the guild it must get the value and display its time. I haven't done this for you, but I have fixed your code:
bot.on("guildDelete", (guild) => {
const leftserverembed = new Discord.MessageEmbed()
.setTitle("Left a server!")
.addField("Guild name:", guild.name)
.addField("Time of removal:", Date.now())
.setColor("RED")
.setThumbnail(guild.iconURL({ dynamic: true }));
bot.channels.cache.get("740121026683207760").send(leftserverembed);
});

Categories

Resources