I’m working on a Python Telegram bot that needs to get information from a web application. When users click a button in the web app, it should send data back to the bot.
I set everything up following Telegram’s documentation and turned off group privacy settings in BotFather. The bot should open a webpage where users type text, then forward that text to a Discord webhook.
main.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__)
BOT_TOKEN = ""
WEBHOOK_URL = ""
WEB_APP_URL = ""
# Send to Discord
async def forward_to_discord(user_data):
try:
async with httpx.AsyncClient() as client:
response = await client.post(WEBHOOK_URL, json={"content": json.dumps(user_data, indent=2), "username": "My Bot"})
logger.info(f"Discord status: {response.status_code}, Response: {response.text}")
except Exception as e:
logger.error(f"Discord sending failed: {e}")
# Start command
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
keyboard = [[InlineKeyboardButton("Open App", web_app=WebAppInfo(url=WEB_APP_URL))]]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(chat_id=update.effective_chat.id, text='Hello! Click to start', reply_markup=reply_markup)
# Process web app data
async def process_webapp_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.effective_message
if message.web_app_data:
user_input = json.loads(message.web_app_data.data)
await forward_to_discord(user_input)
else:
logger.info("Message received without web app data")
# Main function
def main():
app = Application.builder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start_command))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, process_webapp_data))
app.run_polling()
if __name__ == '__main__':
main()
webapp.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Input Form</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<style>
body { font-family: sans-serif; text-align: center; padding: 50px; }
.form-container { max-width: 400px; margin: 0 auto; }
input, button { display: block; width: 100%; margin: 15px 0; padding: 12px; font-size: 18px; }
</style>
</head>
<body>
<div class="form-container">
<h1>Enter Your Message</h1>
<p>Please type your message below:</p>
<input type="text" id="userMessage" placeholder="Type your message here">
<button id="submitBtn">Submit Message</button>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const submitButton = document.getElementById('submitBtn');
const messageInput = document.getElementById('userMessage');
submitButton.addEventListener('click', function() {
const formData = {
message: messageInput.value.trim(),
};
if(formData.message) {
Telegram.WebApp.sendData(JSON.stringify(formData));
} else {
alert("Please enter a message first.");
}
});
Telegram.WebApp.ready();
});
</script>
</body>
</html>
When users click ‘Submit Message’ in the web app, my bot doesn’t receive anything. No errors show up, but the message handler never gets called. I’ve tried different approaches and even asked AI assistants, but nothing works. The bot should take whatever the user types and send it to Discord through the webhook.