How to Build a DeepSeek Telegram Bot With V4 in Python

Build a DeepSeek Telegram bot with deepseek-flash and python-telegram-bot 22 in Python: step-by-step setup, streaming code, cost math and error fixes.

Tutorials·April 25, 2026·By DS Guide Editorial
DeepSeek Telegram bot title card: eyebrow 'Tutorial · Telegram bot', title 'DeepSeek on Telegram', tagline 'Async Python bot on deepseek-flash, via long polling.', and four stats: 3.10 minimum Python, 4096 message character limit, 20 history messages, and 1M context tokens, beside a compact-desktop illustration.

You want a private chat assistant that lives in Telegram, answers in seconds, and costs a few dollars a month at most — not a SaaS subscription. A DeepSeek Telegram bot does exactly that. You wire Telegram’s Bot API to DeepSeek’s OpenAI-compatible chat endpoint, run a small Python process, and you have a working assistant your team can message from any device.

This tutorial builds that bot end to end on DeepSeek’s current API model, deepseek-flash (served by DeepSeek-V4.1-Flash-1017 since 17 October 2026). You’ll register a bot with BotFather, write an async Python handler with python-telegram-bot, call deepseek-flash for fast general chat (and switch thinking mode on when you need it), persist per-chat conversation history, and work out what it costs at peak and off-peak rates. Total build time: about 30 minutes.

What you’ll build

Illustration: smartphone showing a Telegram-style chat with a bot named 'DeepSeek bot' (subtitle 'V4') answering a question about Dijkstra's algorithm; a mock-up, not a real capture.

A single-file Python bot that:

  • Receives messages in Telegram via long polling (no public webhook required for development).
  • Maintains per-chat conversation history in memory, because the DeepSeek API is stateless and will not remember turns for you.
  • Calls deepseek-flash by default with thinking switched off for fast replies, and lets users turn thinking mode on with a /think command.
  • Streams responses back so users see the reply build up instead of staring at a long blank.
  • Keeps the request shape simple enough to check your spend against the DeepSeek API pricing page.

By the end you’ll have a bot you could plausibly leave running for a small team, plus the patterns to harden it for production. If you’ve never touched the DeepSeek API before, skim the DeepSeek API getting started guide first — this tutorial assumes you know what an API key is.

Prerequisites

  • Python 3.10 or newer. The python-telegram-bot library is async-first and requires 3.10+.
  • A Telegram account on any device.
  • A DeepSeek API key from platform.deepseek.com. See get a DeepSeek API key if you don’t have one yet.
  • Two PyPI packages: python-telegram-bot and openai (we’ll use the OpenAI SDK against DeepSeek’s OpenAI-compatible base URL).
  • A code editor and a terminal. No public IP, no SSL certificate, no Docker required for the polling-based version in this tutorial.

Step 1: Register the bot with BotFather

Telegram’s @BotFather is the official tool for creating bots: send it the /newbot command, answer its questions for a name and username, and it generates an authentication token for your new bot.

  1. Open Telegram and search for @BotFather.
  2. Send /newbot.
  3. Choose a display name (e.g. “DeepSeek Helper”) when asked.
  4. Choose a username. Per Telegram’s docs, it must be 5–32 characters long, is not case sensitive, may only include Latin characters, numbers and underscores, and must end in “bot”, like tetris_bot or TetrisBot.
  5. Copy the token BotFather sends you. It looks like 123456789:AA....

Treat that token like a password: anyone who has it can control your bot. If it is ever compromised, send BotFather the /token command to generate a new one. Never commit it to git; we’ll load it from an environment variable.

Optional: register slash commands

While you’re in BotFather, send /setcommands, pick your bot, and paste:

start - Greet and explain the bot
reset - Clear conversation history
think - Toggle thinking mode
mode - Show current model and mode

Telegram then suggests these commands when users type / in the chat with your bot.

Step 2: Project setup

Create a directory and install dependencies. The shell snippet below uses bash:

mkdir deepseek-tg && cd deepseek-tg
python3 -m venv .venv
source .venv/bin/activate
pip install "python-telegram-bot==22.8" openai

Create a .env file (and add it to .gitignore):

TELEGRAM_BOT_TOKEN=123456789:AA-your-token
DEEPSEEK_API_KEY=sk-your-deepseek-key
# optional: deepseek-v4-pro instead of the default deepseek-flash
DEEPSEEK_MODEL=deepseek-flash

Step 3: Wire DeepSeek to Telegram

This is the core file, bot.py. python-telegram-bot (version 22.8 as of October 2026) provides an asynchronous interface for the Telegram Bot API and supports Python 3.10+. Chat requests hit POST /chat/completions, the OpenAI-compatible endpoint at https://api.deepseek.com, so we use the OpenAI Python SDK with a swapped base_url.

import logging
import os
import time
from collections import defaultdict, deque

from openai import AsyncOpenAI
from telegram import Update
from telegram.error import BadRequest
from telegram.ext import (
    ApplicationBuilder, CommandHandler, MessageHandler,
    ContextTypes, filters,
)

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("deepseek-tg")

TG_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
MODEL = os.environ.get("DEEPSEEK_MODEL", "deepseek-flash")  # or deepseek-v4-pro

client = AsyncOpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

SYSTEM_PROMPT = (
    "You are a concise assistant inside Telegram. "
    "Reply in plain text under 1500 characters unless asked for code."
)
TG_LIMIT = 4096  # Telegram's maximum message length

# Per-chat rolling history. Stateless API => we resend each turn.
HISTORY: dict[int, deque] = defaultdict(lambda: deque(maxlen=20))
THINKING: dict[int, bool] = defaultdict(bool)


async def start(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "DeepSeek bot online. Send a message. "
        "/think toggles thinking mode. /reset clears history."
    )


async def reset(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    HISTORY[update.effective_chat.id].clear()
    await update.message.reply_text("History cleared.")


async def toggle_think(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    cid = update.effective_chat.id
    THINKING[cid] = not THINKING[cid]
    await update.message.reply_text(f"Thinking mode: {'ON' if THINKING[cid] else 'OFF'}")


async def show_mode(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    cid = update.effective_chat.id
    await update.message.reply_text(f"Model: {MODEL} | thinking: {THINKING[cid]}")


async def safe_edit(message, text: str):
    try:
        await message.edit_text(text)
    except BadRequest as e:  # e.g. "Message is not modified"
        log.debug("edit skipped: %s", e)


async def on_message(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    cid = update.effective_chat.id
    HISTORY[cid].append({"role": "user", "content": update.message.text})
    messages = [{"role": "system", "content": SYSTEM_PROMPT}, *HISTORY[cid]]

    kwargs = {"model": MODEL, "messages": messages, "stream": True}
    if THINKING[cid]:
        kwargs["max_tokens"] = 8192  # room for reasoning plus the answer
        kwargs["reasoning_effort"] = "high"
        kwargs["extra_body"] = {"thinking": {"type": "enabled"}}
    else:
        # Thinking is on by default; switch it off for quick chat replies.
        kwargs["max_tokens"] = 1500
        kwargs["temperature"] = 1.3  # DeepSeek's guidance for general conversation
        kwargs["extra_body"] = {"thinking": {"type": "disabled"}}

    placeholder = await update.message.reply_text("Thinking…" if THINKING[cid] else "…")
    buffer, last_edit = "", 0.0
    try:
        stream = await client.chat.completions.create(**kwargs)
        async for chunk in stream:
            if not chunk.choices:
                continue
            buffer += chunk.choices[0].delta.content or ""  # reasoning is skipped
            if buffer and time.monotonic() - last_edit > 1.0:  # throttle edits
                await safe_edit(placeholder, buffer[:TG_LIMIT])
                last_edit = time.monotonic()
        final = buffer[:TG_LIMIT] or "(empty response)"
        await safe_edit(placeholder, final)
        HISTORY[cid].append({"role": "assistant", "content": final})
    except Exception as e:
        HISTORY[cid].pop()  # drop the unanswered user turn
        log.exception("DeepSeek call failed")
        await safe_edit(placeholder, f"Error: {e}")


def main():
    app = ApplicationBuilder().token(TG_TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("reset", reset))
    app.add_handler(CommandHandler("think", toggle_think))
    app.add_handler(CommandHandler("mode", show_mode))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_message))
    app.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
    main()

A few things to notice:

  • Stateless API, client-side memory. DeepSeek’s API does not remember previous turns. The HISTORY dict resends the last 20 messages on every call, capped to keep token spend predictable, and drops the user turn again if the call fails. The web/app surface keeps history for you; the API does not.
  • Two model IDs, one parameter for thinking. DeepSeek’s API lists deepseek-flash (DeepSeek-V4.1-Flash-1017) and deepseek-v4-pro (DeepSeek-V4-Pro-0813); set DEEPSEEK_MODEL to switch. Thinking mode is a request parameter on either model and is on by default, so the bot sends {"thinking": {"type": "disabled"}} for normal replies and reasoning_effort="high" with {"thinking": {"type": "enabled"}} after /think — there is no separate “reasoner” model ID.
  • Temperature 1.3 matches DeepSeek’s official guidance for general conversation and translation. Drop it to 0.0 for code, 1.5 for creative writing. It only applies with thinking off; in thinking mode temperature has no effect.
  • Streaming via stream=True yields server-sent-event chunks; we edit the placeholder message at most about once a second so the user sees the answer build without flooding Telegram with edits. Edits that would not change the text raise BadRequest, which safe_edit() ignores.

Step 4: Run it

Illustration: Laptop terminal running a Python Telegram bot beside a phone showing the DeepSeek V4 reply in the chat.

From the project directory, with the venv active:

set -a && source .env && set +a
python bot.py

You should see Application started in the logs. Open Telegram, find your bot by the username you chose, and send /start. A reply means polling works; your first normal message checks the DeepSeek call and streaming.

Verify it worked

  1. Send a multi-turn question (“My name is Sam.” then “What’s my name?”). The second answer should reference Sam — proof that history is being resent correctly.
  2. Run /think and ask a reasoning-heavy question (“If a train leaves Boston at 70 mph and another from NYC at 60 mph…”). The placeholder shows “Thinking…” while the model reasons. Behind the scenes the API returns reasoning_content alongside the final content; the bot only displays content, but the reasoning is available in each chunk as delta.reasoning_content if you want to show it.
  3. Run /reset, ask “What’s my name?” again — the bot should not know.

Step 5: Cost math you can trust

Here’s a worked example for a small team using deepseek-flash, the default in this bot. Assume 10,000 messages per month, with an average 400-token system + history prefix (cached across calls), 60-token user message, and 250-token reply. Rates are from DeepSeek’s pricing page as of October 2026; off-peak is half of peak.

Bucket Tokens Peak rate (USD/1M) Peak cost Off-peak rate (USD/1M) Off-peak cost
Input, cache hit 4,000,000 $0.006 $0.024 $0.003 $0.012
Input, cache miss 600,000 $0.30 $0.180 $0.15 $0.090
Output 2,500,000 $1.20 $3.000 $0.60 $1.500
Total — — $3.204 — $1.602

About $3.20 a month if every message lands in peak hours, or $1.60 if all of them land off-peak. Switch the same workload to deepseek-v4-pro ($0.044 cache hit, $1.32 cache miss and $3.96 output per 1M tokens at peak; $0.022, $0.66 and $1.98 off-peak) and you’d pay $0.176 + $0.792 + $9.900 = $10.868 at peak, or $5.434 off-peak — about 3.4× the Flash bill. For most chat-style traffic deepseek-flash is the right default; DeepSeek’s 10 September 2026 release note says tests by multiple parties put V4.1-Flash ahead of V4-Pro on performance, cost, speed and total runtime. A clean way to plan this is the DeepSeek pricing calculator.

Two cost gotchas to remember:

  • The system-prompt cache hit doesn’t cover the user message on each call — that’s an uncached miss against the prefix. Both lines must appear in any cost example.
  • Peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday, excluding Chinese public holidays; every other hour bills at the off-peak rate. A team bot that is busiest in those windows pays closer to the peak total.

Step 6: Migrating from legacy model IDs

If you copied an older tutorial that uses deepseek-chat or deepseek-reasoner, update it: those IDs were scheduled for retirement on 2026-07-24 at 15:59 UTC and are no longer listed in DeepSeek’s docs. The name deepseek-v4-flash is still accepted, but DeepSeek now serves it with DeepSeek-V4.1-Flash-1017 at the Flash price. The migration is a one-line model= swap in your chat.completions.create call to deepseek-flash or deepseek-v4-pro; base_url does not change.

Common errors and fixes

Symptom Likely cause Fix
Conflict: terminated by other getUpdates request Two copies of the bot running against the same token Stop the duplicate; only one polling instance per token
401 Authentication Fails from DeepSeek Wrong API key Create a new key at platform.deepseek.com; verify the env var is loaded
402 Insufficient Balance Account out of credit Top up; check the billing console for any granted balance
Telegram Message is not modified Streaming edit produced identical text Already caught by safe_edit() in the example
Empty content in response JSON mode without “json” in prompt, or max_tokens too low Include the word “json” plus a schema example; raise max_tokens
Long replies cut off mid-sentence Telegram’s 4,096-character message limit Split with a paginator or send as a file
429 from DeepSeek More concurrent requests than your account’s limit (2,500 for deepseek-flash, 500 for deepseek-v4-pro) Queue requests or retry with backoff

For deeper diagnostics, the DeepSeek API error codes reference lists every status code DeepSeek returns and what it usually means.

Hardening for production

Architecture diagram: a user in Telegram sends updates by webhook or polling to a Python bot service (handler and context), which makes an API call to DeepSeek and sends the reply back to the user.

The polling bot above is fine for personal use. If you’re putting it in front of users, layer in:

  • Rate limiting per user — wrap on_message with a token-bucket keyed on update.effective_user.id. Without it, one user can drain your DeepSeek balance.
  • Persistent history — swap the in-memory HISTORY dict for SQLite or Redis. The current setup loses everything on restart.
  • Webhooks instead of polling for higher throughput. Telegram’s setWebhook method lets you specify a URL and receive incoming updates via an outgoing webhook: whenever there is an update for the bot, Telegram sends an HTTPS POST request to that URL containing a JSON-serialized Update.
  • Allowlist — gate on_message on a set of approved chat_id values until you’re confident in your spend cap.
  • Function calling — for tools like web search or database lookups, declare them in OpenAI-compatible format and let the model invoke them. In thinking mode, requests with tools must pass back earlier reasoning_content. See DeepSeek API function calling.
  • Context caching awareness — keep your system prompt stable across calls so the cache-hit tier kicks in. Details in the DeepSeek context caching guide.

One technical fact worth keeping in mind as you scale: both DeepSeek API models have a 1M-token context window, with output up to 384K tokens. You will not run out of context for a chat workload; you’ll run out of latency budget first. Trim history aggressively.

Next steps

Two natural follow-ups once your bot is alive:

  • Wrap the same DeepSeek call in a DeepSeek Discord bot so your team has the same assistant in both apps.
  • Layer document Q&A on top with the DeepSeek RAG tutorial — the bot becomes a private knowledge assistant rather than a generic chat.

For a wider menu of integration patterns, the DeepSeek tutorials hub collects every step-by-step guide on the site.

How do I create a Telegram bot for DeepSeek?

Open Telegram, message @BotFather, send /newbot, and follow the prompts to pick a name and username ending in “bot”. BotFather replies with a token — that’s your Telegram credential. Pair it with a DeepSeek API key from platform.deepseek.com, then run a small Python script using python-telegram-bot and the OpenAI SDK pointed at https://api.deepseek.com. The full code lives in Step 3 above.

Is the DeepSeek API free for a Telegram bot?

The API is paid per token, not free. As of October 2026, deepseek-flash charges $0.006 cache hit, $0.30 cache miss and $1.20 output per 1M tokens at peak, and half that off-peak ($0.003, $0.15 and $0.60). The worked example above — 10,000 messages a month — comes to $3.204 at peak or $1.602 off-peak. DeepSeek may offer a granted balance — a small promotional credit that can expire — so check the billing console for current offers. For more detail see the is DeepSeek free guide.

What is the difference between deepseek-flash and deepseek-v4-pro?

deepseek-flash is served by DeepSeek-V4.1-Flash-1017 (released 17 October 2026) and is the default: cheaper, and the only current API model that accepts images. deepseek-v4-pro is served by DeepSeek-V4-Pro-0813 (released 13 August 2026) and costs 3.3× as much on output tokens and 4.4× on cache-miss input. Both publish open weights under MIT. Use Flash for chat and compare Pro on your own tasks if you need to. Background on the DeepSeek V4 model page.

Does the DeepSeek API remember previous Telegram messages?

No. The DeepSeek POST /chat/completions endpoint is stateless — it does not store conversation history on the server. Your bot must resend the prior messages array on every request to sustain context. The web chat and mobile app maintain session history, but the API does not. The example in this tutorial keeps a per-chat deque capped at 20 messages. Background in DeepSeek API documentation.

Can I use thinking mode in a DeepSeek Telegram bot?

Yes — it is DeepSeek’s default. Thinking is a request parameter on either model, not a separate model ID. Set reasoning_effort="high" (or "low" / "max") plus extra_body={"thinking": {"type": "enabled"}} on your chat.completions.create call, or {"type": "disabled"} to turn it off. With thinking on, the response returns reasoning_content alongside the final content. The bot in this guide toggles it via a /think command. More patterns in DeepSeek prompt engineering.

Sources & Methodology

Last source check: October 25, 2026

Primary sources

Technical references

Methodology

Information in this article was checked against the official DeepSeek documentation, the article's cited primary sources, and the deepseekai.guide pricing dataset on the date shown above. Where third-party numbers are quoted, the originating source is linked inline so the reader can verify and re-check.

Data confidence

High for facts cited inline with primary-source links; medium for context narrative.

Editorial note

AI tooling moves quickly. If you spot an outdated number or a broken link, the contact link in the footer is the fastest way to flag it for the editorial team.

Leave a Reply

Your email address will not be published. Required fields are marked *