Reference
Resources
arbitrarycallbackdatabot.py
chatmemberbot.py
contexttypesbot.py
conversationbot.py
conversationbot2.py
customwebhookbot.py
deeplinking.py
echobot.py
errorhandlerbot.py
inlinebot.py
inlinekeyboard.py
inlinekeyboard2.py
nestedconversationbot.py
passportbot.py
paymentbot.py
persistentconversationbot.py
pollbot.py
timerbot.py
webappbot.py
Project
webappbot.py
¶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"""11importjson12importlogging1314fromtelegramimportKeyboardButton,ReplyKeyboardMarkup,ReplyKeyboardRemove,Update,WebAppInfo15fromtelegram.extimportApplication,CommandHandler,ContextTypes,MessageHandler,filters1617# Enable logging18logging.basicConfig(19format="%(asctime)s -%(name)s -%(levelname)s -%(message)s",level=logging.INFO20)21# set higher logging level for httpx to avoid all GET and POST requests being logged22logging.getLogger("httpx").setLevel(logging.WARNING)2324logger=logging.getLogger(__name__)252627# Define a `/start` command handler.28asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:29"""Send a message with a button that opens a the web app."""30awaitupdate.message.reply_text(31"Please press the button below to choose a color via the WebApp.",32reply_markup=ReplyKeyboardMarkup.from_button(33KeyboardButton(34text="Open the color picker!",35web_app=WebAppInfo(url="https://python-telegram-bot.org/static/webappbot"),36)37),38)394041# Handle incoming WebAppData42asyncdefweb_app_data(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:43"""Print the received data and remove the button."""44# Here we use `json.loads`, since the WebApp sends the data JSON serialized string45# (see webappbot.html)46data=json.loads(update.effective_message.web_app_data.data)47awaitupdate.message.reply_html(48text=(49f"You selected the color with the HEX value <code>{data['hex']}</code>. The "50f"corresponding RGB value is <code>{tuple(data['rgb'].values())}</code>."51),52reply_markup=ReplyKeyboardRemove(),53)545556defmain()->None:57"""Start the bot."""58# Create the Application and pass it your bot's token.59application=Application.builder().token("TOKEN").build()6061application.add_handler(CommandHandler("start",start))62application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA,web_app_data))6364# Run the bot until the user presses Ctrl-C65application.run_polling(allowed_updates=Update.ALL_TYPES)666768if__name__=="__main__":69main()
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<htmllang="en"> 6<head> 7<metacharset="UTF-8"> 8<title>python-telegram-bot Example WebApp</title> 9<scriptsrc="https://telegram.org/js/telegram-web-app.js"></script>10<scriptsrc="https://cdn.jsdelivr.net/npm/@jaames/iro@5"></script>11</head>12<scripttype="text/javascript">13constcolorPicker=newiro.ColorPicker('#picker',{14borderColor:"#ffffff",15borderWidth:1,16width:Math.round(document.documentElement.clientWidth/2),17});18colorPicker.on('color:change',function(color){19document.body.style.background=color.hexString;20});2122Telegram.WebApp.ready();23Telegram.WebApp.MainButton.setText('Choose Color').show().onClick(function(){24constdata=JSON.stringify({hex:colorPicker.color.hexString,rgb:colorPicker.color.rgb});25Telegram.WebApp.sendData(data);26Telegram.WebApp.close();27});28</script>29<bodystyle="background-color: #ffffff">30<divstyle="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 2vw31 #000000;">32<divid="picker"33style="display: flex; justify-content: center; align-items: center; height: 100%; width: 100%"></div>34</div>35</body>36<scripttype="text/javascript">37Telegram.WebApp.expand();38</script>39</html>