首页 > 解决方案 > 我在处理这段代码时遇到了问题

问题描述

我正在为我的不和谐机器人制作管理齿轮,但我的代码无法识别“ctx”。PyCharm 建议用“self”替换“ctx”,我不知道“self”是做什么的。根据 PyCharm 的说法,我必须写下数以百万计的其他内容。PyCharm 无法识别guildsendauthorchannel,它还说这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))

标签: discord.py

解决方案


在类中,(除非它是 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,您可以简单地使用ANDor逻辑运算符ORreturn

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

推荐阅读