当前位置: 首页 > 知识库问答 >
问题:

我对这段代码有问题

法子昂
2023-03-14

我正在为我的discord机器人制作一个管理cog,我的代码无法识别“ctx”。PyCharm建议用“self”代替“ctx”,我不知道“self”是做什么的。从PyCharm所说的,还有数以百万计的其他东西,我必须写下它是什么。PyCharm无法识别帮会、发送、作者和频道,它还说返回ctx。著者公会许可证。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))

共有1个答案

谢修真
2023-03-14

在类中,(除非是staticmethodclassmethod),您总是将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时是什么情况,它都将结束。如果您还想计算第二个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

 类似资料: