【发布时间】:2021-02-17 22:11:21
【问题描述】:
我几乎是编程新手。我想在我的机器人中添加一个函数来计算具有 x 角色的成员数量,它总是相同的角色。我一直在尝试使用role.members,但我得到了错误
NameError:名称“角色”未定义
谢谢!
【问题讨论】:
-
这只是意味着“角色”不存在,所以你必须定义一个具有该名称的变量。
标签: python discord.py
我几乎是编程新手。我想在我的机器人中添加一个函数来计算具有 x 角色的成员数量,它总是相同的角色。我一直在尝试使用role.members,但我得到了错误
NameError:名称“角色”未定义
谢谢!
【问题讨论】:
标签: python discord.py
在Role.members 上使用len,但要获得角色Guild.get_role(role_id)
下面是代码:
@bot.command()
async def rolemembers(ctx):
role = ctx.guild.get_role(ROLE_ID)
await ctx.send(len(role.members))
【讨论】:
可能有点晚了,但您可能需要检查使用意图以使用解决方案。
参考:Discord Bot can only see itself and no other users in guild
【讨论】:
复制我这是有史以来最简单的方法
import discord
from discord.ext import commands,tasks
intents = discord.Intents.default()
intents.members = True
#If without intents It will return 0 so it should be like this
bot = commands.Bot(command_prefix='?',intents=intents)
@bot.command()
#You can create any name
async def users_in_role(ctx,role: discord.Role):
#this will give the length of the users in role in an embed
embed = discord.Embed(description =
f"**Users in role:**\n{len(role.members)}")
await ctx.send(embed=embed)
@bot.event
async def on_ready():
print('bot online')
#in the discord type ``?users_in_role @role_name`` example ``?users_in_role @Owner``
#for the discord token you should go to discord.dev and make an application and in the bot page create a bot and then copy its token
bot.run("BOT_TOKEN_HERE")
【讨论】: