-1

In my project I need to create many connections with discord bots. I have created a function for creating new thread that handles connection (so each thread sould handle one connection) but I am getting Runtime error: this event loop is already running (interesting that first thread is creating successfully and this error occures only while trying to create second thread). I have modified my code for test how to get around with this error and now I am trying to create two fully separate threads for separate connections on separate objects but I'm still getting this error. Actually I have no idea how to fix it... My code is:

import discord
from threading import Thread

client = discord.Client()

@client.event
    async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    print(message.content)

thread1 = Thread(target=client.run, args=("TOKEN1", ))
thread1.start()



client2 = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    print(message.content)

thread2 = Thread(target=client2.run, args=("TOKEN2", ))
thread2.start()

(Tokens are present but hidden for obvious reasons) Fist thread in this way creates successfully but when I'm trying to create second one it still thows errors: This event loop is already running, then: Cannot clos event loop, then: Event loop is closed

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ferius
  • 1
  • 1
  • 2
  • "In my project I need to create many connections with discord bots." Why? The entire point of the async setup is that a single bot will be able to respond to more commands while it waits on a lengthy calculation. – Karl Knechtel Feb 14 '22 at 20:18
  • My program should work with completely different accounts. Logics of interaction with discord is not a problem. I think that the problem is somewhere with using python multithreading... – Ferius Feb 14 '22 at 20:24

1 Answers1

0

Not sure why you want to do this, but here goes:

The issue is not with multithreading, but with the async loop (as your error suggests).

If you check out the source code, you will find, that if you don't pass a new async loop yourself, it will call the default asyncio.get_event_loop(), which seems like it causes some issues afterwards.

https://github.com/Rapptz/discord.py/blob/master/discord/client.py#:~:text=..%20versionadded%3A%3A%202.0-,Attributes,)%3A,-%23%20self.ws%20is

(sorry, the link is broken, you have to copy it)

This answer seem to provide you with the info on how to create multiple loops: https://stackoverflow.com/a/31643784/13000953

So then you will have to create the two loops, and pass them as a parameter to your discord.Client()

loop1 = asyncio.get_event_loop()
loop2 = asyncio.new_event_loop()

client1 = discord.Client(loop=loop1)
client2 = discord.Client(loop=loop2)
Mahrkeenerh
  • 1,104
  • 1
  • 9
  • 25