Running a Telegram Python Bot with Asyncio Polling
To run a Telegram bot using asyncio for polling, you'll need to use the python-telegram-bot library with its asyncio capabilities. Here's a step-by-step guide:
1. Installation
First, install the required package:
pip install python-telegram-bot
2. Basic Asyncio Bot Structure
Here's a complete example of a Telegram bot using asyncio polling:
import asyncio
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
# Define command handlers
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
await update.message.reply_text("Hello! I'm your asyncio-powered Telegram bot!")
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
await update.message.reply_text("Help message here")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
await update.message.reply_text(update.message.text)
async def main() -> None:
"""Start the bot."""
# Create the Application and pass it your bot's token
application = Application.builder().token("YOUR_TELEGRAM_BOT_TOKEN").build()
# Add handlers
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("help", help_command))
# on non-command i.e. message - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
# Start the Bot using polling (non-webhook mode)
await application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
asyncio.run(main())
3. Customizing Polling Parameters
You can customize the polling behavior with these parameters:
await application.run_polling(
poll_interval=1.0, # Time between polling updates (seconds)
timeout=10, # Request timeout for getting updates
bootstrap_retries=0, # Number of retries for bootstrap phase
read_timeout=2, # Read timeout for getting updates
write_timeout=2, # Write timeout for webhook requests
connect_timeout=2, # Connect timeout for webhook requests
pool_timeout=1, # Timeout for connection pool
allowed_updates=Update.ALL_TYPES, # List of update types to process
drop_pending_updates=False, # Whether to drop pending updates
close_loop=True, # Whether to close the event loop
stop_signals=None # Signals that should stop the bot
)
4. Error Handling
Add error handling to make your bot more robust:
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle errors."""
logger.error(f"Update {update} caused error {context.error}")
# Add to your main() function:
application.add_error_handler(error_handler)
5. Running the Bot
Simply run your Python script, and the bot will start polling for updates using asyncio.
This approach gives you the benefits of asyncio's concurrency model, allowing your bot to handle multiple updates efficiently without blocking.