The bot crashes whe3n i use user id - javascript

const Discord = require('discord.js');
const config = require('../config.json');
const { Permissions } = require('discord.js');
module.exports.run = async (client, message, args) => {
if(!message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('You can\'t use that!')
if(!message.guild.me.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('I don\'t have the permissions.')
const member = message.mentions.members.first();
if(!args[0]) return message.channel.send('Please specify a user');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
message.guild.members.unban(`${member}`, `${reason}`)
.catch(err => {
if(err) return message.channel.send('Something went wrong')
})
let banembed = new Discord.MessageEmbed()
.setTitle('Member Unbanned')
.addField('User Unbanned', member)
.addField('Unbanned by', message.author)
.addField('Reason', reason)
.setFooter('Time Unbanned', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}

You're using a message.mentions.members.first() which is referring to a pinged person. To use their ID's you can use .fetch or cache.get
const member = await message.guild.members.fetch(args[0])
const member = await message.guild.members.cache.get(args[0])
also you can use them on the same line using or ||
const member = message.mentions.members.first() || await message.guild.members.fetch(args[0]) || await message.guild.members.cache.get(args[0])
I only don't know if its going to work with unban because the bot and the user should on the same server

Related

Getting roles of mentioned user

Working on a marriage system for my Discord bot but I am struggling to find out of a user has the "married" role already.
const Discord = require('discord.js');
module.exports = {
name: "marry",
aliases: ['m'],
description: "marry someone",
async run(client, message, args) {
const user = message.mentions.users.first() || client.users.get(args[0]);
let marriedRole = message.guild.roles.cache.find(r => r.name === "Married");
let singleRole = message.guild.roles.cache.find(r => r.name === "Single");
let proposerID = message.author.id;
let proposerName = message.author.username;
if (user.roles.cache.some(marriedRole)) {
let embed = new Discord.MessageEmbed()
.setDescription(`Sorry **${user.tag}**, is already married!`);
let messageEmbed = await message.channel.send({ embeds: [embed] });
}
if (message.member.roles.cache.some(role => role.name === 'Single')) {
let embed = new Discord.MessageEmbed()
.setDescription(`**${user.username}**, **${message.author.username}** is asking for your hand in marriage, would you like to accept?`);
let messageEmbed = await message.channel.send({ embeds: [embed] });
messageEmbed.react('✅');
messageEmbed.react('❌');
}
if (message.member.roles.cache.some(role => role.name === 'Married')) {
let embed = new Discord.MessageEmbed()
.setDescription(`Sorry **${message.author.username}**, but you are already married!`);
let messageEmbed = await message.channel.send({ embeds: [embed] });
}
}
}
I keep getting the error
if (user.roles.cache.some(marriedRole)) {
^
TypeError: Cannot read properties of undefined (reading 'cache')
By using message.mentions.users.first(), you are getting a User object in return which doesn't have the roles property. Instead, you need the GuildMember object. To get it, all you have to do is change the part where you declare the user variable to:
const user = message.mentions.members.first() || client.users.get(args[0]);
Answer from Zsolt Meszaros
Since, if there is no mention in the message, message.mentions.members.first(), so keep that in mind. client.users.get(args[0]) would also just get a User object, so instead of using that, you can use this:
const user = message.guild.members.cache.get(args[0])

Cannot read properties of undefined (reading 'send') (Discord.js v13)

i have been trying to make a leaveserver code for my bot, but i always get the error message Cannot read properties of undefined (reading 'send') I really wanna know why it always says the error messages! Please help me! Thanks!
const Discord = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
var self = this
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leavs a server",
run: async (client, message, args) => {
if (!OWNER_ID)
return message.channel.send("This command is Owner Only")},
async run(message, args) {
const guildId = args[0];
if (!rgx.test(guildId))
return message.channel.send("Please Provide a valid server id!")
const guild = message.client.guild.cache.get(guildId);
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send({embeds: [embed]});
}
}
Try this code
const {
MessageEmbed
} = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leaves a server",
run: async (client, message, args) => {
const guildId = args[0];
const guild = message.client.guilds.cache.get(guildId);
if (!OWNER_ID) return message.channel.send("This command is Owner Only");
if (!rgx.test(guildId)) return message.channel.send("Please Provide a valid server id!")
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter({
text: message.member.displayName,
iconURL: message.author.displayAvatarURL({
dynamic: true
})
})
.setTimestamp()
.setColor(message.guild.me.displayHexColor)
message.channel.send({
embeds: [embed]
})
}
}
Removed the duplicated async run(message, args) {
Try to do this:
const client = new Discord.Client({intents:
["GUILDS", "GUILD_MESSAGES"]});
client.on("message" , msg => {
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(msg.member.displayName, msg.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(msg.guild.me.displayHexColor);
msg.channel.send({embeds: [embed]});
})

JavaScript ReferenceError: member is not defined

So I'm trying to code a utility bot on my server and for some reason, this error popped out "Reference error"
ReferenceError: member is not defined
Every single time I solve a problem another one pops out. I know you guys will be asking me to save it (member) but I already did, like 7 times?
This is my current code:
const { Discord } = require("discord.js");
exports.run = async(client, msg, args) => {
if(!msg.member.hasPermission('BAN_MEMBERS')) return msg.reply('You do not have permission to use this command!')
var user = msg.mentions.user.first() || msg.guild.members.cache.get(args[0]);
if(!user) return msg.reply('You did not mention a user for me to punish!')
var member;
try {
member = await msg.guild.members.fetch(user)
} catch(err) {
member = null;
}
if(member){
if(member.hasPermission('MANAGE_MESSAGES')) return msg.reply('You cannot ban a fellow staff member!');
}
var reason = args.splice(1).join(' ');
if(!reason) return msg.reply('Please make sure to specify a reason for me to punish this user!')
var channel = msg.guild.channels.cache.find(c => c.name === 'mod-logs');
var verify = msg.guild.emojis.cache.find(emoji => emoji.name === 'white_check_mark')
var log = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been kicked by ${msg.author} for "**${reason}**"`)
channel.send(logs);
var userLog = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`You have been banned from the server! Thats sadge. You can appeal the ban by message a staff member!`)
try {
await user.send(userLog);
} catch(err) {
console.warn(err);
}
msg.guild.members.ban(user);
var confir = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been banned by ${msg.author} for "**${reason}**"`)
msg.channel.send(confir);
msg.delete();
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
const { Discord } = require("discord.js");
exports.run = async(client, msg, args) => {
if(!msg.member.hasPermission('BAN_MEMBERS')) return msg.reply('You do not have permission to use this command!')
var user = msg.mentions.user.first() || msg.guild.members.cache.get(args[0]);
if(!user) return msg.reply('You did not mention a user for me to punish!')
var member;
try {
member = await msg.guild.members.fetch(user)
} catch(err) {
member = null;
}
if(member){
if(member.hasPermission('MANAGE_MESSAGES')) return msg.reply('You cannot ban a fellow staff member!');
}
var reason = args.splice(1).join(' ');
if(!reason) return msg.reply('Please make sure to specify a reason for me to punish this user!')
var channel = msg.guild.channels.cache.find(c => c.name === 'mod-logs');
var verify = msg.guild.emojis.cache.find(emoji => emoji.name === 'white_check_mark')
var log = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been kicked by ${msg.author} for "**${reason}**"`)
channel.send(logs);
var userLog = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`You have been banned from the server! Thats sadge. You can appeal the ban by message a staff member!`)
try {
await user.send(userLog);
} catch(err) {
console.warn(err);
}
msg.guild.members.ban(user);
var confir = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been banned by ${msg.author} for "**${reason}**"`)
msg.channel.send(confir);
msg.delete();
}
You can try this code:
const CUser = message.mentions.users.first() || message.guild.members.cache.get(args[0]) || message.guild.member(message.author);
let member
if (message.mentions.members.first()) {
member = CUser
} else {
member = CUser.user
}
instead of your:
var user = msg.mentions.user.first() || msg.guild.members.cache.get(args[0]);
if(!user) return msg.reply('You did not mention a user for me to punish!')
var member;
try {
member = await msg.guild.members.fetch(user)
} catch(err) {
member = null;
}
Please note this code was written on discord.js version 12.5.3

add roles command not working (discord.js)

I am Coding my own discord bot for my server, I have a issue that the bot says no role doesn't exit even if I mentions the role. Here is the code:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on("message", message => {
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase()
if (command === "add") {
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ")
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.has(roleAdd.id)){
return message.channel.send("User already has role")
}
if (member) {
member.addRole(roleAdd).catch((error) =>{
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
}
})
client.login(config.token)
What did I made a mistake? Thanks.
First make sure you are using discord.js v12. Type npm i discord.js#latest in your terminal. Here you can see all changes in discord.js v12.
If you are using discord.js v12 now, this code should work for you:
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ");
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.cache.has(roleAdd.id)) {
return message.channel.send("User already has role")
}
if (member) {
member.roles.add(roleAdd).catch((error) => {
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
Mention the role you want to add won't work because here
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
you just find the role by its name. To fix that you can change that line into:
const roleAdd = message.guild.roles.cache.find(role => role.name === add) || message.mentions.roles.first();
This will allow a user to mention the role as well.

About the Quick.db module:

db module is possible to add writings. But is it possible to subtract the writings? It may also be caused by my incompetence this is my code:
const db = require('quick.db')
const Discord = require('discord.js')
exports.run = async (client, message, args, config) => {
if(message.author.id === 'My ID'){
let user = message.mentions.members.first() || message.author
if (args[0]) return message.channel.send(`${message.author}, bir eşya ismi girmen gerek!`)
db.subtract(`${user.id}.envan`, args[0])
let bal = await db.fetch(`${user.id}.envan`)
let embed = new Discord.RichEmbed()
.setAuthor(`Your item is received!`, message.author.displayAvatarURL)
.addField(`Received Item:`, `${args[0]}`)
.setColor("RED")
.setTimestamp()
message.channel.send(embed)
}else{
return message.channels.send('Yetkin yok knk').then(msg => {
setTimeout(() => {
msg.delete()
}, 2500);
})
}
}
You can use db.delete if you want to delete the reference instead of 'subtracting' (as it seems to be your goal in your question)
db.subtract(`${user.id}.envan`, Math.floor(args[0]))
try this.

Categories