Discord.js: Cannot read property "roles" of undefined - javascript

Ive been working on a bot, and I am trying to get it to create a role and add it, it was working before, but now it is no longer working.
Here is the code:
exports.run = (client, message, args) => {
var member = message.mentions.members.first();
var sender = message.author;
var guild = message.guild;
var name = (message.author.username + "'s party")
var role = sender.guild.roles.cache.find(role => role.name === message.author.username + "'s party");
// sender.roles.add(role);
if (typeof role === undefined) {
let newRole = guild.roles.create({
data: {
name: name,
color: 'BLUE',
},
reason: 'Partee',
})
.then(console.log)
.catch(console.error);
member.roles.add(newRole);
message.channel.send("Your party has been created!")
} else {
member.roles.add(newRole);
message.channel.send("You have been added to your party!")
}
}
I dont know why it is going wrong. here is the error:
TypeError: Cannot read property 'roles' of undefined

I believe the problem is that message.author returns the user that sent the message. You would need the member. The member object returns more details about the user, by giving information on the user's position in a server/guild.
Just change the value of sender to message.member.
Example:
exports.run = (client, message, args) => {
var member = message.mentions.members.first();
var sender = message.member;
var guild = message.guild;
var name = (message.author.username + "'s party")
var role = sender.guild.roles.cache.find(role => role.name === message.author.username + "'s party");
// sender.roles.add(role);
if (typeof role === undefined) {
let newRole = guild.roles.create({
data: {
name: name,
color: 'BLUE',
},
reason: 'Partee',
})
.then(console.log)
.catch(console.error);
member.roles.add(newRole);
message.channel.send("Your party has been created!")
} else {
member.roles.add(newRole);
message.channel.send("You have been added to your party!")
}
}
Hopefully that works!

The message.author doesn't have a guild method, so calling this will return undefined. To make a role and give it to both author and mentioned user, I would do something like this for example:
if(message.author.bot === true) return;
if(message.channel.type === "dm") return;
const name = (message.author.username + "'s party");
const member = message.mentions.members.first();
if(member) {
const authorUser = message.guild.members.cache.get(message.author.id);
// Find the role first
const role = message.guild.roles.cache.find(role => role.name === name);
if(!role) {
// The role has not be found, create a new one.
// Create the new role and give it to the person
// Discord v12: { data: { name: "name", reason: "new role", ...properties } }
// Discord v13: { name: "name", reason: "new role", ...properties }
message.guild.roles.create({
data: {
name: name,
color: "BLUE",
},
reason: "The party has been started 🎉"
}).then(RoleCreated => {
authorUser.roles.add(RoleCreated)
.then(() => member.roles.add(RoleCreated))
.then(() => message.channel.send("PARTY HAS BEEN CREATED! LET'S GET THIS PARTY STARTED! 🎉"))
.catch((error) => {
console.log(error.message);
});
});
}else{
// Role exists, give it to the mentioned user
member.roles.add(role).then(() => message.channel.send("WELCOME TO MY PARTY! LET'S GET THIS PARTY STARTED! 🎉")).catch((error) => {
console.error(error.message);
});
}
}
! You might need to adjust the code to fit with your framework. I have tested this on Discord V13. Should work on V12 as well. Also note that if a user changes it's username, a new role will be created, so your server might get some ghost roles.

Related

Cant use any functions [Type error] Discord.js

The error:
TypeError: Cannot read properties of undefined (reading 'add') line 40
I looked everywhere like even in the discord API but nothing. If there is anything I can do better in my code tell me.
If it's necessary I use VSC and node.js.
The member is a variable and used in if() in the code but it doesn't work.
const { Client , GatewayIntentBits} = require('discord.js')
require('dotenv/config')
var not_stable = "⭕"
var working = "🔛"
var done = "✅"
var failed = "❌"
const client = new Client({
intents:[
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
})
client.on("ready", () => {
console.log("Bot is ready :D");
})
client.on("messageCreate", message => {
if(message.author == client.user) {
return;
}
var member = message.mentions.users.first();
var channel = message.channel;
var bug_channel = message.guild.channels.cache.find(r => r.id === "1030971519754588200");
var sup = message.guild.roles.cache.find(r => r.name == "Suporter")
var ping_sup = "<#&"+sup.id+"> "
if (message.content == "op <#"+member.id+">") {
if (member != undefined) {
let role = message.guild.roles.cache.find(r => r.id === "1030196677472178298");
try {
console.log(member)
member.roles.add(role); //my problem is at the add its not defined
}
catch(error) {
bug_channel.send(ping_sup+"Error while: \n"+error);
}
message.reply("BETA");
message.react(not_stable);
}
if (member === undefined) {
message.reply("There is no user in your command");
message.react(failed);
}
}
if (message.content === "ping") {
message.reply("PAMINHING pong");
message.react(done);
}
if (message.content === "timeout <#"+member.id+">") {
if (member === undefined) {
message.reply("Please do it manually");
message.react(failed)
}
else {
member.timeout(5 * 60 * 1000, 'Time to take a break');
message.reply("Timed out for 5min");
message.react(done);
}
}
if (message.content === "ids") {
message.reply("This is under construction and doesn't work");
}
})
client.login(process.env.TOKEN);
The error is always that noting after member. is recognised and I don't find the solution I'm new to js. ya thx for ya help :D
It's because your member variable is not a GuildMember, but a User. You try to get the roles of a User, but only GuildMembers have roles.
To fix this, you can use message.mentions.members.first() instead as message.mentions.members returns a GuildMember:
var member = message.mentions.members.first();

How can I check for a specific role in a different guild and make it a boolean?

const Command = require("../../Ana/Command")
const config = require("../../config.json")
const prefix = config.prefix;
module.exports = new Command({
name: "team",
aliases: ["tm"],
description: "Gives you your desired team.",
category: "Gamemaster",
run: async (bot, message, args, client, Discord) => {
await message.reply("Please wait!").then(async msg => {
var command = message.content.slice(prefix.length).split(" ")[0],
topic = message.content.split(" ")[1];
const isTRO = message.member.roles.cache.some(role => role.id === '948567643194003476') //Checks if you have a role in a different server, the bot is invited in that specific server
switch (command) {
case "team":
if (!topic) return message.channel.send('no team selected.... are you kid??');
if (topic === "TRO") {
return message.channel.send("Checking if you have access to TRO.")
if (isTRO = 'true') {
message.reply('You have access to TRO.')
}
}
}
})
}
})
I have tried multiple solutions
I am trying to check for a specific role in a guild
and give a role on the "Current" guild.
You can use the message.member.roles.cache.has() method to check if they have a role.
message.member.roles.cache.has('948567643194003476');

How to make a mute, unmute, tempmute command in discord.js

guys i am working on a discord bot i have ban,kick,nuke,ping commands but i need a mute , unmute, tempmute command but idk how to make all yt tutorial is so confusing and dont work please help me in making it
I am using discord.js v12
the prefix is $
i want the command to be $mute #user
this is my whole code since
const Discord = require("discord.js");
const client = new Discord.Client();
const express = require("express")
const app = express()
app.get("/", (req, res) =>{
console.log("helloe")
})
app.listen(3000, () => {
console.log("Ready")
})
const disbut = require('discord-buttons');
disbut(client);
client.once('ready', () => {
console.log('Beast Bot is ready');
client.user.setActivity('Discord Ping Messages || $help || (Made by CaptainBeast#1394) ', { type:"WATCHING"}).catch(console.error)
client.guilds.cache.forEach(guild => {
console.log(`${guild.name} | ${guild.id}`);
})
});
const ownerId = "602113193489203232";
const owner2Id = "725629309854679092";
client.on('clickButton', async(button) => {
})
client.on("message", async message => {
if (message.author.bot) return false;
if (message.mentions.has(ownerId)) {
message.reply(`Thanks for pinging my owner you will be banned with in 24 hours :))`);
};
if (message.mentions.has(owner2Id)) {
message.reply(`Thanks for pinging my co-owner you will be banned with in 24 hours :))`);
};
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'nuke'){
if (!message.member.hasPermission('ADMINISTRATOR')) {
message.channel.send('missing permissions')
}
message.channel.clone().then(channel => {
channel.setPosition(message.channel.position)
channel.send('nuked')
})
message.channel.delete()
}
if(message.content.startsWith("$download")){
let button = new disbut.MessageButton()
.setLabel("Download")
.setURL('http://www.beaststudios.ga')
.setStyle('url');
message.channel.send("Download Firebones at www.beaststudios.ga", button);
}
if(message.content.startsWith("~mute")) {
if(message.member.hasPermission("KICK_MEMBERS"))
{
message.reply(`Thanks for pinging my co-owner you will be banned with in 24 hours :))`);
}
};
if (!message.guild) return;
// if the message content starts with "!ban"
if (message.content.startsWith('$ban')) {
if (message.member.hasPermission("BAN_MEMBERS")) {
// Assuming we mention someone in the message, this will return the user
// Read more about mentions over at https://discord.js.org/#/docs/main/master/class/MessageMentions
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.members.resolve(user);
// If the member is in the guild
if (member) {
/**
* Ban the member
* Make sure you run this on a member, not a user!
* There are big differences between a user and a member
* Read more about what ban options there are over at
* https://discord.js.org/#/docs/main/master/class/GuildMember?scrollTo=ban
*/
member
.ban({
reason: 'They were bad!',
})
.then(() => {
// We let the message author know we were able to ban the person
message.channel.send(`Successfully banned ${user.tag} 🔨`);
})
.catch(err => {
// An error happened
// This is generally due to the bot not being able to ban the member,
// either due to missing permissions or role hierarchy
message.channel.send('I was unable to ban the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.channel.send("That user isn't in this guild!");
}
} else {
// Otherwise, if no user was mentioned
message.channel.send("You didn't mention the user to ban!");
}
} else {
message.channel.send('You dont have permission to ban 🔨')
}
}
if (message.content.startsWith('$kick')) {
if (message.member.hasPermission("KICK_MEMBERS")) {
// Assuming we mention someone in the message, this will return the user
// Read more about mentions over at https://discord.js.org/#/docs/main/master/class/MessageMentions
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.members.resolve(user);
// If the member is in the guild
if (member) {
/**
* Ban the member
* Make sure you run this on a member, not a user!
* There are big differences between a user and a member
* Read more about what ban options there are over at
* https://discord.js.org/#/docs/main/master/class/GuildMember?scrollTo=ban
*/
member
.kick({
reason: 'They were bad!',
})
.then(() => {
// We let the message author know we were able to ban the person
message.channel.send(`Successfully kicked ${user.tag}`);
})
.catch(err => {
// An error happened
// This is generally due to the bot not being able to ban the member,
// either due to missing permissions or role hierarchy
message.channel.send('I was unable to kick the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.channel.send("That user isn't in this guild!");
}
} else {
// Otherwise, if no user was mentioned
message.channel.send("You didn't mention the user to kick!");
}
} else {
message.channel.send('You dont have permission to kick')
}
}
});
// inside a command, event listener, etc.
const help = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Commands')
.setURL('')
.setAuthor('CaptainBeast', 'https://www.clipartmax.com/png/full/307-3072086_discord-icon-discord-icon-png.png')
.setDescription('Here are the list of some available commands')
.setThumbnail('https://www.clipartmax.com/png/full/307-3072086_discord-icon-discord-icon-png.png')
.addFields(
{ name: 'Commands', value: ':) commands' },
{ name: '\u200B', value: '\u200B' },
{ name: '$help', value: 'Displays list of available commands', inline: true },
{ name: '$ping', value: 'sent pong ', inline: true },
{ name: '$download', value: 'sent link to download firebones ', inline: true },
{ name: '$ban #user', value: 'Bans a member 🔨 ', inline: true },
{ name: '$kick #user', value: 'Kicks a member ', inline: true },
)
.addField('More stuffs coming soon', 'the bot is still under development', true)
.setImage('')
.setTimestamp()
.setFooter('Made by CaptainBeast#1394', 'https://www.clipartmax.com/png/full/307-3072086_discord-icon-discord-icon-png.png');
const prefix = "$";
client.on("message", (message) => {
// Exit and stop if it's not there
if (!message.content.startsWith(prefix)) return;
if (message.content.startsWith(prefix + "help")) {
message.channel.send(help);
} else
if (message.content.startsWith(prefix + "foo")) {
message.channel.send("bar!");
}
if (message.content.startsWith(prefix + "ping")) {
message.channel.send("pong!");
}
});
client.login('censored')
The best way to make a mute command is to remove talking permissions from "#everyone", and add the permissions to talk to your "member" rank.
So when the mute command is triggered the member rank will be removed, and a placeholder muted rank without extra permissions will be placed.
For further information on adding and removing roles check the documentation!

Can i set my created channels permisions like only my staff role can edit or delete it. My code so far:

I want my staff role can edit, delete this created channel.
client.on('message', message =>{
if (!message.content.startsWith('*open-channel')) return; //This line for some bug happens in my bot
if (message.channel.id !== '759430340972118026') return; // I set a channel for the users can only use
//this command in
if(message.author.bot || message.channel.type === "dm") return; //For bugs again
if(!message.member.roles.cache.some(role => role.name === 'OWNER')) { //This command only
//for owner role now.
return message.reply('You should be OWNER for using this command.').then(message => {
message.delete({ timeout: 8000 })
})
}
const messageArray = message.content.split(' ');
const cmd = messageArray[0];
const args = messageArray.slice(1).join(' ').toUpperCase();
if (message.content.startsWith('*open-channel'))
var kanal = message.guild.channels.create(`${args} - ${message.author.tag}`,{type : 'voice'})
.then(channel => channel.setParent(message.guild.channels.cache.find(channel => channel.name === "USER CHANNELS"))); //setParent moves my channel to choosen catagory. And 'args - message.author.tag' is channel name
message.channel.send("Its done now buddy :3");
})
Sorry for my bad english if i wrote something wrong. :(
You can use GuildChannelManager.create.options.permissionOverwrites(). Also, you can set the channel parent directly when creating it.
message.guild.channels.create(`${args} - ${message.author.tag}`, {
type: 'voice',
permissionOverwrites: [
{
id: '<Staff Role ID>',
allow: ['MANAGE_CHANNELS'],
},
],
parent: message.guild.channels.cache.find(
(channel) => channel.name === 'USER CHANNELS'
),
});

Server Stats piece of code updates the channel to undefined instead of the total members

so I've been creating a private bot for only one server that shows server stats and much more, but I have a problem; every time a user joins/leaves the guild, the bot updates a channel with 'undefined', but it's meant to be the number of members in total in that guild. Can someone help me? Here's the piece of code:
const serverStats = {
guildID: '474658204475719701',
totalUsersID: '578114537589309441',
};
client.on('guildMemberAdd', member => {
if (member.guild.id !== serverStats.guildID) return;
client.channels.get(serverStats.totalUsersID).setName(`📊 MEMBERS COUNT: ${member.guild.membersCount}`);
});
client.on('guildMemberRemove', member => {
if (member.guild.id !== serverStats.guildID) return;
client.channels.get(serverStats.totalUsersID).setName(`📊 MEMBERS COUNT: ${member.guild.membersCount}`);
});
Thank you.
membersCount is not a valid property of a Guild. It's actually memberCount (singular "member").
member.guild.memberCount
This code will return the expected member count.
This is what I use for my server-info command:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
let sicon = message.guild.iconURL;
let serverembed = new Discord.RichEmbed()
.setDescription("Server Information")
.setColor("#ff0000")
.setThumbnail(sicon)
.addField("Server Name", message.guild.name)
.addField("Created On", message.guild.createdAt)
.addField("You Joined", message.member.joinedAt)
.addField("Total Members", message.guild.memberCount)
.addField("Bot Version", "2.4.4")
message.channel.send(serverembed);
}
I hope you still need him
const embed = new Discord.RichEmbed()
.setDescription(`📊 MEMBERS COUNT: ${message.guild.members.filter(member => !member.user.bot).size}`)
.setThumbnail(message.guild.iconURL)
client.on('guildMemberAdd', member => {
if (member.guild.id !== serverStats.guildID) return;
client.channels.get(serverStats.totalUsersID).send(embed);
});
client.on('guildMemberRemove', member => {
if (member.guild.id !== serverStats.guildID) return;
client.channels.get(serverStats.totalUsersID).send(embed);
});

Categories