Discord.js Send is undefined in unban command - javascript

I have this unban command and I want it to DM the user that got DMd but I cant get it working. send keeps being undefined.
if(command === "unban") {
const user = message.mentions.users.first() || client.users.cache.get(args[0])
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("You need permissions!")
if (!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send("Bot need permissions!")
const reason = args[1] || "There was no reason!";
message.guild.members.unban(user, reason)
message.channel.send(`${user} has been unbanned from the server!`);
user.send("You've been unbanned!")
}

I think the error says "Cannot read property 'send' of undefined". It doesn't mean send is undefined, it means user is.
The problem is that you don't check if someone is mentioned in the message and try to send a DM anyway. Make sure you're checking if there's a user and send an error message if there isn't any.
It's also a good idea to only send a message once the user is unbanned. You can use .then() or async/await:
if (command === 'unban') {
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user)
return message.channel.send('You need to mention someone to unban');
if (!message.member.hasPermission('BAN_MEMBERS'))
return message.channel.send('You need permissions!');
if (!message.guild.me.hasPermission('BAN_MEMBERS'))
return message.channel.send('Bot need permissions!');
const reason = args[1] || 'There was no reason!';
message.guild.members
.unban(user, reason)
.then(() => {
message.channel.send(`${user} has been unbanned from the server!`);
user.send("You've been unbanned!");
})
.catch(console.log);
}

Related

!unban id with spaces discord.js

I'm new to this platform and desperately running in circles to unban a player on discord.
Its id has spaces, and I always run into 400 or 404 errors ...
Do you have any idea to solve my problem ?
I tested a lot of codes, and the last one I have is this :
if (message.content.startsWith('!unban')) {
let args = message.content.split(/ +/g);
let user = message.guild.members.cache.get(args[1]);
if (!user) return message.channel.send('Please specify a user ID');
user.unban().then(() => message.channel.send('Success'));
}
I am currently receiving the message 'Please specify a user ID'.
For information, I am not using the async function :
const Discord = require('discord.js');const client = new Discord.Client();client.on('message', message => {}
Thanks for your help !
Since the user is banned he's not in the guild, and you're trying to get the user from the guild members and this returns undefined so the bot keeps sending the error message.
To unban a user you need to use the GuildMemberManager#unban method.
Here's an example:
if (message.content.startsWith('!unban')) {
let args = message.content.split(/ +/g);
let user = args[1];
if (!user) return message.channel.send('Please specify a user ID');
message.guild.members.unban(user).then((u) => {
message.channel.send(`Successfully unbanned ${u.tag}`);
}).catch((err) => {
console.log(err);
message.channel.send("I couldn't unban this user, please check if i have the required permissions and if the user id is correct");
});
}
if I understand you correctly, you want to use a command like !unban idBeforeSpace afterSpace.
In that case, your code runs like this:
if (message.content.startsWith('!unban')) {
let args = message.content.split(/ +/g); //args = ["!unban", "idBeforeSpace", "afterSpace"]
let user = message.guild.members.cache.get(args[1]); //args[1] = "idBeforeSpace"; user = null
if (!user) return message.channel.send('Please specify a user ID');
user.unban().then(() => message.channel.send('Success'));
}
but instead you wanted this:
args = ["!unban", "idBeforeSpace afterSpace"]
You split your arglist on every whitespace you find. Instead of splitting at every occurence of the regex, just split after the first.

Bot keeps crashing when wrong command is sent. [Discord JS]

I'm trying to make an Arby's Bot. Whenever someone sends a message in the channel, the bot crashes and bot doesn't work.
client.on("message", (message) => {
if (message.content.startsWith("arbys") || message.guild.channel == message.guild.channels.cache.get("843008525335920651")) {
} else
setTimeout(() => message.delete(), 1);
message.author.send("**arbys** Only Arbys. GOT IT?")
});
If someone could please help me that would be amazing.
its because message.guild does not have a channel property, instead do this
if (message.content.startsWith("arbys") || message.channel.id == "843008525335920651"){
hope this helped >:D
message.guild doesn't have a channel property, but that's not the only problem. You can't compare an object (message.guild.channel) to another object (message.guild.channels.cache.get("843008525335920651")) like that. You can, however, check if the channel the message is sent in has the same ID as you want (843008525335920651).
You can also delete the message after you sent a DM to the message author using the .then() method. Check out the code below:
client.on('message', (message) => {
if (
message.content.startsWith('arbys') ||
message.channel.id === '843008525335920651'
) {
// do something ?
console.log('Correct channel or command');
} else {
// send a DM to the author
message.author
.send('**arbys** Only Arbys. GOT IT?')
// and delete the original message
.then(() => message.delete())
// catch them errors :)
.catch((error) => console.log(error));
}
});

How to check if user is undefined

I have a command that sends a DM to user and the user is defined like this:
let user;
if (message.mentions.users.first()) {
user = message.mentions.users.first();
} else if (args[0]) {
user = message.guild.members.cache.get(args[0]).user;
}
But if I ping a user that is not in this server or write something that is not #user, it sends an error "user is not defined". I tried making if (user == "undefined"), but it just aborts before it reaches it or if I put it above it can't work.
Instead of looking for the members with message.guild.members and then get the user from there, you could get the client.users and check if a user with the args[0] ID exists. If it doesn't exist, you can simply check if (!user) you don't have to check if it's undefined.
const user = message.mentions.users.first() || message.client.users.cache.get(args[0]);
if (!user)
return message.channel.send('There is no user mentioned');
message.channel.send(`You mentioned ${user}`);
You can also use fetch() to get the user instead of relying on cache:
let user;
try {
user = message.mentions.users.first() || (await message.client.users.fetch(args[0]));
} catch (error) { console.log(error); }
if (!user)
return message.channel.send('There is no user mentioned');
message.channel.send(`You mentioned ${user}`);
You are currently checking if you have written user as "undefined" when actually you want to see if the user is undefined.
Another issue with your code is that args[0] will return the command name when you want the next argument over from that, args[1].
Full example:
let user;
if (message.mentions.users.first()) {
user = message.mentions.users.first();
} else if (args[0]) {
user = message.guild.members.fetch(args[1]).user;
} else {
return message.channel.send("Please provide a user"); //Sends if the message author did not provide a user
}
if (user == undefined) return message.chanel.send("I could not find the user you are looking for"); //Sends if the user is not in the current guild or doesn't exist
For each variable in javascript you can take its type and obviously if its type is === 'undefined' then it is undefined.
if(typeof comment === 'undefined') {
alert('Variable "comment" is undefined.');
}

Im trying to make a discord bot mostly just for fun but i cant seem to get the if else statements used in my kick command to work properly

the kicking part of the command works correctly and then correctly sends a message saying it has kicked the mentioned person. However I want the bot to send a message saying that you need to mention a user if no user was mentioned. I also want the bot to send a message if either the player trying to use the bot does not have the proper permissions to kick someone or if the bot cant kick the person the user is trying to use the bot to kick.
This is my code for what I'm trying to do.
Crashbot.on('message', message => {
if (message.member.hasPermission("KICK_MEMBERS")) {
if (message.content.startsWith(prefix + 'kick')) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member.kick('optional reason that will display in the audit logs')
.then(() => {
// We let the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick that user');
console.error(err);
});
} else {
message.reply("You need to mention a user to kick");
}
}
}
}
});
That's the one I use. It checks if you have mentioned anything to begin with, it gives you a warning message if it can't find the user, it won't work if you don't have permission to kick people and if it can't kick the person it will tell you that he couldn't kick him. Plus you can provide an optional reason for the kick after.
Example usage: !kick #Apolko24 Bad word usage
const kUser = message.guild.member(message.mentions.users.first());
if (!args[0]) return message.channel.send('Please mention someone');
if (!kUser) return message.channel.send(`I can't find ${args[0]}`);
if (!message.member.hasPermission('KICK_MEMBERS')) return message.channel.send("You can't kick users");
if (kUser.hasPermission('MANAGE_GUILD')) return message.channel.send("That user can't be kicked");
const kReason = args.join(" ").slice(22);
if (kReason) {
const kickEmbed = new MessageEmbed()
.setTitle("Kick")
.setColor(0xbbffff)
.addField("Kicked user:", `${kUser}`)
.addField("Kicked by:", `${message.author}`)
.addField("Reason", kReason)
message.guild.member(kUser).kick();
message.channel.send(kickEmbed);
} else {
const kickEmbed = new MessageEmbed()
.setTitle("Kick")
.setColor(0xbbffff)
.addField("Kicked user:", `${kUser}`)
.addField("Kicked by:", `${message.author}`)
message.guild.member(kUser).kick();
message.channel.send(kickEmbed);
}
(you have to put this into your if (message.content.startsWith(prefix + 'kick')) statement)

How to check if someone has a certain role

Ok, I know that there are similar questions out there but no matter what I try I get the same result. I have been trying for 2 days now to figure out how to check if I had the "OverBot-Admin" role for a ban command. But whenever I run the command it spams the chat! Here is my code:
if (command === "ban") {
if(message.member.roles.has(role => role.name === "OverBot-Admin")) {
let reason = args.slice(1).join(" ");
if (!reason) reason = "No reason provided";
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban({ reason: "They were being bad." })
.then(() => {
message.reply(
":white_check_mark: Successfully banned " +
message.user.id +
"for " +
reason
);
const embed = new Discord.RichEmbed()
.setTitle("Ban")
.addField("Member:", message.user.id)
.addField("Reason:", reason)
.setTimestamp()
.setFooter(
"Created by OverThrow, OverBot SE",
"https://cdn.discordapp.com/avatars/649431468254429224/0b63291c1e7342c2320ca5c3cce806ca.png?size=2048"
);
})
.catch(err => {
message.reply(":x: I was unable to ban that member!");
console.error(err);
});
} else {
message.reply(":x: That user isn't a member to this guild!");
}
} else {
message.reply(":x: You didn't mention a member to ban!");
}
}
} else {
message.reply(":x: I couldn't ban this user, please make sure you have the OverBot-Admin role!")
}
message.member.roles.has() requires a role ID as an argument, whereas here, you are passing in a function. The method I think you are looking for is Collection.exists (although this method is deprecated, if anyone can figure out a different way to go about this, please let me know).
Looking at the message.reply in the then function after banning, I see a message.user.id. However, message.user does not seem to be a valid property of the message object according to the docs. I assume that you would be referring to the user who was just banned, in which case you can reuse the user or member variable you previously defined.
If you have further problems, feel free to comment back.

Categories