A
A
amigo3x2020-06-14 18:15:56
Python
amigo3x, 2020-06-14 18:15:56

How to glue several procedures to work in parallel in asynchronous mode?

There are two files with python scripts.
One listens to websockets in asynchronous mode, the second one receives messages from telegrams.
Individually they work fine.
Their parts (indents fall off when publishing, I will leave only the most important):

#1:

async def socket(websocket, path):
    await addUser(websocket)
    #слушаем и получаем данные из вэбсокета

start_server = websockets.serve(socket, '127.0.0.1', 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

#2
from telethon import TelegramClient, sync, events

client = TelegramClient('session_name', api_id, api_hash)

@client.on(events.NewMessage())
async def normal_handler(event):

    if  str(type(event.message.to_id)) == "<class 'telethon.tl.types.PeerChannel'>":
        print(event.message.to_dict()['message'])

client.start()
client.run_until_disconnected()


Combined all functions into one file. I don't understand how to make them run together.

If you run one first, then the second:
client.start()
client.run_until_disconnected()
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


That does not reach sockets. Only telegram works.

Tried to make a call like this:

async def listen_all():
    task1 = asyncio.create_task(client.run_until_disconnected())
    task2 = asyncio.create_task(start_server)
    await asyncio.gather(task1,task2)

start_server = websockets.serve(socket, '127.0.0.1', 5678)
client.start()
asyncio.run(listen_all())


I get a runtime error

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
omegastripes, 2022-03-26
@omegastripes

Similar test case for Telethon 1.24.0 userbot and aiohttp 3.8.1 web server.

pip install telethon
pip install aiohttp

Tested on Python 3.6.9 Ubuntu 18.04.5 LTS and Python 3.8.6 Windows 7 x64
import asyncio
from telethon import TelegramClient, events
from aiohttp import web

session_name = 'test'
api_id = 6
api_hash = 'eb06d4abfb49dc3eeb1aeb98ae0f581e'


async def main_userbot():
    client = TelegramClient(session_name, api_id, api_hash)

    @client.on(events.NewMessage(pattern='(?i)hellox'))
    async def handler(event):
        print(event.stringify())
        await event.respond('Hi admin!')

    await client.start()
    me = await client.get_me()
    print(me.stringify())
    await client.run_until_disconnected()


async def main_web():
    app = web.Application()
    routes = web.RouteTableDef()

    @routes.get('/')
    @routes.get('/{name}')
    async def handle(request):
        name = request.match_info.get('name', "Anonymous")
        print('get from ' + name)
        text = "Hello, " + name
        return web.Response(text=text)

    app.add_routes(routes)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, host='0.0.0.0', port=8000)
    await site.start()
    print('running web server...')
    await asyncio.Event().wait()


async def main():
    await asyncio.gather(
        main_userbot(),
        main_web(),
    )


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Helped materials on the links
https://docs.telethon.dev/en/latest/concepts/async...
https://docs.aiohttp.org/en/stable/web_quickstart....
https://docs.aiohttp .org/en/stable/web_advanced.ht...
https://stackoverflow.com/questions/53465862/pytho...
https://stackoverflow.com/questions/49978396/detai...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question