【问题标题】:TypeError: Cannot read property 'members' of undefined - Discord.JSTypeError:无法读取未定义的属性“成员” - Discord.JS
【发布时间】:2021-12-10 21:24:30
【问题描述】:

所以这可能是一个“新手”类型的查询,但我很纠结如何解决这个错误。基本上我希望某些频道能够自动更新服务器内的统计信息。 运行最新版本的 Node.JS 和 Discord.JS。

[Error] An error happened in process: 
TypeError: Cannot read property 'members' of undefined
    at Timeout._onTimeout (/home/container/events/Stats.js:20:29)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7)

与之相关的文件是Stats.JS:

function updateStats(client) {
    const Discord = require('discord.js');
    const config = require("../settings/configuration");
    const settings = require("../settings/configuration");
    const guild = client.guilds.cache.get(settings.BOT_SETTINGS.Guild_ID);
    const totalUsers = require("../settings/configuration");
    const onlineUsers = require("../settings/configuration");
    setInterval(async function() {
    //const interval = (async function() {
 /*       for await (const startTime of setInterval(interval, Date.now())) {
          const now = Date.now();
          console.log(now);
          if ((now - startTime) > 1000)
            break;
        }
        console.log(Date.now());
      })();
      */
      console.log('Getting stats update..')
      var userCount = guild.members.size //guild.memberCount || 0;
      var onlineCount = guild.members.filter(m => m.presence.status === 'online').size
      console.log("Total Users: " + userCount);
      console.log("Online Users: " + onlineCount);
      totalUsers.setName("Total Users: " + userCount)
      .then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
      .catch(console.error);
      onlineUsers.setName("Online Users: " + onlineCount)
      .then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
      .catch(console.error);
      }, 120000 /* 30000*/) // update every 2 mins
      }

    module.exports = {
    updateStats
    }

我怀疑会需要它,这是我的配置文件:

module.exports = {
    BOT_SETTINGS: {
        BOT_TOKEN: 'token',
        YT_API_KEY: 'key',
        COMMAND_PREFIX: '?',
        EMBED_COLOR: 'BLUE',
        MUTE_ROLE: '901132102983102575',
        TIMEOUT_ROLE: '901132500229828638',
        BANNED_WORDS: ['**', '**'],
        BYPASS_ROLES: ['900730714457264218', '900730787392028692', '897570746660950026'],
        BANNED_LINKS: ['www.', '.com', '.net', '.gov', '.co', '.uk', '.gg', '.live'],
        BYPASS_LINKS_ROLES: ['900730714457264218', '900730787392028692', '897570746660950026'],
        Member_Count_Channel: '',
        Guild_ID: '896058387542974494',
        Kick_On_Warnings: true,
        Warnings_Until_Kick: '5',
        Time_Muted: '1m',
        LOCALE: 'en',
        Roles_On_Join: ['901133176506822696']
    },
    VERIFICATION: {
        Enabled: false,
        Verify_Channel: 'CHANNELID',
        Verify_Role: '900730843281125376',
        Role_To_Remove: '901133176506822696'
    },
    USER_DMS: {
        Enabled: true,
        Dm_Category: '',
        Dms: 'new-dm-{user}',
        Dm_Channel_Name: 'new-dm-{user}',
        View_Dmchannels_Roles: ['900730714457264218', '900730787392028692', '897570746660950026']
    },
    Ping_Prevention: {
        Enabled: true,
        Enabled_Types: 'user',
        Max_Channel_Pings: '5',
        Max_Role_Pings: '5',
        Max_User_Pings: '5',
        Max_Pings: '10',
        Punishment: 'kick',
        Bypass_Roles: ['900730714457264218', '900730787392028692', '897570746660950026']
    },
    LOCKDOWN_KICK: {
        Enabled: true,
        Kick_Message: '{server} is currently in LOCKDOWN MODE!  We are unable to allow you to join for now, please try joining back later {member}.'
    },
    LEVELING_SYSTEM: {
        Enabled: true,
        Remove_XP_On_Leave: true,
        Level_Up_Message: '{user} has just reached VC Level {level}!',
        Level_Up_Channel_ID: '901140182735134731'
    },
    LOGGING: {
        Report_Channel: '900749525646446622',
        Ban_Channel_Logs: '900749525646446622',
        Unban_Channel_Logs: '900749525646446622',
        Kick_Channel_Logs: '900749525646446622',
        Warn_Channel_Logs: '900749525646446622',
        Mute_Channel_Logs: '900749525646446622',
        Lock_Channel_Logs: '900749525646446622',
        Ticket_Channel_Logs: '900749525646446622',
        Moderation_Channel_Logs: '900749525646446622',
        Server_Updates: '900749525646446622',
        Voice_Updates: '900749525646446622'
    },
    TICKET_SYSTEM: {
        TICKET_CATEGORY: '',
        SUPPORT_TEAM_ROLES: ['900730714457264218', '900730787392028692', '897570746660950026',]
    },
    GREETING_SYSTEM: {
        Enabled: true,
        Welcome_Channel: '896058387979190393',
        Welcome_Type: 'card',
        Welcome_Cards_Image_Link: 'https://ptb.discord.com/channels/835428942570586143/901135850610499695/901139883433795604',
        Welcome_Message: 'Welcome {member} to the server, You are member {joinPosition}!',
        Welcome_Embed: {
            title: '{member.username} has just joined the server!',
            description: 'Welcome {member} to the server, You are member {joinPosition}!',
            color: 'blue'
        }
    },
    stats: {
              "totalUsers": '902148987845488650',
              "onlineUsers": '902149028110811136',
              "onlineStaff": '902149128195284993'
            }
          }

非常感谢任何帮助...这已经困扰我好几个月了!

【问题讨论】:

  • 试试client.guilds.fetch(settings.BOT_SETTINGS.Guild_ID)
  • 你的明星!谢谢!
  • 现在给我这个错误:TypeError: Cannot read property 'size' of undefined
  • 当你的代码中有xxx.yyy.zzz并且遇到Cannot read property 'zzz' of undefined错误时,这意味着xxx.yyyundefined。尝试使用console.log(xxx) 检查xxx 的值是否符合预期。在您的情况下,您可能需要添加 console.log(guild) 以检查 guild 变量是否是有效的 Guild 实例。

标签: javascript node.js discord.js bots


【解决方案1】:

这里的 cmets 大多是正确的。

Discord.js v12+ 使用缓存,而不是 .get("id") 正常工作。

所以是的,你需要使用 client.guilds.fetch("id") 来代替返回一个承诺。

因此,改为使您的函数异步(除非您希望将所有内容都包装在 .then() 中,这是更简单的方法)

// Example, missing out a fair bit of your code, just showing the things you need to edit

async function updateStats(client) {
    let guild = await client.guilds.fetch(settings.BOT_SETTINGS.Guild_ID,{ force:true, cache:true }); // force skips cache checking, cache will cache the user    let members = await guild.members.fetch({ force:true, cache:true, withPresences:true }); // fetches *all* members of the guild, withPresences returns the user's presences, otherwise most will be nullish
    let onlineCount = members.filter(m => m.presence?.status === 'online').size;
}

我还建议使用 guild.memberCount 而不是 guild.members.sizemembers.size 使用获取的成员,这样更准确。

我知道我回答得太晚了,所以你可能已经自己想通了,但如果没有,希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2021-04-16
    • 2018-06-02
    • 1970-01-01
    • 2023-01-14
    • 2020-07-14
    • 2019-07-11
    • 2021-05-29
    • 2020-08-17
    相关资源
    最近更新 更多