Blog | G5 Cyber Security

Secure Telegram Bot Token

TL;DR

Don’t hardcode your Telegram bot token directly into your program! Use environment variables or a secure configuration file to store it. This prevents accidental exposure in version control and makes deployment easier.

Securing Your Telegram Bot Token: A Step-by-Step Guide

  1. Understand the Risk
  • Use Environment Variables
  • export TELEGRAM_BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
  • Accessing the variable in Python:
  • import os
    
    token = os.environ.get("TELEGRAM_BOT_TOKEN")
    if token is None:
        print("Error: TELEGRAM_BOT_TOKEN environment variable not set!")
    else:
        # Use the token to initialize your bot
        print(f"Token loaded successfully.")
  • Accessing the variable in Node.js:
  • const token = process.env.TELEGRAM_BOT_TOKEN;
    if (!token) {
      console.error('Error: TELEGRAM_BOT_TOKEN environment variable not set!');
    } else {
      // Use the token to initialize your bot
      console.log('Token loaded successfully.');
    }
  • Using a Configuration File (Alternative)
  • [Telegram]
    token = YOUR_TELEGRAM_BOT_TOKEN
  • Reading the configuration file in Python (using configparser):
  • import configparser
    
    config = configparser.ConfigParser()
    config.read('config.ini')
    token = config['Telegram']['token']
    print(f"Token loaded successfully.")
  • Protecting Your Configuration File
  • config.ini
  • Ensure the file has appropriate permissions (e.g., only readable by the user running the bot). On Linux/macOS, use chmod 600 config.ini to restrict access.
  • Deployment Considerations
  • Exit mobile version