首页 > 解决方案 > 自定义前缀后的额外空格 [Discord.py]

问题描述

我尝试制作自定义前缀命令,但为了提高效率,如果前缀包含字母字符(az),我将在其中添加额外的空格,但是当我使用它时,它说 new_prefix 是在分配之前引用,它有效,我只是想知道为什么?

    @command(name='prefix')
    @has_permissions(manage_guild=True)
    @guild_only()
    async def prefix_cmd(self, ctx, *, prefix=None):
        if prefix is None:
            async with connect('dumbo.db') as db:
                prefix_db = await db.execute(f"SELECT Prefix FROM guilds WHERE GuildID = {ctx.guild.id}")
                server_prefix = await prefix_db.fetchone()
            await ctx.send(f"{emotrue} This server prefix is: `{server_prefix[0]}`.")
        else:
            for spaced in alphabet:
                if spaced in prefix.lower():
                    new_prefix = f'{prefix} '
            async with connect('dumbo.db') as db:
                await db.execute(f"UPDATE guilds SET Prefix = ? WHERE GuildID = ?", (f'{new_prefix}', ctx.guild.id))
                await db.commit()
            await ctx.send(f"{emotrue} This server prefix is now updated to `{prefix}`.")```

标签: sqlitediscorddiscord.pydiscord.py-rewrite

解决方案


那是因为您new_prefix在 if 语句中定义,所以只有当该语句为 True(有时可能为 False)new_prefix时才会是一个东西,所以它说在定义之前使用。if

如果您new_prefix = ''在命令或 else 语句的开头这样做,它应该可以解决错误


推荐阅读