简体   繁体   English

类型错误:无法读取未定义的属性“成员” - Discord.JS

[英]TypeError: Cannot read property 'members' of undefined - Discord.JS

So this is probably a "rookie"-type query, but I am so stuck on how to resolve this error.所以这可能是一个“菜鸟”类型的查询,但我对如何解决这个错误很困惑。 Basically I am wanting certain channels to automatically update stats within the server.基本上我希望某些频道自动更新服务器内的统计信息。 Running latest versions of Node.JS and Discord.JS.运行最新版本的 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)

The file that relates to it is Stats.JS:与之相关的文件是 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
    }

As I suspect it will be needed, this is my Config file:因为我怀疑它是需要的,这是我的配置文件:

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'
            }
          }

Any help greatly appreciated... this has been bugging me for months!非常感谢任何帮助......这几个月来一直困扰着我!

The comments here are mostly correct.这里的评论大多是正确的。

Discord.js v12+ uses caching as opposed to .get("id") just working. Discord.js v12+ 使用缓存而不是.get("id")只是工作。

So yes, you'd need to use client.guilds.fetch("id") which returns a promise instead.所以是的,你需要使用client.guilds.fetch("id")来代替它返回一个承诺。

So instead, make your function asynchronous (unless you'd prefer to wrap everything in .then(), this is the simpler method)因此,相反,使您的函数异步(除非您更愿意将所有内容都包含在 .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;
}

I also recommend using guild.memberCount over guild.members.size or members.size using the fetched members, just so it's more accurate.我还建议使用guild.memberCount 而不是guild.members.sizemembers.size使用获取的成员,这样会更准确。

I know I'm pretty late to answering so you might've figured it out yourself, but if not hopefully this helps.我知道我的回答已经很晚了,所以您可能已经自己弄清楚了,但如果没有希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:无法读取未定义 Discord.js javascript 的属性“添加” - TypeError: Cannot read property 'add' of undefined Discord.js javascript 类型错误:无法读取未定义的属性 'has' // Discord.js - TypeError: Cannot read property 'has' of undefined // Discord.js 遇到 TypeError:无法读取 Discord.JS 中未定义的属性“0” - Encountering TypeError: Cannot read property '0' of undefined in Discord.JS Discord.JS UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“startsWith” - Discord.JS UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined TypeError:无法读取未定义的属性“数据”| discord.js - TypeError: Cannot read property 'data' of undefined | discord.js 类型错误:无法读取未定义的属性“角色”|| Discord.js - TypeError: Cannot read property 'roles' of undefined || Discord.js (Discord.js)TypeError:无法读取未定义的属性“添加” - (Discord.js) TypeError: Cannot read property 'add' of undefined Discord.js:类型错误:无法读取未定义的属性“删除” - Discord.js : TypeError: Cannot read property 'remove' of undefined Discord.js“类型错误:无法读取未定义的属性‘有’” - Discord.js "TypeError: Cannot read property 'has' of undefined" discord.js错误TypeError:无法读取未定义的属性“ voiceChannel” - discord.js Error TypeError: Cannot read property 'voiceChannel' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM