Untitled

 avatar
unknown
python
a year ago
2.3 kB
15
Indexable
import multiprocessing
import uuid
import asyncio
from pyrogram import Client
from pyrogram.raw import functions
from multiprocessing import Process, Queue


def client_worker(userbot_id, task_queue, result_queue):
    client = Client(f"userbot_{userbot_id}")
    client.start()
    
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    async def process_task(task):
        action = task['action']
        if action == 'get_full_chat':
            chat_id = task['chat_id']
            entity = await client.resolve_peer(chat_id)
            full_chat = await client.invoke(functions.channels.GetFullChannel(channel=entity))
            result_queue.put((task['task_id'], full_chat))
    
    while True:
        task = task_queue.get()
        if task == 'STOP':
            break
        loop.run_until_complete(process_task(task))
    
    client.stop()


class ClientManager:
    def __init__(self, userbot_ids):
        self.clients = {}
        
        for userbot_id in userbot_ids:
            task_queue = Queue()
            result_queue = Queue()
            process = Process(target=client_worker, args=(userbot_id, task_queue, result_queue))
            process.start()
            self.clients[userbot_id] = {
                'process': process,
                'task_queue': task_queue,
                'result_queue': result_queue
            }

    def send_task(self, userbot_id, task):
        task_id = str(uuid.uuid4())
        task['task_id'] = task_id
        self.clients[userbot_id]['task_queue'].put(task)
        return task_id

    def get_result(self, userbot_id, task_id):
        while True:
            result_task_id, result = self.clients[userbot_id]['result_queue'].get()
            if result_task_id == task_id:
                return result

    def stop_clients(self):
        for client in self.clients.values():
            client['task_queue'].put('STOP')
            client['process'].join()


if __name__ == "__main__":
    userbot_ids = ['userbot_1', 'userbot_2']
    manager = ClientManager(userbot_ids)
    
    chat_id = -100123456789
    task_id = manager.send_task('userbot_1', {'action': 'get_full_chat', 'chat_id': chat_id})
    
    full_chat = manager.get_result('userbot_1', task_id)
    print(full_chat)
    
    manager.stop_clients()
Editor is loading...
Leave a Comment