Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

I need to create production ready Telegram chat bot written in Python. This bot will be…

  1. 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.

  2. 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:
      1. Link to Website.
      2. Open Chat (e.g., support chat).
      3. Open MiniApp (your deployed MiniApp).

    We'll use the python-telegram-bot library, which is well-supported and suitable for building robust Telegram bots.

    Prerequisites

    1. Python 3.7+ installed on your system.
    2. Telegram Bot Token: Obtain this by creating a bot via @BotFather on Telegram.
    3. Hosting Environment: For production, consider deploying on platforms like AWS, Heroku, DigitalOcean, or others.
    4. Domain and SSL Certificate: Required if you plan to use webhooks (recommended for production).

    Step 1: Setting Up the Environment

    1. Create a Virtual Environment:

      python3 -m venv telegram_bot_env
      source telegram_bot_env/bin/activate
      
    2. Install Required Libraries:

      pip install python-telegram-bot==20.3
      

      Note: Ensure compatibility with the latest version. At the time of writing, python-telegram-bot 20.x is recommended.

    Step 2: Writing the Bot Code

    Create a file named bot.py and 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

    1. 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 .env file coupled with packages like python-dotenv to manage environment variables securely.

    2. Button Links Customization:

      Replace WEBSITE_URL, SUPPORT_CHAT_URL, and MINIAPP_URL with your actual URLs.

    Step 4: Running the Bot Locally (For Testing)

    1. Activate the Virtual Environment:

      source telegram_bot_env/bin/activate
      
    2. Set the Environment Variable:

      export TELEGRAM_BOT_TOKEN='YOUR_TELEGRAM_BOT_TOKEN_HERE'
      
    3. Run the Bot:

      python bot.py
      
    4. Interact with Your Bot:

      Open Telegram, find your bot, and send the /start command 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.

    1. Modify bot.py for Webhooks:

      Update the main function 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.

    2. Deploy to Heroku (Example):

      • Create a Procfile:

        web: python bot.py
        
      • Install gunicorn (a production-ready web server):

        pip install gunicorn
        

        Update the Procfile if necessary:

        web: gunicorn bot:app
        

        (Modify bot.py to create a FastAPI or Flask app if required by gunicorn. Alternatively, continue using python-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
        
    3. Set Up SSL:

      Ensure your domain uses HTTPS, as Telegram webhooks require secure connections.

    Step 6: Enhancements for Production

    1. Logging and Monitoring:

      • Integrate with logging services like Loggly, Papertrail, or Sentry for error tracking.
      • Ensure logs do not expose sensitive information.
    2. 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.
    3. Scalability:

      • Use asynchronous handlers (async def) to manage multiple requests efficiently.
      • Consider horizontal scaling if expecting high traffic.
    4. 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.
    5. Testing:

      • Implement unit tests for your handlers using frameworks like pytest.
      • Use staging environments before deploying to production.

    Complete Example Code with Enhancements

    Here’s the complete bot.py incorporating 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

    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!