使用 Ollama 创建 AI Discord 机器人
Source: Dev.to
概述
在本教程中,你将学习如何从零开始创建一个 AI 驱动的 Discord 机器人。完成后,你将拥有一个能够:
- 使用 AI 回复消息
- 与用户进行对话
不需要任何先前经验,但掌握基本的 Python 知识会有所帮助。
你将学习
- 如何创建 Discord 机器人应用
- 如何安装并使用 Ollama(完全本地)
- 如何编写 Python 代码将两者连接
- 如何让你的机器人像真人一样聊天
- 如何让机器人 24/7 运行
你需要
- Python 3.8+ – 编程语言
- Discord 账户 – 用于创建机器人
- Ollama – 免费的本地 AI
- 文本编辑器 / IDE – 任意你喜欢的
第 1 部分:设置 Discord 机器人
- 前往 Discord 开发者页面。
- 点击 New Application,为其命名并创建。
- 前往 Bot 选项卡,启用以下特权网关意图:
- Presence Intent
- Server Members Intent
- Message Content Intent
- 点击 Reset Token,复制令牌并安全保存。
- 将机器人邀请到你的服务器:
- 前往 OAuth2 → URL Generator
- Scopes:
bot,applications.commands - Permissions:
- Send Messages
- Send Messages in Threads
- Read Message History
- View Channels
- Use Slash Commands
- Add Reactions
- 复制生成的 URL,选择你的服务器并授权机器人。
在你运行机器人之前,它将在服务器中显示为离线。
第 2 部分:安装 Ollama
Ollama 在本地运行 AI 模型,提供免费、私密且快速的推理。
macOS
brew install ollama
Linux
curl -fsSL https://ollama.ai/install.sh | sh
Windows
从官方网站下载安装程序。
启动 Ollama:
ollama serve
保持此终端打开;机器人将通过它与 Ollama 通信。
下载模型
ollama pull llama3.1
llama3.1 模型免费、开源,非常适合对话。
验证安装
ollama run llama3.1
你应该会看到一个提示符,可以输入并收到响应。
第 3 部分:安装 Python 依赖
创建并激活虚拟环境:
python3 -m venv env
source env/bin/activate # 在 Windows 上使用 `env\Scripts\activate`
安装所需的包:
pip install py-cord requests python-dotenv
- py‑cord – Discord 机器人库
- requests – 与 Ollama 通信的 HTTP 客户端
- python‑dotenv – 加载环境变量(例如 Discord 令牌)
第 4 部分:准备项目
-
创建一个
.env文件来存放你的 Discord 令牌:vim .env -
添加以下行(将
your_token_here替换为你之前复制的令牌):DISCORD_TOKEN="your_token_here"
第 5 部分:完整的机器人代码
创建一个名为 bot.py 的文件并粘贴以下代码。
# ============================================
# IMPORTS
# ============================================
import discord
from discord.ext import commands
import requests
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# ============================================
# CONFIGURATION
# ============================================
TOKEN = os.getenv("DISCORD_TOKEN")
OLLAMA_URL = "http://localhost:11434/api/generate"
OLLAMA_MODEL = "llama3.1"
PREFIX = "!"
# ============================================
# BOT SETUP
# ============================================
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
# ============================================
# HELPER: Talk to Ollama AI
# ============================================
def ask_ai(prompt, temperature=0.9):
"""
Send a prompt to Ollama and get the AI response.
"""
try:
payload = {
"model": OLLAMA_MODEL,
"prompt": prompt,
"stream": False,
"options": {
"temperature": temperature,
"num_predict": 200
}
}
response = requests.post(OLLAMA_URL, json=payload, timeout=30)
if response.status_code == 200:
data = response.json()
return data.get("response", "").strip()
else:
return "Sorry, I had trouble thinking of a response!"
except requests.exceptions.ConnectionError:
return "Error: Ollama is not running! Start it with 'ollama serve'"
except Exception as e:
return f"Error: {str(e)}"
# ============================================
# EVENTS
# ============================================
@bot.event
async def on_ready():
"""Called when the bot successfully connects to Discord."""
print(f"✅ Bot is online as {bot.user.name}")
print(f"✅ Connected to {len(bot.guilds)} server(s)")
print(f"✅ Prefix: {PREFIX}")
print("Ready to chat!")
@bot.event
async def on_message(message):
"""Called whenever a message is sent in a channel the bot can see."""
# Ignore messages from the bot itself or other bots
if message.author == bot.user or message.author.bot:
return
# Respond when the bot is mentioned
if bot.user.mentioned_in(message):
user_message = message.content.replace(f'', '').strip()
if not user_message:
return
# Show typing indicator while processing
async with message.channel.typing():
reply = ask_ai(user_message)
await message.reply(reply)
# Ensure commands still work
await bot.process_commands(message)
# ============================================
# RUN THE BOT
# ============================================
if __name__ == "__main__":
bot.run(TOKEN)
运行机器人
-
确保 Ollama 正在运行(
ollama serve)。 -
激活你的虚拟环境。
-
执行:
python bot.py
机器人应会上线,你可以在 Discord 中提及它以开始对话。
现在,你已经拥有一个由本地 Ollama 模型驱动的完整 AI Discord 机器人。祝你玩得开心,并继续进行自定义和扩展!