微信公众号接入GPT自动回复聊天机器人的可执行代码
时间: 2025-05-08 19:14:33 浏览: 31
### 实现微信公众号 GPT 自动回复聊天机器人的方法
为了实现基于 GPT 的自动回复功能,可以采用现有的开源项目来简化开发过程。一个推荐的选择是 `chatgpt-on-wechat` 项目[^2]。
#### 准备工作
首先需要准备以下几项:
- **微信公众平台账号**:用于创建并管理订阅号或服务号。
- **ChatGPT API Key**:获取 OpenAI 提供的 API 密钥以便调用模型接口。
- **服务器环境配置**:确保拥有可公网访问的服务端部署位置,并完成必要的安全设置。
#### 安装依赖库
安装 Python 环境以及所需的第三方包:
```bash
pip install itchat flask openai
```
其中 `itchat` 是用来模拟登录微信个人版进行消息收发;而 `flask` 则作为轻量级 Web 框架处理 HTTP 请求;最后通过 `openai` 库对接 ChatGPT 接口。
#### Flask 后台逻辑编写
下面是一个简单的 Flask 应用程序框架,它接收来自微信的消息并通过 ChatGPT 返回响应给用户:
```python
from flask import Flask, request, make_response
import hashlib
import xml.etree.ElementTree as ET
import requests
import json
app = Flask(__name__)
@app.route('/wechat', methods=['GET', 'POST'])
def wechat():
if request.method == 'GET':
token = "your_token"
query = request.args
signature = query.get('signature')
timestamp = query.get('timestamp')
nonce = query.get('nonce')
echostr = query.get('echostr')
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
if hashcode == signature:
return make_response(echostr)
elif request.method == 'POST':
web_data = request.stream.read()
rec_msg = parse_xml(web_data)
to_user_name = rec_msg.find('ToUserName').text
from_user_name = rec_msg.find('FromUserName').text
content_type = rec_msg.find('MsgType').text
reply_content = get_chatgpt_reply(rec_msg.find('Content').text)
response = f"""
<xml>
<ToUserName><![CDATA[{from_user_name}]]></ToUserName>
<FromUserName><![CDATA[{to_user_name}]]></FromUserName>
<CreateTime>{int(time.time())}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{reply_content}]]></Content>
</xml>"""
res = make_response(response)
res.content_type = 'application/xml'
return res
def parse_xml(xml_str):
root = ET.fromstring(xml_str.decode())
return root
def get_chatgpt_reply(user_input):
url = "https://api.openai.com/v1/engines/davinci-codex/completions"
headers = {
"Authorization": "Bearer YOUR_OPENAI_API_KEY",
"Content-Type": "application/json"
}
data = {"prompt": user_input,
"max_tokens": 50}
resp = requests.post(url=url, headers=headers, data=json.dumps(data))
result = resp.json()['choices'][0]['text'].strip()
return result
if __name__ == '__main__':
app.run(port=80)
```
此段代码实现了基本的文字交互模式下的自动应答机制。当收到新消息时会触发 POST 方法中的业务逻辑部分,解析 XML 数据结构提取出发送者 ID 和实际内容之后再转发至 ChatGPT 获取智能回应最终封装成标准格式返回给客户端显示出来。
阅读全文
相关推荐
















