I need to create production ready Telegram chat bot written in Python. This bot will be…
- User
I need to create production ready Telegram chat bot written in Python. This bot will be a starting point for my Telegram MiniApp therefore it should only have command start as most of the bots and then show only 3 buttons. Those buttons should be menu buttons so they will produce init_data that will be used in Mini app. 1st button - simple link to my website, second link opens up the chat, third link should open up my MiniApp that will be deployed on one of my domains. This bot should be simple yet effective, efficient and robust.
- Assistant
Creating a production-ready Telegram bot in Python involves several steps, including setting up the bot with the Telegram Bot API, implementing the desired functionality, ensuring robustness, and deploying it securely. Below, I’ll guide you through creating a simple yet effective Telegram bot that meets your specifications:
- /start Command: Initiates interaction.
- Three Buttons:
- Link to Website.
- Open Chat (e.g., support chat).
- Open MiniApp (your deployed MiniApp).
We'll use the
python-telegram-botlibrary, which is well-supported and suitable for building robust Telegram bots.Prerequisites
- Python 3.7+ installed on your system.
- Telegram Bot Token: Obtain this by creating a bot via @BotFather on Telegram.
- Hosting Environment: For production, consider deploying on platforms like AWS, Heroku, DigitalOcean, or others.
- Domain and SSL Certificate: Required if you plan to use webhooks (recommended for production).
Step 1: Setting Up the Environment
-
Create a Virtual Environment:
python3 -m venv telegram_bot_env source telegram_bot_env/bin/activate -
Install Required Libraries:
pip install python-telegram-bot==20.3Note: Ensure compatibility with the latest version. At the time of writing,
python-telegram-bot20.x is recommended.
Step 2: Writing the Bot Code
Create a file named
bot.pyand populate it with the following code:import logging from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ( ApplicationBuilder, ContextTypes, CommandHandler, ) import os # Enable logging logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) logger = logging.getLogger(__name__) # Replace these with your actual links WEBSITE_URL = "https://yourwebsite.com" SUPPORT_CHAT_URL = "https://t.me/your_support_chat" MINIAPP_URL = "https://yourdomain.com/miniapp" # Define the /start command handler async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): user = update.effective_user logger.info(f"User {user.first_name} started the bot.") # Define buttons keyboard = [ [ InlineKeyboardButton("Visit Website", url=WEBSITE_URL), InlineKeyboardButton("Support Chat", url=SUPPORT_CHAT_URL), ], [ InlineKeyboardButton("Open MiniApp", url=MINIAPP_URL), ], ] reply_markup = InlineKeyboardMarkup(keyboard) # Send welcome message with buttons await update.message.reply_text( f"Hello, {user.first_name}! Welcome to our Bot. Please choose an option below:", reply_markup=reply_markup, ) # Error handler to log errors async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE): logger.error(msg="Exception while handling an update:", exc_info=context.error) # You can notify the admin or take other actions here def main(): # Read the bot token from environment variable for security TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") if not TOKEN: logger.error("TELEGRAM_BOT_TOKEN environment variable not set.") return # Create the Application and pass it your bot's token application = ApplicationBuilder().token(TOKEN).build() # on different commands - answer in Telegram application.add_handler(CommandHandler("start", start)) # Log all errors application.add_error_handler(error_handler) # Start the Bot using polling (suitable for development) # For production, consider using webhooks application.run_polling() if __name__ == "__main__": main()Step 3: Configuration and Security
-
Environment Variables:
To keep your bot token secure, store it as an environment variable.
-
Unix/Linux/macOS:
export TELEGRAM_BOT_TOKEN='YOUR_TELEGRAM_BOT_TOKEN_HERE' -
Windows (Command Prompt):
set TELEGRAM_BOT_TOKEN=YOUR_TELEGRAM_BOT_TOKEN_HERE -
Windows (PowerShell):
$env:TELEGRAM_BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN_HERE"
Production Tip: Use a
.envfile coupled with packages likepython-dotenvto manage environment variables securely. -
-
Button Links Customization:
Replace
WEBSITE_URL,SUPPORT_CHAT_URL, andMINIAPP_URLwith your actual URLs.
Step 4: Running the Bot Locally (For Testing)
-
Activate the Virtual Environment:
source telegram_bot_env/bin/activate -
Set the Environment Variable:
export TELEGRAM_BOT_TOKEN='YOUR_TELEGRAM_BOT_TOKEN_HERE' -
Run the Bot:
python bot.py -
Interact with Your Bot:
Open Telegram, find your bot, and send the
/startcommand to see the buttons.
Step 5: Deploying the Bot to Production
For a production environment, using webhooks is more efficient and reliable than long polling. Below is a guide for deploying with webhooks using
python-telegram-bot. Let's assume you're deploying on Heroku, but the steps are similar for other platforms.-
Modify
bot.pyfor Webhooks:Update the
mainfunction to set up webhooks.import os async def main(): TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") if not TOKEN: logger.error("TELEGRAM_BOT_TOKEN environment variable not set.") return # Webhook settings WEBHOOK_URL = os.getenv("WEBHOOK_URL") # e.g., https://yourdomain.com/telegram application = ApplicationBuilder().token(TOKEN).build() # Handlers application.add_handler(CommandHandler("start", start)) application.add_error_handler(error_handler) # Set up webhook await application.initialize() await application.start() await application.bot.set_webhook(WEBHOOK_URL) await application.updater.start_polling() # For graceful shutdown await application.idle()Note: The above is a simplified example. You may need to adjust based on your hosting provider.
-
Deploy to Heroku (Example):
-
Create a
Procfile:web: python bot.py -
Install
gunicorn(a production-ready web server):pip install gunicornUpdate the
Procfileif necessary:web: gunicorn bot:app(Modify
bot.pyto create aFastAPIorFlaskapp if required bygunicorn. Alternatively, continue usingpython-telegram-bot’s webhook capabilities.) -
Push to Heroku:
heroku create your-app-name git add . git commit -m "Deploy Telegram bot" git push heroku main -
Set Environment Variables on Heroku:
heroku config:set TELEGRAM_BOT_TOKEN=YOUR_TELEGRAM_BOT_TOKEN_HERE heroku config:set WEBHOOK_URL=https://your-app-name.herokuapp.com/telegram
-
-
Set Up SSL:
Ensure your domain uses HTTPS, as Telegram webhooks require secure connections.
Step 6: Enhancements for Production
-
Logging and Monitoring:
- Integrate with logging services like Loggly, Papertrail, or Sentry for error tracking.
- Ensure logs do not expose sensitive information.
-
Security Measures:
- Validate incoming webhook requests to ensure they originate from Telegram.
- Regularly update dependencies to patch vulnerabilities.
- Use environment variables or secret managers for sensitive data.
-
Scalability:
- Use asynchronous handlers (
async def) to manage multiple requests efficiently. - Consider horizontal scaling if expecting high traffic.
- Use asynchronous handlers (
-
Database Integration (Optional):
- If you plan to expand functionality, integrate a database (e.g., PostgreSQL, MongoDB) securely.
- Use ORM tools like SQLAlchemy for easier database interactions.
-
Testing:
- Implement unit tests for your handlers using frameworks like
pytest. - Use staging environments before deploying to production.
- Implement unit tests for your handlers using frameworks like
Complete Example Code with Enhancements
Here’s the complete
bot.pyincorporating some production-ready practices:import logging from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ( ApplicationBuilder, ContextTypes, CommandHandler, ) import os import asyncio # Enable logging logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) logger = logging.getLogger(__name__) # Replace these with your actual links WEBSITE_URL = "https://yourwebsite.com" SUPPORT_CHAT_URL = "https://t.me/your_support_chat" MINIAPP_URL = "https://yourdomain.com/miniapp" # Define the /start command handler async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): try: user = update.effective_user logger.info(f"User {user.first_name} started the bot.") # Define buttons keyboard = [ [ InlineKeyboardButton("Visit Website", url=WEBSITE_URL), InlineKeyboardButton("Support Chat", url=SUPPORT_CHAT_URL), ], [ InlineKeyboardButton("Open MiniApp", url=MINIAPP_URL), ], ] reply_markup = InlineKeyboardMarkup(keyboard) # Send welcome message with buttons await update.message.reply_text( f"Hello, {user.first_name}! Welcome to our Bot. Please choose an option below:", reply_markup=reply_markup, ) except Exception as e: logger.error(f"Error in start handler: {e}") await update.message.reply_text( "An error occurred while processing your request." ) # Error handler to log errors async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE): logger.error(msg="Exception while handling an update:", exc_info=context.error) # Optionally notify the admin # admin_id = os.getenv("ADMIN_TELEGRAM_ID") # if admin_id: # await context.bot.send_message( # chat_id=admin_id, # text=f"An error occurred: {context.error}", # ) def main(): # Read the bot token from environment variable for security TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") if not TOKEN: logger.error("TELEGRAM_BOT_TOKEN environment variable not set.") return # Create the Application and pass it your bot's token application = ApplicationBuilder().token(TOKEN).build() # on different commands - answer in Telegram application.add_handler(CommandHandler("start", start)) # Log all errors application.add_error_handler(error_handler) # Start the Bot using polling (suitable for development) # For production, set up webhooks as described earlier application.run_polling() if __name__ == "__main__": try: main() except (KeyboardInterrupt, SystemExit): logger.info("Bot stopped.")Additional Resources
- python-telegram-bot Documentation: https://docs.python-telegram-bot.org/
- Telegram Bot API Documentation: https://core.telegram.org/bots/api
- Deployment Guides: Refer to your hosting provider's documentation for deploying Python applications.
Summary
You now have a blueprint for creating a production-ready Telegram bot in Python with the desired functionality:
- Robustness: Through error handling and logging.
- Security: By using environment variables and secure deployment practices.
- Efficiency: Utilizing
python-telegram-bot's capabilities and asynchronous programming.
Ensure to test thoroughly in a staging environment before deploying to production and monitor the bot continuously for any issues.
If you have any specific questions or need further assistance with particular aspects of the bot, feel free to ask!