DeepSeek 网摘deepseek.wang
EN
📄 查看英文原文

教程 · 2026-04-25 · 机器翻译,仅供参考

如何使用Python和V4构建DeepSeek Telegram机器人

Tutorials·April 25, 2026·By DS Guide Editorial
DeepSeek 电报 bot tutorial card showing the five steps to ship a private V4-Flash assistant on 电报: create the bot 通过 @BotFather and copy the token, pip install python-telegram-bot and the openai SDK, long-poll messages with the Application class,发送 each turn to the OpenAI-compatible /chat/completions endpoint, and persist per-user conversation history in an in-memory dict because the DeepSeek API is stateless.

您需要一个居住在电报中的私人聊天助手,秒级响应,每千次对话仅花费几分钱——而不是SaaS订阅。DeepSeek 电报机器人正是如此。您将电报的Bot API连接到DeepSeek的OpenAI兼容聊天端点,运行一个小的Python进程,就可以拥有一个团队可以从任何设备发送消息的工作助手。

本教程在DeepSeek V4(发布于2026年4月24日)上从头到尾构建了这个机器人,这是当前一代。您将使用BotFather注册一个机器人,编写一个使用`python-telegram-bot`的异步Python处理程序,调用`deepseek-v4-flash`进行低成本通用聊天(并在需要时切换到思考模式),持久化每个用户的对话历史,并交付一个生产就绪的成本计算。总构建时间:大约30分钟。

What you’ll build

Smartphone showing a 电报-style chat with a DeepSeek V4 bot streaming a reply to a user question.

一个单文件Python机器人,它:

  • 通过长轮询从电报接收消息(开发不需要公共webhook)。
  • 由于DeepSeek API是无状态的,不会为您记住对话轮次,因此将每个聊天对话历史保存在内存中。
  • 默认调用 deepseek-v4-flash 以实现快速、经济的回复,并允许用户通过 /think 命令切换到V4-Pro思考模式。
  • 流式传输响应,让用户看到打字风格的更新,而不是盯着一个漫长的空白页面。
  • 记录令牌使用情况,以便您首先对照 DeepSeek API pricing page.

最后,您将拥有一个可以供小型团队使用的机器人,以及将其加固以用于生产的模式。如果您之前从未接触过DeepSeek API,请快速浏览以下内容。 DeepSeek API getting started 指南验证成本计算——本教程假设您知道API密钥是什么。

Prerequisites

  • Python 3.10 or newer. The python-telegram-bot 库是异步优先且需要3.10及以上版本。
  • 一个电报账户 在任何设备上。
  • A DeepSeek API key from platform.deepseek.com. See get a DeepSeek API key 如果您还没有的话。
  • 两个PyPI软件包: python-telegram-bot and openai (我们将使用OpenAI SDK针对DeepSeek的OpenAI兼容基本URL)。
  • 一个代码编辑器 并且需要一个终端。在本教程中,基于轮询的版本不需要公共IP、SSL证书或Docker。

第一步:使用BotFather注册机器人

电报的@BotFather是创建机器人的官方工具。获取令牌就像联系@BotFather、发出/newbot命令并遵循步骤直到获得新的令牌一样简单。

  1. 打开电报并搜索 @BotFather选择带有蓝色验证勾选结果的选项——这确认了它是官方的BotFather,而不是冒充者。
  2. 发送 /newbot.
  3. 当被要求时,选择一个显示名称(例如“DeepSeek助手”)。
  4. 选择一个用户名。它必须介于5到32个字符之间,不区分大小写,只能包含拉丁字母、数字和下划线,并且必须以bot结尾,例如tetris_bot或TetrisBot。
  5. 复制BotFather发给您的token。它看起来像 123456789:AA....

将该令牌视为密码。如果您怀疑您的令牌已被泄露,请立即使用BotFather的/revoke命令撤销它。永远不要将其提交到git;我们将从环境变量中加载它。

可选:注册斜杠命令

当你在BotFather中时,发送 /setcommands,选择你的机器人,并粘贴:

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

电报将在聊天输入中显示这些为菜单。

第二步:项目设置

创建一个目录并安装依赖项。下面的shell代码片段使用bash:

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

创建一个 .env 文件(并将其添加到 .gitignore):

TELEGRAM_BOT_TOKEN=123456789:AA-your-token
DEEPSEEK_API_KEY=sk-your-deepseek-key

第三步:将DeepSeek连接到电报

这是最核心的文件, bot.py. The python-telegram-bot 库是异步的——它为电报 Bot API提供了一个纯Python、异步接口,并且与Python 3.10+版本兼容。聊天请求击中 POST /chat/completions, the OpenAI-compatible endpoint at https://api.deepseek.com,因此我们使用OpenAI Python SDK并进行了交换 base_url.

import os
import logging
from collections import defaultdict, 双端队列
from openai import AsyncOpenAI
from telegram import Update
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"]
DS_KEY   = os.environ["DEEPSEEK_API_KEY"]

client = AsyncOpenAI(
    base_url="https://api.deepseek.com",
    api_key=DS_KEY,
)

SYSTEM_PROMPT = (
    "You are a concise assistant inside 电报. "
    "Reply in plain text under 1500 characters unless asked for code."
)

# Per-chat rolling history. Stateless API => we resend each turn.
HISTORY: dict[int, 双端队列] = defaultdict(lambda: 双端队列(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. 发送 a message. "
        "/think toggles V4-Pro 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 (deepseek-v4-pro)' if THINKING[cid] else 'OFF (deepseek-v4-flash)'}"
    )

async def show_mode(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    cid = update.effective_chat.id
    model = "deepseek-v4-pro" if THINKING[cid] else "deepseek-v4-flash"
    await update.message.reply_text(f"Model: {model} | thinking: {THINKING[cid]}")

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

    messages = [{"role": "system", "content": SYSTEM_PROMPT}, *HISTORY[cid]]

    kwargs = {"model": "deepseek-v4-flash", "messages": messages,
              "temperature": 1.3, "max_tokens": 1500, "stream": True}
    if THINKING[cid]:
        kwargs["model"] = "deepseek-v4-pro"
        kwargs["reasoning_effort"] = "high"
        kwargs["extra_body"] = {"thinking": {"type": "enabled"}}

    placeholder = await update.message.reply_text("…")
    buffer = ""
    try:
        stream = await client.中。(**kwargs)
        async for chunk in stream:
            delta = chunk.choices[0].delta.content or ""
            buffer += delta
            # Edit every ~80 chars to keep 电报 happy
            if len(buffer) % 80 < len(delta):
                try:
                    await placeholder.edit_text(buffer[:4000])
                except Exception:
                    pass
        final = buffer[:4000] or "(empty response)"
        await placeholder.edit_text(final)
        HISTORY[cid].append({"role": "assistant", "content": final})
    except Exception as e:
        log.exception("DeepSeek call failed")
        await placeholder.edit_text(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()

一些需要注意的事项:

  • 无状态API,客户端内存。 DeepSeek的API不会记住之前的回合。 HISTORY dict 在每次调用时重发最后20条消息,以保持token消耗可预测。Web/应用界面在服务器端保留历史记录;API不保留。
  • 两个模型ID,一个用于思考的参数。 Both deepseek-v4-pro (1.6T total / 49B active) and deepseek-v4-flash (284B / 13B 激活) 是MIT下的开放权重MoE模型。通过设置启用思考模式。 reasoning_effort="high" plus extra_body={"thinking": {"type": "enabled"}} —— V4中没有单独的“推理器”模型ID。
  • Temperature 1.3 符合DeepSeek官方指南的一般对话和翻译。对于代码设置为0.0,对于创意写作设置为1.5。
  • Streaming 通过 stream=True 产生服务器发送的事件块;我们逐步编辑占位符消息,以便用户看到答案的构建过程。

第四步:运行它

Laptop terminal running a Python 电报 bot beside a phone showing the DeepSeek V4 reply in the chat.

在项目目录下,激活venv:

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

你应该能在日志中看到 应用程序已启动 。打开电报,通过你选择的用户名找到你的机器人,并发送 /start。几秒钟内收到回复表示轮询、API调用和流式传输都正常工作。

Verify it worked

  1. 发送一个多轮问题("我的名字是Sam。"然后"我的名字是什么?")。第二个答案应该引用Sam——这是历史记录正确重发的一个证明。
  2. Run /think 并提出一个需要大量推理的问题("如果一列火车从波士顿以每小时70英里的速度离开,另一列从纽约以每小时60英里的速度离开……")。回复应该看起来更加谨慎。幕后,V4-Pro返回 reasoning_content alongside the final contentSDK仅公开 content 默认情况下除非你读取 chunk.choices[0].delta.model_extra.
  3. Run /reset,再次询问“我的名字是什么?”——机器人不应该知道。

第五步:可信赖的成本计算

这里是一个使用 deepseek-v4-flash,这是此机器人的默认设置。假设每月10,000条消息,平均400-token系统+历史前缀(跨调用缓存),60-token用户消息,和250-token回复。

Bucket Tokens 比率(V4-Flash,美元/100万)的小团队的工作示例 Cost
Input, cache hit 4,000,000 $0.0028 $0.112
Input, cache miss 600,000 $0.14 $0.084
Output 2,500,000 $0.28 $0.700
Total — — $0.896

在这个量级下每月不到一美元。将相同的工作负载切换到 deepseek-v4-pro 每百万个令牌价格为 $0.0145 / $1.74 / $3.48(75%促销期间有效价格为 $0.003625 / $0.435 / $0.87,促销至 2026-05-31),您将支付大约 $10.30——这是前沿级别的12倍提升。对于大多数聊天式流量,V4-Flash 是正确的默认选择;将 V4-Pro 保留用于需要严格推理、代理循环或编码任务,在这些任务中基准提升很重要。规划这一点的干净方法是 DeepSeek pricing calculator.

两个需要记住的成本陷阱:

  • 系统提示缓存命中不覆盖每个调用中的用户消息——这是对前缀的未缓存缺失。任何成本示例中都必须出现这两行。
  • 峰值折扣已于 2025 年 9 月 5 日结束,并且 V4 没有恢复。不要为“夜间”50% 折扣做预算。

第六步:从旧版模型ID迁移

如果您复制了一个使用旧教程的,那些仍然有效——它们目前路由到 deepseek-chat or deepseek-reasoner,之后使用那些ID的请求将失败。迁移是一个单行 deepseek-v4-flash in non-thinking and thinking mode respectively. They will be retired on 2026-07-24 at 15:59 UTC的交换,在您的 model= 中。 中。 call; base_url does not change.

Common errors and fixes

Symptom Likely cause Fix
冲突:由其他getUpdates请求终止 两个相同的token运行的bot副本 停止重复;每个token只能有一个轮询实例
401 Unauthorized 来自DeepSeek 错误或过期的API密钥 Regenerate at platform.deepseek.com; verify env var is loaded
余额不足 账户余额不足 充值;检查计费控制台以查看是否有已授予的余额
电报 消息未被修改 流式编辑生成了相同的文本 已经包装在 try/except 在示例中
Empty content 作为回应 在提示中不包含 "json" 的 JSON 模式,或 max_tokens too low 包含单词 "json" 以及一个模式示例;引发 max_tokens
长回复被截断在句子中间 电报's 4096-char message limit 使用分页器分割或作为文件发送

对于更深入的诊断,请使用 DeepSeek API error codes 每个状态码及其通常含义的参考列表如下。

Hardening for production

Architecture diagram of a Python 电报 bot routing user messages to DeepSeek V4 通过 webhook.

上面的轮询机器人适合个人使用。如果您将其面向用户,请添加以下层:

  • 每用户速率限制 — 包装 on_message 使用基于token-bucket的 update.effective_user.id作为键。没有它,一个用户可能会耗尽您的DeepSeek余额。
  • 持久历史记录 — 将内存中的 HISTORY dict替换为SQLite或Redis。当前的设置在重启时将丢失所有内容。
  • 使用Webhooks代替轮询 以获得更高的吞吐量。使用此方法指定一个 URL,并通过出站 webhook 接收更新。每当有关于机器人的更新时,电报 将向指定的 URL 发送 HTTPS POST 请求,其中包含 JSON 序列化的更新。
  • 允许列表 — 在一组批准的 on_message 值上设置门控,直到您对自己的支出上限有信心。 值上设置门控,直到您对自己的支出上限有信心。 上下文缓存意识
  • Function calling ——对于像网络搜索或数据库查询这样的工具,以 OpenAI 兼容的格式声明它们,并让 V4 调用它们。参见 DeepSeek API function calling.
  • Context caching awareness — 保持系统提示在通话中稳定,以便缓存命中层能够启动。详细信息见 DeepSeek context caching guide.

在您扩展时值得记住的一个技术事实:V4 的上下文窗口在两个级别上默认为 1,000,000 个令牌,输出最多为 384,000 个令牌。您不会因为聊天负载而耗尽上下文;您首先会耗尽延迟预算。积极削减历史记录。

Next steps

机器人启动后的两个自然后续操作:

  • 将相同的DeepSeek调用封装在 DeepSeek Discord bot ,以便您的团队在两个应用中都有相同的助手。
  • 使用 DeepSeek RAG tutorial 在其上叠加文档问答层——机器人变成一个私人知识助手,而不是一个通用的聊天机器人。

对于更广泛的集成模式菜单, DeepSeek tutorials 中心收集了网站上每个步骤的详细指南。

DeepSeek AI Guide is an independent resource and is not affiliated with DeepSeek or its parent company. Model IDs, pricing and API behaviour change; check the official DeepSeek documentation and pricing page before committing to a production decision.

我该如何为DeepSeek创建一个电报机器人?

Open 电报, message @BotFather,发送 /newbot,并按照提示选择一个以 "bot" 结尾的名称和用户名。BotFather 会回复一个 token —— 这就是您的 电报 凭证。将其与 DeepSeek API 密钥配对,从 platform.deepseek.com,然后使用 python-telegram-bot 和指向 https://api.deepseek.com的OpenAI SDK运行一个小Python脚本。完整代码位于上面的第3步。

DeepSeek API对电报机器人是免费的吗?

API按令牌计费,不是免费的,但费率很低: deepseek-v4-flash 收费为每 1M 令牌 $0.0028 缓存命中 / $0.14 缓存未命中 / $0.28 输出。小型团队的机器人通常每月费用不到一美元。DeepSeek 可能会提供授权余额 —— 一小笔可能过期的促销信用额度,因此请检查计费控制台查看当前优惠。更多详情请参阅 is DeepSeek free guide.

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

两者均为2026年4月24日发布的V4 MoE模型,遵循MIT协议。 deepseek-v4-flash 总计284B / 活跃13B,是成本效益最高的默认选项。 deepseek-v4-pro 的总容量为 1.6T / 活跃 49B,前沿级别,输出价格大约贵 12 倍。使用 Flash 进行聊天;切换到 Pro 进行代理编码或艰难推理。在 DeepSeek V4 model page.

DeepSeek API会记住之前的电报消息吗?

No. DeepSeek POST /chat/completions 端点是无状态的 —— 它不会在服务器上存储对话历史。您的机器人必须在每次请求时重新发送先前的 messages 数组以维持上下文。网页聊天和移动应用会保持会话历史,但 API 不会。本教程中的示例会为每个聊天 双端队列 限制在20次转向。背景在 DeepSeek API documentation.

我可以在DeepSeek 电报机器人中使用思考模式吗?

是的。思考是V4模型上的一个请求参数,而不是一个单独的模型ID。设置 reasoning_effort="high" plus extra_body={"thinking": {"type": "enabled"}} 在您的 中。 调用中。然后响应返回 reasoning_content alongside the final content. The bot in this guide toggles it 通过 a /think 命令切换到V4-Pro思考模式。 More patterns in DeepSeek prompt engineering.

Sources & Methodology

Last source check: April 30, 2026

Primary sources

Methodology

本文信息已对照官方DeepSeek文档、文章引用的主要来源以及上述日期的deepseekai.guide定价数据集进行核对。对于引用的第三方数据,原始来源已在行内链接,以便读者验证和重新检查。

Data confidence

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

Editorial note

人工智能工具发展迅速。如果您发现过时的数字或损坏的链接,页脚中的联系链接是向编辑团队报告的最快方式。