1#!/usr/bin/env python
2# pylint: disable=unused-argument
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"""
11
12import json
13import logging
14
15from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, Update, WebAppInfo
16from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
17
18# Enable logging
19logging.basicConfig(
20 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
21)
22# set higher logging level for httpx to avoid all GET and POST requests being logged
23logging.getLogger("httpx").setLevel(logging.WARNING)
24
25logger = logging.getLogger(__name__)
26
27
28# Define a `/start` command handler.
29async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
30 """Send a message with a button that opens a the web app."""
31 await update.message.reply_text(
32 "Please press the button below to choose a color via the WebApp.",
33 reply_markup=ReplyKeyboardMarkup.from_button(
34 KeyboardButton(
35 text="Open the color picker!",
36 web_app=WebAppInfo(url="https://python-telegram-bot.org/static/webappbot"),
37 )
38 ),
39 )
40
41
42# Handle incoming WebAppData
43async def web_app_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
44 """Print the received data and remove the button."""
45 # Here we use `json.loads`, since the WebApp sends the data JSON serialized string
46 # (see webappbot.html)
47 data = json.loads(update.effective_message.web_app_data.data)
48 await update.message.reply_html(
49 text=(
50 f"You selected the color with the HEX value <code>{data['hex']}</code>. The "
51 f"corresponding RGB value is <code>{tuple(data['rgb'].values())}</code>."
52 ),
53 reply_markup=ReplyKeyboardRemove(),
54 )
55
56
57def main() -> None:
58 """Start the bot."""
59 # Create the Application and pass it your bot's token.
60 application = Application.builder().token("TOKEN").build()
61
62 application.add_handler(CommandHandler("start", start))
63 application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, web_app_data))
64
65 # Run the bot until the user presses Ctrl-C
66 application.run_polling(allowed_updates=Update.ALL_TYPES)
67
68
69if __name__ == "__main__":
70 main()