Discord机器人调用test()报coroutine未等待RuntimeWarning错误求助
报错原因
你遇到的这个报错有两个核心诱因:
test()是用async关键字定义的协程函数,Python 协程不能像普通函数一样直接调用,必须通过await执行,或者提交给 asyncio 事件循环调度才能正常运行,直接调用test()就会触发「协程未被等待」的警告。- 你的爬虫逻辑写在
threading.Thread的子类里,且错误地将run()方法定义为异步方法:普通线程启动时只会同步执行run()逻辑,不会自动初始化异步事件循环来执行这个异步run()方法,导致你写在run()里的await test()根本没有被事件循环调度,相当于直接调用了协程,才触发了对应报错。
此外你现在的代码架构还存在一个隐藏问题:discord.py 完全基于 asyncio 事件循环运行,单独开的线程和 discord 的事件循环不互通,就算你修复了协程调用问题,跨线程调用 discord 的消息发送方法也会触发事件循环安全报错。
修复方案
直接弃用自定义线程逻辑,把爬虫循环做成 asyncio 任务,在 discord 客户端的on_ready钩子中启动,和 discord 共用同一个事件循环,避免跨线程问题。核心修改代码如下:
import discord import asyncio from selenium import webdriver import re listposts=[] listView = None token = 'xxx' client = discord.Client(intents=discord.Intents.all()) # 记得去Discord开发者后台开启对应intents权限 chrome_path = r"C:\Users\crayx\Desktop\chromedriver.exe" driver = webdriver.Chrome(chrome_path) driver.get("C:/Users/crayx/Desktop/testweb.html") async def test(): channel = client.get_channel(123456789) # 替换为你自己的目标频道ID await channel.send(listView[0]) # 爬虫循环改造为异步任务 async def scrape_loop(): while True: try: # 把selenium的同步操作扔到后台线程跑,避免阻塞discord事件循环 await asyncio.to_thread(driver.refresh) posts = await asyncio.to_thread(driver.find_element_by_xpath, """//*[@id="g-mainbar"]/div/div/div/div/div[1]/div/div[2]/div""") listposts.append(posts.text) await asyncio.sleep(5) global listView if listposts and listposts != listView: listView = listposts.copy() print(listView) await test() listposts.clear() except Exception as e: print(f"爬取出错: {e}") await asyncio.sleep(5) continue @client.event async def on_ready(): # 启动爬虫异步任务 client.loop.create_task(scrape_loop()) await asyncio.sleep(5) print("BOT IS RUNNING") # 你原来写的on_message查询逻辑保持不变即可,此处省略原有代码
修改后删除原有main()相关的线程启动代码,直接运行client.run(token)即可正常运行。
内容的提问来源于stack exchange,提问作者terry555
相关产品推荐
相关产品推荐

