简体   繁体   中英

Discord.js Send is undefined in unban command

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM