import json import os from flask import Flask, request, jsonify from handler.card_handler import handle_card from handler.meg_handler import handle_meg from utils.logger import logger from utils.decrypt import AESCipher from dotenv import load_dotenv from functools import wraps load_dotenv() # 加载环境变量 app = Flask(__name__) cipher = AESCipher(os.getenv('BOT_AES_KEY')) def decrypt_request(f): @wraps(f) def decorated_function(*args, **kwargs): if request.json and 'encrypt' in request.json: encrypt = request.json['encrypt'] decrypted_request = json.loads(cipher.decrypt_string(encrypt)) return f(decrypted_request, *args, **kwargs) else: logger.error("/enc_req无法解密: " + request.json) return decorated_function @app.route('/enc_req', methods=['POST']) @decrypt_request def encrypt_challenge(decrypted_request): if 'challenge' in decrypted_request: response = { "challenge": decrypted_request['challenge'] } return jsonify(response), 200 elif 'event_type' in decrypted_request['header']: if decrypted_request['header']['event_type'] == 'im.message.receive_v1': meg = decrypted_request['event']['message'] event_id = decrypted_request['header']['event_id'] user_open_id = decrypted_request['event']['sender']['sender_id']['open_id'] handle_meg(meg, event_id, user_open_id) elif decrypted_request['header']['event_type'] == 'application.bot.menu_v6': logger.info(decrypted_request) return "", 200 else: logger.warn("未知事件: " + decrypted_request) return "", 200 @app.route('/req', methods=['POST']) def challenge(): if 'challenge' in request.json: response = { "challenge": request.json['challenge'] } return jsonify(response), 200 elif 'token' in request.json and 'action' in request.json: # 卡片事件 card_response = handle_card(request.json) return jsonify(card_response), 200 else: logger.info(request.json) return "", 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=7863, debug=True)