discord.py触发随机函数运行出现coroutine未await报错如何修复
修复方案
核心错误原因
- 自定义函数
Hello、Test错误添加了@client.event装饰器,二者属于业务函数不是Discord原生事件 - 构造函数列表时直接调用了协程函数,没有在选中后再执行并等待
- 重复定义了
on_message事件,且重写后没有添加命令处理逻辑,导致预设的_summon、common_phrases命令无法生效 - 异步代码中使用了同步阻塞的
time.sleep(),会卡住整个机器人进程 Hello、Test内的触发逻辑判断有误,你传入的是用户发送please的消息对象,message.content的值是please,不可能匹配quiz/test的判断条件
修复步骤
1. 调整导入包
新增asyncio导入,替换同步sleep:
import discord from discord.ext import commands import random import asyncio
2. 清理错误装饰器
去掉Hello、Test上的@client.event装饰器,调整函数内触发逻辑
3. 修正on_message事件
只保留一个on_message,添加命令处理逻辑,调整随机调用函数的写法
4. 替换阻塞方法
所有time.sleep(2)替换为await asyncio.sleep(2)
完整可运行代码
import discord from discord.ext import commands import random import asyncio # 记得在Discord开发者后台开启Message Content Intent client = commands.Bot(command_prefix = '', intents=discord.Intents.all()) x = 0 @client.event async def on_ready(): print("bot is ready") @client.command(aliases=['Signore']) async def _summon(ctx): await ctx.send('Ciao sono Signore Buffo') @client.command(aliases=['Gib']) async def common_phrases(ctx): responses = [ 'Si. Yes.', 'No. No.', 'Per favore. Please.', 'Grazie. Thank you.','Prego. Youre welcome.', 'Mi scusi. Excuse me.', 'Mi dispiace. I am sorry.', 'Buon giorno. Good morning.', 'Buona sera. Good evening.', 'Buona notte. Good night.' ] await ctx.send(random.choice(responses)) # 自定义业务函数不要加event装饰器 async def Hello(message): global x x = 1 await message.channel.send('what is Hello in italian?') await asyncio.sleep(2) await message.channel.send('Would you like to know the answer? (y/n)') async def Test(message): global x x = 2 await message.channel.send('This is a test') await asyncio.sleep(2) await message.channel.send('this is a test (2)') @client.event async def on_message(message): # 跳过机器人自身消息 if message.author.id == client.user.id: return # 处理please触发逻辑 if message.content == "please": # 列表存储函数引用,不要提前调用 functions = [Hello, Test] # 选中函数后再传参调用并等待 selected_func = random.choice(functions) await selected_func(message) # 处理后续答案回复 global x if x == 1 and message.content == "y": await message.channel.send('Ciao') x = 0 if x == 2 and message.content == "bruh": await message.channel.send('test complete') x = 0 # 必须添加这行,否则自定义命令不会生效 await client.process_commands(message) client.run('你的bot token')
额外注意事项
全局变量x在多服务器/多用户场景下会出现状态冲突,正式使用建议用字典按用户/服务器ID单独存储状态。
内容的提问来源于stack exchange,提问作者Quentin Phillips
相关产品推荐
相关产品推荐

