下面的代码在服务器内部工作:
@client.command()
async def test(ctx):
await ctx.send(len(ctx.author.roles))
Via PM i get:
Command raised an exception: AttributeError: 'User' object has no attribute 'roles'
好像看不懂角色,有什么办法吗?
将Member
视为"协会的用户";和User
作为"不和谐的用户"。
如例外所说:'User' object has no attribute 'roles'
和roles
只是公会不和的事;没有所谓的User.roles
,因为没有"角色"。在"不和谐"中本身。
你要找的是Member
,因为他们是"公会用户"。并且只有"公会用户";可以有roles
.
所以当你的命令在DM(又名PM)中调用时,你的Member
也会消失,因为就像我说的,它们存在于公会中,而在DM中不存在。
在dm中,剩下的是User
。这就是你不能在dm中执行ctx.author.roles
的原因,因为ctx.author
是User
,而User
对象没有任何role
。
你可以尝试获得Member
,但Member
是公会的一部分,所以你需要Guild
。
一旦你有了Guild
:你可以查看Guild
的所有Members
,并在Guild
中找到你的命令作者(又名ctx.author
)的Member
版本,这样你就可以查找它的角色。
整个过程分为三个部分:
- 查找
Guild
。(这是最难的部分。) - 在
Guild
中找到User
的Member
版本。 - 最终得到
Member
的Roles
。
对于第一个进程,我可以链接你:User.mutual_guilds
,Guild.text_channels
,TextChannel.history
,Context.prefix
,Context.invoked_with
对于第二个进程,我可以链接:utils.get
和User.id
对于第三个进程:你可以直接使用Member.roles
哈!现在您已经拥有了使该命令工作所需的所有资源。