首页 > 解决方案 > 如何修复“无法向该用户发送消息”DiscordAPIError?

问题描述

我在发送有关guildMemberAdd活动的私人消息时遇到问题。

这是代码:

bot.on('guildMemberAdd', member => {
    member.send('Welcome to the server.');
});

这会导致此错误:

(node:11760) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user
    at RequestHandler.execute (C:\Users\AckeeXZ\Desktop\BOT\californianetwork\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async RequestHandler.push (C:\Users\AckeeXZ\Desktop\BOT\californianetwork\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11760) 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: 1)
(node:11760) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

标签: javascriptnode.jsdiscorddiscord.jsbots

解决方案


最有可能抛出该错误是因为该成员的 DM 已关闭,这意味着机器人无法向他们发送任何消息。

用户可以在“隐私和安全”设置中禁止来自服务器成员的直接消息。

在此处输入图像描述

没有其他方法可以绕过它,但您可以使用.catch()try - catch块来处理错误。

bot.on('guildMemberAdd', member => {
    member.send('Welcome to the server.').catch(e => console.log(e));
});

// or 

bot.on('guildMemberAdd', async member => {
    try { 
        await member.send('Welcome to the server.'); 
    } catch(e) { 
        console.log(e); 
    }
});

推荐阅读