Mentions, createdAt field - discord.js

I cannot fix the error for mentioning third-party users, errors start on 'Roles' and the server login date, the date the account was created.
Please Help.
... [cut]
} else if (command === 'user') {
let user = message.mentions.users.first() || message.author;
const embed = new Discord.RichEmbed()
.setAuthor(`Akirabot. Find of user.`)
.setColor(0x348fcd)
.setTitle('')
.addField(`Username`,`${user.username}`, true)
.addField(`User id`,`${user.id}`, true)
.addField(`Status`,`${user.presence.status}`, true)
.addField(`Date of create account`, `${moment(user.createdAt).toString().substr(0, 15)}\n(${moment(user.createdAt).fromNow()})`, true)
.addField("Currently Playing", user.presence.game || "Nothing.", true)
.addField(`Join date to server`, `${moment(user.joinedAt).toString().substr(0, 15)}\n(${moment(user.joinedAt).fromNow()})`, true)
.addField('Roles', `${user.members.roles}.`, true)
.setFooter(`— Akirabot, made with love by setosh, 2019.`)
.setTimestamp('')
.setThumbnail(`${user.displayAvatarURL}`)
message.channel.send({ embed });
I get this error message
TypeError: Cannot read property 'roles' of undefined

The User class (which is what both message.mentions.users.first() and message.author return) doesn't have a members property, so you're trying to access something that doesn't exist.
If you want to find out a person's roles you'll have to get a GuildMember representation of that person. One way of doing that is like this:
const guildMember = message.guild.members.find(val => val.id === user.id);
Then you can do guildMember.roles and use that however you like.
Example:
let user = message.mentions.users.first() || message.author;
const guildMember = message.guild.members.find(val => val.id === user.id);
const embed = new Discord.RichEmbed()
// Do whatever you want with the roles:
.addField('Roles', `${guildMember.roles}.`, true)

Related

How could i use user id instead of mention on discord.js to give role?

This is my code for mentions but I want to use id instead
if (message.member.roles.cache.some(r => r.name === "Mod")) {
if (message.mentions.members.first()) {
let role = message.guild.roles.cache.find(r => r.name === "Muted");
let member = message.mentions.members.first();
member.roles.add(role);
message.channel.send(member);
}
}
Here is what I say for mention: moder! Mute #bigboitest
What I want to do: moder! Mute 862743465594191882
Simply, to get the user from their ID you'll need to find the ID in a message and then search for it in the clients users.
Example:
let args = <Message>.content.split(/ +/g); // Define message arguments
let member = <Message>.mentions.users.first() || <Message>.guild.members.fetch(args[2]); // Get the user from a mention or ID
Full example:
if (message.member.roles.cache.some(r => (r.name).toLowerCase() === "mod")) { // Search for the role "Mod"
let role = message.guild.roles.cache.find(r => (r.name).toLowerCase() === "muted"); // Search for the "Muted" role
let args = message.content.split(/ +/g); // Define message arguments
let member = message.mentions.members.first() || message.guild.members.fetch(args[2]); // Get the user from a mention or ID
if (!role) return message.channel.send('I cannot find a muted role'); // If the role doesn't exist, notify the user
if (!member) return message.channel.send(`<#!${message.author.id}>, ${member} is not in this server`); // If the member doesn't exist
member.roles.add(role); // Mute the member by adding the muted role
message.channel.send(`<#!${member.user.id}> was muted by <#!${message.author.id}`); // Send a response
} else {
message.channel.send('You are not a mod'); // Notify the user that they are not able to use the command
}

How do I compare the ID of the new members with the ones in the database?

I am trying to make a jail command when the members who has this role leave the server and rejoin again the role stay with them ,i want when new members enter the server to compare their ID with the one in the database, if is it true it gives a role again. my code:
client.on("guildMemberAdd",async (member)=>{
let injail = await db.fetch(`ja_${member.guild.id}`)
let role = msg.guild.roles.cache.find(n => n.name === 'Jail');
if(member.guild.id = injail){
member.roles.remove(user.roles.cache)
member.roles.add(role)
}
});
client.on('message', msg => {
if(msg.content.startsWith(prefix + 'jail')){
if(!owners.includes(msg.author.id)) return msg.channel.send("**You Dont Have Perms 📛**")
if(!msg.channel.guild) return;
var logChannel = msg.guild.channels.cache.find(channel => channel.id === logID)//LOG
let jailRole = msg.guild.roles.cache.find(n => n.name === 'Jail');
let user = msg.mentions.members.first() //You can change this to an ID
let args = msg.content.split(" ").slice(1).join(" ")
if(!args[0]) return msg.channel.send('**:x: Please Mention A User**')
if(user.hasPermission("ADMINISTRATOR")) return msg.channel.send("**Im NOT Allowed To Do This 📛**")
let there = db.get(`jl_${msg.guild.id}_${user}`, user.id)
if (there) return msg.channel.send('**This User AlREADY In Jail ⛔**')
msg.channel.send(`**ADDED ${user} to the Jail! ✅**`)
db.set(`jl_${msg.guild.id}_${user}`, user.id)
user.roles.remove(user.roles.cache)
user.roles.add(jailRole)
let embed = new Discord.MessageEmbed()
.setTitle('Jail System')
.setAuthor(msg.author.tag,msg.author.avatarURL({dynamic:true}))
.addField("Status",`JOINED THE JAIL 🔴`)
.addField("User",`<#${user.id}> (ID: ${user.id})`)
.addField("By",`<#${msg.author.id}> (ID: ${msg.author.id})`)
.setTimestamp()
logChannel.send(embed)
}
});
Whenever people gets "jail" role, save "yes" to database.
and check condition as you did above.
here I'll give sample code:
// when people gets jail role, add following code:
db.set(`ja_${msg.guild.id}_${user}`, "yes") // or you can simply use boolean operator
// when guildMemberAdd event triggers check condition:
let condition = db.fech(`ja_${member.guild.id}_${member.user.id}`)
if(condition === "yes"){
// write code to add "jail" role to the member
}
else{
// your other code
}
Also don't forget to set "no" in the database whenever you remove jail role from member.

Discord.js problem searching in the roles of a user

I am trying to create a command, in this case it is activated with / attack, the mechanism I am looking for is that if the target user (mentioned) has the role (Lavander) which is a kind of shield, send an embed message saying defended and remove the role from you (break the shield) and if the target user (mentioned) does not have the shield role, just send a different message saying attacked. This is the code that I have been doing but it does not work for me even if it does not give errors, simply when using it, it ignores the role detection and sends both messages for some reason that I do not know, can someone help me?
if (message.content.startsWith('/attack')) {
let Lavander = message.guild.roles.cache.find(role => role.name == "Lavander");
let member = message.mentions.members.first();
if (message.member.roles.cache.has(Lavander)) return
member.roles.remove(Lavander);
message.channel.send(new Discord.MessageEmbed()
.setColor("GOLD")
.setTitle(message.author.username)
.setDescription("Defended"))
message.channel.send(new Discord.MessageEmbed()
.setColor("GOLD")
.setTitle(message.author.username)
.setDescription("Attacked"))
}
For me it seems like let Lavander = message.guild.roles.cache.find(role => role.name == "Lavander"); might be supposed to be let Lavander = message.guild.roles.cache.find(role => role.name === 'Lavander'); but without the info about the glitches and/or errors, I can't tell you anything else.
method collection.has require id as property. So you need somethink like this:
bot.on('message', (message) => {
if (message.content.startsWith('/attack')) {
let lavander = message.guild.roles.cache.find((role) => role.name === 'Lavander');
let member = message.mentions.members.first();
if (!member || !lavander) return message.reply('No role or member');
if (message.member.roles.cache.has(lavander.id)) {
member.roles.remove(lavander);
let embed = new Discord.MessageEmbed()
.setColor('GOLD')
.setTitle(message.author.username)
.setDescription('Defended');
} else {
let embed = new Discord.MessageEmbed()
.setColor('GOLD')
.setTitle(message.author.username)
.setDescription('Attacked');
message.channel.send(embed);
}
}
});

Finding Members with 2 Roles in Discord [Using Discordjs]

I am making a discord bot using discord.js, and what I want to do is to have the bot find members with Roles A and B, and list them in an embedded message. Currently, I have:
else if (message.content === (!'guns') && message.channel.id == '732740415056380044') {
let team = message.guild.roles.find('name', 'WindStar Team');
let awper = message.guild.roles.find('name', 'AWPer');
let rifler = message.guild.roles.find('name', 'Rifler');
const Members1 = awper = awper.filter(val => !team.includes(val)).map(member => member.displayName);
const Members2 = rifler = rifler.filter(val => !team.includes(val)).map(member => member.displayName);
const embedmesage = new Discord.MessageEmbed()
.setTitle('Preferred Guns')
.setColor(0x00AE86)
.addFields(
{ name: 'AWPers', value: `${Members1.join('\n')}` },
{ name: 'Riflers', value: `${Members2.join('\n')}` },
);
message.channel.send(embedmesage);
return console.log('Preferred gun roles command for windstar team executed');
}
Basically, I am trying to cross-check members who have the WindStar Team role and AWPer role, and send the list of all members who have those roles into an embed. I am also trying to cross-check members with the WindStar Team role and the Rifler role, and send the list of those members into an embed.
let awper = message.guild.roles.find('name', 'AWPer');
awper.members //Either .toArray() or .map(m => m.displayName)
I think, I dont have my bot in front of me to test
I think it is maybe too late at this point but I'll give my solution anyway. (using discord.js v12.5.1)
<Message> = your message instance
let roleMembers = <Message>.guild.roles.cache.filter(role => role.name === "AwPer" && role.name === "WindStar").members
// displaying the role members
roleMembers.map(member => member.user.username)
Basically you are getting all the roles in a guild a cache and filtering them to display the roles you want.
This should work ^. Unless you are using a breaking version of discord.js

Bot Crashed When you dont mention

I have this command on my bot where you can mute someone using the command g!mute where the 'user' is mentioned using #. However, if you don't mention e.g GeoGeo instead of #GeoGeo, it causes the bot to crash. I know you need to put .catch(console.error); somewhere, but I'm not sure where. Thanks in advance. The Error is
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
^
TypeError: message.guild.members.get is not a function
Code:
const Discord = require('discord.js');
const ms = require('ms');
module.exports = {
name: 'mute',
description: "this is mute command",
execute(message, args){
if(!message.member.roles.cache.find(r => r.name ==="Staff", "Head Staff", "Owner", "Co-Owner")) return message.channel.send(`YOU DO NOT HAVE PERMISSION TO DO THAT`)
let members = args[0];
if(!members) return message.reply("g!mute <user> <time>")
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
if(!person) return message.reply("That person is not in the server!");
let mainrole = message.guild.roles.cache.find(role => role.name === "Fans");
let muterole = message.guild.roles.cache.find(role => role.name === "muted");
if(!muterole) return message.reply("That role does not exist");
let time = args[1];
if(!time){
return message.reply("g!mute <user> <time>");
}
person.roles.remove(mainrole.id);
person.roles.add(muterole.id);
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has now been muted for ${ms(ms(time))}`)
.setColor(0x01B8FF)
message.channel.send(embed);
setTimeout(function(){
person.roles.add(mainrole.id)
person.roles.remove(muterole.id)
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has been unmuted`)
.setColor(0x01B8FF)
message.channel.send(embed);
}, ms(time));
}
}
When faced with an error like: TypeError: message.guild.members.get is not a function
The logical thing to do is check the docs to see that message.guild.members really has a function named get. Here's the docs: https://discord.js.org/#docs/main/stable/class/GuildMemberManager
No get. But there is a cache like you use elsewhere in the code. Just by checking over the docs you can tell that your existing code is wrong (it's outdated) and you need to use cache like you do elsewhere in your code:
message.guild.members.cache.get(args[1])

Resources