Discord.js:如何检查用户是否有权限在提及频道发送消息并优化代发消息命令
Fixing Permission Check for Discord Bot Message Relay Command
I get what you're trying to do here—instead of relying on a broad MANAGE_MESSAGES permission, you want to make sure the user can actually send messages in the target channel they're specifying (or the current channel if none is mentioned). That makes way more sense for a relay command!
Here's the revised code that implements this precise permission check:
// First, determine the target channel let textChannel = message.mentions.channels.first() || message.channel; // Check if the user has SEND_MESSAGES permission in the target channel if (message.member.permissionsIn(textChannel).has("SEND_MESSAGES")) { let msg; message.delete(); // Adjust args slicing based on whether a channel was mentioned if (message.mentions.channels.first()) { msg = args.slice(1).join(" "); } else { msg = args.join(" "); } if (msg === "") { message.channel.send("Please input a valid sentence/word."); } else { textChannel.send(`**Message from ${message.author.tag}:** ${msg}`); } } else { message.reply(`You lack the required permissions to send messages in ${textChannel}. (Required Permission: \`SEND_MESSAGES\`)`); }
Key Changes Explained:
- Target Channel First: We first set
textChannelto either the mentioned channel or the current command channel—this way we always know which channel we're checking permissions for. - Precise Permission Check: Instead of checking
MANAGE_MESSAGESglobally, we usemessage.member.permissionsIn(textChannel).has("SEND_MESSAGES")to verify the user can send messages specifically in the target channel. - Adjusted Args Handling: Cleaned up the args slicing logic to be more readable (checking if a channel was mentioned instead of relying on the existence of
textChannel, sincetextChannelwill always exist now). - Clearer Error Message: The reply now specifies exactly which channel the user doesn't have permissions for, making it more helpful.
Quick Note for Discord.js v13+
If you're using a newer version of Discord.js, you might need to use the Permissions enum instead of string values for better type safety:
// At the top of your file const { Permissions } = require('discord.js'); // Then in the check if (message.member.permissionsIn(textChannel).has(Permissions.FLAGS.SEND_MESSAGES)) { // ... rest of code }
This should resolve your issue by making the permission check context-aware to the target channel, rather than using a one-size-fits-all permission.
内容的提问来源于stack exchange,提问作者beans
相关产品推荐
相关产品推荐

