1
votes

I am creating a discord.js bot and an express API that work together to allow my desktop application (created in electron) to interact with the server. I am adding a ban management tab to my desktop app and I can unban users from there. After that I try to send a message to the user that was unbanned letting them know they were unbanned, and giving them an invite. However i get the error. "DiscordAPIError: Cannot send messages to this user". I understand that it is impossible to send a message to the user if they don't share a server with the bot, is there a work around?

// Unban user
// guild is the server that the bot is in and unbanning for
// note this is a private bot for only one server, so i don,t need multi-server handling

app.post(`/api/v1/unban/:id`, async (req, res) => {
  let toUnBan = await bot.fetchUser(req.params.id);
  let error = false;

  if (!toUnBan) {
    error = "Unexpected error occurred: User not found...";
  }

  // 585739079585497099 is the bot's id
  if (!guild.members.get("585739079585497099").hasPermission("BAN_MEMBERS")) {
    error = "Bot doesn't have permission to unban members.";
  }

  if (error === false) {
     try {
       guild.unban(toUnBan.id);
       res.status(200).send({
         success: true
       });
       // these lines are returning the error, workaround?
       let invite = await guild.channels.find(c => c.name === "General").createInvite();
       // goes with line above
       bot.users.get(toUnBan.id).createDM().then(dm => {
         dm.send(`Your ban on **${guild.name}** has been lifted. Here you can join again :), ${invite} .`);
       });
     } catch (e) {
       if (e) console.log(e.message);
       res.status(200).send({
         success: false,
         error: e.message
       });
     }
  } else {
    res.status(200).send({
      success: false,
      error: error
    });
  }
});

Thanks in advance!

1

1 Answers

2
votes

Due to privacy settings within Discord, in some cases a client can't send a message to a user whom they are not friends with and don't share a server with. Therefore, banning a user with strict privacy settings may result in the inability to contact them later.