register.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. """QQ Bot platform plugin: interactive setup and registry entry.
  2. The adapter stays in ``adapter.py``. This module is the only thing ``__init__``
  3. exports, so importing the package registers the platform and does not open a portal
  4. connection.
  5. """
  6. from __future__ import annotations
  7. from gateway.platforms._shared import env_is_connected
  8. from gateway.platforms._shared import config_connected_extra
  9. from gateway.platforms.send_targets import StandaloneSendPolicy
  10. from .adapter import QQAdapter, check_qq_requirements
  11. _env_configured = env_is_connected("QQ_APP_ID", "QQ_CLIENT_SECRET")
  12. def is_connected(pconfig) -> bool:
  13. """Both credentials from ``extra`` (config.yaml) or the profile env / ``.env``."""
  14. extra = getattr(pconfig, "extra", None) or {}
  15. if str(extra.get("app_id") or "").strip() and str(extra.get("client_secret") or "").strip():
  16. return True
  17. return _env_configured(pconfig)
  18. async def standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None,
  19. force_document=False, caption=None):
  20. """Late-import the REST sender so cron delivery works without a live gateway process."""
  21. from .send import send_qqbot
  22. return await send_qqbot(
  23. pconfig, chat_id, message, media_files=media_files, caption=caption,
  24. thread_id=thread_id, force_document=force_document,
  25. )
  26. def setup_qqbot() -> None:
  27. """Interactive setup: scan-to-configure or manual App ID / App Secret."""
  28. from hermes_cli.cli_output import print_info, print_success, print_warning
  29. from hermes_cli.config import save_env_value
  30. from hermes_cli.gateway_setup_wizard import (
  31. confirm_reconfigure, offer_home_channel, print_setup_header, prompt_csv, save_env_values,
  32. )
  33. from hermes_cli.setup import prompt, prompt_choice, prompt_yes_no
  34. print_setup_header("🐧 QQ Bot")
  35. if not confirm_reconfigure("QQ Bot", "QQ_APP_ID", "QQ_CLIENT_SECRET"):
  36. return
  37. print()
  38. method_choices = [
  39. "Scan QR code to add bot automatically (recommended)",
  40. "Enter existing App ID and App Secret manually",
  41. ]
  42. credentials = None
  43. if prompt_choice(" How would you like to set up QQ Bot?", method_choices, 0) == 0:
  44. try:
  45. from .onboard import qr_register
  46. credentials = qr_register()
  47. except KeyboardInterrupt:
  48. print()
  49. print_warning(" QQ Bot setup cancelled.")
  50. return
  51. if not credentials:
  52. print_info(" QR setup did not complete. Continuing with manual input.")
  53. if not credentials:
  54. print()
  55. print_info(" Go to https://q.qq.com to register a QQ Bot application.")
  56. print_info(" Note your App ID and App Secret from the application page.")
  57. print()
  58. app_id = prompt(" App ID", password=False)
  59. if not app_id:
  60. print_warning(" Skipped — QQ Bot won't work without an App ID.")
  61. return
  62. app_secret = prompt(" App Secret", password=True)
  63. if not app_secret:
  64. print_warning(" Skipped — QQ Bot won't work without an App Secret.")
  65. return
  66. credentials = {"app_id": app_id.strip(), "client_secret": app_secret.strip(), "user_openid": ""}
  67. save_env_value("QQ_APP_ID", credentials["app_id"])
  68. save_env_value("QQ_CLIENT_SECRET", credentials["client_secret"])
  69. user_openid = credentials.get("user_openid", "")
  70. print()
  71. access_choices = [
  72. "Use DM pairing approval (recommended)",
  73. "Allow all direct messages",
  74. "Only allow listed user OpenIDs",
  75. ]
  76. access_idx = prompt_choice(" How should direct messages be authorized?", access_choices, 0)
  77. if access_idx == 0:
  78. save_env_value("QQ_ALLOW_ALL_USERS", "false")
  79. allowed = ""
  80. if user_openid:
  81. print()
  82. if prompt_yes_no(f" Add yourself ({user_openid}) to the allow list?", True):
  83. allowed = user_openid
  84. print_success(f" Allow list set to {user_openid}")
  85. save_env_value("QQ_ALLOWED_USERS", allowed)
  86. print_success(" DM pairing enabled.")
  87. print_info(" Unknown users can request access; approve with `hermes pairing approve`.")
  88. elif access_idx == 1:
  89. save_env_values(QQ_ALLOW_ALL_USERS="true", QQ_ALLOWED_USERS="")
  90. print_warning(" Open DM access enabled for QQ Bot.")
  91. else:
  92. allowlist = prompt_csv(" Allowed user OpenIDs (comma-separated)", user_openid or "")
  93. save_env_values(QQ_ALLOW_ALL_USERS="false", QQ_ALLOWED_USERS=allowlist)
  94. print_success(" Allowlist saved.")
  95. print()
  96. if user_openid:
  97. offer_home_channel("QQBOT_HOME_CHANNEL", user_openid, "your QQ user ID")
  98. else:
  99. home_channel = prompt(" Home channel OpenID (for cron/notifications, or empty)", password=False)
  100. if home_channel:
  101. save_env_value("QQBOT_HOME_CHANNEL", home_channel.strip())
  102. print_success(f" Home channel set to {home_channel.strip()}")
  103. print()
  104. print_success("🐧 QQ Bot configured!")
  105. print_info(f" App ID: {credentials['app_id']}")
  106. # System-prompt platform hint (PlatformEntry.platform_hint); cached-prompt bytes, keep stable.
  107. _PLATFORM_HINT = (
  108. "You are on QQ, a popular Chinese messaging platform. QQ supports markdown formatting "
  109. "and emoji. You can send media files natively: include MEDIA:/absolute/path/to/file in "
  110. "your response. Images are sent as native photos, and other files arrive as downloadable documents."
  111. )
  112. def register(ctx) -> None:
  113. from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)
  114. ctx.register_platform(
  115. standalone_send=StandaloneSendPolicy(label="QQ Bot", media=True, captionable=True, text_direct=True),
  116. name="qqbot",
  117. dashboard_description="Connect Hermes to a QQ Bot from the QQ Open Platform.",
  118. docs_url="https://q.qq.com",
  119. dashboard_env_vars=("QQ_APP_ID", "QQ_CLIENT_SECRET", "QQ_ALLOWED_USERS"),
  120. label="QQ Bot",
  121. adapter_factory=QQAdapter,
  122. check_fn=check_qq_requirements,
  123. is_connected=is_connected,
  124. config_connected_fn=config_connected_extra("app_id", "client_secret"),
  125. required_env=["QQ_APP_ID", "QQ_CLIENT_SECRET"],
  126. install_hint="QQBot: aiohttp/httpx missing or QQ_APP_ID/QQ_CLIENT_SECRET not configured",
  127. setup_fn=setup_qqbot,
  128. emoji="🐧",
  129. cron_deliver_env_var="QQBOT_HOME_CHANNEL",
  130. standalone_sender_fn=standalone_send,
  131. # QQ's dm/group policy is YAML-only (no env var); QQ_ALLOW_ALL_USERS is still the opt-in.
  132. platform_hint=_PLATFORM_HINT,
  133. env_overrides=gateway_env.ENV_OVERRIDES,
  134. env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS, **gateway_env.AUTHZ,
  135. )