Discord Bot开发问题:isAdmin变量识别及成员提及读取异常
Hey there! Let's work through this Discord Bot issue you're stuck on—sounds like the core problem is that message.mentions.members.first() isn't pulling in the mentioned user correctly, which is breaking your isAdmin check and skipping the rest of your logic. Here's how to troubleshoot and fix this step by step:
If you're using Discord.js v13 or higher, your bot needs explicit intents to access member data and message content. Missing these will cause message.mentions.members to return empty every time.
Make sure your client initialization includes these required intents:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, // Required to read message text/mentions GatewayIntentBits.GuildMembers // Required to fetch member details ] });
Before diving into logic, let's confirm what the bot is actually seeing. Add these logs right at the start of your command handler:
console.log('Full mentions data:', message.mentions); console.log('Mentioned members collection:', message.mentions.members);
- If
message.mentions.membersis an empty Collection, that means the bot isn't detecting any member mentions. Double-check that the user is properly @mentioning a server member (not a role or channel) and that your bot has permission to read message content in the channel.
Your isAdmin variable is failing because you're trying to use it before confirming the mentioned member exists. Add a guard clause to catch this early and notify the user:
const mentionedMember = message.mentions.members.first(); // If no member was mentioned, exit early if (!mentionedMember) { return message.reply('Please tag a valid server member to view their info!'); } // Now safely check admin status const isAdmin = mentionedMember.permissions.has('Administrator');
Once you've confirmed mentionedMember exists, you can build your embed without worrying about undefined values. Handle edge cases like the user not being in a voice channel:
const { EmbedBuilder } = require('discord.js'); // Use MessageEmbed for v13 const memberInfoEmbed = new EmbedBuilder() .setTitle('Member Details') .setColor('#2f3136') .addFields( { name: 'Username', value: mentionedMember.user.tag, inline: true }, { name: 'User ID', value: mentionedMember.id, inline: true }, { name: 'Voice Channel', value: mentionedMember.voice.channel ? mentionedMember.voice.channel.name : 'Not in a voice channel', inline: false }, { name: 'Admin Status', value: isAdmin ? '✅ Yes' : '❌ No', inline: true } ); message.channel.send({ embeds: [memberInfoEmbed] });
Make sure your bot has these server permissions enabled:
- View Channel
- Send Messages
- Embed Links
- Read Message History
- Manage Roles (optional, but helpful for permission checks)
If any of these are missing, the bot might fail to read mentions or send the embed.
内容的提问来源于stack exchange,提问作者ZaKLaKe

