Python多线程运行多个Discord Bot出现无当前事件循环RuntimeError求助
错误根因
asyncio.get_event_loop() 仅会为主线程自动初始化并绑定事件循环。在非主线程的工作线程中,如果没有提前为当前线程显式创建、绑定事件循环,调用该方法就会直接抛出RuntimeError。而discord.py的Client类初始化时,默认会通过该方法获取事件循环实例,因此所有子线程创建Client的环节都会触发报错。
修复方案
有两种可落地的实现路径,第一种适配现有代码的改动量最小,第二种是更优的架构选择:
方案1:为每个bot运行的子线程手动绑定独立事件循环
仅需要在main函数的最开头,为当前子线程创建并绑定独立的事件循环,后续创建discord Client的流程就可以正常执行,不需要改动其他业务逻辑。
核心代码改动点:
- 进入
main函数后第一时间创建当前线程专属的事件循环 - (推荐)创建
discord.Client时显式传入该循环,避免版本兼容边界问题
def main(bottoken, botname): # 核心修复:为当前子线程创建并绑定独立事件循环 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) TOKEN = bottoken # 显式传入事件循环,进一步规避兼容问题 client = discord.Client(loop=loop) @client.event async def on_ready(): print(f'{client.user.name} has connected to Discord!') @client.event async def on_message(message): # 业务逻辑 print('Do stuff') client.run(TOKEN)
配套代码优化
原代码把csv读取、启动线程的逻辑嵌套在runtask函数内部,还在函数里写了if __name__ == '__main__',逻辑分层冗余。可以直接调整为:
- 读取csv时跳过首行表头,避免把字段名当bot配置启动报错
- 对读取到的token、bot名称做空格过滤,避免多余字符导致鉴权失败
- 跳过csv中的空行,避免空token触发线程内报错
优化后的完整可运行代码:
import csv import asyncio from threading import Thread import discord def main(bottoken, botname): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = discord.Client(loop=loop) @client.event async def on_ready(): print(f'[{botname}] {client.user.name} has connected to Discord!') @client.event async def on_message(message): print(f'[{botname}] Received message: {message.content}') client.run(bottoken) if __name__ == '__main__': with open('botinfo.csv', 'r') as f: reader = csv.reader(f, delimiter=',') # 跳过csv表头,文件没有表头的话可删除这行 next(reader, None) for row in reader: # 跳过空行 if not row or not row[0].strip(): continue token = row[0].strip() bot_name = row[1].strip() if len(row) >1 else "unnamed_bot" Thread(target=main, args=(token, bot_name)).start()
方案2(长期更优):单事件循环并发运行所有bot
如果bot规模在几十个以内,多线程并不是最优选择——discord.py原生支持在同一个asyncio事件循环里并发运行多个Client实例,这种方式的资源占用更低,也完全不会碰到线程事件循环绑定的问题。
这种方案不需要创建多线程,只需要在主事件循环中收集所有bot的启动协程,并发执行即可:
import csv import asyncio import discord if __name__ == '__main__': loop = asyncio.get_event_loop() bot_start_tasks = [] with open('botinfo.csv', 'r') as f: reader = csv.reader(f, delimiter=',') next(reader, None) for row in reader: if not row or not row[0].strip(): continue token = row[0].strip() bot_name = row[1].strip() if len(row) >1 else "unnamed_bot" client = discord.Client() @client.event async def on_ready(): print(f'[{bot_name}] {client.user.name} connected to Discord!') # 收集每个bot的启动协程 bot_start_tasks.append(client.start(token)) # 并发运行所有bot,无多线程开销 loop.run_until_complete(asyncio.gather(*bot_start_tasks))
踩坑提醒
- 不要跨线程复用同一个asyncio事件循环,asyncio事件循环不是线程安全的,跨线程调用会触发未知的运行异常
- 跨Python版本的逻辑通用:从3.7到3.12,子线程内未绑定事件循环时调用
get_event_loop()的报错逻辑完全一致,以上修复方案全部兼容 - 每个bot的网络请求、事件处理都不要做长阻塞的同步操作,否则会卡住当前循环的所有后续任务
内容的提问来源于stack exchange,提问作者cordmana
相关产品推荐
相关产品推荐

