DEV Community

William Rodriguez
William Rodriguez

Posted on

Keep the main thread breathing: Non-blocking bot execution with run_async.

Keep the main thread breathing: Non-blocking bot execution with run_async.

You shouldn't need a dedicated virtual machine just to run a lightweight Telegram receiver alongside your FastAPI app. wconnect's run_consumers(block=False) runs in a non-blocking daemon thread with graceful shutdown.

Here is how you implement Non-Blocking Async Consumers in production with wconnect:

import time
from wconnect import Wtelegram, WMessage

bot = Wtelegram()

@bot.on_command(command="ping")
def ping(msg: WMessage):
    bot.send(to=msg.chat_id, message="pong 🏓")

# Launch in background thread without blocking main application
thread = bot.run_consumers(block=False)
print(f"Bot listening in daemon thread: {thread.name}")

# Main application continues executing (FastAPI / ETL pipeline / worker)
for step in range(3):
    print(f"Main loop executing batch #{step}")
    time.sleep(1)

bot.stop_consumers()
Enter fullscreen mode Exit fullscreen mode

Why This Matters:

  • Zero boilerplate decorators (@bot.on_command, @bot.on_message, @bot.consumer).
  • Stream binary files directly from RAM using WFile.
  • Non-blocking daemon poller with run_consumers(block=False).

Check out the repo on GitHub!

Top comments (1)

Collapse
 
william_rodriguez_65a5898 profile image
William Rodriguez •

Decoupling inbound webhook intake from heavy downstream processing is critical to maintaining sub-second API responsiveness.

What patterns have proven most reliable in your conversational bots for handling bursts of concurrent rich media payloads?