2026年如何搭建Discord AI机器人:discord.py(1.6万星)+ 大模型,一步步来
Discord没有内置AI助手,但免费的Bot API + discord.py(16,128星)能让你在30分钟左右给任意服务器加上大模型机器人——支持斜杠命令、私聊,且没有托管费用坑。
💡 你将学到
Discord没有内置AI助手,但免费的Bot API + discord.py(16,128星)能让你在30分钟左右给任意服务器加上大模型机器人——支持斜杠命令、私聊,且没有托管费用坑。
直接给结论
discord.py(16,128星,MIT)是Discord官方Bot API最流行的Python封装。机器人本质就是一个用token登录、对消息做出反应的Python进程。接上任意大模型API,你就能在服务器的每个频道里用上AI助手。
第一步 - 在Discord开发者后台创建机器人
- 打开 https://discord.com/developers/applications,点击 New Application。
- 进入 Bot -> Reset Token -> 复制token(保密保存,像密码一样对待)。
- 在 Bot Settings 里开启 Message Content Intent(读取消息必需)。
- 在 OAuth2 -> URL Generator 勾选
bot权限和Send Messages+Use Slash Commands,打开生成的URL把机器人邀请进你的服务器。
第二步 - 安装并运行最小机器人
pip install discord.py
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.command()
async def ping(ctx):
await ctx.send("pong")
bot.run("YOUR_BOT_TOKEN")
运行后在任意频道输入 !ping,应该回复 "pong"。
第三步 - 接上大模型
import os, requests
@bot.command()
async def ask(ctx, *, prompt):
r = requests.post("https://api.deepseek.com/chat/completions",
headers={"Authorization": f"Bearer {os.environ['LLM_KEY']}"},
json={"model": "deepseek-chat", "messages": [{"role": "user", "content": prompt}],
"max_tokens": 500})
reply = r.json()["choices"][0]["message"]["content"]
# Discord消息上限2000字符 - 长回复要拆分
for i in range(0, len(reply), 1900):
await ctx.send(reply[i:i+1900])
现在在服务器里输入 !ask 帮我写一首关于猫的诗 就能用了。想要斜杠命令,用 discord.py 自带的 @app_commands.command() 即可。
为什么"how to"长尾教程对AI博客最重要
搜索 "how to build a discord bot" 的用户离动手只差一步——转化率远高于 "AI bot" 这类宽泛词。步骤式教程还容易被AI搜索引擎当作直接答案引用,因为每一步都是自包含、可引用的。
3个常见坑
- Token泄露 - 不要把token提交到GitHub,用环境变量。
- Message Content Intent没开 - 机器人能跑但永远看不到消息。
- 2000字符上限 - 大模型长回复直接发送会报错,必须拆分。
相关文章
2026-06-29
高收益主线龙头策略——不花钱的数据,也能抓到龙头
2026-06-29
你笔记本里,藏着一个AI
2026-07-14
免费AI编程助手 2026 配置指南:VS Code 5分钟装 Continue、Copilot、Windsurf
