Skip to content
This repository has been archived by the owner on Jun 2, 2019. It is now read-only.

Async Listener and Handler #451

Open
Yaxit opened this issue Mar 13, 2019 · 0 comments
Open

Async Listener and Handler #451

Yaxit opened this issue Mar 13, 2019 · 0 comments

Comments

@Yaxit
Copy link

Yaxit commented Mar 13, 2019

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!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant