How to Create a Telegram Bot With an LLM API
A Telegram bot with an LLM behind it is about 60 lines of Python. This walkthrough covers BotFather, a system prompt, per-chat memory, rate limits and what the running cost looks like.

Key points
- Create the bot token in BotFather, then run a small python-telegram-bot script that calls the OpenAI SDK with a changed base URL.
- Keep a trimmed history per chat; with a 100,000-token window you rarely need more than the last 20 messages.
- A trial key allows 2 concurrent requests, a full key allows 8, so queue or limit calls inside the bot.
- One user sending 30 messages a day costs about $0.52 a month at $0.15 and $0.50 per 1M tokens.
What you are building
If you searched for how to create bot telegram and want one that holds a real conversation, the setup has three parts. Telegram delivers a user's message to your script. Your script sends the recent chat history to a language model. The model's reply goes back through Telegram. Nothing else is needed: no web server, no database, no webhook, unless you want them later.
For the model side this guide uses the OpenAI-compatible endpoint at https://api.nsfwapi.top/v1 with the model ID uncensored. It is a text-only open-weight model tuned to answer without content refusals for lawful adult use, which suits fiction, roleplay and companion-style bots for adults. It cannot send or generate images, voice or video, so a bot built on it is a text bot. If your users will upload pictures, the model will not see them.
You need three things before you start:
- A Telegram account to talk to BotFather.
- An API key from the key page. New accounts can claim a $0.50 trial credit with one click, which is plenty for building and testing.
- Python 3.9 or newer and a place to run the script, such as your laptop while testing and a small server later.
Step 1: get a bot token from BotFather
Telegram bots are registered through a bot named BotFather. Open a chat with it and follow the prompts.
- Send
/newbot. - Choose a display name, then a username that ends in
bot. - BotFather replies with a token. Treat it like a password.
Store both secrets as environment variables rather than in the source file:
export TELEGRAM_TOKEN="123456:replace-with-your-token"
export LLM_API_KEY="replace-with-your-api-key"
pip install python-telegram-bot openai
The script below uses python-telegram-bot in its current asynchronous form (version 20 or later) and the official OpenAI Python SDK. Any other library works the same way; the only part that matters for the model is the base URL and the model name.
Step 2: the bot script
Save this as bot.py. It keeps a short history for each chat, sends it with a system prompt, and replies in the same chat.
import asyncio
import os
from collections import defaultdict
from openai import AsyncOpenAI, RateLimitError
from telegram import Update
from telegram.ext import (ApplicationBuilder, CommandHandler,
ContextTypes, MessageHandler, filters)
llm = AsyncOpenAI(
base_url="https://api.nsfwapi.top/v1",
api_key=os.environ["LLM_API_KEY"],
)
SYSTEM_PROMPT = (
"You are Mara, a witty storyteller who helps adults write fiction. "
"Stay in character, keep replies under 150 words, and ask one "
"question at the end to keep the story moving."
)
MAX_MESSAGES = 20 # history kept per chat
history = defaultdict(list)
slots = asyncio.Semaphore(2) # raise to 8 on a funded key
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
history[update.effective_chat.id].clear()
await update.message.reply_text("New story started. Say something.")
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_chat.id
history[chat_id].append({"role": "user", "content": update.message.text})
history[chat_id] = history[chat_id][-MAX_MESSAGES:]
await context.bot.send_chat_action(chat_id, "typing")
messages = [{"role": "system", "content": SYSTEM_PROMPT}] + history[chat_id]
try:
async with slots:
resp = await llm.chat.completions.create(
model="uncensored",
messages=messages,
temperature=0.9,
max_tokens=400,
)
except RateLimitError:
await update.message.reply_text("Busy right now, try again in a few seconds.")
return
text = resp.choices[0].message.content or "..."
history[chat_id].append({"role": "assistant", "content": text})
await update.message.reply_text(text[:4096])
app = ApplicationBuilder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat))
app.run_polling()
Run it with python bot.py, open your bot in Telegram and press Start. The first reply should arrive within a few seconds. Polling means the script asks Telegram for new messages, so it works behind a home router with no public address.
Two details are worth explaining. The slice [:4096] exists because Telegram caps a single text message at 4096 characters; with max_tokens at 400 you will not hit it, but the guard costs nothing. And the RateLimitError branch matters because the API answers HTTP 429 when you exceed a limit or when it is briefly overloaded, and the user should see a friendly line instead of silence.
Step 3: write a system prompt that holds up
The system prompt does most of the work of making a bot feel like a product. A good one is short and specific. It names the role, sets the format, and says what to do when the user pushes in an unwanted direction.
- Role and voice. "You are Mara, a dry-humored storyteller" beats "You are a helpful assistant".
- Length. Telegram is a chat medium. Ask for under 150 words, or replies will read like essays.
- Boundaries you control. The model is tuned not to refuse lawful adult requests, so any limits for your bot belong in your prompt and your code. Write them in plain sentences, for example which topics your bot will not continue.
- Age and consent. Content involving minors is not allowed on this API under any circumstances. If your bot is for adults, say so in its description and ask users to confirm it before the first story.
Keep the system prompt stable between messages. It is sent on every call, so every token in it is paid for on every turn. A 500-token prompt costs 500 times $0.15 divided by 1,000,000, which is $0.000075 per message. That is small, but a 3,000-token prompt multiplies it by six.
Memory, context and what 100k tokens means
The model has no memory between calls. What feels like memory is the history you send. The window is 100,000 tokens for prompt and completion together, which is far more than a Telegram chat needs. Twenty messages of 100 to 200 tokens each is only a few thousand tokens.
So why trim at all? Cost and focus. Each call resends the history, so a long chat gets more expensive per message and the model gets slower to start answering. The script above keeps the last 20 messages. For longer stories, use a rolling summary: every 30 messages, ask the model for a 150-word summary of the story so far, replace the old messages with it, and keep going. The story keeps its facts and the input stays small.
Two limits to know about. History in a Python dictionary disappears when the script restarts. If users expect continuity across days, write each chat's list to SQLite or a JSON file after every reply. And the dictionary is shared by all chats in the process, which is fine for one bot but means you should key everything by chat_id, as the script does.
Concurrency, limits and going live
A trial key allows 2 concurrent requests and 60 requests per minute. A full key allows 8 concurrent requests and 300 per minute. The semaphore in the script caps in-flight calls at 2, so it never trips the concurrency limit on a trial key; change it to 8 once you have funded the account.
python-telegram-bot handles updates one after another unless you ask for concurrency. For a few users that is fine. If you enable concurrent updates with ApplicationBuilder().concurrent_updates(True), keep the semaphore, because several users writing at once would otherwise hit the API together and receive 429 with the code concurrency. Over the per-minute cap the code is rate_limited. Under temporary overload you get 429 with a Retry-After: 5 header, so a short wait and one retry is the right response.
If you switch to streaming to show text as it is written, remember that a streamed request holds its slot until the stream ends. For Telegram, non-streaming is simpler: edit-message updates are themselves rate limited by Telegram, and most replies are short.
To run the bot permanently, put it under a process manager such as systemd or a container with a restart policy, keep the two environment variables out of your repository, and log the request ID. Every response includes an X-Request-Id header, and quoting it makes support questions easy to answer on the documentation and support pages.
What a bot like this costs to run
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit with no subscription. Here is a worked example for one active user of the bot above.
- Average call: 3,000 input tokens (system prompt plus 20 messages of history) and 250 output tokens.
- Input: 3,000 times $0.15 divided by 1,000,000 = $0.00045.
- Output: 250 times $0.50 divided by 1,000,000 = $0.000125.
- Per message: $0.000575.
- 30 messages a day: $0.01725, and over 30 days about $0.52.
For 100 users who are that active, the monthly figure is about $51.75. Most real users are much quieter, so treat this as a ceiling to plan against, not a forecast. The credit never expires, failed requests are not charged, and top-ups run from $20 to $500 with a 5% bonus from $50, 10% from $100 and 15% from $200, paid in USDT on TRC20 or USDC on Base. Current numbers are on the pricing page.
One habit pays for itself: read X-Balance-USD from the response headers and message yourself when it falls below a threshold. A bot that goes silent because the balance hit zero is the most common reason users stop trusting it.
More guides
Questions and answers
Do I need a server to run a Telegram bot?
Not for development. The script uses polling, so it runs on any machine with internet access. For a bot that stays online, use a small server or a container with a restart policy.
Can the bot send images or voice messages?
Not through this API. The model is text only, with no image, audio or video generation, so the bot can only reply with text.
Which model name do I put in the request?
Use uncensored as the model ID, with the base URL https://api.nsfwapi.top/v1 and your key as a Bearer token. Any OpenAI SDK works once those two values are changed.
What happens if many users write at once?
Requests above your limit get HTTP 429. Cap concurrent calls with a semaphore (2 on a trial key, 8 on a full key) and retry after a few seconds.
How much history should the bot keep?
Twenty messages is a good start. The window is 100,000 tokens, but a longer history raises the cost of every message, so summarize old messages instead of keeping them all.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.