discord.py - 我在处理这段代码时遇到了问题
问题描述
我正在为我的不和谐机器人制作管理齿轮,但我的代码无法识别“ctx”。PyCharm 建议用“self”替换“ctx”,我不知道“self”是做什么的。根据 PyCharm 的说法,我必须写下数以百万计的其他内容。PyCharm 无法识别guild、send、author和channel,它还说这return ctx.author.guild_permissions.manage_messages
是一个无法访问的代码。如果这似乎是一个非常愚蠢的问题,请注意,我是两周前开始的初学者。
至于代码:
class Administration(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Admin cog ready")
async def cog_check(self, ctx):
admin = get(ctx.guild.roles, name="Admin")
return admin in ctx.author.roles
return ctx.author.guild_permissions.manage_messages
@commands.command(aliases=["purge"])
async def clear(ctx, amount=3):
"""Clears 3 messages"""
await ctx.channel.purge(limit=amount)
@commands.command(pass_context=True)
async def giverole(ctx, user: discord.Member, role: discord.Role):
"""Gives a role to a user"""
await user.add_roles(role)
await ctx.send(f"hey {ctx.author.name}, {user.name} has been giving a role called: {role.name}")
@commands.command(aliases=['make_role'])
@commands.has_permissions(manage_roles=True)
async def create_role(ctx, *, name):
"""Creates a role"""
guild = ctx.guild
await guild.create_role(name=name)
await ctx.send(f'Role `{name}` has been created')
@commands.command(name="slap", aliases=["warn"])
async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
"""Warns someone"""
slapped = ", ".join(x.name for x in members)
await ctx.send('{} just got slapped for {}'.format(slapped, reason))
def setup(client):
client.add_cog(Administration(client))
解决方案
在类中,(除非它是 astaticmethod
或)你总是作为第一个参数classmethod
传递。self
@commands.command(aliases=["purge"])
async def clear(self, ctx, amount=3): # Note how I put `self` as the first arg, do the same in all commands in the cog
"""Clears 3 messages"""
await ctx.channel.purge(limit=amount)
此外,这永远不会奏效
async def cog_check(self, ctx):
admin = get(ctx.guild.roles, name="Admin")
return admin in ctx.author.roles
return ctx.author.guild_permissions.manage_messages
无论何时到达第一个,该函数都会结束,如果您还想评估第二个语句return
,您可以简单地使用AND
or逻辑运算符OR
return
async def cog_check(self, ctx):
admin = get(ctx.guild.roles, name="Admin")
return admin in ctx.author.roles and/or ctx.author.guild_permissions.manage_messages
推荐阅读
- linux - BPF 验证器拒绝代码:“无效的 bpf_context 访问”
- java - 如何在优先级队列中使用对,然后使用键作为优先级返回值
- thunderbird - 如何使用雷鸟命令行添加多个附件?
- django - 我一次又一次地重定向到同一个登录页面,它甚至没有验证凭据
- machine-learning - 文本分类和特征选择有什么区别
- r - map 和 lapply 调用存储在字符串中的函数
- python - Pandas - 希望将基于 int 的窗口转换为基于时间的窗口
- javascript - 我应该如何将 jsons 附加到 javascript 中的变量/另一个 json
- java - 如何在java中使用Split方法
- html - 在其他平台上分享 URL 时图片不显示