discord.py中!coinflip命令报错:'await'不在async函数内
解决discord.py中!coinflip命令的SyntaxError: 'await' outside async function错误
核心问题是缩进混乱——你把await bot.wait_for的代码写到了check同步函数内部,而同步函数里不能用await;同时整体逻辑嵌套错误,导致代码执行路径完全不对。
以下是修复后的完整代码,附带关键优化点说明:
import discord import random import os @bot.event async def on_message(ctx): # 兼容其他命令(如果有的话),不影响当前逻辑 await bot.process_commands(ctx) if ctx.content.startswith('!coinflip'): embed = discord.Embed(title='Choose heads or tails:', color=0x00ff00) embed.set_footer(text='React with either 🐒 Tails or 🗣️ Heads to make your choice. If you win, 10 coins will be added.') msg = await ctx.channel.send(embed=embed) # 补上缺失的tails表情,让用户能选两个选项 await msg.add_reaction('🗣️') await msg.add_reaction('🐒') # check函数只做校验,是同步函数,不要放执行逻辑 def check(reaction, user): return user == ctx.author and str(reaction.emoji) in ['🐒', '🗣️'] # 把await逻辑移到check函数外面,属于on_message这个异步函数的执行流程 reaction, user = await bot.wait_for('reaction_add', check=check) # 根据用户反应判断选择 choice = 'heads' if str(reaction.emoji) == '🗣️' else 'tails' # 模拟抛硬币结果 flip = random.choice(['heads', 'tails']) # 处理输赢和金币更新 if choice == flip: userid = ctx.author.id file_path = f"{userid}.txt" # 用with语句自动管理文件,避免手动close出错 if os.path.isfile(file_path): with open(file_path, 'r') as file: coins = int(file.read()) newcoins = coins + 10 else: # 用户第一次玩,初始给10金币 newcoins = 10 with open(file_path, 'w') as file: file.write(str(newcoins)) await ctx.channel.send(f'You win! The coin landed on {flip}.') else: await ctx.channel.send(f'You lose! The coin landed on {flip}.')
关键修复点:
- 修正缩进:把
await bot.wait_for及后续逻辑从check函数内移出,确保await处于on_message这个异步函数的作用域中。 - 简化check函数:
check只用来过滤符合条件的反应(必须是命令发起者,且表情是指定的两个),不包含执行逻辑。 - 完善交互:补上之前缺失的🐒表情,让用户能选择tails选项。
- 优化文件操作:用
with语句自动处理文件的打开/关闭,同时新增了文件不存在时的初始化逻辑。 - 兼容其他命令:添加
await bot.process_commands(ctx),避免当前on_message逻辑影响其他用@bot.command()定义的命令。
内容的提问来源于stack exchange,提问作者Ronghan Yury
相关产品推荐
相关产品推荐

