File size: 2,748 Bytes
e7c16da
 
 
 
 
 
 
 
8a9b05e
 
e7c16da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a9b05e
 
e7c16da
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
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'

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"""
                <xml>
                <ToUserName><![CDATA[{msg.source}]]></ToUserName>
                <FromUserName><![CDATA[{msg.target}]]></FromUserName>
                <CreateTime>{int(time.time())}</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[{part}]]></Content>
                </xml>
                """)
            
            return ''.join(reply)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)