import time
from flask import Flask,make_response,request
import openai
from flask import Flask, request
from flask_caching import Cache
import xml.etree.cElementTree as ET
import hashlib
import requests
import re
import os
cnt = 0
my_wx_token = "" # 自定义字母和数字组合即可,后续需要填入公众号后台
my_gpt_key = "" # 这里填写你在OpenAI后台创建的API-KEY
my_switch_chatgpt = True
app = Flask(__name__)
env_dist = os.environ
cache = Cache(app, config={'CACHE_TYPE': 'simple', "CACHE_DEFAULT_TIMEOUT": 30})
@app.route('/',methods=['GET','POST'])
def wechat():
if request.method == 'GET':
signature = request.args.get("signature", "")
timestamp= request.args.get("timestamp", "")
nonce= request.args.get("nonce", "")
echostr= request.args.get("echostr", "")
print(signature, timestamp, nonce, echostr)
token=my_wx_token
data =[token, timestamp, nonce]
data.sort()
temp = ''.join(data)
sha1 = hashlib.sha1(temp.encode('utf-8'))
hashcode=sha1.hexdigest()
print(hashcode)
if hashcode == signature:
print("wechat commit check OK")
return echostr
else:
print("GET error input msg")
return "error-return\r\n"
else:
xmlData = ET.fromstring(request.stream.read())
msg_type = xmlData.find('MsgType').text
if msg_type == 'text':
ToUserName = xmlData.find('ToUserName').text
FromUserName = xmlData.find('FromUserName').text
CreateTime = xmlData.find('CreateTime').text
print(ToUserName)
print(FromUserName)
print(CreateTime)
global cnt
cnt += 1
print('-------> ' + str(cnt))
return generate_response_xml(FromUserName, ToUserName, xmlData.find('Content').text)
def text_reply(FromUserName, ToUserName, output_content):
reply = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>
'''
response = make_response(reply % (FromUserName, ToUserName, str(int(time.time())), output_content))
response.content_type = 'application/xml'
return response
def generate_response_xml(FromUserName, ToUserName, input_content):
output_content = generate_response(input_content)
return text_reply(FromUserName, ToUserName, output_content)
outofsevice_txt = "抱歉,<a href=\"https://mp.weixin.qq.com/s/0LN37YiERJgMyvIDpzRcAQ\">攻城狮杰森的ChatGPT服务助手</a>正在维护中,暂时无法预估维护持续时间,请明天再来尝试吧。"
@cache.memoize(timeout=60)
def generate_response(prompt):
if not my_switch_chatgpt:
return outofsevice_txt
openai.api_key = my_gpt_key
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=0,
max_tokens=1024,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0,
)
message = response.choices[0].text
print(message)
ans = message.strip()
return ans
if __name__ == '__main__':
app.run(host='0.0.0.0', port=xxxx, debug=True)#开放xxxx端口
评论