feishu_credentials.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 飞书凭证读取(四个脚本共用)。
  5. 按顺序取第一个可用来源:
  6. 1) 环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET
  7. 2) ~/.sku_audit/credentials.json
  8. 3) 技能包根目录的 credentials.json(托管沙箱无法配置环境变量或用户目录时随包提供)
  9. 文件格式:{"app_id": "...", "app_secret": "..."}
  10. 凭证值不写入任何输出;提示信息只包含路径。
  11. """
  12. import json
  13. import os
  14. FILE_NAME = "credentials.json"
  15. HOME_FILE = os.path.join(os.path.expanduser("~/.sku_audit"), FILE_NAME)
  16. PACKAGE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), FILE_NAME)
  17. def read_file(path):
  18. """读取一个凭证文件;不存在、无法解析或缺项时返回 None。"""
  19. try:
  20. with open(path, encoding="utf-8-sig") as f:
  21. data = json.load(f)
  22. except (OSError, ValueError):
  23. return None
  24. if not isinstance(data, dict):
  25. return None
  26. app_id, secret = data.get("app_id"), data.get("app_secret")
  27. if isinstance(app_id, str) and isinstance(secret, str) and app_id.strip() and secret.strip():
  28. return app_id.strip(), secret.strip()
  29. return None
  30. def load():
  31. """返回 (app_id, app_secret);没有可用来源时返回 None。"""
  32. app_id, secret = os.environ.get("FEISHU_APP_ID"), os.environ.get("FEISHU_APP_SECRET")
  33. if app_id and secret:
  34. return app_id, secret
  35. for path in (HOME_FILE, PACKAGE_FILE):
  36. found = read_file(path)
  37. if found:
  38. return found
  39. return None
  40. def missing_message():
  41. return ("未找到可用凭证。请设置环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,"
  42. f"或写入 {HOME_FILE},或在技能包根目录放置 {FILE_NAME}")