Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord.js how to know if user block the bot or not

I made code that let bot send user to private message, and I need to know if the user block the bot or failed to send him message.

This is what I tried. I don't want bot send message below if it fails:

Message Sent!

image

if(message.content.startsWith(prefix+'send')){
    if(!botOwner.includes(message.author.id)) return;
    let userID = 'ID'; //to send
    let channel = message.guild.channels.get(message.channel.id);
    let user = bot.users.get(userID);
    let myMessage = message.content.split(' ').slice(1).join(' ');
    if(!myMessage) return;


    user.send(myMessage)
    .then(channel.send('Message Sent!')) //The problem in this line <-
    .catch(err => {
        console.error(err)
        message.channel.send(`**${user.username}**, Failed to send him ❌`)
    });
}
like image 941
Anas7z Avatar asked Dec 29 '25 21:12

Anas7z


1 Answers

Pass a function into then().

// Keep in mind that 'user' is a GuildMember the way it's been defined, not a User.

user.send(myMessage)
  .then(() => message.channel.send(':incoming_envelope: Message sent successfully!'))
  .catch(err => {
    console.error(`Error while sending message to ${user.displayName}...\n`, err);

    message.channel.send(':x: Message could not be sent.')
      .catch(err => console.error(`Error while sending error message...\n`, err));
  });
like image 86
slothiful Avatar answered Dec 31 '25 09:12

slothiful



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!