【问题标题】:I am having trouble with this piece of code我在处理这段代码时遇到了问题
【发布时间】:2021-01-05 18:18:59
【问题描述】:

我正在为我的 discord 机器人制作管理 cog,但我的代码无法识别“ctx”。 PyCharm 建议用“self”替换“ctx”,我不知道“self”是做什么的。根据 PyCharm 的说法,还有数以百万计的其他内容,我必须写下它是什么。 PyCharm 无法识别 guildsendauthorchannel,它还说 return ctx.author.guild_permissions.manage_messages 是无法访问的代码。如果这似乎是一个非常愚蠢的问题,请注意,我是 2 周前开始的初学者。

至于代码:

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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 如果有帮助记得采纳答案
    猜你喜欢
    • 2021-06-21
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多