chatGPT微信公众号和web搭建
Flask 主程序
使用大佬写的机器人。项目地址: https://github.com/acheong08/ChatGPT
新建文件夹chat,并在目录下创建python3虚拟环境(注意需要python3.8及以上):
1 2 3 4 5 sudo apt update && sudo apt install python3-pip python3 -m pip install virtualenv python3 -m virtualenv venv
进行先关库的安装
1 pip install flask xmltodict openai flask_cors
用flask web框架进行调用,写一个文件叫chat.py
,代码如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 from flask import Flask, requestimport hashlibimport xmltodictimport openaiimport timefrom revChatGPT.V3 import Chatbotfrom flask_cors import CORSimport jsonopenai_api_key = "YOUR_API_KEY" chat_dic = {} in_key = "为了团建" app = Flask(__name__) @app.route('/we', 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' , '' ) s = [timestamp, nonce, token] s.sort() s = '' .join(s) if hashlib.sha1(s.encode('utf-8' )).hexdigest() == signature: return echostr else : xml_data = request.data data_dict = xmltodict.parse(xml_data) try : user_msg = data_dict['xml' ]['Content' ] except Exception as e: user_msg = None try : if user_msg == None : response = "发生错误" else : if data_dict['xml' ]['FromUserName' ] not in chat_dic.keys(): new_chat = Chatbot(api_key=openai_api_key) chat_dic[data_dict['xml' ]['FromUserName' ]] = new_chat else : new_chat = chat_dic[data_dict['xml' ]['FromUserName' ]] print(data_dict['xml' ]['FromUserName' ]) response = new_chat.ask(user_msg) except Exception as e: response = "发生错误" response_xml = f""" <xml> <ToUserName><![CDATA[{data_dict['xml' ]['FromUserName' ]} ]]></ToUserName> <FromUserName><![CDATA[{data_dict['xml' ]['ToUserName' ]} ]]></FromUserName> <CreateTime>{int(time.time())} </CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{response} ]]></Content> </xml> """ return response_xml @app.route('/chat', methods=['GET', 'POST']) def webchat (): if request.method == 'GET' : return "暗号不对,上暗号" if request.method == 'POST' : data = json.loads(request.data) if data['key' ] != in_key: return "暗号不对,上暗号" else : clear_dic() if data['id' ] not in chat_dic.keys(): new_chat = Chatbot(api_key=openai_api_key) chat_dic[data['id' ]] = new_chat else : new_chat = chat_dic[data['id' ]] response = new_chat.ask(data['msg' ]) return response def clear_dic (): if len(chat_dic) > 120 : chat_dic.clear() if __name__ == '__main__' : app.run(debug=False )
本地测试OK后就可以进行服务器部署了。
服务器部署
和chat.py
同级的目录下创建一个uwsgi.ini
文件内容如下
安装uwsgi 服务器和nginx 服务器
1 2 sudo apt install nginx pip install uwsgi
1 2 3 4 5 6 7 8 [uwsgi] module = chat:app master = true processes = 4 socket = 127.0.0.1:5000 chmod-socket = 660 vacuum = true die-on-term = true
接下来就是使用nginx 服务器了。在/etc/nginx/sites-available/
下创建chat.conf
文,内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 server { listen 80 ; server_name YOUR_DOMAIN_NAME; location /we { include uwsgi_params; uwsgi_pass 127.0.0.1:5000 ; } location /chat { include uwsgi_params; uwsgi_pass 127.0.0.1:5000 ; } }
接下来使用命令,启动服务器测试测试
测试没有问题后,关闭uwsgi 服务器,并使用 supervisor 进行进程守护
1 sudo apt install supervisor
在/etc/supervisor/conf.d
下创建chat.conf
文件
1 2 3 4 5 6 7 8 [program:chat] user=wzq directory=/home/wzq/Desktop/chat command =/home/wzq/Desktop/chat/venv/bin/uwsgi --ini /home/wzq/Desktop/chat/chat.ini autostart=true autorestart=true stdout_logfile=/var/log /chat/stdout.log stderr_logfile=/var/log /chat/stderr.log
创建log 文件夹后加载重新载入 supervisor 配置后就OK了。
1 2 3 4 5 6 7 8 9 mkdir -p /var/log /chat/ sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl start chat sudo supervisorctl stop chat