utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """QQBot shared utilities — User-Agent, HTTP helpers, config coercion."""
  2. from __future__ import annotations
  3. import platform
  4. import sys
  5. from typing import Any, Dict, List
  6. from .constants import QQBOT_VERSION
  7. def _get_hermes_version() -> str:
  8. """Return the hermes-agent package version, or 'dev' if unavailable."""
  9. try:
  10. from importlib.metadata import version
  11. return version("hermes-agent")
  12. except Exception:
  13. return "dev"
  14. def build_user_agent() -> str:
  15. """``QQBotAdapter/<qqbot_version> (Python/<py_version>; <os>; Hermes/<hermes_version>)``."""
  16. v = sys.version_info
  17. return (f"QQBotAdapter/{QQBOT_VERSION} (Python/{v.major}.{v.minor}.{v.micro}; "
  18. f"{platform.system().lower()}; Hermes/{_get_hermes_version()})")
  19. def get_api_headers() -> dict[str, str]:
  20. """Standard QQBot API headers. ``q.qq.com`` requires ``Accept: application/json``
  21. — without it the server returns a JavaScript anti-bot challenge page."""
  22. return {"Content-Type": "application/json", "Accept": "application/json", "User-Agent": build_user_agent()}
  23. def coerce_list(value: Any) -> list[str]:
  24. """Coerce a comma-separated string / list / tuple / set / scalar into a trimmed string list."""
  25. if value is None:
  26. return []
  27. items = value.split(",") if isinstance(value, str) else value if isinstance(value, (list, tuple, set)) else [value]
  28. return [s for s in (str(item).strip() for item in items) if s]