Learn how to build an AI Telegram bot with Python, the Telegram Bot API, and OpenAI to create smart replies and simple automation.
Introduction
Telegram bots are more useful than most people realize.
They are not only for notifications or news feeds. You can build bots that answer questions, summarize text, generate ideas, collect leads, support customers, or act as simple internal assistants.
When you connect a Telegram bot to OpenAI, the bot can receive a user message, send that message to an AI model, get a reply, and send the answer back inside Telegram.
If you want to learn how to build an AI Telegram bot, the goal is not to create a complicated system on day one. The goal is to build a simple working bot that runs locally, listens for messages, calls OpenAI, and replies to the user.
By the end of this guide, you will have a beginner-friendly AI Telegram bot that you can later improve for customer support drafts, content ideas, summaries, or internal team tools.
The basic workflow looks like this:
User message → Telegram bot → Python app → OpenAI → AI reply → Telegram userTelegram’s official Bot API explains that bots can receive updates through getUpdates or webhooks, which are the two main methods for receiving incoming bot messages.
Best ChatGPT Prompts for Business]
How to use n8n with OpenAI
What This AI Telegram Bot Does
The first version of your bot does three things:
- Receives a message from a Telegram user
- Sends that message to OpenAI
- Returns the AI-generated reply inside Telegram
A practical guide on how to build an AI Telegram bot should help you create one working version first.
After that, you can extend the bot to:
- answer customer questions as drafts
- summarize long messages
- generate content ideas from a topic
- classify leads or requests
- create task lists from notes
- connect to Google Sheets or Notion
- send internal notifications
- trigger simple automations
But start simple.
One working bot is better than ten unfinished features.
Tools You Need
You need four main things to build this bot.
1. Telegram BotFather
BotFather is the official Telegram bot used to create and manage Telegram bots.
You use BotFather to:
- create a new bot
- choose a bot name
- choose a bot username
- get your Telegram bot token
- revoke or regenerate the token if needed
Your bot token is private. Treat it like a password.
2. Python 3.10+
Python is a good language for this project because it is beginner-friendly and has useful libraries for Telegram and OpenAI.
The python-telegram-bot library provides a Python interface for the Telegram Bot API. Its current documentation describes it as a pure Python asynchronous interface compatible with Python 3.10+.
3. OpenAI API Key
You need an OpenAI API key so your Python script can send messages to OpenAI and receive AI-generated replies.
OpenAI API usage is paid based on usage. For a private test bot, costs are usually low, but pricing can change, so always check the official pricing page before running a public bot.
4. A Place to Run the Bot
For testing, your computer is enough.
The bot runs as long as your Python script is running.
For a bot that stays online all the time, you need hosting such as:
- VPS
- Railway
- Render
- Fly.io
- Docker server
- cloud server
For beginners, local testing with polling is the easiest starting point.
How to Build an AI Telegram Bot: The 7-Step Workflow
Here is the simple workflow:
- Create a Telegram bot with BotFather
- Set up your Python project
- Install the required libraries
- Store your API keys safely
- Write the bot code
- Test the bot locally
- Improve and deploy the bot
Now let’s go step by step.
Step 1: Create a Telegram Bot With BotFather
The first step in how to build an AI Telegram bot is creating the bot inside Telegram.
Open Telegram and search for:
BotFatherMake sure you are using the official BotFather account.
Then follow these steps:
- Start a chat with BotFather.
- Send this command:
/newbot- Choose a display name for your bot.
Example:
My AI Assistant- Choose a username for your bot.
The username must end in bot.
Example:
myaiassistant_bot- BotFather will give you a bot token.
The token may look like this:
7123456789:AAFhXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxKeep this token private.
Do not put it in:
- public GitHub repositories
- screenshots
- blog posts
- tutorials
- shared documents
- client messages
If your token is ever leaked, go back to BotFather and revoke it.
Step 2: Set Up Your Python Project
Create a new project folder:
mkdir ai-telegram-bot
cd ai-telegram-botCreate a virtual environment:
python -m venv venvActivate it.
On macOS or Linux:
source venv/bin/activateOn Windows:
venv\Scripts\activateYou should see something like this in your terminal:
(venv)Now create your project files.
On macOS or Linux:
touch main.py .env .gitignoreOn Windows Command Prompt:
type nul > main.py
type nul > .env
type nul > .gitignoreAt this point, your project should contain:
ai-telegram-bot/
├── main.py
├── .env
└── .gitignoreStep 3: Install the Required Libraries
With your virtual environment active, install the libraries:
pip install python-telegram-bot openai python-dotenvThis installs:
python-telegram-botfor Telegram bot handlingopenaifor OpenAI API requestspython-dotenvfor loading secret keys from the.envfile
You can check installed versions with:
pip show python-telegram-bot openaiThe current python-telegram-bot documentation says the library is fully asynchronous, which is why the bot code uses async def for message handlers.
This may look new if you are a beginner, but the pattern is simple once you see the full code.
Step 4: Store Your API Keys Safely
Open the .env file and add:
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
OPENAI_API_KEY=your_openai_api_key_hereReplace the placeholder values with your real keys.
Now open .gitignore and add:
.env
venv/
__pycache__/
*.pycThis prevents your secret keys and virtual environment from being uploaded to GitHub.
This step is important.
A beginner learning how to build an AI Telegram bot should learn secret-key safety from the start.
Never hardcode your API keys directly inside your Python file.
Bad example:
OPENAI_API_KEY = "sk-your-key-here"Better approach:
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")Step 5: Write the Bot Code
Now open main.py and add this code:
import os
from dotenv import load_dotenv
from openai import OpenAI
from telegram import Update
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
MessageHandler,
ContextTypes,
filters,
)
# Load environment variables from .env
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Check that both keys exist before starting the bot
if not TELEGRAM_BOT_TOKEN:
raise RuntimeError("Missing TELEGRAM_BOT_TOKEN in .env file")
if not OPENAI_API_KEY:
raise RuntimeError("Missing OPENAI_API_KEY in .env file")
# Initialize the OpenAI client
openai_client = OpenAI(api_key=OPENAI_API_KEY)
# System prompt: controls how the bot behaves
SYSTEM_PROMPT = """
You are a helpful AI assistant inside a Telegram bot.
Rules:
- Keep replies clear, practical, and concise.
- Do not invent facts. If you are unsure, say so.
- For legal, medical, financial, or professional advice, remind the user to consult a qualified professional.
- If the user's message is unclear, ask one short clarifying question.
- Keep replies under 300 words unless the user asks for something longer.
"""
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handles the /start command."""
if update.message:
await update.message.reply_text(
"Hi! I'm an AI assistant. Send me a message and I'll reply using AI.\n\n"
"Use /help to see what I can do."
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handles the /help command."""
if update.message:
await update.message.reply_text(
"Here's what you can do:\n"
"- Ask me a question\n"
"- Request a summary\n"
"- Generate content ideas\n"
"- Draft a short text\n\n"
"Just type your message and I'll reply."
)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handles all regular text messages from users."""
if not update.message or not update.message.text:
return
user_message = update.message.text.strip()
if not user_message:
await update.message.reply_text("Please send a text message.")
return
try:
# Call OpenAI using the Chat Completions API
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
max_tokens=500,
temperature=0.7,
)
# Extract the AI reply from the response
ai_reply = (response.choices[0].message.content or "").strip()
if not ai_reply:
ai_reply = "Sorry, I could not generate a reply. Please try again."
# Telegram messages have a character limit, so keep the reply safe
await update.message.reply_text(ai_reply[:4096])
except Exception as error:
print(f"Error calling OpenAI: {error}")
await update.message.reply_text(
"Something went wrong while generating a reply. Please try again in a moment."
)
def main():
"""Starts the bot with long polling."""
app = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("help", help_command))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
print("Bot is running. Press Ctrl+C to stop.")
app.run_polling()
if __name__ == "__main__":
main()This code creates a simple Telegram bot that:
- responds to
/start - responds to
/help - receives normal text messages
- sends the user message to OpenAI
- returns the AI-generated response inside Telegram
- handles basic errors without crashing
The code uses chat.completions.create(), which is part of OpenAI’s Chat Completions API. OpenAI’s API reference describes Chat Completions as creating a model response for a chat conversation, and OpenAI’s Python reference still documents Chat Completions as a supported API style.
The model used in this beginner example is gpt-4o-mini, which OpenAI describes as a fast and affordable small model for focused tasks.
Step 6: Test the Bot Locally
Run the bot:
python main.pyIf everything is correct, your terminal should show:
Bot is running. Press Ctrl+C to stop.Now open Telegram and search for your bot username.
Send:
/startYou should receive the welcome message.
Then try a normal message:
Give me 5 blog post ideas for a freelance designer.The bot should reply with AI-generated ideas within a few seconds.
At this point, you have a working local version of your AI Telegram bot.
If something goes wrong, check:
- Is your virtual environment active?
- Are your
.envvalues correct? - Is your Telegram bot token correct?
- Is your OpenAI API key valid?
- Does your OpenAI account have available credits?
- Is another copy of the bot already running?
Common errors:
| Error | Likely Cause |
|---|---|
Missing TELEGRAM_BOT_TOKEN | The .env file is missing or not being read |
AuthenticationError | Your OpenAI API key is wrong, expired, or unavailable |
Conflict: terminated by other getUpdates request | The bot is already running somewhere else |
NetworkError | Internet or connection issue |
Step 7: Improve and Deploy the Bot
Your local bot works only while your terminal is running.
If you want the bot online 24/7, you need to deploy it.
Telegram bots can receive updates through polling or webhooks. Telegram’s Bot API explains that getUpdates and webhooks are mutually exclusive ways of receiving updates.
Option 1: Polling
Polling means your bot repeatedly asks Telegram:
Are there any new messages?Polling is good for:
- local testing
- beginner projects
- private bots
- simple prototypes
The code in this article uses polling.
Option 2: Webhooks
Webhooks mean Telegram sends updates to your server when something happens.
Webhooks are better for:
- production bots
- larger usage
- public bots
- faster update handling
- cloud deployments
Webhooks require a public HTTPS URL, so they are more complicated for beginners.
For your first bot, use polling.
Move to webhooks later when your bot is stable.
Deployment Options
You can deploy your bot on:
- Railway
- Render
- Fly.io
- VPS
- Docker server
- cloud server
For deployment, you should also create a requirements.txt file:
pip freeze > requirements.txtThis helps your hosting platform install the same Python packages.
When deploying, set environment variables inside the hosting dashboard.
Do not upload your .env file to GitHub.
Practical Example: AI Customer Support Draft Bot
One useful way to apply what you learned in how to build an AI Telegram bot is customer support.
The bot can help draft replies, but a human should review important responses before sending them to customers.
Workflow:
- A customer sends a question in Telegram.
- The bot generates a helpful draft reply.
- A team member reviews the answer.
- The final reply is sent manually.
Example system prompt:
SYSTEM_PROMPT = """
You are a customer support assistant for a small business.
Rules:
- Be polite, clear, and helpful.
- Do not invent prices, delivery times, refund policies, or product specs.
- If the answer requires a decision from the team, say: "A team member will confirm this for you shortly."
- Keep replies under 150 words.
- Ask one clarifying question if the request is unclear.
"""The important point is that the bot creates a draft, not a final business decision.
Read more about How to automate Gmail with AI
Practical Example: Content Idea Bot
You can also create a Telegram bot for content ideas.
Workflow:
- User sends a topic.
- Bot sends the topic to OpenAI.
- OpenAI generates content ideas.
- Bot replies with the ideas.
Example system prompt:
SYSTEM_PROMPT = """
You are a content strategy assistant.
When the user sends a topic, create:
1. 5 blog post ideas
2. 5 social media post ideas
3. 3 short video ideas
4. 2 newsletter ideas
5. One recommended content angle
Rules:
- Keep ideas practical and specific.
- Avoid generic topics.
- Focus on useful content for creators, freelancers, or small businesses.
"""This type of bot is useful for creators, marketers, freelancers, and small businesses.
AI Workflow for Content Creators]
Practical Example: Summary Bot
Another useful beginner bot is a summary bot.
Workflow:
- User pastes long text.
- Bot sends the text to OpenAI.
- OpenAI returns a structured summary.
- Bot sends the summary back in Telegram.
Example system prompt:
SYSTEM_PROMPT = """
You are a summarization assistant.
When the user sends text, return:
1. A one-paragraph summary
2. Key points as a bullet list
3. Action items, if any
4. Questions worth following up on
Rules:
- Do not add facts that are not in the original text.
- Keep the summary practical and scannable.
"""This is useful for:
- notes
- meeting transcripts
- articles
- client messages
- research
- long Telegram messages
When You Should Build an AI Telegram Bot
You should build an AI Telegram bot when you want a simple chat interface for repeated AI tasks.
Good use cases include:
- internal team assistant
- customer support draft bot
- content idea generator
- summary bot
- lead qualification bot
- personal productivity bot
- notification assistant
- simple automation interface
You should avoid using a beginner AI bot for high-risk decisions.
Be careful with:
- legal advice
- medical advice
- financial decisions
- refunds
- pricing
- account changes
- private customer data
- confidential documents
A safer pattern is:
User message → AI draft → human review when neededThis keeps the bot useful without giving it too much control.
Common Mistakes to Avoid
1. Sharing Your Bot Token Publicly
Your Telegram token gives access to your bot.
If someone gets it, they may be able to control your bot.
Keep it in your .env file and never publish it.
2. Hardcoding API Keys
Do not write API keys directly inside your Python file.
Wrong:
OPENAI_API_KEY = "sk-your-key-here"Right:
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")If you accidentally expose a key, revoke it and create a new one.
3. Not Handling Errors
APIs can fail.
Network connections can break.
OpenAI requests can return errors.
Telegram requests can fail.
Use try/except blocks so the bot replies with a friendly error message instead of crashing.
4. Letting the Bot Make Sensitive Decisions
Do not let a beginner bot automatically decide:
- refunds
- prices
- delivery promises
- medical advice
- legal advice
- financial decisions
- account changes
- private data handling
Use AI for drafts and basic help.
Keep humans involved for important decisions.
5. Forgetting About API Costs
Every message sent to OpenAI uses tokens.
For private testing, costs are usually low.
For public bots, costs can grow quickly.
Add controls later, such as:
- allowed user IDs
- message length limits
- daily usage limits
- rate limits
- logging
- command-based access
6. Only Testing Perfect Inputs
Real users send messy messages.
Test with:
- short messages
- long messages
- unclear requests
- typos
- emojis
- empty messages
- non-English messages
- sensitive questions
A good bot should handle realistic input gracefully.
Best Practices
Start With One Clear Purpose
Do not make your first bot do everything.
Choose one purpose:
- summary bot
- content idea bot
- support draft bot
- assistant bot
- reminder bot
- lead qualification bot
Simple bots are easier to test and improve.
Write a Strong System Prompt
The system prompt controls the bot’s behavior.
Add clear rules such as:
Do not invent facts.
Ask a follow-up question if the request is unclear.
Keep replies short.
Use simple language.
Do not make business promises.This makes the bot safer and more consistent.
read more about the best ChatGPT Prompts for Business
Add Rate Limiting for Public Bots
If your bot becomes public, add user limits.
Examples:
- allow only specific Telegram user IDs
- limit message length
- limit messages per user
- block spam
- log usage
- add a database for tracking requests
This helps control abuse and cost.
Test Before Deploying
Before putting your bot on a server, test:
/start/help- normal text messages
- long messages
- empty messages
- OpenAI failures
- invalid API keys
- bot restart behavior
Document Your System Prompt
When you improve your bot, document why each rule exists.
This helps you understand the bot later and makes it easier to update.
FAQ
What is the easiest way to learn how to build an AI Telegram bot?
The easiest way to learn how to build an AI Telegram bot is to create a bot with BotFather, build a small Python script using python-telegram-bot and the OpenAI library, store your keys in a .env file, and test locally with polling.
Do I need coding skills to build an AI Telegram bot?
You need basic Python knowledge. You should understand installing packages, running scripts, using environment variables, and writing simple functions. You do not need advanced development skills for the first version.
Can I test the bot without a server?
Yes. You can test the bot locally using polling. The bot will run only while your Python script is running. For a bot that stays online all the time, you need hosting.
Should I use polling or webhooks?
Use polling for testing and beginner projects because it is easier to set up. Use webhooks later for production deployments when you have a public HTTPS server.
Can I connect a Telegram bot to OpenAI?
Yes. A Python bot can receive a Telegram message, send the text to OpenAI using the OpenAI Python library, receive the AI response, and send it back to the Telegram user.
How much does it cost to run an AI Telegram bot?
The Telegram bot itself can be built with free libraries, but OpenAI API usage is paid based on token usage. Costs depend on the model, message length, and number of users. Always check OpenAI’s current pricing page before making a public bot.
Is it safe to use AI in a Telegram bot?
It can be safe for low-risk tasks if you protect API keys, avoid unnecessary private data, use clear system prompts, and keep human review for sensitive decisions.
Can I add conversation memory to the bot?
Yes. The beginner code in this guide treats each message as standalone. You can add memory by storing past messages per user and sending recent context with each OpenAI request. This makes the bot more conversational but increases token usage.
Conclusion
Learning how to build an AI Telegram bot is a practical way to turn AI into a simple chat-based tool.
The basic workflow is:
Telegram message → Python bot → OpenAI → AI reply → Telegram userStart with the code in this guide.
Create the bot with BotFather. Store your keys safely. Test locally with polling. Improve the system prompt. Add error handling. Deploy only after the bot works reliably.
Once you understand how to build an AI Telegram bot, you can create bots for summaries, customer support drafts, content ideas, lead qualification, internal tools, and simple automation workflows.
