Running multiple asyncio coroutines together

I would run each client in separate threads.
Here is a similar example to: discord.py · PyPI - Quickstart

import asyncio
import threading
import time

class DummyClient:
    def __init__(self):
        self.loop = asyncio.new_event_loop()
        self.user = 'DummyUser'
    
    async def on_ready(self):
        print(f'We have logged in as {self.user}')
    
    async def on_message(self, message):
        if message.author == self.user:
            return
        
        if message.content.startswith('$hello'):
            await self.send_message('Hello!')
    
    async def send_message(self, content):
        print(f'Message sent: {content}')
    
    async def simulate_message(self, message):
        await self.on_message(message)
    
    async def print_periodically(self):
        while True:
            print('Print from DummyClient')
            await asyncio.sleep(2.0)  # Print every 2 seconds
    
    def run(self):
        asyncio.set_event_loop(self.loop)
        self.loop.run_until_complete(self.on_ready())
        
        # Simulate receiving messages
        self.loop.create_task(self.simulate_message(DummyMessage('User1', '$hello')))
        self.loop.create_task(self.simulate_message(DummyMessage('DummyUser', '$hello')))
        
        # Start printing periodically
        self.loop.create_task(self.print_periodically())
        
        # Keep the loop running
        self.loop.run_forever()

class DummyMessage:
    def __init__(self, author, content):
        self.author = author
        self.content = content

def run_dummy_client():
    client = DummyClient()
    client.run()

# Create a thread to run the dummy client
client_thread = threading.Thread(target=run_dummy_client)

# Start the thread
client_thread.start()

# Now you can continue with other tasks in the main thread
print("Dummy async client is running in a separate thread.")

# This loop runs in the main thread
while True:
    time.sleep(1.0)
    print('Hi!')

Result:

Dummy async client is running in a separate thread.
We have logged in as DummyUser
Message sent: Hello!
Print from DummyClient
Hi!
Hi!
Print from DummyClient
Hi!
Hi!
...
1 Like