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)
34# set higher logging level for httpx to avoid all GET and POST requests being logged
35logging.getLogger("httpx").setLevel(logging.WARNING)
36
37logger = logging.getLogger(__name__)
38
39
40# Define a `/start` command handler.
41async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
42 """Send a message with a button that opens a the web app."""
43 await update.message.reply_text(
44 "Please press the button below to choose a color via the WebApp.",
45 reply_markup=ReplyKeyboardMarkup.from_button(
46 KeyboardButton(
47 text="Open the color picker!",
48 web_app=WebAppInfo(url="https://python-telegram-bot.org/static/webappbot"),
49 )
50 ),
51 )
52
53
54# Handle incoming WebAppData
55async def web_app_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
56 """Print the received data and remove the button."""
57 # Here we use `json.loads`, since the WebApp sends the data JSON serialized string
58 # (see webappbot.html)
59 data = json.loads(update.effective_message.web_app_data.data)
60 await update.message.reply_html(
61 text=f"You selected the color with the HEX value <code>{data['hex']}</code>. The "
62 f"corresponding RGB value is <code>{tuple(data['rgb'].values())}</code>.",
63 reply_markup=ReplyKeyboardRemove(),
64 )
65
66
67def main() -> None:
68 """Start the bot."""
69 # Create the Application and pass it your bot's token.
70 application = Application.builder().token("TOKEN").build()
71
72 application.add_handler(CommandHandler("start", start))
73 application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, web_app_data))
74
75 # Run the bot until the user presses Ctrl-C
76 application.run_polling(allowed_updates=Update.ALL_TYPES)
77
78
79if __name__ == "__main__":
80 main()