DEV Community

Apollo
Apollo

Posted on

The fastest way to build a Telegram Bot natively

The Fastest Way to Build a Telegram Bot Natively

Telegram bots are powerful tools for automating tasks, interacting with users, and extending Telegram's functionality. In this guide, I'll show you how to build a Telegram bot natively using Python and the python-telegram-bot library. This approach ensures maximum performance and control. Let’s dive in!


Prerequisites

Before starting, ensure you have the following:

  • Python 3.7+ installed on your system.
  • A Telegram account and access to the BotFather.
  • Basic knowledge of Python and asynchronous programming.

Step 1: Create Your Bot with BotFather

  1. Open Telegram and search for @BotFather.
  2. Start a chat and use the /newbot command.
  3. Follow the prompts to name your bot and get a unique API token.

Store this token securely; it’s your bot's key to the Telegram API.


Step 2: Install the Required Library

Python’s python-telegram-bot library is the fastest and most native way to interact with Telegram’s API. Install it using pip:

pip install python-telegram-bot
Enter fullscreen mode Exit fullscreen mode

Step 3: Write Your First Bot

Let’s create a simple bot that echoes user messages back to them.

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters

# Replace 'YOUR_API_TOKEN' with your bot's API token
TOKEN = 'YOUR_API_TOKEN'

# Start command handler
async def start(update: Update, context):
    await update.message.reply_text('Hello! I am your bot.')

# Echo message handler
async def echo(update: Update, context):
    user_message = update.message.text
    await update.message.reply_text(f'You said: {user_message}')

# Main function to start the bot
def main():
    application = Application.builder().token(TOKEN).build()

    # Add handlers
    application.add_handler(CommandHandler('start', start))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    # Start the bot
    application.run_polling()

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Application.builder().token(TOKEN).build(): Initializes the bot with your API token.
  2. CommandHandler('start', start): Handles the /start command.
  3. MessageHandler(filters.TEXT & ~filters.COMMAND, echo): Handles all text messages except commands.
  4. application.run_polling(): Starts the bot in polling mode, continuously checking for updates.

Step 4: Run Your Bot

Save the script as bot.py and run it:

python bot.py
Enter fullscreen mode Exit fullscreen mode

Your bot is now live! Interact with it by sending /start or any message in Telegram.


Step 5: Add Advanced Features

Let’s enhance your bot with advanced features like inline queries and custom keyboards.

Inline Query Handler

Inline queries allow users to interact with your bot directly from any chat.

from telegram import InlineQueryResultArticle, InputTextMessageContent

async def inline_query(update: Update, context):
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(
            id='1',
            title="Echo",
            input_message_content=InputTextMessageContent(f'Echo: {query}')
        )
    ]
    await update.inline_query.answer(results)

# Add the handler
application.add_handler(InlineQueryHandler(inline_query))
Enter fullscreen mode Exit fullscreen mode

Custom Reply Keyboard

Custom keyboards improve user experience by providing predefined options.

from telegram import ReplyKeyboardMarkup

async def custom_keyboard(update: Update, context):
    keyboard = [['Option 1', 'Option 2'], ['Option 3']]
    reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)
    await update.message.reply_text('Choose an option:', reply_markup=reply_markup)

# Add the handler
application.add_handler(CommandHandler('keyboard', custom_keyboard))
Enter fullscreen mode Exit fullscreen mode

Step 6: Deploy Your Bot

For production, deploy your bot on a server using PM2 or systemd. Alternatively, use a cloud service like AWS, GCP, or Heroku.

Example PM2 setup:

  1. Install PM2 globally:
   npm install -g pm2
Enter fullscreen mode Exit fullscreen mode
  1. Start your bot with PM2:
   pm2 start bot.py --interpreter python3
Enter fullscreen mode Exit fullscreen mode

Conclusion

You’ve built a native Telegram bot using Python and python-telegram-bot. This approach ensures high performance and flexibility, allowing you to scale your bot with advanced features.

Key takeaways:

  1. Use python-telegram-bot for a native and efficient bot development experience.
  2. Leverage handlers for commands, messages, and inline queries.
  3. Deploy your bot for reliable 24/7 operation.

Now go ahead and build something amazing! 🚀


Additional Resources

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)