公眾號接入chatGPT的詳細教程 附Python源碼
前置準備
- 一個域名
- 一臺服務器
- 一個公眾號
域名配置
在你的域名服務商新建二級域名并綁定服務器主機IP
服務器配置
上傳下面的python文件到你的服務器,并修改代碼段中相應位置代碼(token、api-key、port)
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 = "" # 自定義字母和數字組合即可,后續(xù)需要填入公眾號后臺
my_gpt_key = "" # 這里填寫你在OpenAI后臺創(chuàng)建的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>正在維護中,暫時無法預估維護持續(xù)時間,請明天再來嘗試吧。"
@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端口
使用寶塔是比較快捷的配置方式,安裝寶塔面板后,進入軟件商店,安裝下面兩個插件

打開 python 項目管理器 ,簡單配置下我們要啟動的項目

啟動后映射項目域名,頂級域和二級域都可以,比如我這里填入的是 chatgpt.coder-jason.cn

公眾號配置
進入公眾號后臺,找到設置與開發(fā),進入基本配置,由于我這里已經配置好了,這里僅演示下怎么添加啟用

點擊添加配置

token 值就是在上述代碼段中填入的值,自定義字母和數字組合即可
點擊提交后,如果服務器中的項目啟動無誤,則會提示 token校驗成功

接下來就可以回到公眾號和 chatGPT 愉快的交流啦~

到此這篇關于公眾號接入 chatGPT教程 附Python源碼的文章就介紹到這了,更多相關公眾號接入 chatGPT內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python數據分析matplotlib設置多個子圖的間距方法
今天小編就為大家分享一篇Python數據分析matplotlib設置多個子圖的間距方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
一文搞懂Python中pandas透視表pivot_table功能
透視表是一種可以對數據動態(tài)排布并且分類匯總的表格格式。或許大多數人都在Excel使用過數據透視表,也體會到它的強大功能,而在pandas中它被稱作pivot_table,今天通過本文給大家介紹Python中pandas透視表pivot_table功能,感興趣的朋友一起看看吧2021-11-11
詳解Django關于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法
這篇文章主要介紹了詳解Django關于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01

