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

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

如何在2026年使用V4-Flash构建DeepSeek Discord机器人

Tutorials·April 25, 2026·By DS Guide Editorial
DeepSeek Discord 机器人 tutorial card showing the five steps to ship a V4-Flash 机器人: register a Discord application and copy the 机器人 token, install discord.py 2.7.1 and the openai SDK, wire an 斜杠命令(一次性问题,可选思考模式)和一个 slash command and an 提及,默认情况下,通过一个可选的升级标志将单个问题提升到 chat handler, stream the V4-Flash response into the channel, and cache a stable system prompt to keep input costs near zero on cache hits.

你想要一个在服务器语音中回答、每天只需几分钱,并且可以使用以后可以替换的开源重量级模型的Discord机器人。基于`deepseek-v4-flash`构建的DeepSeek Discord机器人能帮你实现:1000万个token的上下文,与OpenAI兼容的SDK,截至2026年4月每百万token的输入缺失定价为0.14美元。下面的教程将指导你注册Discord应用程序,将`discord.py` 2.7.1连接到DeepSeek的`POST /chat/completions`端点,添加斜杠命令和流媒体,通过上下文缓存控制支出,并将机器人部署到小型VPS。到那时,你将拥有一个可工作的机器人、一个成本模型以及一个保持其健康的清单。

What you’ll build

Chat-client UI mockup showing a DeepSeek V4-Flash 机器人 replying to a slash-command in a community channel.

本指南中的机器人监听 Discord 中的两件事:一个 斜杠命令(一次性问题,可选思考模式)和一个 斜杠命令(一次性问题,可选思考模式)和一个 提及,默认情况下,通过一个可选的升级标志将单个问题提升到 提及,默认情况下,通过一个可选的升级标志将单个问题提升到 在它可以读取的任何频道中(多轮对话,记得最后几条消息)。回复在生成时流式传输到Discord,因此用户看到token到达而不是等待一堵文本墙。成本持续存在 deepseek-v4-flash 解决更难的问题。 deepseek-v4-pro DeepSeek Telegram 机器人

你可以将相同的框架扩展来总结线程、翻译消息或运行管理员助手。对于使用相同底层模型的不同聊天界面,请参阅我们的 指南——大约 80% 的代码是共享的。 (推荐使用 3.11 或 3.12)。

Prerequisites

  • Python 3.10+ 一个 Discord 账户
  • 具有在开发者门户中创建应用的权限。 with permission to create applications at the Developer Portal.
  • A DeepSeek API key — see get a DeepSeek API key 如果您没有的话。
  • ~$5的API余额 用于测试。一个小型服务器消耗的是分而不是美元。
  • 一台持续在线的机器 ——您的笔记本电脑用于测试,每月$5的VPS或免费层级的Fly.io机器用于生产。

调用的模型和端点

DeepSeek’s current generation is DeepSeek V4,于2026年4月24日发布,并以两个开源的专家混合模型的形式发布,遵循MIT许可证。 DeepSeek V4-Flash 是成本效益层(总参数量284B,活跃参数量13B),是聊天机器人的正确默认选择。 DeepSeek V4-Pro 是前沿层(1.6T / 49B活跃参数),适用于更复杂的推理或编码工作。两者都共享一个1,000,000个token的上下文窗口,最多可输出384,000个token。

Chat requests hit POST /chat/completions, the OpenAI-compatible endpoint at https://api.deepseek.com。一旦您拥有API密钥,您可以使用OpenAI API格式的示例脚本访问DeepSeek;相同的端点接受流参数,并且针对相同的基URL提供了一个Anthropic兼容的界面。思考模式是一种 request parameter 适用于任何V4型号,而不是单独的型号ID——设置 reasoning_effort="high" with extra_body={"thinking": {"type": "enabled"}} 以启用它。

如果您维护一个使用较旧机器人的 deepseek-chat or deepseek-reasoner, 这些旧ID仍然有效,但路由到 deepseek-v4-flash。DeepSeek已声明,deepseek-chat和deepseek-reasoner将在2026年7月24日15:59 UTC之后完全退役且不可访问,并且目前两种模式都路由到deepseek-v4-flash。迁移是一个单行 model= swap; the base_url does not change.

步骤 1:注册 Discord 应用和机器人

  1. Open discord.com/developers/applications 点击 新应用。给它起一个名字(机器人的显示名称)。
  2. In the left sidebar, open 机器人. Click 重置令牌 并将令牌复制到您的密码管理器中。您将不会再看到它。
  3. 仍然在 机器人下,滚动到 特权网关意图 并切换开启 消息内容意图 (必需以读取 提及,默认情况下,通过一个可选的升级标志将单个问题提升到 文本)和 服务器成员意图.
  4. Open OAuth2 → URL生成器.勾选 机器人 and applications.commands under scopes, then under 机器人 permissions tick 发送消息, 读取消息历史, 使用斜杠命令, and 嵌入链接.
  5. Copy the generated URL into a browser and invite the 机器人 to a test server you own.

步骤 2:安装依赖项

创建一个项目文件夹和一个虚拟环境,然后安装您需要的两个库。discord.py是Discord API的Python封装;最新版本2.7.1于2026年3月3日发布。

python3 -m venv .venv
source .venv/bin/activate          # Windows: .venvScriptsactivate
pip install -U "discord.py==2.7.1" "openai>=1.40.0" python-dotenv

Create a .env 文件位于项目根目录:

DISCORD_TOKEN=paste-your-机器人-token-here
DEEPSEEK_API_KEY=paste-your-deepseek-key-here

Add .env to .gitignore 立即。泄露任何令牌都是糟糕的下午。

步骤 3:最小工作机器人

将以下Python代码保存为 机器人.py。它注册了一个单条 斜杠命令(一次性问题,可选思考模式)和一个 斜杠命令,将用户的提问转发给DeepSeek,并回复答案。

import os
import discord
from discord import app_commands
from dotenv import load_dotenv
from openai import AsyncOpenAI

load_dotenv()

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

SYSTEM_PROMPT = (
    "You are a concise Discord assistant. "
    "Answer in under 1500 characters. Use Markdown for code."
)

intents = discord.Intents.default()
intents.message_content = True

class 机器人(discord.Client):
    def __init__(self):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        await self.tree.sync()

机器人 = 机器人()

@机器人.tree.command(name="ask", description="Ask DeepSeek a question")
@app_commands.describe(prompt="What do you want to ask?", think="Use thinking mode")
async def ask(interaction: discord.Interaction, prompt: str, think: bool = False):
    await interaction.response.defer(thinking=True)
    kwargs = {
        "model": "deepseek-v4-flash",
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": prompt},
        ],
        "max_tokens": 1024,
        "temperature": 1.3,
    }
    if think:
        kwargs["reasoning_effort"] = "high"
        kwargs["extra_body"] = {"thinking": {"type": "enabled"}}
        kwargs.pop("temperature", None)  # ignored in thinking mode

    resp = await deepseek.chat.completions.create(**kwargs)
    answer = resp.choices[0].message.content or "(empty response)"
    await interaction.followup.send(answer[:1990])

机器人.run(os.environ["DISCORD_TOKEN"])

Run it: python 机器人.py。在Discord中,输入 斜杠命令(一次性问题,可选思考模式)和一个 在任何机器人存在的频道中提问。第一个斜杠命令同步可能需要一分钟才能传播到Discord客户端。

在继续之前,有几个值得了解的细节:

  • 异步客户端。 OpenAI SDK提供了一个 AsyncOpenAI 类。在 discord.py would block the event loop and freeze the 机器人 under load.
  • Temperature 1.3 符合DeepSeek官方指南的一般对话。代码使用0.0,创意写作使用1.5。
  • 思考模式规则。 思考模式不支持温度、top_p、存在惩罚或频率惩罚;为了兼容性,设置这些参数不会触发错误,但不会有任何效果。代码会减少 temperature 当 think=True.
  • 延迟交互。 Discord要求在3秒内回复。 defer() 可为您争取多达15分钟的时间。

步骤 4:添加多轮 提及,默认情况下,通过一个可选的升级标志将单个问题提升到 聊天

Discord-style channel showing a DeepSeek V4-Flash 机器人 reply streaming token by token via message edits.

API是无状态的——DeepSeek不会记住其侧面的先前回合,因此客户端必须在每个请求中重新发送对话历史。这与DeepSeek网页聊天和移动应用形成对比,它们为用户保持会话状态。为了在Discord中支持双向对话,机器人必须读取最近的频道消息并自行重建消息列表。

将此处理程序添加到 机器人.py 上面 机器人.run(...):

HISTORY_TURNS = 6  # last 6 message pairs ≈ ~1500 input tokens typical

@机器人.event
async def on_message(message: discord.Message):
    if message.author == 机器人.user or 机器人.user not in message.mentions:
        return

    # Build conversation history from the channel
    history = []
    async for m in message.channel.history(limit=HISTORY_TURNS * 2):
        if m.author == 机器人.user:
            history.append({"role": "assistant", "content": m.clean_content})
        elif 机器人.user in m.mentions:
            text = m.clean_content.replace(f"@{机器人.user.display_name}", "").strip()
            history.append({"role": "user", "content": text})
    history.reverse()

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

    async with message.channel.typing():
        resp = await deepseek.chat.completions.create(
            model="deepseek-v4-flash",
            messages=messages,
            max_tokens=1024,
            temperature=1.3,
        )
    await message.reply(resp.choices[0].message.content[:1990])

限制历史记录。六轮对话足以进行日常交流,并使您的输入账单可预测。如果您想进行长时间运行的线程,请在SQLite中存储对话ID,并通过令牌数量而不是消息数量进行修剪。

步骤 5:将回复流式传输到 Discord

流式传输使机器人感觉更快,即使它实际上并没有变快。Discord允许每个频道每秒最多编辑五条消息,因此您可以更新单个占位符消息以包含部分响应。

import asyncio

async def stream_to_message(stream, placeholder: discord.Message):
    buffer = ""
    last_edit = 0.0
    async for chunk in stream:
        delta = chunk.choices[0].delta.content or ""
        buffer += delta
        now = asyncio.get_event_loop().time()
        if now - last_edit > 0.7 and buffer:
            await placeholder.edit(content=buffer[:1990])
            last_edit = now
    await placeholder.edit(content=(buffer or "(empty)")[:1990])

然后从您的处理程序中使用 stream=True 在聊天完成请求上。占位符模式——发送“正在思考...”消息,然后随着令牌的到来编辑它——将API调用次数限制为一次,并尊重Discord的速率限制。

步骤 6:验证是否成功

在宣布胜利之前,请通过此清单:

  • 刀片命令出现。 Type / 在一个频道中并确认 斜杠命令(一次性问题,可选思考模式)和一个 出现。如果没有,给它60秒并重试——全局命令同步是缓存的。
  • 提及回复功能正常。 Type @Your机器人 what's 2+2?。您应该看到正在输入的指示符,然后是回复。
  • 思考模式标志。 Run 斜杠命令(一次性问题,可选思考模式)和一个 prompt:"Plan a 3-day Tokyo itinerary" think:True. 回复应更慢且更有结构。
  • 成本仪表板。 打开DeepSeek计费控制台并确认已记录令牌使用情况。

成本:100 用户服务器的示例

假设一个小型服务器:每月1,000次机器人交互,平均800个输入令牌(系统提示+历史)和400个输出令牌。系统提示会重复,因此DeepSeek的上下文缓存会命中前缀;每次调用的用户消息总是对该前缀的未缓存未命中。

2026年4月的价格——在承诺预算前与以下页面进行核对。以下示例的成本为 DeepSeek API pricing 大约 deepseek-v4-flash:

Input, cache hit (system 600 tokens × 1,000)   :   600,000 × $0.0028/M = $0.0168
Input, cache miss (200 tokens × 1,000)         :   200,000 × $0.14/M  = $0.0280
Output (400 tokens × 1,000)                    :   400,000 × $0.28/M  = $0.1120
                                                                       --------
Total                                                                    $0.1568

每月0.16美元 对于一千条回复。在 Bot在线但忽略@提及 deepseek-v4-pro 在促销价0.435美元/0.87美元(至2026年5月31日75%折扣;目录价0.0145美元/1.74美元/3.48美元)下,每1,000,000个令牌的运行费用约为1.83美元——大约是成本的11倍,这对于更难的问题来说才合理。更多关于成本控制的详细信息,请参阅页面上的内容。 DeepSeek context caching.

Common errors and fixes

Symptom Likely cause Fix
机器人 online but ignores 提及,默认情况下,通过一个可选的升级标志将单个问题提升到s 消息内容意图 off Enable it in Developer Portal and restart the 机器人
过期或错误的机器人令牌 Stale or wrong 机器人 token 在开发者门户中重置令牌;更新 .env
401 Unauthorized from DeepSeek 缺失或过期的API密钥 生成新的密钥;检查Bearer令牌格式
Empty content 使用JSON模式 截断或缺少模式提示 Increase max_tokens;在提示中包含单词“json”和一个示例模式
斜杠命令从未出现 全局同步延迟或缺少作用域 Use tree.copy_global_to(guild=...) 用于开发期间的即时仅限公会同步
回复被截断在句子中间 Discord的2,000字符限制 分成多条消息或通过嵌入分页
insufficient_system_resource 提供商负载峰值 使用指数退避重试;如果之前使用的是V4-Pro,考虑回退到V4-Flash

JSON模式值得单独一行。将response_format设置为json_object启用JSON输出;您还必须通过系统或用户消息指示模型生成JSON,否则模型可能会生成一个无休止的空白流,直到达到令牌限制,导致长时间运行且看似卡住的需求。DeepSeek文档将JSON模式描述为 designed 返回有效的JSON,但不保证——优雅地处理空内容,并始终包含一个示例模式。

Hardening for production

Architecture diagram of a Discord 机器人 routing slash-command events to DeepSeek V4-Flash and back.
  • 每用户速率限制。 一个简单的内存中 defaultdict 带有时间戳可以阻止一个用户在下午花光你的月度预算。
  • 允许列表频道。 传递一个 CHANNEL_IDS env var and reject messages from anywhere else.
  • 记录使用情况。 API响应包括 usage.prompt_cache_hit_tokens and usage.prompt_cache_miss_tokens — 将它们写入SQLite以监控缓存有效性。
  • 包装调用 in try/except for openai.APIError and asyncio.TimeoutError以友好的消息回复而不是崩溃。
  • 在进程管理器下运行 (systemd, pm2, Fly.io machines). The 机器人 must reconnect after gateway disconnects, which discord.py 如果您想在网络上实现相同的流程,更广泛的中心索引了网站上每个步骤指南。

Next steps

从这里,两个值得您花时间的自然扩展:

  1. Sharpen the 机器人’s voice with stronger system prompts — see DeepSeek prompt engineering 了解在聊天风格应用中有效模式的示例。
  2. 通过连接检索增强生成,让模型了解您服务器的wiki、FAQ或代码库。 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 Discord 机器人的成本是多少?

如常。相同的模式适用于其他在本文档中涵盖的Python集成 deepseek-v4-flash预计每月费用约为0.10-0.50美元。截至2026年4月,V4-Flash按每1M个token计费为0.0028美元缓存命中输入、0.14美元缓存未命中输入和0.28美元输出。大型或繁忙的机器人仍然可以通过合理的会话历史记录限制保持在每月5美元以下。查看完整信息。 DeepSeek API pricing breakdown.

DeepSeek Discord 机器人能记住之前的消息吗?

不是单独的——API是无状态的,不会在服务器端存储会话历史。机器人必须在每个请求中重新发送之前的消息。大多数实现从Discord频道本身读取最后N条消息,或将会话ID存储在SQLite中。这种模式与任何OpenAI兼容客户端的多轮聊天模式相同。关于更深入的线格式信息,请参阅。 DeepSeek API documentation.

对于 Discord 机器人来说,deepseek-v4-flash 和 deepseek-v4-pro 有什么区别?

V4-Flash(284B / 13B active)是成本效益的默认选择——足够快以用于聊天,足够便宜以运行公共机器人。V4-Pro(1.6T / 49B active)是复杂推理和编码任务的尖端级别,但输出token的成本大约是12倍。大多数Discord机器人应在Flash上运行,并将选定的命令升级到Pro。请参阅。 DeepSeek V4 for full specs.

DeepSeek 是否与 discord.py 2.x 兼容?

是的。discord.py 2.7.1(2026年3月)处理slash命令、intents、modals和components,并以异步模式干净地集成到OpenAI Python SDK中。在Discord层中没有DeepSeek特定的内容——将OpenAI客户端指向。 https://api.deepseek.com and call POST /chat/completions as usual. The same pattern applies to other Python integrations covered in the DeepSeek Python integration guide.

DeepSeek API 对于公共 Discord 机器人来说是否安全使用?

是的,但需采取正常预防措施:将API密钥存储在环境变量中,永远不要将其提交到git,按用户进行速率限制以防止滥用,如果机器人在大型服务器中,请允许列表中的频道。对话由DeepSeek的基础设施处理,因此不要在没有披露的情况下通过公共机器人传输敏感数据。关于权衡,请参阅关于的文章。 DeepSeek privacy.

Sources & Methodology

Last source check: April 30, 2026

Primary sources

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 上面. 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

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