DEV Community

Joey Umanito
Joey Umanito

Posted on

Build an AI-Powered Telegram Bot with Python (Complete Guide)

Telegram bots are powerful tools for automation, customer service, and productivity. In this tutorial, I will show you how to build a feature-rich Telegram bot with Python in just 15 minutes.

Why Telegram Bots?

Telegram bots are perfect for:

  • Customer support automation
  • Daily notifications and reminders
  • Data collection and surveys
  • File sharing and processing
  • E-commerce order tracking

Step 1: Create Your Bot

First, create a bot with BotFather on Telegram:

  1. Open Telegram and search for @BotFather
  2. Send /newbot
  3. Choose a name and username for your bot
  4. Copy your bot token (keep it secret!)

Step 2: Install python-telegram-bot

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

Step 3: Build a Basic Bot

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

TOKEN = "YOUR_BOT_TOKEN_HERE"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "Hello! I am your AI assistant bot.\n\n"
        "Commands:\n"
        "/start - Show this message\n"
        "/help - Get help\n"
        "/weather - Get weather info\n"
        "Or just send me any message!"
    )

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Send me any text and I will respond intelligently!")

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_text = update.message.text
    user_name = update.effective_user.first_name

    response = f"Hi {user_name}! You said: {user_text}"
    await update.message.reply_text(response)

def main():
    app = Application.builder().token(TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("help", help_command))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    print("Bot is running...")
    app.run_polling()

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

Step 4: Add AI Responses with OpenAI

Make your bot intelligent:

import openai

openai_client = openai.OpenAI(api_key="YOUR_OPENAI_KEY")

async def ai_response(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_message = update.message.text

    await update.message.reply_text("Thinking...")

    response = openai_client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant bot on Telegram."},
            {"role": "user", "content": user_message}
        ]
    )

    ai_reply = response.choices[0].message.content
    await update.message.reply_text(ai_reply)

# Replace the echo handler with AI response handler
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, ai_response))
Enter fullscreen mode Exit fullscreen mode

Step 5: Add Inline Buttons

Create interactive menus:

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [
        [InlineKeyboardButton("Option 1", callback_data="opt1"),
         InlineKeyboardButton("Option 2", callback_data="opt2")],
        [InlineKeyboardButton("Contact Support", url="https://t.me/yoursupport")]
    ]

    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text("Choose an option:", reply_markup=reply_markup)
Enter fullscreen mode Exit fullscreen mode

Step 6: Deploy to a Server

Use a Dockerfile for easy deployment:

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY bot.py .
CMD ["python", "bot.py"]
Enter fullscreen mode Exit fullscreen mode

Deploy free on Railway.app or Render.com!

Common Use Cases for Businesses

  1. E-commerce: Order status updates, tracking notifications
  2. Customer Support: Auto-answer FAQs, ticket creation
  3. Content: Daily news digests, blog post notifications
  4. HR: Leave requests, attendance tracking
  5. Restaurants: Menu ordering, reservations

Want a Custom Telegram Bot Built for You?

Building a production-ready Telegram bot with AI features, database integration, and business logic takes expertise. Instead of spending days learning, let me build it for you:


Got questions about Telegram bot development? Drop a comment below!

Top comments (0)