Async Client¶
Working with Neonize's asynchronous client.
Overview¶
The async client (NewAClient) provides full async/await support for high-performance applications. Since Python 3.10+, Neonize uses asyncio.run() as the standard entry point and obtains the event loop via asyncio.get_running_loop() internally — no manual loop management needed.
Quick Links¶
- Getting Started - Start with async client
- Event Handling - Async event handlers
- Best Practices - Async patterns and tips
Basic Usage¶
Event Loop Architecture¶
Neonize receives events from Go callbacks running on separate OS threads.
These callbacks dispatch coroutines to the Python event loop using
asyncio.run_coroutine_threadsafe(). For this to work, Neonize needs a
reference to the running event loop.
How It Works¶
asyncio.run(main())creates and starts an event loop.- Inside
main(),await client.connect()callsasyncio.get_running_loop()and stores a reference. - Go callbacks use
run_coroutine_threadsafe(coro, loop)to schedule your event handlers on that loop. await client.idle()awaits the connection task, keeping the loop alive.
Why NOT get_event_loop() or new_event_loop()?¶
| Pattern | Problem |
|---|---|
asyncio.get_event_loop() |
Deprecated since Python 3.10. Raises DeprecationWarning. On Python 3.12+ it raises RuntimeError if no loop is running. |
asyncio.new_event_loop() |
Creates an orphan loop. Unless you manually call loop.run_forever() in a thread, any run_coroutine_threadsafe() call targeting it will silently fail — events are never executed. |
loop.run_until_complete() |
Works but is the low-level API. asyncio.run() is the recommended high-level replacement since Python 3.7. |
Correct Pattern (Python 3.7+)¶
Inside main() (an async function), the event loop is guaranteed to be running.
Neonize's connect() captures it automatically — no manual loop passing required.
Multi-Session (ClientFactory)¶
One-Shot Usage¶
Send a message and exit without keeping the bot alive:
Integration with Async Frameworks¶
FastAPI¶
When to Use Async¶
Use async client when you need:
- High concurrency - Handle many connections simultaneously
- Non-blocking I/O - Don't block on network operations
- Integration - Work with async frameworks (FastAPI, aiohttp)
- Performance - Maximum throughput
Async vs Sync¶
| Feature | Async Client | Sync Client |
|---|---|---|
| Entry point | asyncio.run() |
client.connect() |
| Event handlers | async def |
def |
| Performance | ⚡ Higher | 🐌 Lower |
| Concurrency | ✅ Excellent | ⚠️ Limited |
| Complexity | 🔴 Higher | 🟢 Lower |
| Best For | Production | Prototyping |
Next Steps¶
Continue to:
- Async Quick Start - Build your first async bot
- Async Events - Handle events asynchronously
- Best Practices - Write efficient async code