The Fastest Way to Build a Telegram Bot Natively: A Comprehensive Guide for Developers
Building a Telegram bot can be a rewarding experience, especially when you leverage the native Telegram Bot API. This tutorial will guide you through the fastest and most efficient way to create a Telegram bot using Python and the python-telegram-bot library. We'll focus on setting up a bot that can handle commands, messages, and inline queries, all while emphasizing performance and scalability.
Prerequisites
Before diving into the code, ensure you have the following installed:
- Python 3.8 or higher
-
python-telegram-botlibrary (pip install python-telegram-bot) - A Telegram account
- A bot token obtained from BotFather on Telegram
Setting Up Your Bot
First, let's import the necessary modules and initialize our bot:
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, CallbackContext
Initialization
TOKEN = 'YOUR_BOT_TOKEN_HERE'
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher
Here, we initialize the Updater class, which will handle the polling mechanism to fetch updates from Telegram. The dispatcher is responsible for routing these updates to the appropriate handlers.
Handling Commands
Let's start by handling basic commands like /start and /help.
def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Welcome! Use /help to see available commands.')
def help_command(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Available commands:\n/start - Start the bot\n/help - Show this help message')
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('help', help_command))
Here, we define two simple command handlers and register them using CommandHandler.
Handling Messages
Now, let's add a handler to respond to text messages:
def echo(update: Update, context: CallbackContext) -> None:
user_message = update.message.text
update.message.reply_text(f'You said: {user_message}')
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
This handler listens to all text messages that are not commands and echoes them back to the user.
Inline Queries
Inline queries allow users to interact with your bot directly from the chat input field. Let's implement a simple inline query handler:
def inline_query(update: Update, context: CallbackContext) -> None:
query = update.inline_query.query
if not query:
return
results = [
InlineQueryResultArticle(
id='1',
title='Echo',
input_message_content=InputTextMessageContent(f'You typed: {query}')
)
]
update.inline_query.answer(results)
dispatcher.add_handler(CallbackQueryHandler(inline_query))
This handler responds with an inline query result that echoes the user's input.
Adding a Custom Keyboard
Let's enhance our bot by adding a custom keyboard that users can use to send predefined responses:
def custom_keyboard(update: Update, context: CallbackContext) -> None:
keyboard = [
[InlineKeyboardButton("Option 1", callback_data='1')],
[InlineKeyboardButton("Option 2", callback_data='2')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
dispatcher.add_handler(CommandHandler('keyboard', custom_keyboard))
This command handler sends a message with a custom inline keyboard.
Handling Button Presses
When a user presses a button on the custom keyboard, we need to handle the callback:
def button(update: Update, context: CallbackContext) -> None:
query = update.callback_query
query.answer()
query.edit_message_text(text=f'Selected option: {query.data}')
dispatcher.add_handler(CallbackQueryHandler(button))
This callback handler updates the message to show which button the user pressed.
Starting the Bot
Finally, we start the bot and begin polling for updates:
if __name__ == '__main__':
updater.start_polling()
updater.idle()
The start_polling method initiates the polling process, and idle keeps the bot running until you stop it.
Conclusion
In this tutorial, we've built a fully functional Telegram bot using the python-telegram-bot library. We covered command handling, message echoing, inline queries, custom keyboards, and button press handling. This setup provides a robust foundation for more complex bot functionalities.
Remember to keep your bot secure by not exposing your token in public repositories and to adhere to Telegram's bot development guidelines. 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)