The Fastest Way to Build a Telegram Bot Natively
Building a Telegram bot can seem daunting at first, but with the right tools and approach, you can have a fully functional bot up and running in minutes. This guide will walk you through the fastest way to build a Telegram bot natively using Python and the python-telegram-bot library. We'll cover everything from setting up your bot to handling advanced features like inline queries and commands.
Prerequisites
Before we dive in, ensure you have the following:
- Python 3.7 or higher installed
- A Telegram account
-
pipfor installing Python packages
Step 1: Create Your Bot
First, you need to create a bot on Telegram. Open Telegram and search for the BotFather bot. Start a chat with BotFather and use the /newbot command to create a new bot.
- Follow the instructions to name your bot and choose a username.
- Once the bot is created, BotFather will provide you with a token. This token is essential for interacting with the Telegram API.
Step 2: Set Up Your Development Environment
Install the python-telegram-bot library, which is a pure Python implementation of the Telegram Bot API.
pip install python-telegram-bot
Step 3: Write Your First Bot
Create a new Python file, bot.py, and add the following code to initialize your bot and handle basic commands.
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Hello! I am your new Telegram bot.')
def main() -> None:
# Replace 'YOUR_TOKEN' with your bot's token
updater = Updater('YOUR_TOKEN')
dispatcher = updater.dispatcher
# Register the start command
dispatcher.add_handler(CommandHandler('start', start))
# Start the bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT, SIGTERM or SIGABRT
updater.idle()
if __name__ == '__main__':
main()
Run your bot by executing the script:
python bot.py
Now, open Telegram, find your bot, and type /start. You should receive a response saying "Hello! I am your new Telegram bot."
Step 4: Handling Commands and Messages
Let's expand our bot to handle more commands and messages. Add the following functions to your bot.py file:
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Hello! I am your new Telegram bot.')
def echo(update: Update, context: CallbackContext) -> None:
update.message.reply_text(update.message.text)
def help_command(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Available commands:\n/start - Start the bot\n/help - List available commands')
def main() -> None:
updater = Updater('YOUR_TOKEN')
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('help', help_command))
# Add a handler to echo any text message
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Now, your bot can echo back any text message and provide a list of available commands when /help is invoked.
Step 5: Advanced Features
Inline Queries
Inline queries allow users to interact with your bot in any chat, not just the chat where your bot is present. Add the following code to handle inline queries:
from telegram import InlineQueryResultArticle, InputTextMessageContent
from telegram.ext import InlineQueryHandler
def inline_query(update: Update, context: CallbackContext) -> None:
query = update.inline_query.query
results = [
InlineQueryResultArticle(
id='1',
title='Echo',
input_message_content=InputTextMessageContent(query)
)
]
update.inline_query.answer(results)
def main() -> None:
updater = Updater('YOUR_TOKEN')
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('help', help_command))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
dispatcher.add_handler(InlineQueryHandler(inline_query))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Now, users can type @your_bot_username followed by a query in any chat, and your bot will respond with an inline result.
Custom Keyboards
You can also create custom keyboards to provide users with predefined options. Add the following code to create a custom keyboard:
from telegram import ReplyKeyboardMarkup
def keyboard(update: Update, context: CallbackContext) -> None:
custom_keyboard = [['Option 1', 'Option 2'], ['Option 3']]
reply_markup = ReplyKeyboardMarkup(custom_keyboard)
update.message.reply_text('Choose an option:', reply_markup=reply_markup)
def main() -> None:
updater = Updater('YOUR_TOKEN')
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('help', help_command))
dispatcher.add_handler(CommandHandler('keyboard', keyboard))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
dispatcher.add_handler(InlineQueryHandler(inline_query))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Step 6: Deploying Your Bot
To keep your bot running 24/7, you can deploy it to a cloud provider like Heroku, AWS, or Google Cloud. Here's a basic guide to deploying on Heroku:
- Create a
Procfilein your project directory with the following content:
worker: python bot.py
- Initialize a Git repository:
git init
git add .
git commit -m "Initial commit"
- Install the Heroku CLI and create a new Heroku app:
heroku create your-app-name
- Push your code to Heroku:
git push heroku master
Your bot should now be running on Heroku.
Conclusion
Building a Telegram bot natively using Python and the python-telegram-bot library is a straightforward process. With the steps outlined in this guide, you can quickly create a bot that handles commands, messages, inline queries, and custom keyboards. Once your bot is functional, deploying it to a cloud provider ensures it remains accessible to users around the clock.
Happy bot building!
🚀 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)