Discord.js中Collector返回null,遍历成员游戏状态遇null报错如何处理?
Discord.js Issues Troubleshooting: Collector Returns Null & Member Game Status Error
Hey there! Let's break down and fix your two Discord.js problems step by step.
1. Fixing the "Cannot read property 'name' of null" Error When Fetching Member Game Status
First, let's tackle the game status error since you provided specific code and a clear error message. Here's what's going wrong and how to fix it:
What Caused the Error?
Your original code has three key issues:
- Variable Mix-Up: You used
userin the map callback, but your parameter ism(short for member) — that's likely a typo. It should referenceminstead ofuser. - Unchecked Null Values: Not all members are playing a game, so
presence.gamewill benullfor those users. Trying to access.nameon anullvalue throws the TypeError you're seeing. - Member Caching (Discord.js v12+): In newer versions,
message.guild.membersis aGuildMemberManager, not a direct collection. You need to fetch members first to get the full list (including offline members, if your bot has theGUILD_MEMBERSintent enabled).
Solution Code
Here are two robust fixes depending on what you need:
Option 1: Only Collect Members Who Are Playing a Game
This filters out users without an active game first, then maps their game names:
// Mark your message event handler as async to use await async function handleMessage(message) { try { // Fetch all guild members (requires GUILD_MEMBERS intent enabled) const members = await message.guild.members.fetch(); // Filter members with a non-null game presence, then extract game names const playingMembers = members .filter(member => member.presence?.game) .map(member => member.presence.game.name); console.log("Members playing games:", playingMembers); } catch (err) { console.error("Error fetching members:", err); } }
Option 2: Show Status for All Members (Including "Not Playing")
Use optional chaining (?.) to safely access nested properties, and provide a fallback for users not playing anything:
message.guild.members.fetch() .then(members => { const allGameStatuses = members.map(member => member.presence?.game?.name || "Not playing anything" ); console.log("All member game statuses:", allGameStatuses); }) .catch(err => console.error("Error fetching members:", err));
Key Notes
- For Discord.js v13+,
presence.gamewas replaced withpresence.activities. Use this instead to get playing status:member.presence?.activities.find(act => act.type === "PLAYING")?.name || "Not playing anything" - Ensure your bot has the
GUILD_MEMBERSintent enabled in the Discord Developer Portal and in your client initialization.
2. Troubleshooting Collector Returns Null
Since you didn't share your collector code, I'll cover the most common reasons collectors return null/empty results and how to fix them:
Common Causes & Fixes
- Overly Strict Filter: Your collector's filter might be too narrow. For example, a message collector that only accepts messages from a specific user won't collect anything if that user doesn't send a message.
- Fix: Test your filter with relaxed conditions first, then tighten it once you confirm it works.
- Timeout Expired: If the user doesn't interact within the collector's
timelimit, it will end with no collected items.- Fix: Increase the timeout duration or add a message prompting the user to act faster.
- Incorrect Collector Initialization: For reaction collectors, you might have bound the collector to the wrong message, or the bot lacks permissions to add reactions. For message collectors, you might be listening to the wrong channel.
- Fix: Verify the collector is attached to the correct message/channel, and ensure your bot has the necessary permissions (e.g.,
Add Reactionsfor reaction collectors).
- Fix: Verify the collector is attached to the correct message/channel, and ensure your bot has the necessary permissions (e.g.,
- No Matches Found: If the collector is set to collect a maximum number of items (
max) but no items meet the filter criteria, it will return empty.
Example of a Robust Message Collector
const filter = msg => msg.author.id === message.author.id; // Only collect from the command sender // Create collector with 30-second timeout, max 1 message const collector = message.channel.createMessageCollector({ filter, time: 30000, max: 1 }); collector.on('collect', collectedMsg => { console.log(`Collected message: ${collectedMsg.content}`); }); collector.on('end', collected => { if (collected.size === 0) { console.log("Collector returned null/empty — no valid messages were collected."); message.reply("You didn't send a valid message in time!"); } });
内容的提问来源于stack exchange,提问作者Neuheit
相关产品推荐
相关产品推荐

