Simplest Telegram AI Chatbot Using Groq

Build Your First AI Telegram Bot — Beginner's Guide
Beginner Guide · MVP

Build Your First AI Telegram Bot with Python

A complete, beginner-friendly walkthrough — from zero to a fully responsive AI chatbot on Telegram. No prior API experience needed. Every line of code explained in plain English.

AI
Beginner Series
· 12 min read · Python 3.10+ · Free Stack
Python 3.10+ python-telegram-bot v20 Groq Cloud API Llama 3.3 70B python-dotenv

01 What we're building

By the end of this guide, you'll have a real, working AI chatbot running on Telegram — completely free to build and test. You send a message on your phone, and the bot replies using Meta's flagship open-weights model running on Groq's fast inferencing platform.

It remembers your conversation thread as you chat, provides a /reset command to start fresh, shows a live typing status while generating responses, and handles API errors smoothly without crashing.

User on Telegram
Your Python Script
Groq LPU (Llama 3.3)

Your Python script acts as the orchestrator — receiving webhook messages from Telegram, managing context history, calling Groq's API, and sending replies back.

This is a clean, production-ready Minimum Viable Product (MVP). It is intentionally lightweight so you can master the underlying mechanics before extending it with custom databases, RAG, or image generation.

02 Prerequisites

You don't need advanced backend engineering experience, but you should have these basics ready:

  • Python 3.10 or newer installed on your machine. Check with python3 --version in your terminal.
  • A terminal or command prompt to execute installation commands and run your script.
  • A active Telegram account on mobile, desktop, or web.
  • Basic knowledge of environment variables (we will guide you through setting up a .env file).

03 What the libraries do

Before writing code, let's understand the core libraries in our application stack:

🤖
python-telegram-bot pip install

An asynchronous Python wrapper for Telegram's official Bot API. It converts raw HTTP webhooks into intuitive Python objects and manages continuous background message polling using modern Python async/await patterns.

groq pip install

Groq accelerates LLM execution using specialized LPU (Language Processing Unit) hardware, yielding generation speeds exceeding 300 tokens per second. The official SDK provides an OpenAI-compatible API client for fast inference.

🔐
python-dotenv pip install

Loads secret keys automatically from a hidden .env file into your operating system's environment variables, protecting your secrets from being accidentally committed to version control.

04 Create your Telegram bot

Every Telegram bot is created and managed through @BotFather — Telegram's administrative system bot.

1
Open BotFather in Telegram

Search for @BotFather in Telegram. Look for the blue verified checkmark badge, then press Start.

2
Issue the /newbot command

Send /newbot. BotFather will prompt you for a display name (e.g., My AI Assistant) followed by a unique username ending in _bot (e.g., my_groq_ai_bot).

3
Secure your access token

BotFather will send an API HTTP token formatted like 7123456789:AAFx.... Save this token securely — you will use it in your environment file shortly.

⚠️ Security Warning: Never commit your Telegram bot token or API keys directly to public repositories like GitHub. Always isolate credentials using environment variables.

05 Get a free Groq API key

Groq provides free developer access tier with high rate limits for open-weights models like Llama 3.3.

1
Log into the Groq Console

Navigate to console.groq.com and sign up with your email or GitHub/Google SSO.

2
Generate an API Key

Click on API Keys in the left sidebar menu, then click Create API Key. Label it Telegram Bot.

3
Copy and store the key

Copy the string beginning with gsk_.... Groq will only show this full secret key once.

06 Install dependencies & environment setup

Set up a clean project directory, create a virtual environment, and install the required dependencies:

Terminal
# 1. Create a project directory
mkdir ai-telegram-bot && cd ai-telegram-bot

# 2. Set up virtual environment (optional but recommended)
python3 -m venv venv
source venv/bin/activate  # On Windows use: venv\Scripts\activate

# 3. Install required packages
pip install python-telegram-bot groq python-dotenv

Next, create a .env file in the root of your project folder:

.env
TELEGRAM_BOT_TOKEN="your_telegram_bot_token_here"
GROQ_API_KEY="gsk_your_groq_api_key_here"

07 The full code — explained

Create a file named bot.py and add the complete code below:

python / bot.py
import logging
import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import (
    ApplicationBuilder,
    CommandHandler,
    MessageHandler,
    ContextTypes,
    filters,
)
from groq import Groq

# Load secret variables from .env file
load_dotenv()

TELEGRAM_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

# Configure logging output
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)

# Initialize the Groq Client
groq_client = Groq(api_key=GROQ_API_KEY)

SYSTEM_PROMPT = (
    "You are a helpful, concise AI assistant inside Telegram. "
    "Provide clear, well-formatted markdown responses."
)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handles the /start command and initializes context."""
    context.user_data['history'] = [{"role": "system", "content": SYSTEM_PROMPT}]
    welcome_text = (
        "👋 *Hello! I am your AI Assistant powered by Groq & Llama 3.3.*\n\n"
        "Send me any text message to start chatting!\n"
        "Type /reset to clear conversation memory."
    )
    await update.message.reply_text(welcome_text, parse_mode="Markdown")

async def reset(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Clears the chat history for the user."""
    context.user_data['history'] = [{"role": "system", "content": SYSTEM_PROMPT}]
    await update.message.reply_text("🔄 *Conversation history cleared!*", parse_mode="Markdown")

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Processes incoming user text, prompts Groq, and replies."""
    user_text = update.message.text

    # Ensure conversation history exists for this specific user
    if 'history' not in context.user_data:
        context.user_data['history'] = [{"role": "system", "content": SYSTEM_PROMPT}]

    history = context.user_data['history']
    history.append({"role": "user", "content": user_text})

    # Show 'typing...' status while generating response
    await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")

    try:
        response = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=history,
            temperature=0.7,
            max_tokens=1024,
        )

        ai_reply = response.choices[0].message.content
        history.append({"role": "assistant", "content": ai_reply})

        # Maintain rolling window of last 10 conversational turns
        if len(history) > 21:
            context.user_data['history'] = [history[0]] + history[-20:]

        await update.message.reply_text(ai_reply)

    except Exception as e:
        logging.error(f"Groq API Error: {e}")
        await update.message.reply_text("⚠️ Sorry, an error occurred communicating with AI services.")

def main():
    """Start the Telegram Bot polling engine."""
    if not TELEGRAM_TOKEN or not GROQ_API_KEY:
        raise ValueError("Missing TELEGRAM_BOT_TOKEN or GROQ_API_KEY in .env file")

    app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()

    # Command & Message Handlers
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("reset", reset))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))

    logging.info("🚀 Bot successfully started! Press Ctrl+C to stop.")
    app.run_polling()

if __name__ == "__main__":
    main()

Key Mechanics Breakdown

  • Per-User Memory Isolation: We store chat history inside context.user_data['history']. The framework manages this state separately for every user interacting with the bot.
  • Memory Sliding Window: If history exceeds 20 messages, we truncate old messages while preserving the initial system prompt to prevent token limit overflows.
  • Chat Action Indicators: Calling send_chat_action("typing") provides immediate visual feedback on Telegram while awaiting API responses.

08 How to run it

Execute your Python script directly from your terminal:

Terminal
python3 bot.py

When you see 🚀 Bot successfully started! in your terminal logs, navigate to Telegram on your mobile device or computer, search for your bot's username, click Start, and send your first message.

09 Keeping it online 24/7

Running the script on your laptop means the bot shuts down when your computer sleeps. Deploy your bot to a cloud platform for continuous uptime:

Render Free Tier

Deploy as a Background Worker process. Connect your GitHub repository and set env vars in the Render Dashboard.

🚂 Railway

Extremely fast deployment using automatic Docker or Python runtime detection with low latency server nodes.

🌐 Hugging Face Free Tier

Host via HF Spaces using Docker containers or simple Python SDK runtimes with persistent log management.

🖥️ VPS / Docker

Run on a $4/mo Hetzner or DigitalOcean Linux VPS managed via systemd service or Docker Compose.

10 Why this stack is worth learning

🚀 Extreme Performance

Groq's LPU architecture offers fast time-to-first-token (TTFT), making AI interactions feel instant on chat platforms.

💰 Zero Upfront Cost

Groq and Telegram both provide generous free tiers, allowing you to prototype full applications without credit cards.

🧠 Flagship Reasoning

Llama 3.3 70B delivers benchmark performance comparable to leading closed models for coding and general conversation.

🛠️ Extensible Foundation

The code uses async Python primitives, enabling easy integration with vector databases, tools, or web hooks.

11 What to build next

Once your basic chat bot is online, consider adding these advanced features:

📚
Document RAG (PDF Queries)

Allow users to upload PDFs in Telegram and perform context retrieval using Supabase Vector or FAISS.

🎙️
Voice Note Transcription

Accept Telegram voice messages, pass audio to Groq's Whisper API endpoint, and answer voice notes with text or TTS.

🔍
Live Web Browsing Tool

Integrate search tools like DuckDuckGo or Tavily API to give your AI access to real-time internet data.

💾
Persistent Database Memory

Replace temporary in-memory context.user_data storage with Supabase or SQLite database persistence.

Build Your First AI Telegram Bot Updated for 2026

Comments

Popular posts from this blog

How to Send Emails from Your React/Next.js App Using EmailJS

Running AI models without internet

Docker for curious beginners!