The Fastest Way to Build a Telegram Bot Natively
Building a Telegram bot is a powerful way to automate tasks, deliver updates, or create interactive experiences for users. In this tutorial, we’ll focus on building a Telegram bot natively using Python and the python-telegram-bot library, ensuring high performance and scalability. By the end, you’ll have a fully functional bot running on your machine.
Prerequisites
Before starting, ensure you have the following installed:
- Python 3.8+ (Download Python)
- pip (Python package manager)
- Telegram Bot Token (Obtain from BotFather)
Install the required library:
pip install python-telegram-bot
Step 1: Create a Basic Bot
The python-telegram-bot library provides a clean API for interacting with Telegram’s Bot API. Let’s start by creating a simple bot that responds to /start commands.
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
# Define the /start command handler
def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Hello! I am your Telegram bot. How can I assist you?')
def main() -> None:
# Replace 'YOUR_TOKEN' with your bot's token
updater = Updater("YOUR_TOKEN")
# Register the /start command
updater.dispatcher.add_handler(CommandHandler("start", start))
# Start the bot
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
Explanation:
- Updater: Core component that fetches updates from Telegram’s servers.
-
CommandHandler: Handles specific commands like
/start. - start_polling(): Starts the bot in polling mode, continuously checking for new messages.
Save this script as bot.py and run it:
python bot.py
Send /start to your bot in Telegram, and it should respond with a greeting.
Step 2: Add More Functionality
Let’s enhance our bot with additional commands and functionality.
Example: Echo Command
def echo(update: Update, context: CallbackContext) -> None:
user_message = update.message.text
update.message.reply_text(f'You said: {user_message}')
def main() -> None:
updater = Updater("YOUR_TOKEN")
# Register handlers
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("echo", echo))
updater.start_polling()
updater.idle()
Now, send /echo Hello! to your bot, and it will repeat your message.
Step 3: Deploy to Production
Running the bot locally is great for development, but deploying it ensures it’s always available. We’ll use Heroku for deployment.
- Install Heroku CLI: Install Heroku CLI
-
Create
Procfile:
worker: python bot.py
-
Create
requirements.txt:
pip freeze > requirements.txt
- Login to Heroku:
heroku login
- Create Heroku App:
heroku create your-app-name
- Deploy:
git init
git add .
git commit -m "Initial commit"
git push heroku master
- Start Worker:
heroku ps:scale worker=1
Your bot is now deployed! It will restart automatically if there’s an issue.
Step 4: Optimize for Performance
Polling is simple but inefficient for high-traffic bots. Instead, use Webhooks for better performance.
Set Up Webhooks
- Install Flask (for handling webhooks):
pip install flask
- Webhook Server Code:
from flask import Flask, request
from telegram import Update
from telegram.ext import Dispatcher, CommandHandler, MessageHandler, Filters
app = Flask(__name__)
# Initialize dispatcher
dispatcher = Dispatcher(bot, None, workers=0)
# Register handlers
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
@app.route('/webhook', methods=['POST'])
def webhook() -> str:
update = Update.de_json(request.get_json(force=True), bot)
dispatcher.process_update(update)
return 'ok'
def main() -> None:
app.run(port=5000)
if __name__ == "__main__":
main()
- Set Webhook URL:
Replace YOUR_DOMAIN with your Heroku app URL.
from telegram import Bot
bot = Bot(token="YOUR_TOKEN")
bot.set_webhook(url="https://YOUR_DOMAIN/webhook")
- Deploy to Heroku:
Follow the same deployment steps as before.
Advanced Features
1. Inline Queries
Allow users to interact with your bot directly from the chat input box.
from telegram import InlineQueryResultArticle, InputTextMessageContent
def inline_query(update: Update, context: CallbackContext) -> None:
query = update.inline_query.query
results = [
InlineQueryResultArticle(
id="1",
title="Echo",
input_message_content=InputTextMessageContent(f"You said: {query}")
)
]
update.inline_query.answer(results)
dispatcher.add_handler(InlineQueryHandler(inline_query))
2. Persistent Data
Use a database (e.g., SQLite, PostgreSQL) to store user data.
import sqlite3
# Initialize database
conn = sqlite3.connect('bot.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
conn.commit()
def save_user(update: Update, context: CallbackContext) -> None:
user_id = update.message.from_user.id
user_name = update.message.from_user.first_name
cursor.execute('INSERT OR IGNORE INTO users (id, name) VALUES (?, ?)', (user_id, user_name))
conn.commit()
3. Error Handling
Log errors and notify admins.
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def error(update: Update, context: CallbackContext) -> None:
logging.error(f'Update {update} caused error {context.error}')
Conclusion
You’ve now built a Telegram bot from scratch, enhanced it with advanced features, and deployed it to production. By leveraging python-telegram-bot, Flask, and Heroku, you’ve created a scalable, efficient bot ready to handle real-world use cases.
Feel free to explore additional features like keyboards, payment integrations, and more. Happy coding! 🚀
🚀 Stop Writing Boilerplate Prompts
If you want to skip the setup and code 10x faster with complete AI architecture patterns, grab my Senior React Developer AI Cookbook ($19). It includes Server Action prompt libraries, UI component generation loops, and hydration debugging strategies.
Browse all 10+ developer products at the Apollo AI Store | Or snipe Solana tokens free via @ApolloSniper_Bot.
Top comments (0)