Async Listener and Handler
Yaxit opened this issue · 0 comments
Yaxit commented
Hello, I recently switched to the async version, and I'm trying to replicate the behavior I had before, which is the following.
the bot must be able to do two different things:
- Receive a msg and handle it, doing some stuff depending on the content
- Send some msg when some data is collected (by sensors)
This is the code in the standard (not async version) I used to run:
import telepot
from telepot.loop import MessageLoop
from multiprocessing.connection import Listener, Client
addr = ('localhost', 4000)
listener = Listener(addr)
telegram_id = "my ID"
def handle(msg):
# do some processing and maybe sending a msg
bot = telepot.Bot(token)
MessageLoop(bot, handle).run_as_thread()
while True:
conn = listener.accept()
data = conn.recv()
conn.close()
# some processing on data
bot.sendMessage(telegram_id, data)
I cannot replicate this behavior in the async version (I'm not very fond on async programming, actually)
I tried many thing, including the following.
from multiprocessing.connection import Listener, Client
import asyncio
import telepot
import telepot.aio
addr = ('localhost', 4000)
listener = Listener(addr)
telegram_id = "myid"
async def get_data():
print("Waiting for data")
conn = listener.accept()
data = conn.recv()
conn.close()
return data
async def internal_handle():
while True:
data = await asyncio.run(get_data())
# process data
await bot.sendMessage(telegram_id, data)
async def handle(msg):
# same stuff as before
bot = telepot.aio.Bot("token")
loop = asyncio.get_event_loop()
loop.create_task(internal_handle())
loop.create_task(MessageLoop(bot, handle).run_forever())
loop.run_forever()
I thought this would run internale_handle()
and the msg handler together, but it doesn't. Instead, it gets stuck waiting for data from the Listener.
Thank you for any suggestion!