by moonboy
Telegram Mini App Example
from flask import Flask, render_template, url_for, redirect
import os
import logging
import threading
from telegram import Update, WebAppInfo
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext, Filters
from web_app_routes import app
from utils import get_bot_username
TELEGRAM_API_TOKEN = os.getenv('TELEGRAM_API_TOKEN')
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#DO NOT CHANGE THIS
webapp_url = f"{app.config['BASE_URL']}"
def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text(
"Hi! I'm a Telegram Web App. Click the link below to open my simple web app!",
reply_markup=telegram.InlineKeyboardMarkup([[
telegram.InlineKeyboardButton("Open Web App", web_app=WebAppInfo(url=webapp_url))
]])
Frequently Asked Questions
What are some potential business applications for this Basic Telegram Bot template?
The Basic Telegram Bot template offers versatile applications for businesses: - Customer support: Create a bot to handle frequently asked questions and provide instant responses. - Order tracking: Develop a mini app that allows customers to track their orders directly through Telegram. - Appointment scheduling: Implement a booking system within the Telegram interface. - Product catalogs: Showcase and sell products directly through the Telegram mini app. - Employee communication: Use the bot for internal announcements and updates.
How can the Basic Telegram Bot template improve customer engagement?
The Basic Telegram Bot template enhances customer engagement by: - Providing 24/7 availability for customer inquiries. - Offering a seamless, familiar interface within Telegram. - Enabling quick access to information without leaving the messaging app. - Allowing for personalized interactions based on user data. - Creating interactive experiences through the mini app functionality.
What industries could benefit most from implementing this Basic Telegram Bot template?
Several industries can leverage the Basic Telegram Bot template: - E-commerce: For order tracking, product recommendations, and customer support. - Healthcare: Appointment reminders, basic health inquiries, and medication schedules. - Education: Course information, assignment submissions, and study reminders. - Hospitality: Hotel bookings, travel information, and local recommendations. - Finance: Account balance checks, transaction alerts, and basic financial advice.
How can I customize the user interface of the Basic Telegram Bot template?
You can customize the user interface by modifying the HTML and CSS files. For example, to change the app name and add a custom message to the index.html file, you would edit it like this:
```html
{% include 'partials/header.html' %}
Welcome to MyCustomBot
This is a personalized Telegram mini app!
```
Don't forget to update the app name in the header.html file as well:
html
<span style="color: #ffffff;">MyCustomBot</span>
How do I add new commands to the Basic Telegram Bot template?
To add new commands, you'll need to modify the main.py file. Here's an example of how to add a new "/help" command:
```python def help_command(update: Update, context: CallbackContext) -> None: update.message.reply_text("This is a help message. You can use /start to begin or /profile to view your profile.")
def main(): # ... existing code ... dispatcher.add_handler(CommandHandler("help", help_command)) # ... rest of the main function ... ```
This adds a new "/help" command that users can use to get assistance. Remember to import any necessary modules and update your bot's command list with BotFather if you add new commands.
Created: | Last Updated:
Introduction to the Telegram Mini App Example Template
This template provides a starting point for creating a Telegram mini app. It includes a Flask web application and a Telegram bot that can interact with users and display a simple web interface. The template is designed to be easily customizable, allowing you to build the Telegram mini app of your desires.
Getting Started
To get started with this template, click Start with this Template.
Initial Setup
Environment Secrets
This template requires a Telegram API token to function. Follow these steps to obtain and set up the token:
- Get a Telegram bot API key:
- Open Telegram and search for "BotFather".
- Start a chat with BotFather and type
/newbot
. - Follow the prompts to create a new bot.
-
BotFather will provide you with an API key for your new bot.
-
Set up your bot:
- Copy the API key provided by BotFather.
- In the Lazy Builder, go to the Environment Secrets tab.
- Add a new secret with the name
TELEGRAM_API_TOKEN
and paste the API key as the value.
Test
Press the Test button to deploy the app and launch the Lazy CLI. The CLI will guide you through any required user input.
Using the App
Telegram Bot
- Start the Bot:
- Open Telegram and search for your bot using the username provided by BotFather.
- Start a chat with your bot and type
/start
. -
The bot will respond with a message and a button to open the web app.
-
Interact with the Bot:
- You can send text messages to the bot, and it will echo your messages back with a button to open the web app.
Web App
- Open the Web App:
- Click the "Open Web App" button in the bot's response.
-
The web app will open in your browser.
-
Profile Page:
- If you open the web app from Telegram, it will display your profile information.
- If you open the web app outside of Telegram, it will prompt you to use it from Telegram.
Integrating the App
Customizing the Web Interface
- Change the App Name:
- Open
header.html
and find the line with<span style="color: #ffffff;">App Name</span>
. -
Replace "App Name" with your desired app name.
-
Add Content to the Web App:
- Open
index.html
and add your content inside the<div class="container mt-5">
element.
Customizing the Bot
- Add New Commands:
- Open
main.py
and add new command handlers using theCommandHandler
class. -
For example, to add a
/help
command, add the following code: ```python def help_command(update: Update, context: CallbackContext) -> None: update.message.reply_text("This is a help message.")dispatcher.add_handler(CommandHandler("help", help_command)) ```
-
Modify Existing Commands:
- Modify the
start
,profile
, andecho
functions inmain.py
to change the bot's responses.
External Integrations
If you need to integrate the app with external tools or services, follow these steps:
- Telegram Web App Data:
- The web app can receive data from Telegram using the
initData
parameter. -
Modify the
/profile
route inweb_app_routes.py
to handle additional data as needed. -
API Endpoints:
- Add new routes to
web_app_routes.py
to create additional API endpoints. - Use the
Flask
framework to handle requests and responses.
Conclusion
This template provides a flexible starting point for building a Telegram mini app and bot. Customize the web interface and bot commands to suit your needs, and integrate with external tools as required. Happy building!
Template Benefits
-
Rapid Telegram Bot Development: This template provides a ready-to-use structure for creating Telegram bots, significantly reducing development time and allowing businesses to quickly deploy custom bot solutions.
-
Seamless Web App Integration: The template includes a Flask-based web application that integrates smoothly with Telegram, enabling businesses to create rich, interactive experiences beyond basic bot functionality.
-
Enhanced User Engagement: By combining bot commands with a web interface, businesses can offer a more engaging and versatile user experience, potentially increasing user retention and interaction rates.
-
Secure User Authentication: The template implements secure user authentication through Telegram's Web App API, ensuring that only authorized users can access sensitive information or perform certain actions.
-
Scalable and Customizable Framework: The modular structure of the template allows for easy customization and expansion, making it suitable for a wide range of business applications, from customer support to e-commerce integrations within Telegram.