Discord JS错误:未处理的PromiseRejection警告:DiscordAPI错误:无法向该用户发送消息



试图建立一个系统,当你说一个列入黑名单的单词时,它会删除它,并去DM告诉他它被删除了哪个频道,原因和他说的消息。但我的代码一直告诉我:

2020-02-25T02:05:30.557281+00:00 app[worker.1]: (node:4) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user
2020-02-25T02:05:30.557293+00:00 app[worker.1]:     at /app/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:85:15
2020-02-25T02:05:30.557294+00:00 app[worker.1]:     at /app/node_modules/snekfetch/src/index.js:215:21
2020-02-25T02:05:30.557295+00:00 app[worker.1]:     at processTicksAndRejections (internal/process/task_queues.js:97:5)
2020-02-25T02:05:30.557358+00:00 app[worker.1]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 6)

这是我的代码:

bot.on('message', async message => {
var sender = message.author
var channel = message.channel.id
if(sender.id === 'BOT ID') {
return;
}

if(message.content.includes('discord.gg/')) {
message.delete();
message.author.send(`**Your message in <#${channel}> had been deleted.**  
n**__Reason:__** *Promotion*
n**__Your Message:__** *${message.content}*`)
};

用户不能允许从此服务器向他发送DM消息。最好不要使用try - catch结构。方法如果消息接收成功,DM通道发送返回消息的promise,如果出现问题,则拒绝错误。您可以使用单块.catch(err => )进行处理

if(message.content.includes('discord.gg/')) {
message.delete();
message.author.send(`**Your message in <#${channel}> had been deleted.**  
n**__Reason:__** *Promotion*
n**__Your Message:__** *${message.content}*`).catch(err => console.log('User don`t allow to send DM message from him'))
}

该用户可能不允许来自该服务器的DM。您基本上可以拒绝其他用户从特定服务器对您进行DM。为了避免出现错误,您需要使用try catch块并进行相应的处理。

最新更新