【问题标题】:discord.py SyntaxError: 'await' outside async functiondiscord.py SyntaxError: 'await' 在异步函数之外
【发布时间】:2021-03-05 03:41:51
【问题描述】:

我在下面的整个代码中遇到了错误。 我想就错误寻求帮助。 我可以通过查看下面的代码来寻求帮助吗?

async def ban(ctx, member: discord.Member, *, reason: typing.Optional[str] = "사유 없음."):
    await ctx.message.delete()
    author = ctx.message.author
    embed = None
    ch = bot.get_channel(id=772349649553850368)

    mesge = await ctx.send("차단을 시킬까요?")
    await mesge.add_reaction('✅')
    await mesge.add_reaction('❌')
        
    def check1(reaction, user):
        return user == ctx.message.author and str(reaction.emoji) == "✅"

        try:
            reaction, user = await bot.wait_for("reaction_add", timeout = 30.0, check = check1)
            embed = discord.Embed(title="종합게임 커뮤니티 제재내역 - 차단", description=f'담당자 : {author.mention} \n대상자 : {member.mention} \n제재사유 : {reason} \n\n위와 같은 사유로 인해 제재처리 되었습니다.', color=0xff0000)
            embed.set_author(name=f"{str(member)}님을 서버에서 영구적으로 차단했어요.", icon_url=member.avatar_url_as(static_format='png', size=2048))
            embed.set_footer(text=f'처리 시각 - {str(now.year)} 년 {str(now.month)} 월 {str(now.day)} 일 | {str(now.hour)} 시 {str(now.minute)} 분 {str(now.second)}초 - 담당자 : {author.display_name}')
            await ch.send(embed=embed)
            await member.send(embed=embed)
            await ctx.guild.ban(member, reason=f'사유 : {reason}  -  담당자 : {author.display_name}')
    
        except asyncio.TimeoutError:
            print("Timeout")
    
    def check2(reaction, user):
        return user == ctx.message.author and str(reaction.emoji) == "❌"

        try:
            reaction, user = await bot.wait_for("reaction_add", timeout = 30.0, check = check2)
            await ctx.send("취소되었다")
        
        except asyncio.TimeoutError:
            print("Timeout")

以上代码出现如下错误。

reaction, user = await bot.wait_for("reaction_add", timeout = 30.0, check = check1)
                     ^
SyntaxError: 'await' outside async function

如果你知道如何解决它,请帮忙。

我用了翻译器。

【问题讨论】:

  • 您是否尝试将def check1 更改为async def check1def check2 更改为async def check2?我对 async/await 做的不多,但这是我首先要尝试的,因为它似乎是错误消息建议你做的。
  • 我认为它的标识。请注意,try 块在函数 check1 内...您要删除该代码,使其位于 ban 中。
  • check2 也一样。当它应该向左缩进 4 个空格以便它是父函数的一部分时,您将以下 try 放在函数内。

标签: python discord discord.py


【解决方案1】:

Python 使用标识来识别代码块。在您的代码中,您将 await 调用置于非异步函数 check1 内。以下是相同问题的示例:

async def foo():

    def check1():
        return True
        
        baz = await bar() # improperly indented and in fact can never
                          # run because it is after the function `return`

解决方法是将代码移出check1。它应该与上面的“def”语句一致。

async def foo():

    def check1():
        return True
        
    baz = await bar()

【讨论】:

    【解决方案2】:

    您的问题是两次检查后的缩进。

    我添加了# ---- here ----,以便您知道check的结束位置

    async def ban(ctx, member: discord.Member, *, reason: typing.Optional[str] = "사유 없음."):
        await ctx.message.delete()
        author = ctx.message.author
        embed = None
        ch = bot.get_channel(id=772349649553850368)
    
        mesge = await ctx.send("차단을 시킬까요?")
        await mesge.add_reaction('✅')
        await mesge.add_reaction('❌')
            
        def check1(reaction, user):
            return user == ctx.message.author and str(reaction.emoji) == "✅"
        
        # ---- here ----
        
        try:
            reaction, user = await bot.wait_for("reaction_add", timeout = 30.0, check = check1)
            embed = discord.Embed(title="종합게임 커뮤니티 제재내역 - 차단", description=f'담당자 : {author.mention} \n대상자 : {member.mention} \n제재사유 : {reason} \n\n위와 같은 사유로 인해 제재처리 되었습니다.', color=0xff0000)
            embed.set_author(name=f"{str(member)}님을 서버에서 영구적으로 차단했어요.", icon_url=member.avatar_url_as(static_format='png', size=2048))
            embed.set_footer(text=f'처리 시각 - {str(now.year)} 년 {str(now.month)} 월 {str(now.day)} 일 | {str(now.hour)} 시 {str(now.minute)} 분 {str(now.second)}초 - 담당자 : {author.display_name}')
            await ch.send(embed=embed)
            await member.send(embed=embed)
            await ctx.guild.ban(member, reason=f'사유 : {reason}  -  담당자 : {author.display_name}')
    
        except asyncio.TimeoutError:
            print("Timeout")
        
        def check2(reaction, user):
            return user == ctx.message.author and str(reaction.emoji) == "❌"
        # ---- here ----
        
        try:
            reaction, user = await bot.wait_for("reaction_add", timeout = 30.0, check = check2)
            await ctx.send("취소되었다")
        
        except asyncio.TimeoutError:
            print("Timeout")
    

    【讨论】:

    • check1check2 都不需要是 async。它们是简单的逻辑检查,不会阻塞。
    • 我现在看到了,我以为try 在它之外,
    • 一开始我也被它抓住了。对您为什么要在 返回之后执行 try 块感到困惑。
    猜你喜欢
    • 2022-08-21
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多