import os from flask import Flask, request, abort import hashlib import xmltodict import openai from wechatpy import parse_message from wechatpy.utils import check_signature from wechatpy.exceptions import InvalidSignatureException app = Flask(__name__) # 配置 # TOKEN = 'your_wechat_token' # APPID = 'your_wechat_appid' # APPSECRET = 'your_wechat_appsecret' # OPENAI_API_KEY = 'your_openai_api_key' TOKEN = os.getenv("TOKEN") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") APPID = os.getenv("APPID") APPSECRET = os.getenv("APPSECRET") openai.api_key = OPENAI_API_KEY # 存储用户当前使用的模型 user_models = {} def split_message(message, max_length=500): """Split a message into chunks of max_length characters.""" return [message[i:i+max_length] for i in range(0, len(message), max_length)] def get_gpt_response(message, model="gpt-3.5-turbo"): """Get response from GPT model.""" try: response = openai.ChatCompletion.create( model=model, messages=[{"role": "user", "content": message}] ) return response.choices[0].message.content except Exception as e: return f"Error: {str(e)}" @app.route('/', methods=['GET', 'POST']) def wechat(): if request.method == 'GET': token = TOKEN signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echostr = request.args.get('echostr', '') try: check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: abort(403) return echostr else: xml_data = request.data msg = parse_message(xml_data) if msg.type == 'text': user_id = msg.source content = msg.content if content.startswith('/model'): # 切换模型 model = content.split(' ')[1] user_models[user_id] = model return f'Model switched to {model}' model = user_models.get(user_id, "gpt-3.5-turbo") response = get_gpt_response(content, model) # 拆分长消息 response_parts = split_message(response) # 构建回复消息 reply = [] for part in response_parts: reply.append(f""" {int(time.time())} """) return ''.join(reply) if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)