discord.py运行报SyntaxError: 'await' outside function如何解决
报错原因
SyntaxError: 'await' outside function是Python基础语法错误:await关键字只能在被async def定义的异步函数内部使用,你当前的await ctx.send(...)直接写在了全局顶层作用域,没有放到异步函数里,不符合语法要求。
解决方法
discord.py中发送消息的逻辑通常要放在命令回调、事件回调这类异步函数中,你可以参考如下修正后的完整代码结构:
import discord from discord.ext import commands # 初始化bot实例,按需配置前缀和网关意图 bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) class Counter(discord.ui.View): @discord.ui.button(label='0', style=discord.ButtonStyle.red) async def counter(self, button: discord.ui.Button, interaction: discord.Interaction): number = int(button.label) button.label = str(number + 1) if number + 1 >= 5: button.style = discord.ButtonStyle.green await interaction.response.edit_message(view=self) # 将发送计数器消息的逻辑放在异步命令函数内 @bot.command() async def start_count(ctx: commands.Context): view = Counter() await ctx.send('Press to increment', view=view) # 填入你自己的Bot令牌启动 bot.run('YOUR_BOT_TOKEN')
额外注意事项
- 所有discord.py提供的异步API(包括
ctx.send、消息编辑、交互回复等)都必须用await调用,且调用位置必须在异步函数内部 - 你定义的
Counter视图类的按钮回调本身写法没有问题,已经符合异步函数的要求,仅需调整顶层发送消息的代码位置即可
内容的提问来源于stack exchange,提问作者discord.py_fanboy
相关产品推荐
相关产品推荐

