Skip to content
Advertisement

BotBuilder display message while waiting for blocking function

I’m trying to build a bot using Microsoft’s Bot framework in Python following this guide. I can’t figure out how to display a message while waiting for a blocking function to return. I’ve read up on async and await in general, but haven’t found any examples specific to the Bot Framework. Here’s a simple example. With this code, it waits 2 seconds before displaying both messages. I want to acknowledge the user input immediately, then wait for a long blocking function and return the result.

class MyBot(ActivityHandler):
    async def on_message_activity(self, turn_context: TurnContext):
        start = time.time()

        elapsed = time.time() - start
        await turn_context.send_activity(f"Message received after {elapsed:.1f} seconds")

        await self._blocker()

        elapsed = time.time() - start
        await turn_context.send_activity(f"Finished after {elapsed:.1f} seconds!")
        
    
    async def _blocker(self):
        time.sleep(2)

The full source code is available through the guide above, or directly from here. I only changed the MyBot class.

Advertisement

Answer

It turns out that this is an Emulator problem after all and has nothing to do with the Bot Builder Python SDK. I’ve reported the bug here: https://github.com/microsoft/BotFramework-Emulator/issues/2262

At first I thought the problem was that you were using time.sleep instead of asyncio.sleep. While this turned out to not be your problem, you should still prefer asyncio.sleep when writing asynchronous code: Python 3.7 – asyncio.sleep() and time.sleep()

You can safely ignore the issue for now. In the future, always remember to test on your target channel because you can’t assume Emulator will behave the same way.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement