简体   繁体   English

RuntimeError: There is no current event loop in thread … DiscordPy MultiThreading

[英]RuntimeError: There is no current event loop in thread … DiscordPy MultiThreading

so I have a python script where I want to run multiple discord bots at the same time.所以我有一个 python 脚本,我想在其中同时运行多个 discord 机器人。 These are defined by how many users there are in the database (Firebase).这些由数据库(Firebase)中有多少用户定义。 What I now do is that I have an loop for every user in the database it add's it to an array.我现在要做的是,我为数据库中的每个用户都有一个循环,它将它添加到一个数组中。 Then for every user in that array it starts a script:然后对于该数组中的每个用户,它都会启动一个脚本:

def main(user):

        client = discord.Client()

        token = db.child("users").child(user).child("token").get().val()
        print(user + ": " + token)

        applicationId = db.child("users").child(user).child("appid").get().val()

        discordId = user

        @client.event
        async def on_ready():
                print('Online')

        @client.event
        async def on_message(message):
                print(message)
        client.start(token, bot=False)

def testFunction(some_args):
        print(some_args)
        discord_thread = threading.Thread(target=main, args=(some_args,))
        discord_thread.start()

for user in usersArray:
        testFunction(user)

When I start the script it works until the client.start part.当我启动脚本时,它会一直工作到 client.start 部分。 Then I get an error for every thread.然后我得到每个线程的错误。 Error:错误:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\jonah\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\jonah\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "discordnotify.py", line 39, in main
    client = discord.Client()
  File "C:\Users\jonah\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\client.py", line 206, in __init__
    self.loop = asyncio.get_event_loop() if loop is None else loop
  File "C:\Users\jonah\AppData\Local\Programs\Python\Python37\lib\asyncio\events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-2'.

Is there anyone who can maybe help me somehow?有没有人可以以某种方式帮助我? It's driving me crazy!这让我疯狂!

You don't want to use threading when running multiple discord bots.在运行多个 discord 机器人时,您不想使用线程。 You can view here for some more info, but I can lay it out for you right now.您可以在此处查看更多信息,但我现在可以为您列出。 Fixing how you start your discord bots will help you a ton.修复如何启动 discord 机器人将对您有很大帮助。

For starters, you have to realise that Client.run is an abstraction of a couple of more lower level concepts.对于初学者,您必须意识到Client.run是几个更底层概念的抽象。

There is Client.login which logs in the client and then Client.connect which actually runs the processing. Client.login登录客户端,然后Client.connect实际运行处理。 These are coroutines.这些是协程。

asyncio provides the capability of putting things in the event loop for it to work whenever it has time to. asyncio提供了将事物放入事件循环的能力,以便它在有时间的时候工作。

Something like this eg像这样的东西,例如

loop = asyncio.get_event_loop()

async def foo():
  await asyncio.sleep(10)
  loop.close()

loop.create_task(foo())
loop.run_forever()

If we want to wait for something to happen from another coroutine, asyncio provides us with this functionality as well through the means of synchronisation via asyncio.Event.如果我们想等待另一个协程发生某些事情,asyncio 也通过 asyncio.Event 的同步方式为我们提供了这个功能。 You can consider this as a boolean that you are waiting for:您可以将其视为您正在等待的 boolean:

e = asyncio.Event()
loop = asyncio.get_event_loop()

async def foo():
  await e.wait()
  print('we are done waiting...')
  loop.stop()

async def bar():
  await asyncio.sleep(20)
  e.set()

loop.create_task(bar())
loop.create_task(foo())
loop.run_forever() # foo will stop this event loop when 'e' is set to true
loop.close()

Using this concept we can apply it to the discord bots themselves.使用这个概念,我们可以将其应用于 discord 机器人本身。

import asyncio
import discord
from collections import namedtuple

# First, we must attach an event signalling when the bot has been
# closed to the client itself so we know when to fully close the event loop.

Entry = namedtuple('Entry', 'client event')
entries = [
  Entry(client=discord.Client(), event=asyncio.Event()),
  Entry(client=discord.Client(), event=asyncio.Event())
]

# Then, we should login to all our clients and wrap the connect call
# so it knows when to do the actual full closure

loop = asyncio.get_event_loop()

async def login():
  for e in entries:
    await e.client.login()

async def wrapped_connect(entry):
  try:
    await entry.client.connect()
  except Exception as e:
    await entry.client.close()
    print('We got an exception: ', e.__class__.__name__, e)
    entry.event.set()

# actually check if we should close the event loop:
async def check_close():
  futures = [e.event.wait() for e in entries]
  await asyncio.wait(futures)

# here is when we actually login
loop.run_until_complete(login())

# now we connect to every client
for entry in entries:
  loop.create_task(wrapped_connect(entry))

# now we're waiting for all the clients to close
loop.run_until_complete(check_close())

# finally, we close the event loop
loop.close()


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RuntimeError: 线程 'Thread-1' 中没有当前事件循环,多线程和异步错误 - RuntimeError: There is no current event loop in thread 'Thread-1' , multithreading and asyncio error 多线程 python 时的运行时错误“运行时错误:线程 'Thread-1' 中没有当前事件循环。” - RuntimeError when multithreading python "RuntimeError: There is no current event loop in thread 'Thread-1'." RuntimeError:线程'Dummy-1'中没有当前事件循环 - RuntimeError: There is no current event loop in thread 'Dummy-1' Pytest:运行时错误线程“主线程”中没有当前事件循环 - Pytest: runtimeerror there is no current event loop in thread 'mainthread' RuntimeError:异步+ apscheduler中的线程中没有当前事件循环 - RuntimeError: There is no current event loop in thread in async + apscheduler RuntimeError:线程“MainThread”中没有当前事件循环 - RuntimeError: There is no current event loop in thread 'MainThread' /accounts/register/ 处的 RuntimeError 线程 'Thread-1' 中没有当前事件循环 - RuntimeError at /accounts/register/ There is no current event loop in thread 'Thread-1' RuntimeError:线程 'Thread-7' 中没有当前事件循环。 配discord.py - RuntimeError: There is no current event loop in thread 'Thread-7'. With discord.py Flask asyncio aiohttp - RuntimeError:线程'Thread-2'中没有当前事件循环 - Flask asyncio aiohttp - RuntimeError: There is no current event loop in thread 'Thread-2' Discord.py RuntimeError:线程中没有当前事件循环 - Discord.py RuntimeError: There is no current event loop in thread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM