简体   繁体   中英

Check if a Discord.js DM went through

I know you can send a DM like this:

message.author.send("Go to example.com for help");

But some people have the setting that allows other server members to DM them off:

该选项的屏幕截图

How do I find out if the DM actually sent or not? I know this is possible in the Discord API, since other bots do it.

If the user has that option, or isn't DMable, it will throw an error, namely:

DiscordAPIError: Cannot send messages to this user   

Now, we can catch that error and run a command based on it, say replying in the channel that the user can't be DMed.

user.send(...).catch(async err => message.reply("I can't DM this user"));
// In the above, async is useless, but you can actually do what you want with it.

To run more than a single line of command, use a promise based catch.

user.send(...).catch(async err => {
  console.log(err);
  message.reply("I can't DM this user");
});

如果用户启用了该选项,DMing 他们将返回错误,因此您将能够使用.catch()语句:

user.send().catch(() => console.log('Could not DM this user'));

You can get error notices aswell as information about the error using .catch()

In this example I log the error type and description

member.send(...).catch(error => {
   console.error(`${error.name} :\n${error}`)
   message.channel.send('There was an error when trying to DM this member')
})

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