Telegram

CommunicationMessagingBot APIMini AppsSecurityCloud Storage

Communication Tool

Telegram

Overview

Telegram is a security and privacy-focused cloud-based messaging application. It supports end-to-end encryption, large file transfers, Bot API, mini app development, and provides super groups with up to 200,000 members and unlimited channel subscribers. It features open-source, cross-platform support, and high-speed synchronization capabilities.

Details

Telegram is a cloud-based messaging platform founded in 2013 by Russian entrepreneur Pavel Durov. Currently serving over 800 million active users worldwide, it's supported by users who value privacy and free information sharing. It's particularly known for its commitment to security and open source.

In 2024-2025, significant feature enhancements were implemented including full-screen Mini Apps display, media sharing functionality, geolocation access, DeviceStorage and SecureStorage APIs, business account APIs, Telegram Premium feature enhancements, webhook improvements, and channel management API expansion.

Telegram Bot API provides comprehensive bot development capabilities, enabling webhook integration, inline keyboards, file operations, payment processing, game development, and mini app development. It also features advanced security through MTProto protocol and unlimited storage via Telegram Cloud.

Pros and Cons

Pros

  • Strong Security: End-to-end encryption (Secret Chat), MTProto protocol
  • Rich Bot API: Comprehensive bot development features, mini app development support
  • Large File Transfers: Up to 2GB file transfers, unlimited cloud storage
  • Large Groups: Super groups with up to 200,000 members, unlimited channels
  • Cross-Platform: All platform support, real-time synchronization
  • Open Source: Client applications are open source
  • Free Usage: Basic features completely free, no advertisements
  • High Speed: Lightweight design and fast message delivery

Cons

  • Anonymity Issues: Phone number required, not completely anonymous
  • Privacy Concerns: Potential regulation or surveillance in some countries
  • Limited Enterprise Features: Restrictions on business-oriented features
  • Support System: Limitations of official support
  • Governance: Centralized management structure
  • Default Encryption: Regular chats not encrypted by default

Key Links

Code Examples

Bot Development with python-telegram-bot

# Telegram Bot implementation using python-telegram-bot v20.x
import asyncio
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler

# Logging configuration
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

class TelegramBot:
    def __init__(self, token: str):
        self.application = Application.builder().token(token).build()
        self.setup_handlers()
    
    def setup_handlers(self):
        """Setup handlers"""
        # Command handlers
        self.application.add_handler(CommandHandler("start", self.start_command))
        self.application.add_handler(CommandHandler("help", self.help_command))
        self.application.add_handler(CommandHandler("weather", self.weather_command))
        self.application.add_handler(CommandHandler("task", self.task_command))
        self.application.add_handler(CommandHandler("miniapp", self.miniapp_command))
        
        # Message handlers
        self.application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.echo_message))
        self.application.add_handler(MessageHandler(filters.PHOTO, self.photo_handler))
        self.application.add_handler(MessageHandler(filters.Document.ALL, self.document_handler))
        
        # Callback query handler
        self.application.add_handler(CallbackQueryHandler(self.button_handler))
    
    async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle start command"""
        user = update.effective_user
        welcome_text = f"Hello, {user.first_name}! 🚀\n\nWelcome to Telegram Bot.\n\nAvailable commands:\n/help - Show help\n/weather - Weather information\n/task - Task management\n/miniapp - Open mini app"
        
        # Create inline keyboard
        keyboard = [
            [InlineKeyboardButton("🌤️ Weather", callback_data='weather_tokyo')],
            [InlineKeyboardButton("📋 Create Task", callback_data='create_task')],
            [InlineKeyboardButton("🚀 Mini App", web_app=WebAppInfo(url="https://your-webapp.com"))],
            [InlineKeyboardButton("ℹ️ Help", callback_data='help')]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        await update.message.reply_text(welcome_text, reply_markup=reply_markup)
    
    async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle help command"""
        help_text = """
🤖 **Bot Commands**

**Basic Commands:**
/start - Start the bot
/help - Show this help

**Feature Commands:**
/weather [city] - Get weather information
/task [task name] - Create a task
/miniapp - Launch mini app

**File Features:**
- Send images for automatic OCR processing
- Send documents for analysis
- Voice message support

**Special Features:**
- Inline button operations
- Web app integration
- Payment processing (Telegram Payments)
        """
        await update.message.reply_text(help_text, parse_mode='Markdown')
    
    async def weather_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle weather command"""
        # Get city name from arguments (default: Tokyo)
        city = ' '.join(context.args) if context.args else 'Tokyo'
        
        try:
            # Call external weather API (e.g., OpenWeatherMap)
            weather_data = await self.get_weather_info(city)
            
            if weather_data:
                weather_text = f"""
🌤️ **Weather in {weather_data['name']}**

Weather: {weather_data['weather']}
Temperature: {weather_data['temperature']}°C
Humidity: {weather_data['humidity']}%
Wind Speed: {weather_data['wind_speed']} m/s

Updated: {weather_data['updated_at']}
                """
                
                # Inline keyboard for other cities
                keyboard = [
                    [InlineKeyboardButton("🗾 Tokyo", callback_data='weather_tokyo'),
                     InlineKeyboardButton("🗽 New York", callback_data='weather_newyork')],
                    [InlineKeyboardButton("🗼 London", callback_data='weather_london'),
                     InlineKeyboardButton("🥖 Paris", callback_data='weather_paris')]
                ]
                reply_markup = InlineKeyboardMarkup(keyboard)
                
                await update.message.reply_text(weather_text, reply_markup=reply_markup, parse_mode='Markdown')
            else:
                await update.message.reply_text(f"❌ Failed to get weather information for {city}.")
                
        except Exception as e:
            logger.error(f"Weather API error: {e}")
            await update.message.reply_text("❌ Error occurred while fetching weather information.")
    
    async def task_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle task command"""
        if context.args:
            task_title = ' '.join(context.args)
            # Save task to database or file
            task_id = await self.save_task(task_title, update.effective_user.id)
            
            task_text = f"""
✅ **Task Created**

Task ID: {task_id}
Title: {task_title}
Creator: {update.effective_user.first_name}
Created: {asyncio.get_event_loop().time()}
            """
            
            # Task management inline keyboard
            keyboard = [
                [InlineKeyboardButton("✅ Complete", callback_data=f'complete_task_{task_id}')],
                [InlineKeyboardButton("✏️ Edit", callback_data=f'edit_task_{task_id}')],
                [InlineKeyboardButton("📋 Task List", callback_data='list_tasks')]
            ]
            reply_markup = InlineKeyboardMarkup(keyboard)
            
            await update.message.reply_text(task_text, reply_markup=reply_markup, parse_mode='Markdown')
        else:
            await update.message.reply_text("Please specify a task name.\nExample: /task Go shopping")
    
    async def miniapp_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle mini app command"""
        # Mini app inline keyboard
        keyboard = [
            [InlineKeyboardButton("🎮 Game", web_app=WebAppInfo(url="https://your-game-app.com"))],
            [InlineKeyboardButton("📊 Dashboard", web_app=WebAppInfo(url="https://your-dashboard-app.com"))],
            [InlineKeyboardButton("🛒 Shop", web_app=WebAppInfo(url="https://your-shop-app.com"))]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        await update.message.reply_text(
            "🚀 **Select a Mini App:**\n\nYou can launch apps using the buttons below.",
            reply_markup=reply_markup,
            parse_mode='Markdown'
        )
    
    async def echo_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle regular messages"""
        message_text = update.message.text.lower()
        
        # Keyword detection and auto-response
        if 'hello' in message_text or 'hi' in message_text:
            await update.message.reply_text(f"Hello, {update.effective_user.first_name}! 😊")
        elif 'thanks' in message_text or 'thank you' in message_text:
            await update.message.reply_text("You're welcome! 🙏")
        elif 'help' in message_text:
            await self.help_command(update, context)
        else:
            # Echo functionality
            await update.message.reply_text(f"Message received: {update.message.text}")
    
    async def photo_handler(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle photo messages"""
        photo = update.message.photo[-1]  # Get highest resolution image
        
        # Download file
        file = await context.bot.get_file(photo.file_id)
        file_path = f"downloads/{photo.file_id}.jpg"
        await file.download_to_drive(file_path)
        
        # OCR processing (example)
        try:
            extracted_text = await self.extract_text_from_image(file_path)
            
            response_text = f"""
📸 **Image Received**

File Size: {photo.file_size} bytes
OCR Result:
{extracted_text if extracted_text else 'No text detected'}
            """
            
            await update.message.reply_text(response_text, parse_mode='Markdown')
        except Exception as e:
            logger.error(f"Image processing error: {e}")
            await update.message.reply_text("❌ Error occurred during image processing.")
    
    async def document_handler(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle document messages"""
        document = update.message.document
        
        # Check file size (50MB limit)
        if document.file_size > 50 * 1024 * 1024:
            await update.message.reply_text("❌ File size is too large (please keep under 50MB).")
            return
        
        # Download file
        file = await context.bot.get_file(document.file_id)
        file_path = f"downloads/{document.file_name}"
        await file.download_to_drive(file_path)
        
        response_text = f"""
📄 **Document Received**

File Name: {document.file_name}
Size: {document.file_size} bytes
MIME Type: {document.mime_type}

File saved successfully.
        """
        
        # Processing options based on file type
        keyboard = []
        if document.mime_type == 'text/plain':
            keyboard.append([InlineKeyboardButton("📖 Analyze Text", callback_data=f'analyze_text_{document.file_id}')])
        elif document.mime_type.startswith('image/'):
            keyboard.append([InlineKeyboardButton("🔍 Analyze Image", callback_data=f'analyze_image_{document.file_id}')])
        
        reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
        await update.message.reply_text(response_text, reply_markup=reply_markup, parse_mode='Markdown')
    
    async def button_handler(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle inline button presses"""
        query = update.callback_query
        await query.answer()
        
        callback_data = query.data
        
        if callback_data.startswith('weather_'):
            city = callback_data.replace('weather_', '')
            weather_data = await self.get_weather_info(city)
            
            if weather_data:
                await query.edit_message_text(
                    f"🌤️ **Weather in {weather_data['name']}**\n\n"
                    f"Weather: {weather_data['weather']}\n"
                    f"Temperature: {weather_data['temperature']}°C",
                    parse_mode='Markdown'
                )
        
        elif callback_data == 'create_task':
            await query.edit_message_text(
                "📋 To create a task, use the following command:\n\n"
                "/task [task name]\n\n"
                "Example: /task Go shopping"
            )
        
        elif callback_data.startswith('complete_task_'):
            task_id = callback_data.replace('complete_task_', '')
            await self.complete_task(task_id)
            await query.edit_message_text(f"✅ Task {task_id} completed!")
        
        elif callback_data == 'help':
            await self.help_command(update, context)
    
    async def get_weather_info(self, city: str) -> dict:
        """Get weather information (external API call)"""
        # In actual implementation, use external weather API
        # Here we return sample data
        import random
        
        weather_conditions = ['Sunny', 'Cloudy', 'Rainy', 'Snowy']
        return {
            'name': city.title(),
            'weather': random.choice(weather_conditions),
            'temperature': random.randint(-10, 35),
            'humidity': random.randint(30, 90),
            'wind_speed': round(random.uniform(0, 15), 1),
            'updated_at': 'Now'
        }
    
    async def save_task(self, title: str, user_id: int) -> str:
        """Save task"""
        import uuid
        task_id = str(uuid.uuid4())[:8]
        # In actual implementation, save to database
        return task_id
    
    async def complete_task(self, task_id: str):
        """Complete task"""
        # In actual implementation, update database
        pass
    
    async def extract_text_from_image(self, image_path: str) -> str:
        """Extract text from image (OCR)"""
        # In actual implementation, use OCR library (Tesseract, etc.)
        return "Sample OCR text"
    
    def run(self):
        """Run bot"""
        logger.info("Bot starting...")
        self.application.run_polling(allowed_updates=Update.ALL_TYPES)

# Bot usage example
async def main():
    """Main function"""
    bot_token = "YOUR_BOT_TOKEN"  # Token obtained from BotFather
    bot = TelegramBot(bot_token)
    bot.run()

if __name__ == '__main__':
    asyncio.run(main())

Webhook Integration (Flask)

from flask import Flask, request, jsonify
import requests
import json
import logging

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

class TelegramWebhook:
    def __init__(self, bot_token: str, webhook_url: str):
        self.bot_token = bot_token
        self.api_url = f"https://api.telegram.org/bot{bot_token}"
        self.webhook_url = webhook_url
    
    def set_webhook(self):
        """Set webhook"""
        url = f"{self.api_url}/setWebhook"
        data = {"url": self.webhook_url}
        response = requests.post(url, json=data)
        return response.json()
    
    def send_message(self, chat_id: int, text: str, reply_markup=None):
        """Send message"""
        url = f"{self.api_url}/sendMessage"
        data = {
            "chat_id": chat_id,
            "text": text,
            "parse_mode": "Markdown"
        }
        if reply_markup:
            data["reply_markup"] = reply_markup
        
        response = requests.post(url, json=data)
        return response.json()
    
    def send_photo(self, chat_id: int, photo_url: str, caption: str = ""):
        """Send photo"""
        url = f"{self.api_url}/sendPhoto"
        data = {
            "chat_id": chat_id,
            "photo": photo_url,
            "caption": caption
        }
        response = requests.post(url, json=data)
        return response.json()

# Global instance
telegram_webhook = TelegramWebhook(
    bot_token="YOUR_BOT_TOKEN",
    webhook_url="https://yourdomain.com/telegram/webhook"
)

@app.route('/telegram/webhook', methods=['POST'])
def telegram_webhook_handler():
    """Handle webhook from Telegram"""
    try:
        data = request.get_json()
        
        if 'message' in data:
            message = data['message']
            chat_id = message['chat']['id']
            user = message['from']
            text = message.get('text', '')
            
            # Command processing
            if text.startswith('/'):
                return handle_command(chat_id, text, user)
            
            # Regular message processing
            return handle_message(chat_id, text, user)
        
        elif 'callback_query' in data:
            callback_query = data['callback_query']
            return handle_callback_query(callback_query)
        
        return jsonify({"status": "ok"})
    
    except Exception as e:
        logging.error(f"Webhook processing error: {e}")
        return jsonify({"status": "error"}), 500

def handle_command(chat_id: int, command: str, user: dict):
    """Process commands"""
    if command == '/start':
        welcome_text = f"Hello, {user['first_name']}!\n\nWelcome to Telegram Webhook Bot."
        telegram_webhook.send_message(chat_id, welcome_text)
    
    elif command.startswith('/notify'):
        # GitHub notification example
        return handle_github_notification(chat_id, command)
    
    elif command.startswith('/deploy'):
        # Deployment notification example
        return handle_deployment_command(chat_id, command)
    
    return jsonify({"status": "ok"})

def handle_message(chat_id: int, text: str, user: dict):
    """Process regular messages"""
    # Keyword detection
    if 'alert' in text.lower():
        alert_keyboard = {
            "inline_keyboard": [
                [{"text": "🚨 Critical", "callback_data": "alert_critical"}],
                [{"text": "⚠️ Warning", "callback_data": "alert_warning"}],
                [{"text": "ℹ️ Info", "callback_data": "alert_info"}]
            ]
        }
        telegram_webhook.send_message(
            chat_id, 
            "Please select alert level:", 
            reply_markup=alert_keyboard
        )
    else:
        telegram_webhook.send_message(chat_id, f"Message received: {text}")
    
    return jsonify({"status": "ok"})

def handle_callback_query(callback_query: dict):
    """Process callback queries"""
    query_id = callback_query['id']
    chat_id = callback_query['message']['chat']['id']
    data = callback_query['data']
    
    # Alert processing
    if data.startswith('alert_'):
        level = data.replace('alert_', '')
        handle_alert(chat_id, level)
    
    # Answer callback query
    answer_url = f"{telegram_webhook.api_url}/answerCallbackQuery"
    requests.post(answer_url, json={"callback_query_id": query_id})
    
    return jsonify({"status": "ok"})

def handle_github_notification(chat_id: int, command: str):
    """Process GitHub notifications"""
    # Actual GitHub webhook integration example
    github_data = {
        "repository": "example/repo",
        "commits": 3,
        "pusher": "developer",
        "branch": "main"
    }
    
    notification_text = f"""
🚀 **GitHub Push Notification**

Repository: {github_data['repository']}
Branch: {github_data['branch']}
Commits: {github_data['commits']}
Pusher: {github_data['pusher']}
    """
    
    telegram_webhook.send_message(chat_id, notification_text)
    return jsonify({"status": "ok"})

def handle_deployment_command(chat_id: int, command: str):
    """Process deployment commands"""
    deployment_keyboard = {
        "inline_keyboard": [
            [{"text": "🔧 Staging", "callback_data": "deploy_staging"}],
            [{"text": "🚀 Production", "callback_data": "deploy_production"}]
        ]
    }
    
    telegram_webhook.send_message(
        chat_id,
        "Please select deployment environment:",
        reply_markup=deployment_keyboard
    )
    return jsonify({"status": "ok"})

def handle_alert(chat_id: int, level: str):
    """Process alerts"""
    emojis = {
        "critical": "🚨",
        "warning": "⚠️", 
        "info": "ℹ️"
    }
    
    alert_text = f"{emojis[level]} **{level.upper()} Alert**\n\nAlert occurred. Please check details."
    telegram_webhook.send_message(chat_id, alert_text)

# External system integration endpoint
@app.route('/api/send-notification', methods=['POST'])
def send_notification():
    """Send notification from external systems"""
    try:
        data = request.get_json()
        chat_id = data.get('chat_id')
        message = data.get('message')
        
        if chat_id and message:
            telegram_webhook.send_message(chat_id, message)
            return jsonify({"status": "sent"})
        
        return jsonify({"status": "error", "message": "chat_id and message required"}), 400
    
    except Exception as e:
        logging.error(f"Notification send error: {e}")
        return jsonify({"status": "error"}), 500

if __name__ == '__main__':
    # Set webhook
    webhook_result = telegram_webhook.set_webhook()
    print(f"Webhook setup result: {webhook_result}")
    
    # Run Flask app
    app.run(debug=True, port=5000)

Mini App Development (JavaScript)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Telegram Mini App</title>
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: var(--tg-theme-bg-color);
            color: var(--tg-theme-text-color);
        }
        
        .container {
            max-width: 400px;
            margin: 0 auto;
        }
        
        .card {
            background: var(--tg-theme-secondary-bg-color);
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
        }
        
        .button {
            background: var(--tg-theme-button-color);
            color: var(--tg-theme-button-text-color);
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            margin-bottom: 8px;
        }
        
        .input {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--tg-theme-hint-color);
            border-radius: 8px;
            background: var(--tg-theme-bg-color);
            color: var(--tg-theme-text-color);
            font-size: 16px;
            margin-bottom: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h2>🎯 Task Management Mini App</h2>
            <input type="text" id="taskInput" class="input" placeholder="Enter new task...">
            <button class="button" onclick="addTask()">➕ Add Task</button>
        </div>
        
        <div class="card">
            <h3>📋 Task List</h3>
            <div id="taskList"></div>
        </div>
        
        <div class="card">
            <h3>🎮 Game Features</h3>
            <button class="button" onclick="startGame()">🎲 Start Game</button>
            <button class="button" onclick="shareScore()">📊 Share Score</button>
        </div>
        
        <div class="card">
            <h3>💰 Payment Features</h3>
            <button class="button" onclick="makePurchase()">🛒 Make Purchase</button>
        </div>
    </div>

    <script>
        // Initialize Telegram Web App
        const tg = window.Telegram.WebApp;
        
        // Web App configuration
        tg.ready();
        tg.expand();
        
        // Get user information
        const user = tg.initDataUnsafe?.user;
        if (user) {
            console.log('User:', user);
        }
        
        // Task data
        let tasks = [];
        
        // Add task functionality
        function addTask() {
            const taskInput = document.getElementById('taskInput');
            const taskText = taskInput.value.trim();
            
            if (taskText) {
                const task = {
                    id: Date.now(),
                    text: taskText,
                    completed: false
                };
                
                tasks.push(task);
                taskInput.value = '';
                renderTasks();
                
                // Send data to Telegram Bot
                sendDataToBot('task_created', task);
                
                // Haptic feedback
                tg.HapticFeedback.impactOccurred('medium');
                
                // Success message
                tg.showAlert('Task added successfully!');
            }
        }
        
        // Render task list
        function renderTasks() {
            const taskList = document.getElementById('taskList');
            
            if (tasks.length === 0) {
                taskList.innerHTML = '<p>No tasks available</p>';
                return;
            }
            
            taskList.innerHTML = tasks.map(task => `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--tg-theme-hint-color);">
                    <span style="${task.completed ? 'text-decoration: line-through; opacity: 0.6;' : ''}">${task.text}</span>
                    <div>
                        <button onclick="toggleTask(${task.id})" style="background: none; border: none; font-size: 20px; cursor: pointer;">
                            ${task.completed ? '✅' : '⭕'}
                        </button>
                        <button onclick="deleteTask(${task.id})" style="background: none; border: none; font-size: 16px; cursor: pointer; color: #ff4444;">
                            🗑️
                        </button>
                    </div>
                </div>
            `).join('');
        }
        
        // Toggle task status
        function toggleTask(taskId) {
            const task = tasks.find(t => t.id === taskId);
            if (task) {
                task.completed = !task.completed;
                renderTasks();
                sendDataToBot('task_updated', task);
                tg.HapticFeedback.impactOccurred('light');
            }
        }
        
        // Delete task
        function deleteTask(taskId) {
            tg.showConfirm('Delete this task?', (confirmed) => {
                if (confirmed) {
                    tasks = tasks.filter(t => t.id !== taskId);
                    renderTasks();
                    sendDataToBot('task_deleted', { id: taskId });
                    tg.HapticFeedback.impactOccurred('heavy');
                }
            });
        }
        
        // Game functionality
        function startGame() {
            // Simple clicker game
            let score = 0;
            let gameTime = 10;
            
            const gameContainer = document.createElement('div');
            gameContainer.innerHTML = `
                <div style="text-align: center; padding: 20px;">
                    <h3>🎯 Clicker Game</h3>
                    <div style="font-size: 24px; margin: 20px 0;">Time: <span id="gameTimer">${gameTime}</span>s</div>
                    <div style="font-size: 32px; margin: 20px 0;">Score: <span id="gameScore">${score}</span></div>
                    <button id="clickButton" style="font-size: 48px; padding: 20px; border: none; border-radius: 50%; background: var(--tg-theme-button-color);">🎯</button>
                </div>
            `;
            
            // Replace existing content
            document.querySelector('.container').innerHTML = '';
            document.querySelector('.container').appendChild(gameContainer);
            
            const timer = setInterval(() => {
                gameTime--;
                document.getElementById('gameTimer').textContent = gameTime;
                
                if (gameTime <= 0) {
                    clearInterval(timer);
                    endGame(score);
                }
            }, 1000);
            
            document.getElementById('clickButton').onclick = () => {
                score++;
                document.getElementById('gameScore').textContent = score;
                tg.HapticFeedback.impactOccurred('light');
            };
        }
        
        // End game
        function endGame(finalScore) {
            tg.showAlert(`Game Over!\\nScore: ${finalScore} points`, () => {
                location.reload(); // Reload app
            });
            
            // Send score to bot
            sendDataToBot('game_finished', { score: finalScore });
        }
        
        // Share score
        function shareScore() {
            const totalTasks = tasks.length;
            const completedTasks = tasks.filter(t => t.completed).length;
            
            const shareText = `🎯 My Task Progress\\n✅ Completed: ${completedTasks}/${totalTasks}\\n📊 Achievement: ${totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0}%`;
            
            // Share text
            tg.shareText(shareText);
        }
        
        // Purchase functionality
        function makePurchase() {
            // Use Telegram Payments API
            const invoice = {
                title: 'Premium Features',
                description: 'Unlock advanced task management features',
                payload: 'premium_upgrade',
                provider_token: 'YOUR_PAYMENT_PROVIDER_TOKEN',
                currency: 'USD',
                prices: [{ label: 'Premium Features', amount: 500 }] // $5.00 (amount in smallest units)
            };
            
            tg.invoiceCreate(invoice, (result) => {
                if (result.success) {
                    tg.showAlert('Purchase completed!');
                    sendDataToBot('purchase_completed', result);
                } else {
                    tg.showAlert('Purchase cancelled.');
                }
            });
        }
        
        // Send data to bot
        function sendDataToBot(action, data) {
            tg.sendData(JSON.stringify({
                action: action,
                data: data,
                user: user,
                timestamp: Date.now()
            }));
        }
        
        // Close app
        function closeApp() {
            tg.close();
        }
        
        // Configure MainButton
        tg.MainButton.setText('Complete');
        tg.MainButton.onClick(() => {
            sendDataToBot('app_completed', { tasks: tasks });
            tg.close();
        });
        tg.MainButton.show();
        
        // Configure BackButton
        tg.BackButton.onClick(() => {
            tg.showConfirm('Exit app?', (confirmed) => {
                if (confirmed) {
                    tg.close();
                }
            });
        });
        tg.BackButton.show();
        
        // Initial rendering
        renderTasks();
        
        // Get device information
        console.log('Platform:', tg.platform);
        console.log('Version:', tg.version);
        console.log('ViewportHeight:', tg.viewportHeight);
        console.log('ViewportStableHeight:', tg.viewportStableHeight);
    </script>
</body>
</html>

Environment Variables Configuration

# .env file
# Telegram Bot settings
TELEGRAM_BOT_TOKEN=your-bot-token-from-botfather
TELEGRAM_WEBHOOK_URL=https://yourdomain.com/telegram/webhook

# External API integration
OPENWEATHER_API_KEY=your-openweather-api-key
GOOGLE_TRANSLATE_API_KEY=your-google-translate-key

# Database settings
DATABASE_URL=postgresql://user:password@localhost/telegram_bot
REDIS_URL=redis://localhost:6379

# File storage
AWS_S3_BUCKET=your-s3-bucket
AWS_ACCESS_KEY_ID=your-aws-access-key
AWS_SECRET_ACCESS_KEY=your-aws-secret-key

# Payment processing
STRIPE_SECRET_KEY=your-stripe-secret-key
TELEGRAM_PAYMENT_PROVIDER_TOKEN=your-payment-provider-token

# Mini app settings
MINI_APP_URL=https://your-mini-app.com
MINI_APP_SECRET=your-mini-app-secret

Docker Configuration Example

# Dockerfile
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    tesseract-ocr \
    tesseract-ocr-eng \
    libgl1-mesa-glx \
    libglib2.0-0 \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application files
COPY . .

# Environment variables
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1

# Expose port
EXPOSE 5000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:5000/health || exit 1

# Start application
CMD ["python", "bot.py"]

Docker Compose Configuration

# docker-compose.yml
version: '3.8'

services:
  telegram-bot:
    build: .
    container_name: telegram-bot
    restart: unless-stopped
    environment:
      - TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
      - DATABASE_URL=postgresql://postgres:password@postgres:5432/telegram_bot
      - REDIS_URL=redis://redis:6379
    depends_on:
      - postgres
      - redis
    volumes:
      - ./downloads:/app/downloads
    ports:
      - "5000:5000"
  
  postgres:
    image: postgres:15-alpine
    container_name: postgres
    restart: unless-stopped
    environment:
      - POSTGRES_DB=telegram_bot
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=password
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
  
  redis:
    image: redis:7-alpine
    container_name: redis
    restart: unless-stopped
    volumes:
      - redis_data:/data
    ports:
      - "6379:6379"

volumes:
  postgres_data:
  redis_data:

CI/CD Notification Integration Example

# ci_cd_integration.py - CI/CD pipeline notifications
import requests
import json
from datetime import datetime

class TelegramCINotifier:
    def __init__(self, bot_token: str, chat_id: str):
        self.bot_token = bot_token
        self.chat_id = chat_id
        self.api_url = f"https://api.telegram.org/bot{bot_token}"
    
    def send_build_notification(self, status: str, project: str, branch: str, commit: str):
        """Send build notification"""
        emoji = "✅" if status == "success" else "❌"
        
        message = f"""
{emoji} **Build {status.upper()}**

Project: {project}
Branch: {branch}
Commit: {commit[:8]}
Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        """
        
        keyboard = {
            "inline_keyboard": [
                [{"text": "📊 View Details", "url": f"https://ci.example.com/builds/{commit}"}],
                [{"text": "🚀 Deploy", "callback_data": f"deploy_{project}_{branch}"}]
            ]
        } if status == "success" else None
        
        self.send_message(message, keyboard)
    
    def send_deployment_notification(self, environment: str, status: str, version: str):
        """Send deployment notification"""
        emoji = "🚀" if status == "success" else "💥"
        
        message = f"""
{emoji} **Deployment {status.upper()}**

Environment: {environment}
Version: {version}
Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        """
        
        self.send_message(message)
    
    def send_message(self, text: str, reply_markup=None):
        """Send message"""
        url = f"{self.api_url}/sendMessage"
        data = {
            "chat_id": self.chat_id,
            "text": text,
            "parse_mode": "Markdown"
        }
        if reply_markup:
            data["reply_markup"] = reply_markup
        
        requests.post(url, json=data)