【问题标题】:Discord list all members python不和谐列出所有成员python
【发布时间】:2021-04-21 10:09:16
【问题描述】:

我正在尝试制作一个机器人来列出拥有我询问的角色的成员列表(命令:$role 管理员回答:3 人具有管理员角色)以及何时询问(命令:$role list 管理员回答:@Justyn、@JustBoy、@JustBoss)。

我试过这段代码:

@bot.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def members(ctx,*args):
    server = ctx.message.guild
    role_name = (' '.join(args))
    role_id = server.roles[0]
    for role in server.roles:
        if role_name == role.name:
            role_id = role
            break
    else:
        await ctx.send("Role doesn't exist")
        return
    for member in server.members:
        if role_id in member.roles:
            await ctx.send(f"{member.display_name} - {member.id}")

但是当我问 $members Botz 时,答案只是“Justyn Bot - 799779320906121236”(在服务器上,我有 8 个角色为 Botz 的机器人,但它只列出了自己的机器人(本身))。所以我很困惑。

如果有人知道怎么做,请告诉我!谢谢。

【问题讨论】:

  • 您是否启用了意图?
  • 应该不会吧?我什至不知道它是什么。
  • 我知道我错过了@bot.command(pass_context=True)

标签: python discord bots discord.py


【解决方案1】:

列出成员

Guild.members 需要启用intents.members,才能启用它们:

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(..., intents=intents)

还要确保在developer portal, (here's how) 中启用它们

编辑

列出具有特定角色的成员

async def whatever(ctx, role: discord.Role): # The `role` arg will be converted to a `discord.Role` instance
    await ctx.send(f"There's {len(role.members)} users with the role {role.name}")

参考:

【讨论】:

  • 和它的工作一样,只需要发出“有X人角色管理员”的命令
  • 最简单的方法是获取discord.Role 实例并使用members 属性,我将通过示例编辑我的答案
  • 有没有办法用名字替换ID? (所以命令将是 !role Admin 并带有答案`There's X users with the role Admin)
  • 你可以用RoleConverter,让我也编辑一下答案
  • 太棒了!您可以对其进行编辑,以便他们了解答案的第一部分是列出用户,第二部分是写下有多少人担任角色?之后我会将其标记为已回答。
【解决方案2】:

您必须启用来自Discord Developer Portal 的意图,并且您必须在代码中定义它才能使用一些事件和方法,例如discord.Member.roles

在开发者门户中,您必须这样做:

选择应用程序 -> 机器人 -> 特权网关意图 -> 启用存在意图和服务器成员意图

在您的代码中:

import discord
from discord.ext import commands

intents = discord.Intents().all()
bot = commands.Bot(command_prefix="<prefix>", intents=intents)

更多信息,您可以查看API References about intents

【讨论】:

  • 它的工作!谢谢,对于我的第二个“问题”,如何制作;role Admin 和答案There are X people in role Admin 你知道怎么做吗? + 有什么方法可以将其作为一条消息发送(它发送名称 - ID、新消息名称 ID ....)
  • 喜欢这个 .js let roleID = "264410914592129025"; let membersWithRole = message.guild.roles.cache.get(roleID).members; console.log(Got ${membersWithRole.size} 个具有该角色的成员。);
猜你喜欢
  • 1970-01-01
  • 2018-05-23
  • 2021-10-07
  • 1970-01-01
  • 2021-09-15
  • 2018-10-22
  • 1970-01-01
  • 2020-11-27
  • 2020-11-22
相关资源
最近更新 更多