main.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import json
  2. import os
  3. from flask import Flask, request, jsonify
  4. from handler.card_handler import handle_card
  5. from handler.meg_handler import handle_meg
  6. from utils.logger import logger
  7. from utils.decrypt import AESCipher
  8. from dotenv import load_dotenv
  9. from functools import wraps
  10. load_dotenv() # 加载环境变量
  11. app = Flask(__name__)
  12. cipher = AESCipher(os.getenv('BOT_AES_KEY'))
  13. def decrypt_request(f):
  14. @wraps(f)
  15. def decorated_function(*args, **kwargs):
  16. if request.json and 'encrypt' in request.json:
  17. encrypt = request.json['encrypt']
  18. decrypted_request = json.loads(cipher.decrypt_string(encrypt))
  19. return f(decrypted_request, *args, **kwargs)
  20. else:
  21. logger.error("/enc_req无法解密: " + request.json)
  22. return decorated_function
  23. @app.route('/enc_req', methods=['POST'])
  24. @decrypt_request
  25. def encrypt_challenge(decrypted_request):
  26. if 'challenge' in decrypted_request:
  27. response = {
  28. "challenge": decrypted_request['challenge']
  29. }
  30. return jsonify(response), 200
  31. elif 'event_type' in decrypted_request['header']:
  32. if decrypted_request['header']['event_type'] == 'im.message.receive_v1':
  33. meg = decrypted_request['event']['message']
  34. event_id = decrypted_request['header']['event_id']
  35. user_open_id = decrypted_request['event']['sender']['sender_id']['open_id']
  36. handle_meg(meg, event_id, user_open_id)
  37. elif decrypted_request['header']['event_type'] == 'application.bot.menu_v6':
  38. logger.info(decrypted_request)
  39. return "", 200
  40. else:
  41. logger.warn("未知事件: " + decrypted_request)
  42. return "", 200
  43. @app.route('/req', methods=['POST'])
  44. def challenge():
  45. if 'challenge' in request.json:
  46. response = {
  47. "challenge": request.json['challenge']
  48. }
  49. return jsonify(response), 200
  50. elif 'token' in request.json and 'action' in request.json:
  51. # 卡片事件
  52. card_response = handle_card(request.json)
  53. return jsonify(card_response), 200
  54. else:
  55. logger.info(request.json)
  56. return "", 200
  57. if __name__ == '__main__':
  58. app.run(host='0.0.0.0', port=7863, debug=True)