Getting GuildMember Object with user ID Discord.js v13 - javascript

I'm fairly new to discord.js and Javascript in general. Here I created a simple userinfo command which fetches data of the user and embeds it neatly as you can see below. You can also see that the command requires the author/mod to mention the user to get the result embed but I want to get the same result by member's discord userID.
I tried message.mentions.users.first() || message.guild.member.length(args[0]) but this creates a lot of problems. So basically how do I get to use the same command/code by discord ID.
const moment = require('moment');
const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js')
module.exports = {
description: 'whois',
run: async (client, message, args) => {
const user = message.mentions.users.first()
const embed = new MessageEmbed()
.setTitle(`**PASSION ISLAND MODERATIONS**`)
.setColor('#ffc0cb')
.setThumbnail(user.displayAvatarURL({ dynamic: true }))
.addField('Username', user.username)
.addField('User Id', user.id)
.addField('Account Type', `${user.bot ? 'Bot' : 'Human'}`)
.addField(`Roles`, `${message.member.roles.cache.size}`)
.addField(`Joined At`, `${moment.utc(message.member.joinedAt).format('ddd, MMM Do, YYYY, h:mm a')}`)
.addField(`created At`, `${moment.utc(message.member.createdAt).format('ddd, MMM Do, YYYY, h:mm a')}`)
.setTimestamp()
.setFooter(`Requested by ${message.author.username}`)
message.channel.send({ embeds: [embed] })
},
}

You can try using
let user;
if(message.mentions.members.first()) {
user = message.mentions.members.first()
} else {
let x = await message.guild.members.cache.get(`${args[0]}`)
user = x.user;
}
This would work well with IDs since you can pass a snowflake within the .get() function.

This is the code I'm using, can find by user's id, user's name or user's tag.
let user = message.mentions.users.first()||null;
if (!user && args.length > 0) {
let input = args.join(' ')
let temp = message.guild.members.cache.get(input) || message.guild.members.cache.find(mem => mem.user.username === input) || mmessage.guild.members.cache.find(mem => mem.user.discriminator === input) || null
if (temp) user = temp.user;
}

If you want to be 100% sure you will find the user if he exists in the server can do:
message.mentions.users.first() || message.guild.members.fetch(args[0])

You can try using
message.mentions.members.first().then((m) => {
if (!m) {
// code
}
})
// or do this
const member = await message.mentions.members.first();
if (!member) {
// Code
}
or change the members to an users
as other people have shown you can do that by finding the id in the server like so
message.guild.members.cache.get(args[0]);
// This will return null if it doesnt exist so you can do this
const member = await message.guild.members.cache.get(args[0]);
if (!member) {
// code
}
You can combine both of them to check it and be sure that the member exists like this
const member = await message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!member) {
// Code
}
hopefully this helped
NOTE : I see that you are using multiple .addField() you can use .addFields() to optimize your code
like this
const embed = new MessageEmbed()
.addFields(
{ name: 'name', value: 'the description', inline: true || false },
{ name: 'name', value: 'the description', inline: true || false },
)

Related

Quick.db .add function not working correctly

Im making an addmoney cmd for my discord bot but when the money, it gets added weirdly.
Eg. normally it would be 200 if i add 100 and there was already 100 but im my occasion its 100100.
Anyways code:
const { QuickDB } = require('quick.db');
const db = new QuickDB();
const discord = require("discord.js")
module.exports.run = async (bot, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return message.reply("You do not have the permissions to use this command😔.")
if (!args[0]) return message.reply("Please specify a user❗")
let user = message.channel.members.first() || message.guild.members.cache.get(args[0]) || messsage.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.member.cache.find(r => r.displayName.toLowerCase() === args[0].toLocaleLowerCase())
if (!user) return message.reply("Enter a valid user⛔.")
if (!args[1]) return message.reply("Please specify the amount of money💰.")
var embed = new discord.MessageEmbed()
.setColor("#C06C84")
.setAuthor(message.author.tag, message.author.displayAvatarURL({dynamic: true}))
.setDescription(`Cannot give that much money⛔.
Please specify a number under 10000💸.`)
.setTimestamp()
if (isNaN(args[1]) ) return message.reply("Your amount is not a number❗.")
if (args[0] > 10000) return message.reply({embeds: [embed]})
await db.add(`money_${user.id}`, args[1])
let bal = await db.get(`money_${user.id}`)
let moneyEmbed = new discord.MessageEmbed()
.setColor("#C06C84")
.setDescription(`Gave $${args[1]} \n\nNew Balance: ${bal}`)
message.reply({embeds: [moneyEmbed]})
}
module.exports.help = {
name: "addmoney",
category: "economy",
description: 'Adds money!',
}
One way you could get this kind of behaviour is if args[1] was a string. In that case, instead of adding the value, it would just concatenate it with the current value of money_${user.id}. So, to fix it all you have to do is, instead of passing it directly, use parseInt() and then pass it. Then, your fixed part might look like this =>
await db.add(`money_${user.id}`, parseInt(args[1]))

I'm trying to create a channel named like user args. [DISCORD.JS V12]

It just gives me an error that the function message.guild.channels.create does not work because it's not a correct name.
My intention is to create a command where you will be asked how the channel you want to create be named. So it's ask you this. After this you send the wanted name for the channel. Now from this the bot should name the channel.
(sorry for bad english and low coding skills, im a beginner)
module.exports = {
name: "setreport",
description: "a command to setup to send reports or bugs into a specific channel.",
execute(message, args) {
const Discord = require('discord.js')
const cantCreate = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`Can't create channel.`)
const hasPerm = message.member.hasPermission("ADMINISTRATOR");
const permFail = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`${message.author}, you don't have the permission to execute this command. Ask an Admin.`)
if (!hasPerm) {
message.channel.send(permFail);
}
else if (hasPerm) {
const askName = new Discord.MessageEmbed()
.setColor(' #4f6abf')
.setDescription(`How should the channel be called?`)
message.channel.send(askName);
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { max: 1, time: 10000 });
console.log(collector)
var array = message.content.split(' ');
array.shift();
let channelName = array.join(' ');
collector.on('collect', message => {
const created = new Discord.MessageEmbed()
.setColor('#16b47e')
.setDescription(`Channel has been created.`)
message.guild.channels.create(channelName, {
type: "text",
permissionOverwrites: [
{
id: message.guild.roles.everyone,
allow: ['VIEW_CHANNEL','READ_MESSAGE_HISTORY'],
deny: ['SEND_MESSAGES']
}
],
})
.catch(message.channel.send(cantCreate))
})
}
else {
message.channel.send(created)
}
}
}
The message object currently refers to the original message posted by the user. You're not declaring it otherwise, especially seeing as you're not waiting for a message to be collected before defining a new definition / variable for your new channel's name.
NOTE: In the following code I will be using awaitMessages() (Message Collector but promise dependent), as I see it more fitting for this case (Seeing as you're more than likely not hoping for it to be asynchronous) and could clean up the code a little bit.
const filter = m => m.author.id === message.author.id
let name // This variable will later be used to define our channel's name using the user's input.
// Starting our collector below:
try {
const collected = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
name = collected.first().content /* Getting the collected message and declaring it as the variable 'name' */
} catch (err) { console.error(err) }
await message.guild.channels.create(name, { ... })

unban command with discord.js v12

I am trying to make an unban command but I get an error const member; ERROR: Missing initializer in const declaration
client.on('message', async message => {
if (message.content.toLowerCase().startsWith(prefix + "unban"))
if (!message.member.hasPermission("BAN_MEMBERS")) {
return message.channel.send(`You cant use this command since you're missing "BAN_MEMBERS" perm`)
}
if (!args[0]) return (await message.channel.send('pls enter a users id to unban.')).then(msg => msg.delete({timeout: 5000}))
const member;
try {
member = await client.users.fetch(args[0])
} catch (e) {
console.log(e)
return message.channel.send(('an error accured'));
}
const reason = args[1] ? args.slice(1).join(' ') : 'no reason';
const newEmbed = new Discord.MessageEmbed()
.setFooter(`${message.author.tag} | ${message.author.id}`, message.author.displayAvatarURL({dynamic: true}))
message.guild.fetchBans().then( bans => {
const user = bans.find(ban => ban.user.id === member.id);
if (user) {
newEmbed.setTitle(`Successfully Unbanned ${user.user.tag}`)
.setColor('#FFFF00')
.addField({name: 'User ID', value: user.user.id, inline: true})
.addField({name: 'User Tag', value: user.user.tag, inline: true})
.addField({name: 'Banned Reason', value: user.reason})
message.channel.send(newEmbed)
}})})
const means that the variable will be immutable (constant). Thus, declaring a const-type variable and not immediately assigning it a value is pointless, and not allowed in Javascript.
To make a mutable variable, instead of const, you should use let.
So, in your code, line 7 should look like this:
let member;

How to show roles of user discord.js / userinfo command

I'm trying to make a userinfo command, and I'm currently stuck on showing roles of the user.
Here is my code:
const Discord = module.require('discord.js');
const moment = require('moment');
module.exports.run = async (bot, message, args) => {
let user = message.mentions.users.first() || message.author;
const joinDiscord = moment(user.createdAt).format('llll');
const joinServer = moment(user.joinedAt).format('llll');
let embed = new Discord.RichEmbed()
.setAuthor(user.username + '#' + user.discriminator, user.displayAvatarURL)
.setDescription(`${user}`)
.setColor(`RANDOM`)
.setThumbnail(`${user.displayAvatarURL}`)
.addField('Joined at:', `${moment.utc(user.joinedAt).format('dddd, MMMM Do YYYY, HH:mm:ss')}`, true)
.addField('Status:', user.presence.status, true)
.addField('Roles:', user.roles.map(r => `${r}`).join(' | '), true)
.setFooter(`ID: ${user.id}`)
.setTimestamp();
message.channel.send({ embed: embed });
return;
}
module.exports.help = {
name: 'userinfo'
}
I'm getting this error TypeError: Cannot read property 'map' of undefined and I don't know how to fix it?
User.roles is undefined because that property doesn't exist: try using GuildMember.roles instead:
let member = message.mentions.members.first() || message.member,
user = member.user;
let embed = new Discord.RichEmbed()
// ... all the other stuff ...
.addField('Roles:', member.roles.map(r => `${r}`).join(' | '), true)
The other properties will still use user, but .roles will be related to the GuildMember.
try adding this .addField("Roles:", member.roles.map(roles =>${roles}).join(', '), true)
My whole code for this is
let user;
if (message.mentions.users.first()) {
user = message.mentions.users.first();
} else {
user = message.`enter code here`author;
}
const member = message.guild.member(user);
const embed = new Discord.RichEmbed()
.setColor("RANDOM")
.setThumbnail(message.author.avatarURL)
.addField(`${user.tag}`, `${user}`, true)
.addField("ID:", `${user.id}`, true)
.addField("Nickname:", `${member.nickname !== null ? `${member.nickname}` : 'None'}`, true)
.addField("Status:", `${user.presence.status}`, true)
.addField("In Server", message.guild.name, true)
.addField("Game:", `${user.presence.game ? user.presence.game.name : 'None'}`, true)
.addField("Bot:", `${user.bot}`, true)
.addField("Joined The Server On:", `${moment.utc(member.joinedAt).format("dddd, MMMM Do YYYY")}`, true)
.addField("Account Created On:", `${moment.utc(user.createdAt).format("dddd, MMMM Do YYYY")}`, true)
.addField("Roles:", member.roles.map(roles => `${roles}`).join(', '), true)
.setFooter(`Replying to ${message.author.username}#${message.author.discriminator}`)
message.channel.send({embed});
TypeError: Cannot read property 'map' of undefined - this means that somewhere in your code happening a situation of execution .map function of undefined variable.
You have only one map. Here:
.addField('Roles:', user.roles.map(r => `${r}`).join(' | '), true)
// ^^^
This line trows this error, so this means that user.roles is undefined.
Try to:
let user = message.mentions.users.first() || message.author;
console.log(user.roles); // it is undefined
Propably user.roles is undefined.
If it's ok that user has no roles, you can replace:
.addField('Roles:', user.roles.map(r => `${r}`).join(' | '), true)
with:
.addField('Roles:', user.roles ? user.roles.map(r => `${r}`).join(' | ') : "", true)
This will set empty string in case when there's no roles property in user object.
Another option is to set user.roles to empty array if it doesn't exist (or do something else in this if, i.e. throw error):
let user = /* get user*/
if (!user.roles){
user.roles = [];
}
For roles i also suggest you to remove the #everyone role
Here are an example
message.member.roles.cache.map(r => r.name)
// ["Mod","Member","Staff","Owner","#everyone"]
// If you don't want the everyone role use :
message.member.roles.cachemap(r => r.name).slice(0,-1).
// ["Mod","Member","Staff","Owner"]
So the roles field would be :
.addField("Roles", member.roles.cache.map(r => '`'+r.name+'`').join(' - '), true)
this is working 100% for discord.js 12.x
<#&${message.guild.member(message.author)._roles.join('> <#&')}>

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources