以下是一个结合企业微信机器人与深度求索(Deepseek)AIGC模型的交互式应用实现示例,包含完整代码及逐行注释:
1. 实现架构
用户消息 -> 企业微信服务器 -> 自建服务端 -> Deepseek API -> 处理响应 -> 返回企业微信群
2. 完整实现代码(deepseek_wechat_bot.py)
# -*- coding: utf-8 -*-
import os
import json
import requests
from flask import Flask, request, jsonify
from datetime import datetime
# ================= 初始化配置 =================
app = Flask(__name__)
# 配置参数(需替换为实际值)
DEEPSEEK_API_KEY = "your-api-key-here" # Deepseek控制台获取
WECHAT_WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_key" # 企业微信群机器人Webhook
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions" # Deepseek API地址
# ================= 工具函数 =================
def generate_deepseek_response(prompt):
"""
调用Deepseek API生成内容
参数:
prompt (str): 用户输入的提示文本
返回:
str: AI生成的回复内容/错误信息
"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {DEEPSEEK_API_KEY}"
}
payload = {
"model": "deepseek-chat", # 根据可用模型调整
"messages": [
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 1024
}
try:
response = requests.post(
DEEPSEEK_API_URL,
headers=headers,
json=payload,
timeout=10 # 设置超时时间
)
response.raise_for_status() # 检查HTTP错误
result = response.json()
return result['choices'][0]['message']['content'].strip()
except requests.exceptions.RequestException as e:
return f"API请求失败: {str(e)}"
except KeyError:
return "响应解析失败,请检查API格式"
def send_wechat_message(content):
"""
发送消息到企业微信群
参数:
content (str): 要发送的文本内容
"""
payload = {
"msgtype": "text",
"text": {
"content": content,
# 可选@功能(示例@所有人)
# "mentioned_list": ["@all"]
}
}
try:
resp = requests.post(
WECHAT_WEBHOOK,
json=payload,
headers={"Content-Type": "application/json"},
timeout=5
)
resp.raise_for_status()
except Exception as e:
print(f"消息发送失败: {str(e)}")
# ================= 路由处理 =================
@app.route('/wechat', methods=['POST'])
def handle_message():
"""
处理企业微信消息的主入口
"""
# 解析请求数据
req_data = request.get_json()
# 基础验证(生产环境需增加签名验证)
if not req_data or 'text' not in req_data:
return jsonify({"code": 400, "msg": "Invalid request"})
# 提取用户消息
user_input = req_data['text']['content'].strip()
# 生成回复
start_time = datetime.now()
ai_response = generate_deepseek_response(user_input)
process_time = (datetime.now() - start_time).total_seconds()
print(f"Processed: '{user_input}' => {process_time:.2f}s")
# 发送回复到企业微信
send_wechat_message(ai_response)
# 返回成功响应
return jsonify({"code": 0, "msg": "success"})
# ================= 主程序 =================
if __name__ == '__main__':
# 生产环境建议使用Gunicorn部署
app.run(host='0.0.0.0', port=5000, debug=True)
3. 关键代码注释
代码部分 | 功能说明 |
---|---|
DEEPSEEK_API_URL | Deepseek API 的访问端点(需根据官方文档确认最新地址) |
generate_deepseek_response | 封装API请求: - 设置认证Header - 构建符合Deepseek格式的请求体 - 处理异常 |
messages 数据结构 | 遵循Deepseek的消息格式要求,支持多轮对话(示例为单轮) |
send_wechat_message | 企业微信消息发送封装,支持扩展@功能和富文本格式 |
handle_message 路由 | 消息处理主流程: 1. 请求验证 2. 消息提取 3. 调用AI生成 4. 结果返回 |
process_time 记录 | 性能监控:记录AI处理耗时,便于后续优化 |
4. 部署步骤
-
环境准备
# 安装依赖 pip install flask requests python-dotenv
-
配置参数
建议使用.env
文件管理敏感信息:# .env 文件 DEEPSEEK_API_KEY=your_actual_key WECHAT_WEBHOOK=your_webhook_url
-
修改代码加载配置
在文件开头添加:from dotenv import load_dotenv load_dotenv() # 加载.env文件 DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") WECHAT_WEBHOOK = os.getenv("WECHAT_WEBHOOK")
-
启动服务
# 开发模式 python deepseek_wechat_bot.py # 生产模式(使用Gunicorn) gunicorn -w 4 -b 0.0.0.0:5000 deepseek_wechat_bot:app
-
配置企业微信
- 在群机器人设置中配置消息接收URL:
http://你的域名/wechat
- 开启加密验证时需处理签名(参考企业微信开发文档)
- 在群机器人设置中配置消息接收URL:
5. 高级扩展建议
-
对话上下文管理
# 使用Redis存储对话历史 import redis r = redis.Redis() def get_session_history(session_id): history = r.get(f"session:{session_id}") return json.loads(history) if history else [] def update_session_history(session_id, messages): r.setex(f"session:{session_id}", 3600, json.dumps(messages)) # 1小时过期
-
敏感词过滤
BANNED_WORDS = ["暴力", "敏感词"] def content_filter(text): for word in BANNED_WORDS: if word in text: return "内容包含违规词汇,请重新输入" return text # 在生成回复后调用 filtered_response = content_filter(ai_response)
-
限流控制
from flask_limiter import Limiter from flask_limiter.util import get_remote_address limiter = Limiter( app=app, key_func=get_remote_address, # 根据IP限流 default_limits=["200 per day", "50 per hour"] ) @app.route('/wechat', methods=['POST']) @limiter.limit("10/minute") # 每个IP每分钟10次 def handle_message(): # ...原有代码...
6. 注意事项
- API计费:监控Deepseek API调用量,避免超额费用
- 超时处理:企业微信要求5秒内响应,建议:
# 在生成回复前先发送空响应 from flask import Response @app.route('/wechat', methods=['POST']) def handle_message(): # 立即返回空响应 Response(headers={'Content-Type': 'application/json'}, status=200) # 异步处理后续逻辑...
- 日志记录:添加详细日志记录请求/响应数据
- HTTPS:生产环境必须启用HTTPS,可通过Nginx配置SSL证书
该方案可实现企业微信群内与Deepseek AI的自然对话交互,适用于智能问答、数据分析、内容创作等场景。根据实际需求可扩展文件处理、多模态生成等功能。