guild.member.hasPermission is not a function - javascript

I was rummaging through an old source of discord.js from v11, and merged most of it to v12, mind you this script is erroring within the ready event, I'd prefer not to put it elsewhere.
This is what I have for now:
client.on('ready', async () => {
log.success(`Authenticated as ${client.user.tag}`);
client.user.setPresence({
activity: {
name: env.PRESENCE_ACTIVITY,
type: env.PRESENCE_TYPE.toUpperCase(),
},
});
const guild = client.guilds.cache.find((g) => g.id === '000000000');
if (!guild)
return console.log(`Can't find any guild with the ID "${env.GUILD_ID}"`);
if (guild.member.hasPermission('ADMINISTRATOR', false)) {
log.success("Bot has the 'ADMINISTRATOR' permission");
} else
log.warn("Bot does not have 'ADMINISTRATOR' permission");
client.guilds.cache
.get(env.GUILD_ID)
.roles.fetch()
.then((roles) => {
goodieRole = roles.cache.get(env.GOODIE_ROLE_ID);
});
});

There is no member property on guilds. If you want to get the bot as a member of that guild, you can fetch() them from guild.members. If you're using discord.js v12, you can use the hasPermission() method to check if the bot has an ADMINISTRATOR flag:
client.on('ready', async () => {
log.success(`Authenticated as ${client.user.tag}`);
client.user.setPresence({
activity: {
name: env.PRESENCE_ACTIVITY,
type: env.PRESENCE_TYPE.toUpperCase(),
},
});
const guild = client.guilds.cache.get(env.GUILD_ID);
if (!guild)
return console.log(`Can't find any guild with the ID "${env.GUILD_ID}"`);
let botMember = await guild.members.fetch(client.user);
if (botMember.hasPermission('ADMINISTRATOR', false)) {
log.success("Bot has the 'ADMINISTRATOR' permission");
} else
log.warn("Bot does not have 'ADMINISTRATOR' permission");
// ...

Related

How to add an array of roles to member at once discord.js v13

I want to add the "Auto-Role System" to my discord bot.
I was doing well but it went into an error, You can check the end of the article for errors.
What I want to do is:
The owner uses the command by mentioning a role or a bunch of roles
Bot stores them in an array and then saves it on the database
When a user joined the guild, the bot gives that roles array to a member
So at first, we need to make a model for the database so I did create one:
// Guild.js
const mongoose = require('mongoose');
const guildConfigSchema = mongoose.Schema({
guildId: { type: String, match: /\d{18}/igm, required: true },
autoRoleDisabled: {
type: Boolean,
},
autoRoleRoles: {type: Array},
});
module.exports = mongoose.model('guild', guildConfigSchema);
Then I coded the setup command:
const role = message.mentions.roles.first();
if (!role) return message.channel.send('Please Mention the Role you want to add to other Auto Roles.');
Schema.findOne({ guildId: message.guild.id }, async (err, data) => {
if (data) {
data.autoRoleDisabled = false;
data.autoRoleRoles.push(role.id);
data.save();
} else {
new Schema({
guildId: message.guild.id,
autoRoleDisabled: false,
$push: { autoRoleRoles: role.id }
}).save();
}
message.channel.send('Role Added: ' + `<#&${role.id}>`);
})
In the end we need to make it work:
// Main.js
client.on("guildMemberAdd", async (member) => {
// ****Auto-Role****
const Welcome = require('./models/Guild');
try {
Welcome.findOne({ guildId: member.guild.id }, async (err, data) => {
if (!data) {
return;
} else {
if (data.autoRoleDisabled == false) {
let roles = data.autoRoleRoles;
roles.forEach(r => {
guildRrole = member.guild.roles.cache.find(role => role.id)
member.roles.add(guildRrole);
})
} else {
return;
}
}
});
} catch (e) {
console.log(e);
}
});
But it doesn't work and gives an error:
Error: cyclic dependency detected
at serializeObject (C:\Users\Pooyan\Desktop\PDMBot\node_modules\bson\lib\bson\parser\serializer.js:333:34)
And I think the problem is from pushing role IDs in the array.
Notes: I am using discord.js#13.8.0 and Node.js v16
You can simply change
guildRrole = member.guild.roles.cache.find(role => role.id)
member.roles.add(guildRrole);
to
guildRrole = member.guild.roles.cache.get(r);
if (!guildRrole) return;
member.roles.add(guildRrole);
because you are not finding role with id, you just did .find(role => role.id) which just gives role id so you have to check role id with your role id if you want to do with .find() like:
.find((role) => {
role.id === r
})

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

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.

discord.js error "channel is not defined"

So im making a mute command which creates a mute role and gives it to the mentioned user, and currently i am getting an error: channel is not defined,
I do not know how to fix this error and i need help with this
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send("I do not have Permission to mute members.");
let reason = args.slice(1).join(' ');
let roleName = 'Muted';
let muteRole = message.guild.roles.cache.find(x => x.name === roleName);
if (typeof muteRole === undefined) {
guild.roles.create({ data: { name: 'Muted', permissions: ['SEND_MESSAGES', 'ADD_REACTIONS'] } });
} else {
}
muteRole = message.guild.roles.cache.find(x => x.name === roleName);
channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });
const mentionedMember = message.mentions.member.first() || message.guild.members.cache.get(args[0]);
const muteEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setImage(message.mentionedMember.displayAvatarURL());
if (!args[0]) return message.channel.send('You must mention a user to mute.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == message.author.id) return message.channel.send('You cannot mute yourself.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You cannot mute me smh.');
if (!reason) reason = 'No reason given.';
if (mentionedMember.roles.cache.has(muteRole.id)) return message.channel.send('This user has already been muted.');
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.chanel.send('You cannot mute someone whos role is higher and/or the same as yours');
await mentionedMember.send(muteEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muteRole.id).catch(err => console.log(err).then(message.channel.send('There was an issue while muting the mentioned Member')));
}
}
I beileive that there could be even more errors than i think in this code as I am fairly new to coding.
You have used "channel" without declaring it. Hence, it is undefined.
check your line "channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });"
const { Client, Intents } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
});
});
Please refer the below links
Discord.JS documentation: https://github.com/discordjs/discord.js
Stack-overflow answer: Discord.js sending a message to a specific channel

DiscordJS Play audio file on voice channel

I followed some tutorials and mixed some of the codes around and it works but I'm having difficulty understanding async with message.guild.channels.forEach no matter how i play to change it.
I want the bot to join only the voice channel where the user typed 'test' without running on all voice channels.
thank you
exports.run = async (client, message, args, level) => {
async function play(channel) {
await channel.join().then(async (connection) => {
let dispatcher = await connection.playFile('./img/aniroze.mp3');
await dispatcher.on('end', function () {
message.channel.send("🎧 **x** 🎧").then(sentEmbed => {
sentEmbed.react("👍")
sentEmbed.react("👎")
channel.leave();});
});
});
}
let timer = 10000;
message.guild.channels.forEach(async (channel) => {
if (channel.type == 'voice' && channel.members.size > 1) {
const embed2 = new Discord.RichEmbed()
.setTitle('🎧 🎧')
.setColor("#3498DB")
.setThumbnail(`${message.author.displayAvatarURL}`)
.setTimestamp()
message.channel.send(embed2);
setTimeout(function () {
play(channel);
}, timer);
}});
setTimeout(function () {
}, timer);
};
exports.conf = {
enabled: true,
aliases: ['test'],
guildOnly: true,
permLevel: 'User'
}
If you want the bot to join the voice channel of the user that sent the command then use this:
const voiceChannel = message.member.voiceChannel
if (!voiceChannel) return message.reply('you are not in a voice channel')
voiceChannel.join()
Note: This is a discord.js v11 answer, for v12 replace member.voiceChannel with member.voice.channel

bot's username is not defined

I am getting this error UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined which is caused by client.user.username in embed's .setFooter().
module.exports = {
name: 'suggest',
aliases: ['sug', 'suggestion'],
description: 'Suggest something for the Bot',
execute(message, client, args) {
const Discord = require('discord.js');
const filter = m => m.author.id === message.author.id;
message.channel.send(`Please provide a suggestion for the Bot or cancel this command with "cancel"!`)
message.channel.awaitMessages(filter, { max: 1, })
.then(async (collected) => {
if (collected.first().content.toLowerCase() === 'cancel') {
message.reply("Your suggestion has been cancelled.")
}
else {
let embed = new Discord.MessageEmbed()
.setFooter(client.user.username, client.user.displayAvatarURL)
.setTimestamp()
.addField(`New Suggestion from:`, `**${message.author.tag}**`)
.addField(`New Suggestion:`, `${collected.first().content}`)
.setColor('0x0099ff');
client.channels.fetch("702825446248808519").send(embed)
message.channel.send(`Your suggestion has been filled to the staff team. Thank you!`)
}
})
},
catch(err) {
console.log(err)
}
};
According to your comment here
try { command.execute(message, args); } catch (error) { console.error(error); message.reply('There was an error trying to execute that command!'); } });
You are not passing client into execute(), you need to do that.
You also need to use await on channels.fetch() since it returns a promise so replace client.channels.fetch("702825446248808519").send(embed) with:
const channel = await client.channels.fetch("702825446248808519")
channel.send(embed)

Categories