簡體   English   中英

Discord.js 知道機器人的所有公會有多少用戶

[英]Discord.js Know how many users are in all the guilds of the bot

我正在 discord.js v12 中編寫一個不和諧的機器人。 我想知道我的機器人所在的所有服務器中有多少用戶。我不想多次計算同一個用戶,這會導致結果錯誤。 我也不想計算機器人。

這是我的代碼,(這給了我用戶和機器人的數量,並且還多次給我一個用戶,因為他在機器人所在的多個服務器中):

bot.on('message', msg => {
    if(msg.content === PREFIX + "total members") {
        msg.channel.send(bot.guilds.cache.reduce((a, g) => a + g.memberCount, 0))
    }
})

希望你能幫忙。 謝謝!

添加到 Skulaurun Mrusal 的答案中,您希望在計算大小之前確保機器人的所有用戶都在緩存中。 為此,您需要在獲取緩存大小之前獲取所有用戶。

代碼如下:

// Get all the users and dump to cache before filtering
client.users.fetch()
const users = client.users.cache.filter(user => !user.bot);
console.log(users.size);

(因為在大型機器人中,並非所有用戶都被緩存,如果不獲取所有用戶,則可能占真實用戶數的 25-50%)

您可以使用Client.users並過濾掉機器人。

您無法獲取所有User ,當每個公會的 websocket 上發出事件GUILD_CREATE時,它們會自動緩存多達 75k 個用戶。 根據Discord 開發者門戶 對於 discord.js v13,您需要啟用GUILD_PRESENCES意圖。

請注意,您不能使用UserManager.fetch()來獲取所有用戶,因為它有一個必需的參數id (參考雷霆的回答。)

// A Discord.Collection of users
const users = client.users.cache.filter(user => !user.bot);
// Use .size property to access the total count of cached users
console.log(users.size);

不能保證所有用戶都將在GUILD_CREATE事件上發送到客戶端,有關更准確的解決方案,請參見下面的解決方案。

您可以使用GuildMemberManager.fetch()來獲取每個公會的所有GuildMember 請參見下面的示例(保證userIds包含用戶的所有唯一 ID,即使他們處於離線狀態):

// Initialize a storage for the user ids
const userIds = new Set();
// Iterate over all guilds (always cached)
for (const guild of client.guilds.cache.values()) {
    // Fetch all guild members and iterate over them
    for (const member of (await guild.members.fetch()).values()) {
        // Fetch the user, if user already cached, returns value from cache
        // Will probably always return from cache
        const user = await client.users.fetch(member.id);
        // Check if user id is not already in set and user is not a bot
        if (!userIds.has(user.id) && !user.bot) {
            // Add unique user id to our set
            userIds.add(user.id);
        }
    }
}
// Use .size property to access the size of the set
console.log(userIds.size);

請注意, clientDiscord.Client一個實例。

使用 discord.js ^12.5.3測試。

我寫了一個快速且經過驗證的代碼:

var usersCount= 0;
client.guilds.cache.mapValues(guild => {
const _x = client.guilds.cache.get(guild.id);
      usersCount += client.guilds.cache.reduce((a, g) => a + g.memberCount, 0)
});
message.channel.send(usersCount);
usersCount = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM