discord.py:如何关联两个on_message事件变量并存入数据库
解决方法
核心思路
当用户发送;stats请求时,先记录用户的userid,再通过asyncio.wait_for监听第三方bot的对应回复,将两者关联后存入数据库,避免单独处理两个事件导致的变量脱节问题。
修改后的代码示例
import asyncio @bot.listen() async def on_message(message): # 捕获用户的;stats请求 if message.content.startswith(';stats') and message.channel.id == 970590429861003284: user_id = message.author.id try: # 等待第三方bot的回复,超时时间设为10秒(可按需调整) bot_reply = await bot.wait_for( 'message', timeout=10.0, # 检查条件:来自目标bot、同一频道,且是对当前用户请求的回复(如果bot是回复消息的话) check=lambda m: ( m.author.id == [替换为第三方bot的ID] and m.channel.id == 970590429861003284 and m.reference is not None and m.reference.message_id == message.id ) ) # 从bot回复中提取username new_embed = database.embedder(bot_reply) author = new_embed['author'] username_from_bot = author['name'].split("'s Stats")[0] # 关联userid和username,存入数据库 await database.save_user_association(user_id, username_from_bot) # 若需保留原newuser逻辑,可调整参数传入关联后的数据 # await database.newuser(message, user_id, username_from_bot) except asyncio.TimeoutError: # 处理第三方bot超时未回复的情况 await message.channel.send("获取数据超时,请稍后重试")
关键细节说明
wait_for的使用:专门监听message事件,直到满足check条件或触发超时。相比单独处理两个on_message事件,能直接在用户请求的上下文里关联回复数据。- 精准匹配回复:如果第三方bot是通过回复用户消息的方式发送统计结果,
check里的m.reference.message_id == message.id能确保捕获的是对应当前用户请求的回复,避免同一频道多用户请求时的数据混淆。 - 超时处理:必须用
try-except捕获TimeoutError,防止bot因无限等待而崩溃。 - 数据库适配:将
save_user_association替换为你实际的数据库存储方法,传入关联后的user_id和username_from_bot即可。
内容的提问来源于stack exchange,提问作者AgilyX
相关产品推荐
相关产品推荐

