Ok, lets begin from the begining, as far as I understand I don't really need this endpoint, because I just can share BOT_TOKEN between the bot itself and my service, therefore service will use it to call TG API and verify user without going through the bot, so it will be straight call without any middleman. Therefore I need from you a full code for my bot that will be made FastAPI for webhooks and will have command start + 3 buttons to open website, chat and miniapp. That's it.
Assistant
Certainly! Below is a comprehensive guide and full code to create a Telegram bot using FastAPI for handling webhooks. The bot will include the /start command and present three buttons: Open Website, Chat, and MiniApp.
Overview
Libraries Used:
FastAPI: To create the web server that will handle incoming webhook requests from Telegram.
python-telegram-bot: To interact with the Telegram Bot API.
uvicorn: To run the FastAPI application.
ngrok (optional): For local development to expose your FastAPI server to the internet.
Workflow:
Setting Up the Webhook: The bot needs to set a webhook URL where Telegram will send updates.
Handling Updates: FastAPI will receive the updates and pass them to the bot for processing.
Responding to /start Command: When a user sends the /start command, the bot will reply with three inline buttons.
Prerequisites
Python 3.7+: Ensure you have Python installed.
Telegram Bot Token: Create a bot using BotFather and obtain the BOT_TOKEN.
Server with HTTPS: Telegram requires the webhook URL to be HTTPS. For local development, tools like ngrok can be used to create an HTTPS tunnel.
Step-by-Step Implementation
1. Install Required Libraries
First, install the necessary Python libraries:
bash
pip install fastapi python-telegram-bot uvicorn
2. Create the FastAPI Application
Here's the complete Python script for the bot:
python
import os
import logging
from fastapi import FastAPI, Request, HTTPException
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, Bot
from telegram.ext import Dispatcher, CommandHandler, CallbackContext
from starlette.responses import JSONResponse
# Configure logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Initialize FastAPI app
app = FastAPI()
# Read the BOT_TOKEN from environment variables for security
BOT_TOKEN = os.getenv("BOT_TOKEN")
if not BOT_TOKEN:
logger.error("BOT_TOKEN is not set in environment variables.")
raise ValueError("BOT_TOKEN is not set in environment variables.")
bot = Bot(token=BOT_TOKEN)
# Initialize Dispatcher
dispatcher = Dispatcher(bot, None, use_context=True)
# Define /start command handler
def start_command(update: Update, context: CallbackContext):
user_first_name = update.effective_user.first_name
logger.info(f"/start command received from user: {user_first_name}")
# Define inline keyboard buttons
keyboard = [
[InlineKeyboardButton("Open Website", url="https://yourwebsite.com")],
[InlineKeyboardButton("Chat", callback_data="chat")],
[InlineKeyboardButton("MiniApp", callback_data="miniapp")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
# Send welcome message with buttons
update.message.reply_text(
f"Hello, {user_first_name}! Welcome to our bot. Choose an option below:",
reply_markup=reply_markup
)
# Optional: Define handlers for button callbacks
def button_handler(update: Update, context: CallbackContext):
query = update.callback_query
query.answer()
if query.data == "chat":
query.edit_message_text(text="You clicked on Chat. How can we assist you?")
elif query.data == "miniapp":
query.edit_message_text(text="Launching MiniApp...")
# Register handlers
dispatcher.add_handler(CommandHandler("start", start_command))
dispatcher.add_handler(telegram.ext.CallbackQueryHandler(button_handler))
# Webhook route
@app.post("/webhook")
async def telegram_webhook(request: Request):
# Get the raw body as bytes
body = await request.body()
if not body:
raise HTTPException(status_code=400, detail="Empty request body")
# Convert the update to a Telegram Update object
try:
update = Update.de_json(await request.json(), bot)
except Exception as e:
logger.error(f"Failed to parse update: {e}")
raise HTTPException(status_code=400, detail="Invalid update")
# Process the update using dispatcher
dispatcher.process_update(update)
return JSONResponse(content={"status": "ok"})
# Root endpoint
@app.get("/")
async def index():
return {"message": "Telegram Bot is running."}
# Function to set the webhook (Run this once)
def set_webhook(webhook_url: str):
try:
response = bot.set_webhook(url=webhook_url)
if response:
logger.info(f"Webhook set to {webhook_url}")
else:
logger.error("Failed to set webhook.")
except Exception as e:
logger.error(f"Error setting webhook: {e}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Run the Telegram Bot with FastAPI.")
parser.add_argument("--host", type=str, default="0.0.0.0", help="Host to run the server on.")
parser.add_argument("--port", type=int, default=8443, help="Port to run the server on.")
parser.add_argument("--webhook", type=str, help="Webhook URL to set for Telegram.")
args = parser.parse_args()
if args.webhook:
set_webhook(args.webhook)
# Run the FastAPI app with uvicorn
import uvicorn
uvicorn.run(app, host=args.host, port=args.port)
3. Explanation of the Code
Imports & Logging:
Imports necessary modules and sets up logging for debugging purposes.
Environment Variables:
The BOT_TOKEN is fetched from environment variables for security. Ensure you set this variable before running the script.
Bot & Dispatcher Initialization:
Initializes the Telegram Bot and Dispatcher from python-telegram-bot.
Command Handler (/start):
Defines the /start command which sends a welcome message along with three inline buttons:
Open Website: Opens a URL.
Chat: Triggers a callback to handle chat-related actions.
MiniApp: Triggers a callback to handle mini-app actions.
Button Callback Handler:
Handles button presses for Chat and MiniApp. You can customize these handlers based on your requirements.
Webhook Endpoint:
Defines a POST endpoint /webhook that Telegram will use to send updates.
The incoming JSON is converted to a Update object and passed to the dispatcher for processing.
Set Webhook Function:
A helper function to set the webhook URL with Telegram. This is typically run once during deployment.
Running the Server:
The script can be run directly, setting the webhook if a URL is provided, and starts the FastAPI server using Uvicorn.
4. Setting Up the Webhook
To set up the webhook, you need to provide a publicly accessible HTTPS URL. If you're developing locally, you can use ngrok to create a secure tunnel.
Start ngrok:
bash
ngrok http 8443
This will provide you with a forwarding HTTPS URL like https://abcd1234.ngrok.io.
Replace your_bot_script.py with the filename you saved the script as, and https://abcd1234.ngrok.io/webhook with your actual ngrok URL appended with /webhook.
Start the Server:
The script will set the webhook and start the FastAPI server. Ensure that ngrok remains running to keep the tunnel open.
5. Deploying to Production
For production, you'd typically deploy the FastAPI application to a reliable server or cloud service that provides HTTPS out of the box (like AWS, Heroku, Google Cloud, etc.).
Set Environment Variables:
Ensure that BOT_TOKEN is set in your production environment.
Set the Webhook:
Point Telegram to your production HTTPS URL with the /webhook endpoint.
Run the Server:
Use a robust ASGI server setup, possibly with process managers like Gunicorn combined with Uvicorn workers.
Final Notes
Security: Always keep your BOT_TOKEN secure. Do not hardcode it in your scripts. Use environment variables or secret management tools.
Error Handling: The script includes basic error handling. Depending on your use case, you might want to expand on this, especially for production environments.
Extensibility: This setup provides a foundation. You can add more commands and handlers as needed to extend the bot's functionality.
Callback Data Handling: The button_handler currently handles chat and miniapp callbacks. You can expand this to handle more complex interactions or integrate with other services.
With this setup, your Telegram bot using FastAPI is ready to handle webhooks effectively and respond to user interactions with the desired buttons.