NSFW WriterHow to Write a Telegram Bot with an LLM API
How to Write a Telegram Bot with an LLM API
If you are working out how to write telegram bot code that answers with a language model, the job is smaller than it looks: one Telegram library, one OpenAI-style client and a list of messages per chat. This walkthrough builds it step by step.
Updated
Key points
- The bot needs a token from BotFather, the python-telegram-bot library and the openai package pointed at the API base URL.
- Keep a short message history per chat and trim it, because input tokens are billed on every turn.
- Handle HTTP 429 with a wait and a retry, and cap concurrency at your key's limit.
- Streaming, tool calling and JSON mode all work through the normal OpenAI parameters.

What you need before you start
A Telegram bot is a normal program that talks to Telegram's Bot API. It receives messages, calls your code, and sends text back. The language model is just one more HTTP call inside that handler. For this build you need four things.
- A bot token. Open a chat with BotFather inside Telegram, send
/newbot, choose a name and a username, and copy the token it gives you. - An API key for the model. After sign-up you can claim the trial credit and copy a key. The trial is $0.50, valid for 7 days, and needs no card.
- Python 3.10 or newer.
- Two packages:
python-telegram-bot(version 20 or later, which is async) andopenai.
python -m venv .venv
source .venv/bin/activate
pip install "python-telegram-bot>=21" openai
export TELEGRAM_TOKEN="123456:replace-me"
export LLM_API_KEY="replace-me"
Keep both secrets in environment variables. A token pasted into a repository will be found by scanners within hours, and anyone holding it can control your bot.
The smallest working bot
The model endpoint is OpenAI-compatible, so the official OpenAI SDK works once you change the base URL and key. The model ID is uncensored. Chat completions go to POST /v1/chat/completions, and the SDK builds that path for you from the base URL.
import os
from openai import AsyncOpenAI
from telegram import Update
from telegram.ext import (
ApplicationBuilder, CommandHandler, MessageHandler,
ContextTypes, filters,
)
client = AsyncOpenAI(
base_url="https://api.nsfwwriter.com/v1",
api_key=os.environ["LLM_API_KEY"],
)
SYSTEM = "You are a story companion for adult users. Keep replies under 200 words."
MAX_MESSAGES = 20 # user and assistant messages kept per chat
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.chat_data["history"] = []
await update.message.reply_text("Ready. Send me a prompt.")
async def reply(update: Update, context: ContextTypes.DEFAULT_TYPE):
history = context.chat_data.setdefault("history", [])
history.append({"role": "user", "content": update.message.text})
del history[:-MAX_MESSAGES]
await context.bot.send_chat_action(update.effective_chat.id, "typing")
resp = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + history,
temperature=0.8,
)
text = resp.choices[0].message.content or ""
history.append({"role": "assistant", "content": text})
await update.message.reply_text(text[:4096])
def main():
app = ApplicationBuilder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, reply))
app.run_polling()
if __name__ == "__main__":
main()
Run it with python bot.py and message your bot. Polling is the easiest mode: your program asks Telegram for new messages, so you need no public URL, no TLS certificate and no open port. Move to webhooks later if you deploy behind a web server.
Two details are worth knowing. Telegram caps a single text message at 4,096 characters, which is why the code slices the answer. And context.chat_data is kept in memory, so history disappears when the process restarts. For a production bot, write the history to SQLite or Redis keyed by chat ID.
Memory and the cost of every turn
A language model API has no memory. Each request must carry the whole conversation, so the number of input tokens grows with every turn. This is the main cost driver in a chat bot, and it is why the code above trims history.
Take a chat where each turn sends about 2,000 input tokens and gets 500 back. The input costs 2,000 × $0.15 / 1M = $0.0003, and the output costs 500 × $0.50 / 1M = $0.00025. One turn is $0.00055. A user who sends 100 messages in a session costs $0.055. A bot with 50 such users in a day costs $2.75. These are examples, not promises: your own prompts decide the numbers, and the usage field in each response tells you the real ones.
Two ways to hold history down:
- Sliding window. Keep the last N messages, as the sample does. It is simple and predictable.
- Rolling summary. When history passes a size you pick, ask the model to compress the oldest part into a short paragraph, store that paragraph, and drop the old messages. It costs one extra call now and saves tokens on every later turn.
The context window is 100,000 tokens for prompt plus completion, so even a long-running roleplay has room. You pay for what you send, though, and a window that is mostly full costs about $0.015 of input per request. Full per-token pricing is on the pricing page.
Streaming the answer into a Telegram message
Long answers feel slow when the user stares at a typing indicator. Telegram does not stream natively, but you can fake it: send a placeholder message, then edit it as chunks arrive. The API supports stream: true over server-sent events, and the SDK turns that into an async iterator.
import time
async def reply_streaming(update: Update, context: ContextTypes.DEFAULT_TYPE):
history = context.chat_data.setdefault("history", [])
history.append({"role": "user", "content": update.message.text})
del history[:-MAX_MESSAGES]
sent = await update.message.reply_text("...")
parts, last_edit = [], 0.0
stream = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + history,
stream=True,
stream_options={"include_usage": True},
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
parts.append(chunk.choices[0].delta.content)
if time.monotonic() - last_edit > 1.5 and parts:
await sent.edit_text("".join(parts)[:4096])
last_edit = time.monotonic()
if chunk.usage:
print("tokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
final = "".join(parts)
if final:
await sent.edit_text(final[:4096])
history.append({"role": "assistant", "content": final})
Two points matter here. First, edit no more often than about once per second or two. Telegram limits how fast a bot may send and edit messages, and a tight edit loop earns you errors. Second, a streamed request holds its concurrency slot until the stream ends. A trial key allows 2 concurrent requests and a full key allows 8, so a slow stream that is never finished can starve other users. Always let the loop run to the end or close the stream explicitly.
Telegram will also reject an edit that leaves the text unchanged, so keep the time check and the final edit separate from the loop condition, as above.
Handling limits and errors
The limits are per key, not per Telegram user. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Going over returns HTTP 429 with the error code rate_limited (too many requests per minute) or concurrency (too many at once). On temporary overload the API also returns 429 with a Retry-After: 5 header.
A bot with many chats needs a guard. A semaphore sized to your key's concurrency limit is the shortest one, and a retry wrapper handles the rest.
import asyncio
from openai import RateLimitError
gate = asyncio.Semaphore(8) # use 2 for a trial key
async def ask(messages, **kwargs):
for attempt in range(4):
try:
async with gate:
return await client.chat.completions.create(
model="uncensored", messages=messages, **kwargs
)
except RateLimitError as e:
wait = int(e.response.headers.get("Retry-After", 5))
await asyncio.sleep(wait + attempt)
raise RuntimeError("model busy, try again later")
When the final attempt fails, send the user a short message instead of a stack trace. Failed requests are not charged, so retries do not cost money. The SDK also retries some errors by itself; if you want full control, pass max_retries=0 when you create the client.
The response headers help with monitoring: X-Request-Id goes into your logs for support questions, and X-Balance-USD lets you warn yourself before credit runs out.
Adding tools and structured output
Tool calling works as in the OpenAI format. You describe functions, the model returns a call with JSON arguments, you run it, and you send the result back with role: "tool". In a bot this is how you give the model a dice roller, a character sheet or a lookup in your own database.
import json, random
TOOLS = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll a die with the given number of sides.",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer", "minimum": 2, "maximum": 100}},
"required": ["sides"],
},
},
}]
async def answer_with_tools(history):
messages = [{"role": "system", "content": SYSTEM}] + history
resp = await client.chat.completions.create(
model="uncensored", messages=messages, tools=TOOLS, tool_choice="auto"
)
msg = resp.choices[0].message
if not msg.tool_calls:
return msg.content or ""
messages.append(msg.model_dump(exclude_none=True))
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = {"roll": random.randint(1, max(2, min(int(args["sides"]), 100)))}
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = await client.chat.completions.create(
model="uncensored", messages=messages, tools=TOOLS
)
return final.choices[0].message.content or ""
Validate the arguments yourself. The model produces them, and a model can emit a value outside the range you described. The clamp in the example is the cheap version of that check.
For commands that need machine-readable output, use JSON mode with response_format={"type": "json_object"}. Tell the model in the prompt which keys you expect, then parse the reply with json.loads and handle a parse error with one retry. That is a good fit for a /character command that returns a name, a trait list and a greeting, which your bot then formats into a Telegram message.
Deploying and keeping it healthy
A script on your laptop stops when you close the lid. For a bot that stays up, a small VPS and a process manager are enough. Create a systemd unit or run the script inside a container with a restart policy, and keep the two environment variables in an env file that only the service user can read.
- Persist chat state. A restart should not wipe every conversation. SQLite is enough for a few thousand chats.
- Log request IDs. Store the
X-Request-Idvalue next to each failed call. - Rate-limit users. One chat sending 50 messages a minute can drain your per-minute allowance. Cap each chat at a few messages per minute.
- State your content rules. If your bot is open to the public, say in its description that it is for lawful adult use. Sexual content involving minors is never allowed on this API, and your bot should refuse that request in its own code too.
- Publish a privacy note for your bot. Prompts sent to this API are not used for training, but Telegram and your own server also see the text. Tell users where it goes.
The quickstart documentation lists the full parameter set, and the support page is the place to ask when a response looks wrong.
More guides
Questions and answers
Do I need a webhook to run the bot?
No. Long polling, as in the sample, needs no public URL. Switch to webhooks when you host the bot behind a web server and want Telegram to push updates.
Which model ID do I use?
Use uncensored as the model value, with the base URL https://api.nsfwwriter.com/v1 and your key as a Bearer token. GET /v1/models lists what the key can use.
Why does my bot answer 429 under load?
You passed the per-key limit: 8 concurrent requests and 300 per minute on a full key, 2 and 60 on a trial key. Add a semaphore and a retry that honours Retry-After.
How long can a reply be?
The model can write far more than Telegram will show. A single Telegram message holds 4,096 characters, so split longer answers into several messages.
Can the bot call my own functions?
Yes. Tool calling uses the OpenAI format with tools and tool_choice, and results go back as messages with role tool.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.