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

