Discord bot add role - discord

I'm trying to add a mute command
This is my current code:
if (message.member.roles.cache.some(role => role.name === 'Admin')) {
let target = message.mentions.members.first;
let role = message.member.guild.roles.cache.find(role => role.name === "muted");
target.roles.add(role);
message.channel.send('${user} has been muted by ${message.author.username}');
}
I'm getting this error:
(node:11052) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined

I recommend you use Roles#has for searching for a member role
if (message.member.roles.cache.has('role-id') { ... }
Collection#first is a method, not a property, add () to first
let target = message.mentions.members.first();
You are getting Cannot read property 'add' of undefined because you did not properly acces the first mention
Here is all the code fixed and put together:
if (message.member.roles.cache.has('ROLE-ID-HERE')) {
let target = message.mentions.members.first();
let role = message.member.guild.roles.cache.find(role => role.name === "muted");
target.roles.add(role);
message.channel.send('${user} has been muted by ${message.author.username}');
}

Related

TypeError: Cannot read property 'activities' of null

My problem is that when the user starts a game and has the game status in discord, on the console I get the error "TypeError: Unable to read property 'activities' of null"
I hope the bot gives the member a role when starting the game. I'm using a game as an example, I need the function when starting the stream
Discord.js - v13 Code:
const client = require('../index')
client.on('presenceUpdate', function(oldMember, newMember) {
const guild = newMember.guild;
const streamingRole = guild.roles.cache.find(role => role.name === 'Fazendo Live');
// if (newMember.user.bot || newMember.presence.clientStatus === 'mobile' || oldMember.status !== newMember.status) return;
const oldGame = oldMember.activities ? oldMember.activities.find(activity => activity.type === 'PLAYING') : false;
const newGame = newMember.activities ? newMember.activities.find(activity => activity.type === 'PLAYING') : false;
if (!oldGame && newGame) { // Started playing.
newMember.member.roles.add(streamingRole)
.then(() => console.log(`${streamingRole.name} added to ${newMember.user.tag}.`))
.catch(console.error);
}
else if (oldGame && !newGame) { // Stopped playing.
newMember.member.roles.remove(streamingRole)
.then(() => console.log(`${streamingRole.name} removed from ${newMember.user.tag}.`))
.catch(console.error);
}
});
member.activities is not a thing. You need to go through presence first to go through activities.
const oldGame = oldMember.presence.activities ? oldMember.presence.activities.find(activity => activity.type === 'PLAYING') : false;
const newGame = newMember.presence.activities ? newMember.presence.activities.find(activity => activity.type === 'PLAYING') : false;
Did more digging...
...and found out that presenceUpdate actually outputs old and new presences and not the member. So in that way you are correct with
const oldGame = oldMember.activities
Now while doing my own testings I came across that when trying simply doing message.member.presence and console logging that, it comes out as null, and this is because I had no Intents set to my client for GUILD_PRESENCES now when I enabled this, it showed me the activity.
So my guess is that if you are getting null from it, or the error that Cannot read properties of null (reading 'activities') which I got aswell (before declaring intents), you might be setting your intents wrong.
Are you sure you have declared your intents correctly in index.js?
Mine for example:
const { Client, Intents } = require("discord.js");
client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_PRESENCES]
});

Discord.js v12 Role add to mentioned user problem

so I am trying to make a command like $roletested #user which should give the user mentioned the specific role. I get an error called:_ "Cannot read property 'roles' of undefined... Help me out please, here's my code :D
if (message.content.startsWith(prefix + "roletested")) {
let testedUser = message.mentions.members.first()
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'));
if(!testedUser) return message.channel.send("You have to mention the person you want to assign the role to!").then((declineMsg) => { message.react('❌');
declineMsg.delete({timeout: 5000});
let testedRole = message.guild.roles.cache.find(role => role.id === "724676382776492113");
testedUser.roles.add(testedRole);
message.channel.send("Added the role `TESTED` to user.")
})}})
Your code but fixed
if (message.content.startsWith(prefix + "roletested")) {
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'))
let testedRole = message.guild.roles.cache.get('724676382776492113');
let testedUser = message.mentions.members.first();
if(!testedUser) return message.channel.send("You have to mention the person you want to assign the role to!").then((declineMsg) => { message.react('❌')
declineMsg.delete({timeout: 5000});
});
testedUser.roles.add(testedRole);
message.channel.send("Added the role `TESTED` to user.")
}
I fixed your code :
I put in order something (the code is the same, I only changed something)
You can't use message.guild.roles.cache.find(...) so I changed it to message.guild.role.cache.get('Role ID')
Source : Link
Code :
if (message.content.startsWith(prefix + 'roletested')) {
const testedUser = message.mentions.members.first();
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'));
if (!testedUser) {
message.channel.send('You have to mention the person you want to assign the role to!').then(declineMsg => {
message.react('❌');
declineMsg.delete({ timeout: 5000 });
return;
});
}
const testedRole = message.guild.roles.cache.get('395671618912780289');
testedUser.roles.add(testedRole);
message.channel.send('Added the role `TESTED` to user.');
}
I tested this code on my bot and it worked as expected.

Discord.js removing role

I am trying to make a mute command using roles but I keep getting the error saying remove role is not a function. Im confused
let mainrole = message.guild.roles.cache.find(role => role.name === "Verified");
let role = message.guild.roles.cache.find(role => role.name === "Muted");
if (!role) return message.reply("Sorry! Couldn't find the mute role.")
let time = args[2];
if (!time) {
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function() {
person.addRole(mainrole.id)
person.removeRole(role.id);
Error: TypeError: person.removeRole is not a function
Since discord.js v12 you need to use roles.add() and roles.remove() instead of addRole() and removeRole()
person.roles.remove(mainrole.id)
person.roles.add(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function() {
person.roles.add(mainrole.id)
person.roles.remove(role.id);

TypeError [INVALID_TYPE]: Supplied options is not an object

Code:
client.on('message', message => {
if (message.content.startsWith(`${prefix2}red`)){
if (message.member.roles.cache.some(role => role.name === 'streamer')) return message.channel.send("You already has that role")
let role = message.guild.roles.cache.find(r => r.name === 'streamer');
let member = message.member;
message.delete(1)
member.addRole(role).catch(console.error)
}
})
Error Is:
if (typeof options !== 'object') throw new TypeError('INVALID_TYPE','options', 'object', true);
^
TypeError [INVALID_TYPE]: Supplied options is not an object
not sure what I did to make this happen
Discord.JS doesn't accept a number anymore in message.delete() according to the documentation, message#delete only accepts an object. For your case it would be: message.delete({ timeout: 1 }) but for that amount of time, you don't need to provide anything at all, unless you meant 1 second which would instead be message.delete({ timeout: 1000 }).

How do I check if the bot has permmsion to manage webhooks?

My problem is that I'm getting an error whenever I use the following code:
else if (cmd === "sayw") {
const embed2 = new Discord.RichEmbed()
.setDescription("❌ You can't make me say nothing! \nWait, you just did-")
.setFooter(`Requsted by ${message.author.tag}.`, message.author.avatarURL)
if(!args[0]) return message.channel.send(embed2)
const guild = message.guild
const embed = new Discord.RichEmbed()
.setAuthor("Say Webhook", bot.user.avatarURL)
.setDescription("❌ I need the `MANAGE_WEBHOOKS` permision first!" )
.setImage(`https://i.gyazo.com/d1d5dc57aa1dd20d38a22b2f0d4bd2f6.png`)
const member = guild.members.get(bot.id)
if (member.hasPermission("MANAGE_WEBHOOKS")) {
message.channel.createWebhook(message.author.username, message.author.avatarURL)
.then(webhook => webhook.edit(message.author.username, message.author.avatarURL))
.then(wb => {wb.send(args.join(" "))
setTimeout(() => {
bot.fetchWebhook(wb.id, wb.token)
.then(webhook => {
console.log("deleted!")
webhook.delete("Deleted!")
}, 5000)})})
} else {
message.channel.send(embed)
}}
I want the bot to tell the user if it can't create the webhook, but instead, I get this error when trying to use this command:
(node:10044) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of undefined
How do I make this code work?
If you're using Discord.js v12 (the latest verison), guild.members.get(bot.id) won't work as guild.memebrs is now a GuildMemberManager.
Use
const member = guild.members.cache.get(bot.id)
or you could even use this as a shortcut:
const member = guild.me

Resources