How to Build a DeepSeek Discord Bot in Python (2026 Guide)

You want a Discord bot that answers in your server’s voice, costs pennies a day, and uses an open-weight model you can swap out later. A DeepSeek Discord bot built on deepseek-flash gets you there: a 1M-token context, the OpenAI-compatible SDK, and cache-miss input pricing of $0.30 per million tokens at peak ($0.15 off-peak) as of October 2026. The tutorial below walks through registering a Discord application, wiring up discord.py 2.7.1 to the DeepSeek POST /chat/completions endpoint, adding slash commands and streaming, controlling spend with context caching, and running the bot on an always-on machine. By the end you’ll have a working bot, a cost model, and a checklist for keeping it healthy.
What you’ll build

The bot in this guide listens on Discord for two things: an /ask slash command (one-shot question, optional thinking mode) and an @mention in any channel it can read (multi-turn chat that remembers the last few messages). Replies can stream into Discord as they generate, so users see text arrive instead of waiting for a wall of text. Every call goes to deepseek-flash by default; changing one constant moves the bot to deepseek-v4-pro.
You can extend the same skeleton to summarise threads, translate messages, or run a moderator assistant. For a different chat surface using the same API calls, see our DeepSeek Telegram bot tutorial.
Prerequisites
- Python 3.10+ (the current
openaiSDK requires it). - A Discord account with permission to create applications at the Developer Portal.
- A DeepSeek API key — see get a DeepSeek API key if you don’t have one.
- A topped-up or granted DeepSeek balance. A small server burns through cents, not dollars: the cost example below puts 1,000
deepseek-flashreplies at about $0.54 at peak rates ($0.27 off-peak). - A machine that stays online — your laptop for testing, a small VPS or container host for a bot that runs around the clock.
The model and endpoint you’re calling
DeepSeek’s API lists two models today. deepseek-flash is served by DeepSeek-V4.1-Flash-1017 (released 17 October 2026) and is the right default for a chat bot. deepseek-v4-pro is served by DeepSeek-V4-Pro-0813 (released 13 August 2026) and costs 3.3× as much per output token. Both publish open weights under the MIT licence and share a 1M-token context window with up to 384K output tokens. Background on each: DeepSeek V4-Flash and DeepSeek V4-Pro.
Chat requests hit POST /chat/completions, the OpenAI-compatible endpoint at https://api.deepseek.com; the same endpoint streams when you pass stream=True. An Anthropic-compatible API is also available, at its own base URL, https://api.deepseek.com/anthropic. Thinking mode is a request parameter on either model, not a separate model ID, and it is on by default: set reasoning_effort="high" with extra_body={"thinking": {"type": "enabled"}} to request it explicitly, or {"type": "disabled"} for fast plain replies.
If you maintain an older bot using deepseek-chat or deepseek-reasoner, those legacy IDs were scheduled for retirement on 2026-07-24 at 15:59 UTC and are no longer listed in DeepSeek’s docs; deepseek-v4-flash is still accepted but is served by DeepSeek-V4.1-Flash-1017. Migration is a one-line model= swap; the base_url does not change.
Step 1: Register a Discord application and bot
- Open discord.com/developers/applications and click New Application. Give it a name (the bot’s display name).
- In the left sidebar, open Bot. Click Reset Token and copy the token to your password manager. You will not see it again.
- Leave the privileged gateway intents off for now. Discord’s docs say apps without the Message Content Intent still receive the content of messages that mention the app, DMs with the app and the app’s own messages — which is everything this bot reads. Turn it on only if you extend the bot to read other messages (and set
intents.message_content = Truein the code). - Open OAuth2 → URL Generator. Tick
botandapplications.commandsunder scopes, then under bot permissions tickSend MessagesandRead Message History. - Copy the generated URL into a browser and invite the bot to a test server you own.
Step 2: Install dependencies
Create a project folder and a virtual environment, then install the libraries you need. discord.py is a Python wrapper for the Discord API; its latest version on PyPI, 2.7.1, was released on 3 March 2026.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -U "discord.py==2.7.1" openai python-dotenv
Create a .env file in the project root:
DISCORD_TOKEN=paste-your-bot-token-here
DEEPSEEK_API_KEY=paste-your-deepseek-key-here
# optional: your test server's ID, for instant slash-command sync
DISCORD_GUILD_ID=
Add .env to .gitignore immediately. Leaking either token is a bad afternoon.
Step 3: Minimal working bot
Save the following Python as bot.py. It registers a single /ask slash command that forwards the user’s question to DeepSeek and replies with the answer.
import asyncio
import os
import re
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",
)
MODEL = "deepseek-flash"
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 # only to read messages that don't mention the bot
class Bot(discord.Client):
def __init__(self):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
guild_id = os.getenv("DISCORD_GUILD_ID") # optional: one test server
if guild_id:
guild = discord.Object(id=int(guild_id))
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
else:
await self.tree.sync()
bot = Bot()
def chat_kwargs(messages: list, think: bool) -> dict:
kwargs = {"model": MODEL, "messages": messages}
if think:
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"] = 1024
kwargs["temperature"] = 1.3 # DeepSeek's guidance for general conversation
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
return kwargs
@bot.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)
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": prompt},
]
resp = await deepseek.chat.completions.create(**chat_kwargs(messages, think))
answer = resp.choices[0].message.content or "(empty response)"
await interaction.followup.send(answer[:1990])
bot.run(os.environ["DISCORD_TOKEN"])
Run it: python bot.py. In Discord, type /ask in any channel where the bot is present and ask a question. Global slash commands can take a while to show up in the client; set DISCORD_GUILD_ID to your test server’s ID to sync the command to that server directly while you develop.
A few details worth understanding before moving on:
- Async client. The OpenAI SDK ships an
AsyncOpenAIclass. Using the sync client insidediscord.pywould block the event loop and freeze the bot under load. - Thinking off by default here. DeepSeek enables thinking unless you disable it, so
chat_kwargs()sends{"thinking": {"type": "disabled"}}for quick replies and only enables it when the user passesthink:True, with a largermax_tokensto leave room for the reasoning. - Temperature 1.3 matches DeepSeek’s official guidance for general conversation. Use 0.0 for code, 1.5 for creative writing. Thinking mode does not support
temperature,presence_penaltyorfrequency_penalty; setting them there causes no error but has no effect, so the thinking path leavestemperatureout. - Defer the interaction. Discord requires an initial response within 3 seconds;
defer()is that response, and the interaction token then stays valid for 15 minutes of follow-ups.
Step 4: Add multi-turn @mention chat

The API is stateless — DeepSeek does not remember prior turns on its side, so the client must resend the conversation history with every request. Contrast this with the DeepSeek web chat and mobile app, which keep session state for the user. To support a back-and-forth conversation in Discord, the bot has to read recent channel messages and rebuild the message list itself.
Add this handler to bot.py above bot.run(...):
HISTORY_LIMIT = 12 # recent channel messages to scan for context
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user or bot.user not in message.mentions:
return
# Rebuild the conversation from the channel: the API is stateless.
mention = re.compile(rf"<@!?{bot.user.id}>")
history = []
async for m in message.channel.history(limit=HISTORY_LIMIT):
if m.author == bot.user:
history.append({"role": "assistant", "content": m.content})
elif bot.user in m.mentions:
history.append({"role": "user", "content": mention.sub("", m.content).strip()})
history.reverse()
# Merge back-to-back turns from the same role into one message.
turns = []
for turn in history:
if turns and turns[-1]["role"] == turn["role"]:
turns[-1]["content"] += "\n" + turn["content"]
else:
turns.append(turn)
messages = [{"role": "system", "content": SYSTEM_PROMPT}, *turns]
async with message.channel.typing():
resp = await deepseek.chat.completions.create(**chat_kwargs(messages, think=False))
answer = resp.choices[0].message.content or "(empty response)"
await message.reply(answer[:1990])
Cap the history. A dozen recent channel messages is plenty for casual conversation and keeps your input bill predictable. If you want long-running threads, store conversation IDs in SQLite and prune by token count rather than message count.
Step 5: Stream replies into Discord
Streaming makes the bot feel faster even when it isn’t. Instead of waiting for the full answer, send a placeholder message and edit it as text arrives. Discord rate-limits message edits, so throttle them — the helper below edits at most about once a second:
async def stream_to_message(stream, placeholder: discord.Message):
buffer = ""
last_edit = 0.0
loop = asyncio.get_running_loop()
async for chunk in stream:
if not chunk.choices:
continue
buffer += chunk.choices[0].delta.content or ""
now = loop.time()
if buffer and now - last_edit > 1.0:
await placeholder.edit(content=buffer[:1990])
last_edit = now
await placeholder.edit(content=(buffer or "(empty response)")[:1990])
Then replace the last four lines of on_message — the async with message.channel.typing(): block, the answer line and the message.reply(...) call — with a streaming request:
placeholder = await message.reply("Thinking…")
stream = await deepseek.chat.completions.create(
**chat_kwargs(messages, think=False), stream=True
)
await stream_to_message(stream, placeholder)
The placeholder pattern — send a “Thinking…” message, then edit it as tokens arrive — keeps it to one DeepSeek call per reply and a bounded number of Discord edits.
Step 6: Verify it worked
Run through this checklist before claiming victory:
- Slash command appears. Type
/in a channel and confirm/askshows up. If not, setDISCORD_GUILD_IDand restart the bot to sync it to your test server. - Mention reply works. Type
@YourBot what's 2+2?. You should see a typing indicator and then a reply. - Thinking mode flag. Run
/ask prompt:"Plan a 3-day Tokyo itinerary" think:True. The reply can take longer, because the model reasons before it answers. - Usage. Check your token usage in the DeepSeek platform console, or log
resp.usagefrom the bot (see Hardening below).
Cost: a worked example for a 100-user server
Assume a small server: 1,000 bot interactions per month, average 800 input tokens (system prompt + history) and 400 output tokens. The system prompt repeats so DeepSeek’s context cache will hit on the prefix; the per-call user message is always an uncached miss against that prefix.
Rates are from DeepSeek’s pricing page as of October 2026 — confirm against the DeepSeek API pricing page before committing budget. Off-peak rates are half of peak; peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday, excluding Chinese public holidays. The example below costs out deepseek-flash:
PEAK OFF-PEAK
Input, cache hit (system 600 tokens × 1,000) : 600,000 × $0.006/M = $0.0036 × $0.003/M = $0.0018
Input, cache miss (200 tokens × 1,000) : 200,000 × $0.30/M = $0.0600 × $0.15/M = $0.0300
Output (400 tokens × 1,000) : 400,000 × $1.20/M = $0.4800 × $0.60/M = $0.2400
-------- --------
Total $0.5436 $0.2718
Roughly $0.54 a month at peak rates, or half that ($0.2718) off-peak, for a thousand replies. The same workload on deepseek-v4-pro ($0.044 cache hit, $1.32 cache miss and $3.96 output per 1M tokens at peak; half that off-peak) comes to $0.0264 + $0.2640 + $1.5840 = $1.8744 at peak, or $0.9372 off-peak — about 3.4× the Flash bill. For more aggressive cost controls see the page on DeepSeek context caching.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Bot online but ignores @mentions | The bot cannot see the channel or send messages there | Check the channel permissions for the bot’s role (View Channel, Send Messages, Read Message History) |
PrivilegedIntentsRequired at startup |
Code sets intents.message_content = True but the intent is off in the Developer Portal |
Enable Message Content Intent under Bot, or remove that line |
discord.errors.LoginFailure |
Stale or wrong bot token | Reset token in Developer Portal; update .env |
401 Unauthorized from DeepSeek |
Missing or wrong API key | Generate a fresh key; check Bearer token format |
Empty content with JSON mode |
Truncation or missing schema hint | Increase max_tokens; include the word “json” and an example schema in the prompt |
| Slash command never appears | Global sync delay or missing applications.commands scope |
Set DISCORD_GUILD_ID so setup_hook copies the commands to your test server and syncs them there |
| Reply cut off mid-sentence | Discord’s 2,000-character message limit | Split into multiple messages or paginate via embeds |
finish_reason is insufficient_system_resource |
DeepSeek interrupted the request for lack of inference capacity | Retry with exponential backoff |
| HTTP 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 |
JSON mode deserves its own line. DeepSeek’s API reference says that when you set response_format to json_object, you must also instruct the model to produce JSON in a system or user message; otherwise the model may generate an unending stream of whitespace until it reaches the token limit, resulting in a long-running and seemingly stuck request. DeepSeek’s JSON Output guide adds that the API may occasionally return empty content, so treat JSON mode as designed to return valid JSON rather than guaranteed — handle empty content gracefully and always include an example schema.
Hardening for production

- Rate-limit per user. A simple in-memory
defaultdictwith timestamps stops one user from spending your monthly budget in an afternoon. - Allow-list channels. Pass a
CHANNEL_IDSenv var and reject messages from anywhere else. - Log usage. The API response includes
usage.prompt_cache_hit_tokensandusage.prompt_cache_miss_tokens— write them to SQLite to monitor cache effectiveness. - Wrap the call in
try/exceptforopenai.APIErrorandasyncio.TimeoutError. Reply with a friendly message instead of crashing. - Run under a process supervisor (systemd, pm2, or your container platform’s restart policy).
discord.pyreconnects after gateway disconnects, but the process itself can still crash or run out of memory.
Next steps
From here, two natural extensions are worth your time:
- Sharpen the bot’s voice with stronger system prompts — see DeepSeek prompt engineering for patterns that work in chat-style applications.
- Give it knowledge about your server’s wiki, FAQ, or codebase by wiring up retrieval-augmented generation. The DeepSeek RAG tutorial walks through embeddings, chunking, and a vector store.
If you’d like the same workflow on the web instead, the broader DeepSeek tutorials hub indexes every step-by-step guide on the site.
How much does it cost to run a DeepSeek Discord bot?
Using the worked example above (800 input and 400 output tokens per reply on deepseek-flash), 1,000 replies cost about $0.54 at peak rates or half that ($0.2718) off-peak, and the bill scales linearly with volume and history length. As of October 2026, deepseek-flash bills $0.006 cache-hit input, $0.30 cache-miss input and $1.20 output per 1M tokens at peak, and half that off-peak. See the full DeepSeek API pricing breakdown.
Can a DeepSeek Discord bot remember previous messages?
Not on its own — the API is stateless and does not store conversation history server-side. The bot has to resend prior messages with each request. Most implementations read the last N messages from the Discord channel itself or store conversation IDs in SQLite. The pattern is identical to multi-turn chat in any OpenAI-compatible client. For a deeper dive on the wire format, see the DeepSeek API documentation.
What’s the difference between deepseek-flash and deepseek-v4-pro for a Discord bot?
deepseek-flash (DeepSeek-V4.1-Flash-1017) is the default — the cheaper model and the only current one that accepts images. deepseek-v4-pro (DeepSeek-V4-Pro-0813) costs 3.3× as much on output tokens and 4.4× on cache-miss input. 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, so most Discord bots should run on Flash. See DeepSeek V4 for background.
Does DeepSeek work with discord.py 2.x?
Yes. discord.py 2.7.1 (March 2026) handles slash commands, intents, modals and components and works with the OpenAI Python SDK’s async client. There’s nothing DeepSeek-specific in the Discord layer — point the OpenAI client at 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.
Is the DeepSeek API safe to use for a public Discord bot?
Yes, with normal precautions: store the API key in an environment variable, never commit it to git, rate-limit per user to prevent abuse, and allow-list channels if the bot is in a large server. Conversations are processed by DeepSeek’s infrastructure, so don’t pipe sensitive data through a public bot without disclosure. For more on the trade-offs, see the article on DeepSeek privacy.
Sources & Methodology
Primary sources
- OfficialDeepSeek API documentationEndpoints, request/response shape, model IDsLast checked: October 25, 2026
- OfficialDiscord Developer Portal: applicationsWhere to register the bot and copy its tokenLast checked: October 25, 2026
- Official documentationDiscord docs — Receiving and responding to interactionsInitial response within 3 seconds; interaction token valid for 15 minutesLast checked: October 25, 2026
- Official documentationDiscord docs — Gateway (Message Content Intent)Content still delivered for mentions, DMs and the app's own messages without the intent; approval after verificationLast checked: October 25, 2026
- Official documentationDiscord docs — Message resourceMessage content up to 2,000 charactersLast checked: October 25, 2026
- Official documentationDeepSeek pricing pagePeak/off-peak rates, peak hours, model names, 1M context / 384K outputLast checked: October 25, 2026
- Official documentationDeepSeek API docs — Thinking ModeThinking on by default; extra_body toggle; reasoning_effort; unsupported sampling parametersLast checked: October 25, 2026
- Official documentationDeepSeek API reference — Create Chat CompletionJSON Output whitespace warning; finish_reason insufficient_system_resource; max_tokens defaultsLast checked: October 25, 2026
- Official documentationDeepSeek API docs — Rate Limit & IsolationConcurrency limits 2,500 / 500; HTTP 429Last checked: October 25, 2026
Technical references
- Package registrydiscord.py on PyPIVersion 2.7.1 released 3 March 2026Last checked: October 25, 2026
- Library documentationdiscord.py docs — IntentsWhen message_content is neededLast checked: October 25, 2026
- Library documentationdiscord.py docs — Interactions APICommandTree, copy_global_to, sync, app_commands.describeLast checked: October 25, 2026
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.
