Trying to add a role to a mentioned user - javascript

I am trying to make a bot for a game of tag. I am making it so you can mention a user and it adds the 'IT' role to them, but when they don't mention a member, it's added to them. My code is here:
const args = message.content.slice(prefix.length).trim().split(/ +/g);
if (message.content.startsWith(`${prefix}tag`)) {
if (!message.mentions.users.size) {
let roleenter = message.guild.roles.get("555947490315075600");
let member = message.member;
member.addRole(roleenter).catch(console.error);
message.reply("you are now it!")
client.channels.get("555943069271457792").send(member + " is now in!")
await message.guild.fetchMembers();
const role = message.guild.roles.get("555947490315075600");
for (const member of role.members.array()) {
await member.removeRole(role);
}} else {
let member = message.mentions.users.first();
let roleenter = message.guild.roles.get("555947490315075600");
member.addRole(roleenter).catch(console.error);
message.reply("you are now it!")
client.channels.get("555943069271457792").send(member + " is now in!")
await message.guild.fetchMembers();
const role = message.guild.roles.get("555947490315075600");
for (const member of role.members.array()) {
await member.removeRole(role);
Whenever I try #tag #user, it says member.addRole is not a function when I use it earlier on and it works.

Change this line:
let member = message.mentions.users.first();
To this line:
let member = message.mentions.members.first();
You used the user Object of the mentioned user, but you have to use the guildMember Object because you can‘t assign a role to an user.

Related

Check if the message sender has a specific role

I'm new in Discord bot coding and I want to create a command where the bot only replies if the message sender has a specific role.
According to the discord.js documentation I have to use GuildMemberRoleManager.cache. Sadly, it isn't working.
The whole command looks like this:
client.on('messageCreate', (message) => {
if (
message.content.toLowerCase() === prefix + 'test' &&
GuildMemberRoleManager.cache.has(AdminRole)
)
message.reply('test');
});
You should get the author's roles. Only members have roles, so you will need to get the author as a member using message.member. message.member returns a GuildMember and GuildMembers have a roles property that returns a GuildMemberRoleManager (the one you mentioned in your original post).
Its cache property is a collection of the roles of this member, so you can use its has() method to check if the user has the admin role:
client.on('messageCreate', (message) => {
let adminRole = 'ADMIN_ROLE';
let isAdmin = message.member.roles.cache.has(adminRole);
if (message.content.toLowerCase() === prefix + 'test' && isAdmin)
message.reply('test');
});
Define the variables which will make you easy to understand as you are new
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
and make if statement like
if(member.roles.cache.has(role.id)) {
return message.channel.send("test")
}
if you want bot to check if user have administrator perm than
message.member.hasPermission('ADMINISTRATOR')
Check all perm flags on Discord Perm Flags
So according to your code it will be
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
client.on("messageCreate",(message) => {
if(message.content.toLowerCase() === prefix + "test" && member.roles.cache.has(role.id))
message.reply("test")
})

How do I use Repl.it's database?

I need my bot to save user violations to a database when a user uses a command. For example, when #violate #user red light pass is used, the bot should save the red light pass to the database for the mentioned user. I'm using Repl.it's database and this is my code:
client.on("message", async message => {
if (message.content.toLowerCase().startsWith("#violations")) {
let violation = await db.get(`wallet_${message.author.id}`)
if (violation === null) violation = "you dont have any tickets"
let pembed = new Discord.MessageEmbed()
.setTitle(`${message.author.username} violations`)
.setDescription(`المخالفات المرورية : ${violation}`)
.setColor("RANDOM")
.setFooter("L.S.P.D")
message.channel.send(pembed)
}
if (message.channel.id === '844933512514633768') {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
console.log(args);
const command = args.shift().toLowerCase();
if (command == 'red light pass') {
const member = message.mentions.members.first(); //
let light = "red lightpass"
await db.set(`wallet_${memeber}`, light)
}
}
})
First of all, in `wallet_${memeber}`, memeber is not defined. You probably intended to use `wallet_${member}`.
I believe the issue is you're using the key `wallet_${message.author.id}` (e.g. 'wallet_12345') to get the violation/ticket, but then `wallet_${member}` (e.g. 'wallet_<#12345>') (e.g. 'wallet) to set the violation. Interpolating a GuildMember in a string calls its toString method, which creates a string of the mention of the member, not the id.
Also, it's good practice to use === instead of == as == casts the items being compared so things like 3 == '03' and [] == false are true.
The final code should like this:
if (command === "red light pass") {
const member = message.mentions.members.first();
const light = "red lightpass";
// Note how I've changed this to member.id (which is just a shortcut for
// member.user.id) from memeber
await db.set(`wallet_${member.id}`, light);
}

Role is not getting added to member [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have some code that detects when someone enters the command role and gives them the role with the name of the first argument passed to the command (args[0]). For example, the bot would try to detect something like !role nameOfTheRole, which would give the user the role with the name nameOfTheRole.
However, the code is not working and I'm not sure why. Here is what I have mnaged to get so far:
var cmdmap = {
role: gimmerole
}
function gimmerole(member, args, message) {
var memb = message.member() //<------- ERROR
const role = memb.guild.roles.find(r => r.name == args[0])
memb.roles.add(role)
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild
if (author.id != client.user.id && cont.startsWith(config.prefix)) {
var invoke = cont.split(' ')[0].substr(config.prefix.length),
args = cont.split(' ').slice(1)
console.log(invoke, args)
if (invoke in cmdmap) {
cmdmap[invoke](msg, args)
}
}
})
I have made a few modifications to your code:
I changed the line function gimmerole(member, args, message) { to function gimmerole(message, args) {, as in the line cmdmap[invoke](msg, args);, you are calling it with the message object and the arguments, so the message was getting assigned to member instead and message would have been undefined.
I changed message.member() to message.member, as member is a property of message, not a method.
I also changed the code that parses the message and splits it into a command and arguments so that it's a lot cleaner.
Added a sanity check (if (!role) return console.log(`The role "${args[0]}" does not exist`);) to make the bot log to the console if the role does not exist.
Changed args[0] to args.join(' ') to enable roles with spaces to be specified.
var cmdmap = {
role: gimmerole
};
function gimmerole(message, args) {
const member = message.member;
const role = message.guild.roles.cache.find(r => r.name === args.join(' '));
if (!role) return console.log(`The role "${args.join(' ')}" does not exist`);
member.roles.add(role);
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild;
if (author.id !== client.user.id && cont.startsWith(config.prefix)) {
const [invoke, ...args] = cont.slice(config.prefix.length).trim().split(' ');
console.log(invoke, args);
if (invoke in cmdmap) {
cmdmap[invoke](msg, args);
}
}
})
There is the Discord.js Guide that you can use if you want something to follow along with. It is really helpful and detailed.
I have noticed you're improperly trying to find a role. In order to get a full roles collection, you will need to use the cache method of message.guild.roles, resulting in the line:
const roleObject = memb.guild.roles.cache.find(...);
var cmdmap = {
role: gimmerole
};
function gimmerole(message, args) {
const member = message.member;
const role = message.guild.roles.cache.find(r => r.name === args.join(' '));
if (!role) return console.log(`The role "${args.join(' ')}" does not exist`);
member.roles.add(role);
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild;
if (author.id !== client.user.id && cont.startsWith(config.prefix)) {
const [invoke, ...args] = cont.slice(config.prefix.length).trim().split(' ');
console.log(invoke, args);
if (invoke in cmdmap) {
cmdmap[invoke](msg, args);
}
}
}
Credits to Deamon Beast

First name mentions in a text using discord.js

I am trying to make some sort of kick system. I would like to know how I would get the first name mentioned in a text.
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS"],["BAN_MEMBERS"])){
if(message.content == "!kick"){
let member = message.mentions.members();
console.log(member)
member.kick("You have been kicked").then ((member) => {
message.channel.send( member.displayName + " has been Kicked!");
})
}
}
});
No error is thrown that I know of.
First off, if you want to check multiple permissions in GuildMember.hasPermission(), you need to pass an array. The way your code is written now, you're passing an array with "KICK_MEMBERS" as the permissions to check and an array with "BAN_MEMBERS" for the explicit parameter.
Solution: message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMEBRS"])
Secondly, you're declaring member as a Collection, when it should be a GuildMember.
Solution: const member = message.mentions.members.first()
client.on("message", async message => {
if (message.content === "!kick" && message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
try {
const member = message.mentions.members.first();
if (!member) return await message.channel.send(`No user mentioned.`);
await member.kick(`Kicked by ${message.author.tag}`);
await message.channel.send(`${member.user.tag} has been kicked.`);
} catch(err) {
console.error(err);
}
}
});

I am trying to make a discord.js avatar command, and the mentioning portion doesn't work correctly

I have an avatar command in my discord bot. When the user uses h.avatar, it outputs their avatar, which works fine. Whenever they try to use h.avatar #user, nothing happens.
Here is my code:
} if (message.content.startsWith(config.prefix + "avatar")) {
if (!message.mentions.users.size) {
const avatarAuthor = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(message.author.username)
.setImage(message.author.avatarURL)
message.channel.send(avatarAuthor);
let mention = message.mentions.members.first();
const avatarMention = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(mention.user.username)
.setImage(mention.user.avatarURL)
message.channel.send(avatarMention);
You have a check if (!message.mentions.users.size) { which makes the command run only if you do not mention somebody. You either need to use an else { in your code or do:
if (message.content.startsWith(config.prefix + 'avatar')) {
const user = message.mentions.users.first() || message.author;
const avatarEmbed = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(user.username)
.setImage(user.avatarURL);
message.channel.send(avatarEmbed);
}
The const user = message.mentions.users.first() || message.author; tries to get the user that was mentioned but if it does not find anyone it will use the author's used.
This can also be used like this:
if (!message.mentions.users.size) {
message.channel.send('Nobody was mentioned');
return;
}
// continue command here, after guard clause
There's nothing like avatarUrl unless you have defined it.
Use this code to get the url of a user:
message.channel.send("https://cdn.discordapp.com/avatars/"+message.author.id+"/"+message.author.avatar+".jpeg");
Just replacemessage.author with the user who is mentioned
These is the updated version of the answer that works
if (message.content.startsWith(config.prefix + 'avatar')) {
const user = msg.mentions.users.first() || msg.author;
const avatarEmbed = new MessageEmbed()
.setColor(0x333333)
.setAuthor(`${user.username}'s Avatar`)
.setImage(
`https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=256`
);
msg.lineReply(avatarEmbed);
}
This uses discord's avatar url, and msg.lineReply(avatarEmbed); is a function that sends the embed as a reply to the message
My
if (msg.content.startsWith(prefix + 'avatar')) {
const user = msg.mentions.users.first() || msg.author;
const avatarEmbed = new MessageEmbed()
.setColor('')
.setAuthor(`${user.username}'s Avatar`)
.setImage(
`https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=256`
);
msg.reply(avatarEmbed);
}
if(message.content.startsWith(prefix+'av')){
if(message.mentions.users.size){
let member=message.mentions.users.first()
if(member){
const emb=new Discord.MessageEmbed().setImage(member.displayAvatarURL()).setTitle(member.username)
message.channel.send(emb)
}
else{
message.channel.send("Sorry none found with that name")
}
}else{
const emb=new Discord.MessageEmbed().setImage(message.author.displayAvatarURL()).setTitle(message.author.username)
message.channel.send(emb)
}
}
if (message.content.startsWith(prefix + 'avatar')) {
let user = message.mentions.users.first();
if(!user) user = message.author;
let color = message.member.displayHexColor;
if (color == '#000000') color = message.member.hoistRole.hexColor;
const embed = new Discord.RichEmbed()
.setImage(user.avatarURL)
.setColor(color)
message.channel.send({embed});
}

Categories