File size: 7,638 Bytes
3cfb69c ef7a51f 3cfb69c |
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, request, make_response
import hashlib
import time
import xml.etree.ElementTree as ET
import os
import json
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from openai import OpenAI
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
app = Flask(__name__)
# 配置
TOKEN = os.getenv('TOKEN')
API_KEY = os.getenv("API_KEY")
BASE_URL = os.getenv("OPENAI_BASE_URL")
EMAIL_KEY = os.getenv("EMAIL_KEY")
client = OpenAI(api_key=API_KEY, base_url=BASE_URL)
# 存储用户会话信息
user_sessions = {}
# 定义发送邮件的函数
FUNCTIONS = [
{
"name": "send_email",
"description": "发送电子邮件。",
"parameters": {
"type": "object",
"properties": {
"to": {
"type": "string",
"description": "收件人邮箱地址"
},
"subject": {
"type": "string",
"description": "邮件主题"
},
"content": {
"type": "string",
"description": "邮件内容"
}
},
"required": ["to", "subject", "content"]
}
}
]
def verify_wechat(request):
# 获取微信服务器发送过来的参数
data = request.args
signature = data.get('signature')
timestamp = data.get('timestamp')
nonce = data.get('nonce')
echostr = data.get('echostr')
# 对参数进行字典排序,拼接字符串
temp = [timestamp, nonce, TOKEN]
temp.sort()
temp = ''.join(temp)
# 加密
if (hashlib.sha1(temp.encode('utf8')).hexdigest() == signature):
return echostr
else:
return 'error', 403
def getUserMessageContentFromXML(xml_content):
# 解析XML字符串
root = ET.fromstring(xml_content)
# 提取数据
content = root.find('Content').text
from_user_name = root.find('FromUserName').text
to_user_name = root.find('ToUserName').text
return content, from_user_name, to_user_name
def generate_response_xml(from_user_name, to_user_name, output_content):
output_xml = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>'''
response = make_response(output_xml % (from_user_name, to_user_name, str(int(time.time())), output_content))
response.content_type = 'application/xml'
return response
def get_openai_response(messages, functions=None, function_call=None):
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
functions=functions,
function_call=function_call
)
return response.choices[0].message
except Exception as e:
print(f"调用OpenAI API时出错: {str(e)}")
return None
def send_email(to, subject, content):
try:
with smtplib.SMTP('106.15.184.28', 8025) as smtp:
smtp.login("jwt", EMAIL_KEY)
message = MIMEMultipart()
message['From'] = "Me <[email protected]>"
message['To'] = to
message['Subject'] = subject
message.attach(MIMEText(content, 'html'))
smtp.sendmail("[email protected]", to, message.as_string())
return True
except Exception as e:
print(f"发送邮件时出错: {str(e)}")
return False
def process_function_call(response_message):
function_name = response_message.function_call.name
function_args = json.loads(response_message.function_call.arguments)
if function_name == "send_email":
to = function_args.get('to', '')
subject = function_args.get('subject', '')
content = function_args.get('content', '')
if not to or not subject or not content:
return None
success = send_email(to, subject, content)
return {
"success": success,
"to": to,
"subject": subject,
"content": content
}
else:
return None
def split_message(message, max_length=500):
return [message[i:i+max_length] for i in range(0, len(message), max_length)]
@app.route('/api/wx', methods=['GET', 'POST'])
def wechatai():
if request.method == 'GET':
return verify_wechat(request)
else:
# 处理POST请求
print("user request data: ", request.data)
user_message_content, from_user_name, to_user_name = getUserMessageContentFromXML(request.data)
print("user message content: ", user_message_content)
if user_message_content.lower() == '继续':
if from_user_name in user_sessions and user_sessions[from_user_name]['pending_response']:
response_content = user_sessions[from_user_name]['pending_response'].pop(0)
if user_sessions[from_user_name]['pending_response']:
response_content += '\n\n回复"继续"获取下一部分。'
else:
response_content += '\n\n回复结束。'
else:
response_content = "没有待发送的消息。"
else:
if from_user_name not in user_sessions:
user_sessions[from_user_name] = {'messages': [], 'pending_response': [], 'email_sent': False}
session = user_sessions[from_user_name]
session['messages'].append({"role": "user", "content": user_message_content})
# 检查是否需要调用函数
decision_response = get_openai_response(session['messages'], functions=FUNCTIONS, function_call="auto")
if decision_response.function_call and not session['email_sent']:
# 处理函数调用
function_result = process_function_call(decision_response)
if function_result:
session['email_sent'] = True
if function_result['success']:
response_content = f"邮件已成功发送到 {function_result['to']}。\n\n主题:{function_result['subject']}\n\n内容:\n{function_result['content']}"
else:
response_content = "邮件发送失败,请稍后再试。"
else:
response_content = "无法处理该请求,请重试。"
else:
# 正常的对话响应
gpt_response = get_openai_response(session['messages'])
response_content = gpt_response.content if gpt_response else "抱歉,我遇到了一些问题,无法回答您的问题。"
session['messages'].append({"role": "assistant", "content": response_content})
# 重置email_sent标志,为下一次消息做准备
session['email_sent'] = False
response_parts = split_message(response_content)
if len(response_parts) > 1:
response_content = response_parts[0] + '\n\n回复"继续"获取下一部分。'
session['pending_response'] = response_parts[1:]
else:
response_content = response_parts[0]
return generate_response_xml(from_user_name, to_user_name, response_content)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True) |