多线程处理python时发生RuntimeError“RuntimeError:线程'Thread1'中没有当前事件循环。”

2024-05-18 18:37:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用相同的脚本同时运行多个discord机器人。我这样做的方式是下载一个csv文件,以获取bot令牌和bot名称。然后我开始我的脚本:

import time, csv, re, random, string, sys, os, asyncio
from datetime import datetime
from threading import Thread
import discord
from dotenv import load_dotenv
from discord_webhook import DiscordWebhook, DiscordEmbed

def main(bottoken, botname):
    TOKEN = (bottoken)
    client = discord.Client()

    @client.event
    async def on_ready():
        print(f'{client.user.name} has connected to Discord!')

    @client.event
    async def on_message(message):
         #do stuff
         print('Do stuff')

    client.run(TOKEN)

def runtask():

    if __name__ == '__main__':
        with open('botinfo.csv', 'r') as f:
            reader = csv.reader(f, delimiter=',')
            for i, row in enumerate(reader):
                Thread(target = main, args=(row[0], row[1])).start()

if __name__ == '__main__':
    runtask()

但是我得到了这个错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/alexforman/Documents/GitHub/bot-price-monitor/frontend_multithread.py", line 14, in main
    client = discord.Client()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 216, in __init__
    self.loop = asyncio.get_event_loop() if loop is None else loop
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/alexforman/Documents/GitHub/bot-price-monitor/frontend_multithread.py", line 14, in main
    client = discord.Client()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 216, in __init__
    self.loop = asyncio.get_event_loop() if loop is None else loop
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-2'.

有没有人对我如何修复它有什么想法


Tags: inpyselfclientloopeventlibline
1条回答
网友
1楼 · 发布于 2024-05-18 18:37:40

您不需要为每个机器人启动单独的线程,asyncio事件循环完全能够同时为所有机器人提供服务。(这就是事件循环设计的目的。)

您只需将所有bot作为同一asyncio事件循环的协程启动:

async def run_client(bottoken, botname):
    TOKEN = (bottoken)
    client = discord.Client()

    @client.event
    async def on_ready():
        print(f'{client.user.name} has connected to Discord!')

    @client.event
    async def on_message(message):
         #do stuff
         print('Do stuff')

    # can't use client.run() because it would block the event loop
    # but we can use client.start(), which is a coroutine that does
    # the same thing (and which is internally called by client.run)
    await client.start(TOKEN)

async def main():
    coros = []
    with open('botinfo.csv', 'r') as f:
        reader = csv.reader(f, delimiter=',')
        for i, row in enumerate(reader):
            coros.append(run_client(row[0], row[1]))
    await asyncio.gather(*coros)

if __name__ == '__main__':
    asyncio.run(main())

相关问题 更多 >

    热门问题