Certainly! It looks like you're trying to create a Telegram bot that serves a web application with a clickable button, which counts the number of clicks and displays the count both on the web app and sends the count back to the bot.
I've updated and fixed your code to meet your requirements. Below is the improved code with explanations for the changes made:
import telebot
from flask import Flask, render_template_string
# Telegram bot token
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE' # Replace with your actual bot token
bot = telebot.TeleBot(BOT_TOKEN)
app = Flask(__name__)
# HTML template embedded within Python code
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>Click Counter</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
.button {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: lightblue;
border: none;
cursor: pointer;
}
#clickCount {
margin-top: 20px;
font-size: 24px;
}
</style>
</head>
<body>
<button class="button"></button>
<p>Clicks: <span id="clickCount">0</span></p>
<script>
let clickCount = 0;
const button = document.querySelector('.button');
const clickCountDisplay = document.getElementById('clickCount');
button.addEventListener('click', () => {
clickCount++;
clickCountDisplay.textContent = clickCount;
// Send click count to the bot using Telegram Web App JS
Telegram.WebApp.sendData(clickCount.toString());
});
</script>
</body>
</html>
"""
@app.route('/')
def index():
return render_template_string(HTML_TEMPLATE)
@bot.message_handler(commands=['start'])
def start(message):
# Replace with your actual Flask app URL
web_app_url = 'https://yourpublicdomain.com/' # Make sure your Flask app is publicly accessible
# Create a Web App keyboard button
markup = telebot.types.InlineKeyboardMarkup()
web_app = telebot.types.WebAppInfo(web_app_url)
button = telebot.types.InlineKeyboardButton(text="Open Web App", web_app=web_app)
markup.add(button)
bot.send_message(message.chat.id, "Welcome! Use the web app to count clicks.", reply_markup=markup)
# Handler for receiving data from the Web App
@bot.message_handler(content_types=['web_app_data'])
def handle_web_app_data(message):
data = message.web_app_data.data # The data sent from Web App
bot.send_message(message.chat.id, f"Click count received: {data}")
if __name__ == '__main__':
from threading import Thread
# Run the Flask app in a separate thread
flask_thread = Thread(target=app.run, kwargs={'host': '0.0.0.0', 'port': 5000})
flask_thread.start()
bot.infinity_polling()
Explanation of Changes:
-
Fixed the /start Command Handler:
- Issue: The original code used
bot.set_chat_menu, which is not a valid method in the telebot library.
- Solution: Replaced it with sending an
InlineKeyboardMarkup containing an InlineKeyboardButton with a WebAppInfo object, which allows users to open the web app directly from the bot.
@bot.message_handler(commands=['start'])
def start(message):
web_app_url = 'https://yourpublicdomain.com/' # Replace with your public URL
markup = telebot.types.InlineKeyboardMarkup()
web_app = telebot.types.WebAppInfo(web_app_url)
button = telebot.types.InlineKeyboardButton(text="Open Web App", web_app=web_app)
markup.add(button)
bot.send_message(message.chat.id, "Welcome! Use the web app to count clicks.", reply_markup=markup)
-
Implemented Data Sending from Web App to Bot:
- Issue: The original JavaScript had a
TODO for sending data to the bot.
- Solution: Used
Telegram.WebApp.sendData() method to send the click count back to the bot when the button is clicked.
Telegram.WebApp.sendData(clickCount.toString());
-
Added a Handler for web_app_data:
- Issue: The bot wasn't handling the data sent from the web app.
- Solution: Added a message handler that processes the data received from the web app.
@bot.message_handler(content_types=['web_app_data'])
def handle_web_app_data(message):
data = message.web_app_data.data # The data sent from Web App
bot.send_message(message.chat.id, f"Click count received: {data}")
-
Removed Unnecessary Global Variables:
- Issue: The
click_count variable in the Flask app wasn't being used effectively.
- Solution: Removed it to simplify the code, since the click count is managed client-side in the web app.
-
Ensured the Flask App Is Accessible:
- Note: For the web app to work with your bot, your Flask app needs to be hosted on a public server with HTTPS enabled. Services like Heroku, PythonAnywhere, or any VPS can be used to host the Flask app.
- Updated:
app.run parameters to allow external access.
flask_thread = Thread(target=app.run, kwargs={'host': '0.0.0.0', 'port': 5000})
-
Corrected the HTML Template:
- Cleaned up the template and ensured the button and click counter display correctly.
Next Steps:
This should provide a functioning Telegram bot with an integrated web application that meets your requirements.