You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js技术问题:如何预先检测用户是否接受机器人私信?

Can I pre-check if a user accepts DMs before sending one with Discord.js?

Great question! While Discord's API doesn't offer a direct way to check if a user accepts DMs upfront, there's a reliable indirect method to verify this before you attempt to send a message. Here's how to implement it:

The Proactive Approach: Pre-Create the DM Channel

Instead of sending a message first and catching the error afterward, you can attempt to create a DM channel with the user first. This operation will fail immediately if the user’s privacy settings block DMs (whether from server members or entirely), letting you handle the issue before sending any content.

Modified Code Example

exports.run = async (client, message) => {
  try {
    // First, try to create a DM channel – this validates if DMs are allowed
    const dmChannel = await message.author.createDM();
    // If we reach this line, DMs are accessible, so send your message
    await dmChannel.send(`:ok_hand:`);
  } catch (err) {
    // This triggers if the user has blocked DMs or restricted privacy settings
    message.reply('Cannot send Direct Messages to your user!');
  }
};

Why This Works

  • The user.createDM() method in Discord.js initiates a DM conversation with the target user. If their privacy settings prevent DMs (like disabling DMs from server members they don’t follow), this method throws an error right away.
  • This is more proactive than your original code: you confirm DM eligibility before attempting to send content, rather than catching a failure after the fact.

Quick Note

There’s no 100% foolproof way to guarantee DM success (a user could change their settings immediately after your check), but this method is the closest you can get to pre-verifying access with Discord.js.

内容的提问来源于stack exchange,提问作者Persik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:06:25