discord.py - 未定义的变量“公会”
问题描述
我试图制作一个 addrole 命令,但它不起作用。我收到错误:`undefined Variable 'guild' 我编写了代码 abc=guild.roles() 以列出服务器中的角色,但它不起作用请帮助
@client.command(pass_context=True)
async def addrole(ctx, user: discord.Member, role: discord.Role):
if ctx.author.guild_permissions.administrator:
xx=user.roles
abc= guild.roles()
if role in xx:
if role in abc:
await user.add_roles(role)
await ctx.send(f'{user.mention}, {role} is given')
else:
await ctx.send(f'The role you are looking for is not in the server')
else:
await ctx.send(f'The User already have the role')
else:
await ctx.send(f'You Have not enough permissions to run this command')
解决方案
guild
目前在您的范围内不存在。您需要一个discord.Guild
对象才能获得其角色。
通过使用context
,您可以获取发送命令的公会:
@client.command() # context is automatically passed in rewrite
async def addrole(ctx, user: discord.Member, role: discord.Role):
if ctx.author.guild_permissions.administrator:
xx = user.roles
abc = ctx.guild.roles
if role in xx:
if role in abc: # see footnote
await user.add_roles(role)
await ctx.send(f'{user.mention}, {role} is given')
else:
await ctx.send('The role you are looking for is not in the server')
else:
await ctx.send('The User already have the role')
else:
await ctx.send('You Have not enough permissions to run this command')
# irrelevent check, as if the user has it, then it's guaranteed to be in the guild.
# Also, if it didn't exist, the command would error
# because the role needs to exist in the guild (discord.Role in arg types)
# in order for the command to execute
我还删除了不需要的 f 弦。它们用于格式化,因此f
, 并且在某些地方你没有格式化字符串中的变量,所以我把它们拿出来了。
除此之外,到目前为止,您的代码看起来不错,请继续努力!
参考:
- f-string 用法- Python 3.6.0+
- 自动上下文传递
commands.Context
- 在命令的上下文中,您可以使用所有这些属性。它是第一个参数,通常命名为ctx
.Context.guild
Guild.roles
- 注意它不是协程/函数,所以你不需要用括号来调用它()
。在文档中,如果它是函数,您将在末尾看到括号,await
如果是协程,则在前面看到括号。
推荐阅读
- memory - 为什么 CPU 访问对齐的内存
- classification - 如何为随机森林设置 class_weight 字典?
- postgresql - How to insert data into multiple table using single query in postgresql
- r - 堆积线面积图在ggplot中不起作用
- c# - 如何使用 EF Core 迁移在我的数据库中创建许多表
- javascript - Wierd Error while working with unlimited argument function Node JS
- azure - Terrafrom Dynamic block with tags
- python - How do I create one column in pandas (Python) based on indexes out of multiple columns?
- c++ - Pointer to class with only static methods
- java - 在类/方法之间交换值