1.申请微信公众号;
2.申请大模型kpi;
3.使用内网穿透工具建立域名,并将域名映射到本地计算机上,选则端口;
4.利用python flask编写代码,建立ip端口连接,代码如下:
import os
import dashscope
import hashlib
from xml.etree.ElementTree import Element, SubElement, tostring
import xml.etree.ElementTree as ET
from flask import Flask, request, render_template, jsonify
from flask import make_response
import time
urls = (
'/wx'
)
# 创建Flask应用实例
app = Flask(__name__)
# 从环境变量读取API密钥
dashscope.api_key = os.getenv('DASHSCOPE_API_KEY')
def parse_request(xml_data):
try:
tree = ET.fromstring(xml_data)
msg_type = tree.find('MsgType').text
# 添加对 FromUserName 和 ToUserName 的解析
from_user_name = tree.find('FromUserName').text
to_user_name = tree.find('ToUserName').text
if msg_type == 'text':
content = tree.find('Content').text
return {'type': 'text', 'content': content, 'from_user_name': from_user_name, 'to_user_name': to_user_name}
elif msg_type == 'image':
media_id = tree.find('MediaId').text
return {'type': 'image', 'media_id': media_id, 'from_user_name': from_user_name, 'to_user_name': to_user_name}
# 处理其它类型的消息...
else:
return None
except Exception as e:
print(f"Error parsing request: {e}")
return None
def generate_response_xml(answer, parsed_request):
# 构建微信需要的XML格式响应
root = Element('xml')
to_user = SubElement(root, 'ToUserName')
to_user.text = parsed_request['from_user_name']
from_user = SubElement(root, 'FromUserName')
from_user.text = parsed_request['to_user_name']
create_time = SubElement(root, 'CreateTime')
create_time.text = str(int(time.time()))
msg_type = SubElement(root, 'MsgType')
msg_type.text = 'text'
content = SubElement(root, 'Content')
content.text = answer
return '<?xml version="1.0" encoding="UTF-8"?>' + tostring(root, encoding='unicode')
def call_with_prompt(prompt):
try:
response = dashscope.Generation.call(
model=dashscope.Generation.Models.qwen_turbo,
prompt=prompt
)
if isinstance(response, dict) and 'output' in response:
return response['output']["text"]
else:
# Log the unexpected response and return a default message
app.logger.error("Unexpected response format from DashScope: %s", response)
return "I'm sorry, but I couldn't process your request right now."
except Exception as e:
# Log the error and return a default message
app.logger.error("Error calling DashScope: %s", str(e))
return "An error occurred while processing your request."
@app.route('/')
def index():
return render_template('index.html')
@app.route('/ask', methods=['POST'])
def ask_question():
question = request.form['question']
answer = call_with_prompt(question)
return jsonify({'answer': answer})
@app.route('/wechat', methods=['GET', 'POST'])
def handle_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')
token = "maluguang"
# 使用列表推导式确保所有元素都不是None,然后再排序
list = [x for x in [token, timestamp, nonce] if x is not None]
list.sort()
sha1 = hashlib.sha1()
sha1.update(''.join(list).encode('utf-8'))
hashcode = sha1.hexdigest()
if hashcode == signature:
# 使用make_response()并设置Content-Type
response = make_response(echostr)
response.headers['Content-Type'] = 'text/plain'
return response
else:
return ""
elif request.method == 'POST':
xml_data = request.data.decode('utf-8')
parsed_request = parse_request(xml_data)
if parsed_request is not None:
# Use only the content part of the parsed_request for generating the answer
answer = call_with_prompt(parsed_request['content'])
# Generate the response XML using the answer and parsed_request
response_xml = generate_response_xml(answer, parsed_request)
return response_xml
else:
# Return an error response in XML format
return '<?xml version="1.0" encoding="UTF-8"?><xml><ToUserName><![CDATA[error]]></ToUserName><FromUserName><![CDATA[error]]></FromUserName><CreateTime>0</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Invalid request]]></Content></xml>', 400
if __name__ == '__main__':
app.run(host='0.0.0.0', port="8080")
#app.run(debug=True)
4.下载nginx,并更改conf文件中的local地址和监听端口;
5.在微信公众平台上的基础设置中修改,将域名加子名称输入(此处需留意,应与上述的local地址相互对应),进行token验证,该token和代码中token一致
6.enjoy。