webappbot.py

 1#!/usr/bin/env python
 2# pylint: disable=unused-argument,wrong-import-position
 3# This program is dedicated to the public domain under the CC0 license.
 4
 5"""
 6Simple example of a Telegram WebApp which displays a color picker.
 7The static website for this website is hosted by the PTB team for your convenience.
 8Currently only showcases starting the WebApp via a KeyboardButton, as all other methods would
 9require a bot token.
10"""
11import json
12import logging
13
14from telegram import __version__ as TG_VER
15
16try:
17    from telegram import __version_info__
18except ImportError:
19    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
20
21if __version_info__ < (20, 0, 0, "alpha", 1):
22    raise RuntimeError(
23        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
24        f"{TG_VER} version of this example, "
25        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
26    )
27from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, Update, WebAppInfo
28from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
29
30# Enable logging
31logging.basicConfig(
32    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
33)
34logger = logging.getLogger(__name__)
35
36
37# Define a `/start` command handler.
38async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
39    """Send a message with a button that opens a the web app."""
40    await update.message.reply_text(
41        "Please press the button below to choose a color via the WebApp.",
42        reply_markup=ReplyKeyboardMarkup.from_button(
43            KeyboardButton(
44                text="Open the color picker!",
45                web_app=WebAppInfo(url="https://python-telegram-bot.org/static/webappbot"),
46            )
47        ),
48    )
49
50
51# Handle incoming WebAppData
52async def web_app_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
53    """Print the received data and remove the button."""
54    # Here we use `json.loads`, since the WebApp sends the data JSON serialized string
55    # (see webappbot.html)
56    data = json.loads(update.effective_message.web_app_data.data)
57    await update.message.reply_html(
58        text=f"You selected the color with the HEX value <code>{data['hex']}</code>. The "
59        f"corresponding RGB value is <code>{tuple(data['rgb'].values())}</code>.",
60        reply_markup=ReplyKeyboardRemove(),
61    )
62
63
64def main() -> None:
65    """Start the bot."""
66    # Create the Application and pass it your bot's token.
67    application = Application.builder().token("TOKEN").build()
68
69    application.add_handler(CommandHandler("start", start))
70    application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, web_app_data))
71
72    # Run the bot until the user presses Ctrl-C
73    application.run_polling()
74
75
76if __name__ == "__main__":
77    main()

HTML Page

 1<!--
 2    Simple static Telegram WebApp. Does not verify the WebAppInitData, as a bot token would be needed for that.
 3-->
 4<!DOCTYPE html>
 5<html lang="en">
 6<head>
 7    <meta charset="UTF-8">
 8    <title>python-telegram-bot Example WebApp</title>
 9    <script src="https://telegram.org/js/telegram-web-app.js"></script>
10    <script src="https://cdn.jsdelivr.net/npm/@jaames/iro@5"></script>
11</head>
12<script type="text/javascript">
13    const colorPicker = new iro.ColorPicker('#picker', {
14        borderColor: "#ffffff",
15        borderWidth: 1,
16        width: Math.round(document.documentElement.clientWidth / 2),
17    });
18    colorPicker.on('color:change', function (color) {
19        document.body.style.background = color.hexString;
20    });
21
22    Telegram.WebApp.ready();
23    Telegram.WebApp.MainButton.setText('Choose Color').show().onClick(function () {
24        const data = JSON.stringify({hex: colorPicker.color.hexString, rgb: colorPicker.color.rgb});
25        Telegram.WebApp.sendData(data);
26        Telegram.WebApp.close();
27    });
28</script>
29<body style="background-color: #ffffff">
30<div style="position: absolute; margin-top: 5vh; margin-left: 5vw; height: 90vh; width: 90vw; border-radius: 5vh; background-color: var(--tg-theme-bg-color); box-shadow: 0 0 2vw
31 #000000;">
32    <div id="picker"
33         style="display: flex; justify-content: center; align-items: center; height: 100%; width: 100%"></div>
34</div>
35</body>
36<script type="text/javascript">
37    Telegram.WebApp.expand();
38</script>
39</html>