Answer the question
In order to leave comments, you need to log in
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()
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()
client.start()
client.run_until_disconnected()
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
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())
Answer the question
In order to leave comments, you need to log in
Similar test case for Telethon 1.24.0 userbot and aiohttp 3.8.1 web server.
pip install telethon
pip install aiohttp
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())
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question