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

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 user in the map callback, but your parameter is m (short for member) — that's likely a typo. It should reference m instead of user.
  • Unchecked Null Values: Not all members are playing a game, so presence.game will be null for those users. Trying to access .name on a null value throws the TypeError you're seeing.
  • Member Caching (Discord.js v12+): In newer versions, message.guild.members is a GuildMemberManager, not a direct collection. You need to fetch members first to get the full list (including offline members, if your bot has the GUILD_MEMBERS intent 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.game was replaced with presence.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_MEMBERS intent 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 time limit, 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 Reactions for reaction collectors).
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:54:28