Telegram bot in Python not getting web app data transmission

I’m working on a Python Telegram bot that needs to get information from a web application. When users click a button in the web app, it should send data back to the bot.

I set everything up following Telegram’s documentation and turned off group privacy settings in BotFather. The bot should open a webpage where users type text, then forward that text to a Discord webhook.

main.py:

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters
import logging
import json
import httpx
from datetime import datetime

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

BOT_TOKEN = ""
WEBHOOK_URL = ""
WEB_APP_URL = ""

# Send to Discord
async def forward_to_discord(user_data):
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(WEBHOOK_URL, json={"content": json.dumps(user_data, indent=2), "username": "My Bot"})
            logger.info(f"Discord status: {response.status_code}, Response: {response.text}")
    except Exception as e:
        logger.error(f"Discord sending failed: {e}")

# Start command
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    keyboard = [[InlineKeyboardButton("Open App", web_app=WebAppInfo(url=WEB_APP_URL))]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await context.bot.send_message(chat_id=update.effective_chat.id, text='Hello! Click to start', reply_markup=reply_markup)

# Process web app data
async def process_webapp_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    message = update.effective_message
    if message.web_app_data:
        user_input = json.loads(message.web_app_data.data)
        await forward_to_discord(user_input)
    else:
        logger.info("Message received without web app data")

# Main function
def main():
    app = Application.builder().token(BOT_TOKEN).build()
    app.add_handler(CommandHandler("start", start_command))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, process_webapp_data))
    app.run_polling()

if __name__ == '__main__':
    main()

webapp.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Input Form</title>
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <style>
        body { font-family: sans-serif; text-align: center; padding: 50px; }
        .form-container { max-width: 400px; margin: 0 auto; }
        input, button { display: block; width: 100%; margin: 15px 0; padding: 12px; font-size: 18px; }
    </style>
</head>
<body>
<div class="form-container">
    <h1>Enter Your Message</h1>
    <p>Please type your message below:</p>
    <input type="text" id="userMessage" placeholder="Type your message here">
    <button id="submitBtn">Submit Message</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const submitButton = document.getElementById('submitBtn');
    const messageInput = document.getElementById('userMessage');

    submitButton.addEventListener('click', function() {
        const formData = {
            message: messageInput.value.trim(),
        };

        if(formData.message) {
            Telegram.WebApp.sendData(JSON.stringify(formData));
        } else {
            alert("Please enter a message first.");
        }
    });
    Telegram.WebApp.ready();
});
</script>
</body>
</html>

When users click ‘Submit Message’ in the web app, my bot doesn’t receive anything. No errors show up, but the message handler never gets called. I’ve tried different approaches and even asked AI assistants, but nothing works. The bot should take whatever the user types and send it to Discord through the webhook.

The problem is web app data comes through as a special message type that your current handler won’t catch. You need to filter specifically for web app data messages. Change your message handler to:

app.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, process_webapp_data))

Ditch the text filter completely - web app data isn’t regular text messages. I hit this exact same issue when I started with Telegram web apps. Spent hours debugging before I figured out the filter was wrong. Make this change and your process_webapp_data function should start receiving the data properly.

Had the same frustrating experience with my first Telegram web app. Yeah, it’s your message handler filter like everyone said, but here’s what got me too - your web app needs HTTPS. Telegram won’t work with regular HTTP connections. If you’re testing locally, use ngrok to tunnel your local server. Also check that your WEB_APP_URL is actually reachable from Telegram’s servers. I spent an entire afternoon debugging Python code when my local server just wasn’t accessible externally.

Use filters.StatusUpdate.WEB_APP_DATA instead of filters.TEXT for your message handler. Web app data isn’t regular text - it’s a different message type, so your current filter won’t catch it.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.