skip to Main Content

I am developing a Telegram bot in Python which must receive data from a web mini-app. The mini-app is supposed to send data to the bot when the user clicks a button.
I followed the official Telegram documentation to configure the mini-app and the bot to communicate with each other. I also disabled group message privacy in BotFather so that the bot can receive all messages.

The bot is supposed to open a web page, the user puts text in the dedicated area and the bot sends what the user has enter into the Discord webhook

bot.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__)

TOKEN = ""
DISCORD_WEBHOOK_URL = ""
MINI_APP_URL=""

#Discord
async def send_message_to_discord(order_data):
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(DISCORD_WEBHOOK_URL, json={"content": json.dumps(order_data, indent=4), "username": "Test Bot"})
            logger.info(f"Discord response: Status {response.status_code}, Body {response.text}")
    except Exception as e:
        logger.error(f"Failed to send message to Discord: {e}")

#/start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    keyboard = [[InlineKeyboardButton("Commander", web_app=WebAppInfo(url=MINI_APP_URL))]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await context.bot.send_message(chat_id=update.effective_chat.id, text='Welcome', reply_markup=reply_markup)

#Mini App data processing
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    message = update.effective_message
    if message.web_app_data:
        data = json.loads(message.web_app_data.data)
        send_message_to_discord(data)
    else:
        logger.info("Received a message that doesn't contain web_app_data")

#launch app
def main():
    application = Application.builder().token(TOKEN).build()
    application.add_handler(CommandHandler("start", start))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    application.run_polling()

if __name__ == '__main__':
    main()

index.html:

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Test Mini App</title>
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <style>
        body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
        .container { text-align: center; }
        input, button { margin-top: 20px; padding: 10px; font-size: 16px; }
    </style>
</head>
<body>
<div class="container">
    <h2>Welcome</h2>
    <p>Type Text :</p>
    <input type="text" id="deliveryOption" placeholder="Entrez l'option de livraison ici">
    <br>
    <button id="sendOrder">Envoyer le texte</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const sendOrderButton = document.getElementById('sendOrder');
    const deliveryOption = document.getElementById('deliveryOption');

    sendOrderButton.addEventListener('click', function() {
        const orderData = {
            delivery: deliveryOption.value.trim(),
        };

        if(orderData.delivery) {
            // Envoie les données au bot Telegram
            Telegram.WebApp.sendData(JSON.stringify(orderData));
        } else {
            alert("Veuillez entrer une option de livraison.");
        }
    });
    Telegram.WebApp.ready();
});
</script>
</body>
</html>

When the user clicks ‘Envoyer le texte’ in the mini-app, the bot does not receive the data as expected. There are no errors, but the handle_message function does not seem to be triggered

I followed the official Telegram documentation to establish communication between the mini-app and the bot. I used the "Telegram.WebApp.sendData" method in my mini-app to send data to the bot, and configured the bot to listen for incoming messages using "MessageHandler" with filters to process messages that are not commands. I also disabled group message privacy through BotFather. I also asked for help from ChatGPT who told me that my code looked good and didn’t know what to do.

The bot should send the message to Discord what the user put in the

2

Answers


  1. The data will be available via Message.web_app_data rather than Message.text. Please use filters.StatusUpdate.WEB_APP_DATA to catch these messages as demonstrated in this example.


    Disclaimer: I’m currently the maitainer of python-telegram-bot.

    Login or Signup to reply.
  2. First of all the filter you should be using is filters.StatusUpdate.WEB_APP_DATA to capture web-app data

    Second and the most sad part is that sendData in mini-app is only available for KeyboardButton , not for InlineKeyboardButton which you are using.

    This method is only available for Mini Apps launched via a Keyboard button.

    Office doc

    In case you have been able to figure it out using InlineKeyboardButton please share the solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search