onboarding.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. """Discord onboarding: check a bot token against Discord and walk the user through setup.
  2. The Developer Portal is where Discord setup goes wrong: a token copied from the wrong page, the
  3. Message Content Intent left off (Discord then refuses the bot's connection), an invite URL built
  4. by hand, and Developer Mode just to learn your own user ID. ``GET /applications/@me`` with the
  5. bot token answers all of it at once — the token works, which intents are on, how many servers the
  6. bot is in, and who owns the application — so the CLI wizard and the dashboard/Desktop check route
  7. both read :func:`check_bot_token` instead of asking the user to verify those by hand.
  8. """
  9. from __future__ import annotations
  10. from dataclasses import dataclass
  11. from typing import Optional
  12. from urllib.parse import urlencode
  13. # Every permission the adapter exercises (text, threads, reactions, voice). Named so the integer
  14. # in the invite link and the docs can be re-derived instead of trusted.
  15. INVITE_PERMISSION_BITS = {
  16. "Add Reactions": 6,
  17. "View Channels": 10,
  18. "Send Messages": 11,
  19. "Embed Links": 14,
  20. "Attach Files": 15,
  21. "Read Message History": 16,
  22. "Connect": 20,
  23. "Speak": 21,
  24. "Create Public Threads": 35,
  25. "Send Messages in Threads": 38,
  26. }
  27. INVITE_PERMISSIONS = sum(1 << bit for bit in INVITE_PERMISSION_BITS.values())
  28. _TEAM_MEMBER_ACCEPTED = 2
  29. @dataclass(frozen=True)
  30. class DiscordBotCheck:
  31. app_id: str
  32. bot_name: str
  33. # (user_id, username): the application owner, or every accepted member of the owning team.
  34. owners: tuple[tuple[str, str], ...]
  35. message_content: bool
  36. server_members: bool
  37. server_count: Optional[int]
  38. @property
  39. def invite_url(self) -> str:
  40. # integration_type=0 is a server install, so Discord skips the "add to server or to my
  41. # apps?" question for applications that also allow user installs.
  42. query = urlencode({"client_id": self.app_id, "scope": "bot applications.commands",
  43. "permissions": INVITE_PERMISSIONS, "integration_type": 0})
  44. return f"https://discord.com/oauth2/authorize?{query}"
  45. @property
  46. def bot_settings_url(self) -> str:
  47. return f"https://discord.com/developers/applications/{self.app_id}/bot"
  48. def _owners(app: dict) -> tuple[tuple[str, str], ...]:
  49. team = app.get("team")
  50. if isinstance(team, dict):
  51. return tuple(
  52. (str(m["user"]["id"]), str(m["user"].get("username") or m["user"]["id"]))
  53. for m in team.get("members") or []
  54. if m.get("membership_state") == _TEAM_MEMBER_ACCEPTED and m.get("user", {}).get("id")
  55. )
  56. owner = app.get("owner") or {}
  57. return ((str(owner["id"]), str(owner.get("username") or owner["id"])),) if owner.get("id") else ()
  58. def check_bot_token(token: str) -> DiscordBotCheck:
  59. """Read the application behind ``token``. Raises :class:`DiscordAPIError` (401 = bad token)
  60. or ``OSError`` when Discord is unreachable."""
  61. from tools.discord_tool import _FLAGS_GUILD_MEMBERS, _FLAGS_MESSAGE_CONTENT, _discord_request
  62. app = _discord_request("GET", "/applications/@me", token.strip(), timeout=10)
  63. flags = int(app.get("flags") or 0)
  64. bot = app.get("bot") or {}
  65. count = app.get("approximate_guild_count")
  66. return DiscordBotCheck(
  67. app_id=str(app["id"]),
  68. bot_name=str(bot.get("username") or app.get("name") or app["id"]),
  69. owners=_owners(app),
  70. message_content=bool(flags & _FLAGS_MESSAGE_CONTENT),
  71. server_members=bool(flags & _FLAGS_GUILD_MEMBERS),
  72. server_count=count if isinstance(count, int) else None,
  73. )
  74. # ── CLI wizard (hermes setup / hermes gateway setup) ─────────────────────────
  75. def _clean_discord_user_ids(raw: str) -> list:
  76. """Strip common Discord mention prefixes from a comma-separated ID string."""
  77. cleaned = []
  78. for uid in raw.replace(" ", "").split(","):
  79. uid = uid.strip()
  80. if uid.startswith("<@") and uid.endswith(">"):
  81. uid = uid.lstrip("<@!").rstrip(">")
  82. if uid.lower().startswith("user:"):
  83. uid = uid[5:]
  84. if uid:
  85. cleaned.append(uid)
  86. return cleaned
  87. def _discord_token_shape_error(token: str) -> Optional[str]:
  88. """Reject a Discord bot token that is really the numeric application ID.
  89. Users routinely paste the application ID from the Developer Portal's General Information page
  90. instead of the bot token (Bot page). A real bot token is dot-separated base64 and never purely
  91. numeric, so this is a safe, narrow shape check.
  92. """
  93. if token and token.strip().isdigit():
  94. return ("That looks like a numeric application ID, not a bot token. "
  95. "Paste the bot token from the Discord Developer Portal (Bot page), "
  96. "not the application ID (General Information page).")
  97. return None
  98. def _prompt_discord_bot_token(prompt) -> str:
  99. """Prompt for the bot token, re-prompting once when the answer is a numeric app ID."""
  100. from hermes_cli.cli_output import print_error
  101. token = ""
  102. for _attempt in range(2):
  103. token = prompt("Discord bot token", password=True)
  104. if not token:
  105. return ""
  106. error = _discord_token_shape_error(token)
  107. if error is None:
  108. return token
  109. print_error(error)
  110. # Second consecutive numeric answer: trust the user, keep the value.
  111. return token
  112. def _prompt_checked_token(prompt) -> tuple[str, Optional[DiscordBotCheck]]:
  113. """A token Discord accepted (with its check), an unverifiable one (offline: ``None`` check),
  114. or ``("", None)`` when the user gave up."""
  115. from hermes_cli.cli_output import print_error, print_success, print_warning
  116. from hermes_cli.config import _check_non_ascii_credential
  117. from tools.discord_tool import DiscordAPIError
  118. for _attempt in range(3):
  119. # Same stripping save_env_value applies, done first: a non-ASCII paste can't go in an HTTP header.
  120. token = _check_non_ascii_credential("DISCORD_BOT_TOKEN", _prompt_discord_bot_token(prompt)).strip()
  121. if not token:
  122. return "", None
  123. try:
  124. check = check_bot_token(token)
  125. except ValueError: # whitespace/control characters inside the paste: not a header-safe token
  126. print_error("That isn't a bot token (it contains a line break). Copy it again from the Bot page.")
  127. continue
  128. except DiscordAPIError as exc:
  129. if exc.status == 401:
  130. print_error("Discord rejected that token. On the Bot page click Reset Token, "
  131. "copy the new token and paste it here.")
  132. continue
  133. print_warning(f"Couldn't verify the token (Discord answered {exc.status}); saving it anyway.")
  134. return token, None
  135. except OSError as exc:
  136. print_warning(f"Couldn't reach Discord to verify the token ({exc}); saving it anyway.")
  137. return token, None
  138. print_success(f"Token works: this is the bot \"{check.bot_name}\"")
  139. return token, check
  140. print_error("Discord rejected three tokens in a row; nothing was saved.")
  141. return "", None
  142. def _ensure_message_content_intent(token: str, check: DiscordBotCheck, prompt) -> DiscordBotCheck:
  143. from hermes_cli.cli_output import print_info, print_success, print_warning
  144. from tools.discord_tool import DiscordAPIError
  145. for _attempt in range(5):
  146. if check.message_content:
  147. break
  148. print_warning("Message Content Intent is OFF: Discord will refuse the bot's connection until it's on.")
  149. print_info(f" Turn it on here: {check.bot_settings_url}")
  150. print_info(" (Privileged Gateway Intents → Message Content Intent → Save Changes)")
  151. if prompt("Press Enter once it's saved to re-check, or type 'skip'").strip().lower() == "skip":
  152. return check
  153. try:
  154. check = check_bot_token(token)
  155. except (DiscordAPIError, OSError):
  156. return check
  157. if check.message_content:
  158. print_success("Message Content Intent is on")
  159. if not check.server_members:
  160. print_info("Optional: turn on Server Members Intent on the same page if you want to "
  161. "allow people by username or role instead of user ID.")
  162. return check
  163. def _print_invite(check: DiscordBotCheck) -> None:
  164. from hermes_cli.cli_output import print_info
  165. print()
  166. if check.server_count == 0:
  167. print_info("📨 The bot isn't in any server yet. Open this link to add it to yours:")
  168. else:
  169. print_info("📨 Invite link (adds the bot to a server with the permissions Hermes uses):")
  170. print_info(f" {check.invite_url}")
  171. print_info(" Once you share a server with the bot you can also DM it directly.")
  172. def _prompt_allowlist(check: Optional[DiscordBotCheck], prompt, prompt_yes_no) -> None:
  173. from hermes_cli.cli_output import print_info, print_success
  174. from hermes_cli.config import get_env_value, save_env_value
  175. print()
  176. print_info("🔒 Security: only allowlisted Discord users can talk to your bot.")
  177. # Reconfiguring keeps whoever is already allowed; the wizard only adds.
  178. allowed = _clean_discord_user_ids(get_env_value("DISCORD_ALLOWED_USERS") or "")
  179. if allowed:
  180. print_info(f" Already allowed: {', '.join(allowed)}")
  181. if check and check.owners and not all(uid in allowed for uid, _name in check.owners):
  182. who = ", ".join(f"@{name}" for _uid, name in check.owners)
  183. question = (f"Allow yourself ({who}) to talk to the bot?" if len(check.owners) == 1
  184. else f"Allow your team ({who}) to talk to the bot?")
  185. if prompt_yes_no(question, True):
  186. allowed += [uid for uid, _name in check.owners if uid not in allowed]
  187. print_info(" Others need their Discord user ID: Settings → Advanced → Developer Mode,")
  188. print_info(" then right-click their name → Copy User ID. Usernames work too.")
  189. raw = prompt("Other allowed users (comma-separated, Enter to skip)" if allowed
  190. else "Allowed user IDs or usernames (comma-separated, leave empty for open access)")
  191. extra = _clean_discord_user_ids(raw or "")
  192. allowed += [uid for uid in extra if uid not in allowed]
  193. if check and not check.server_members and any(not uid.isdigit() for uid in extra):
  194. print_info(" Usernames are resolved when the gateway connects, which needs Server Members Intent: "
  195. f"{check.bot_settings_url}")
  196. if allowed:
  197. save_env_value("DISCORD_ALLOWED_USERS", ",".join(allowed))
  198. print_success("Discord allowlist configured")
  199. else:
  200. print_info(
  201. "⚠️ No allowlist set. Discord will deny messages until you set "
  202. "DISCORD_ALLOWED_USERS, DISCORD_ALLOWED_ROLES, DISCORD_ALLOWED_CHANNELS, "
  203. "or DISCORD_ALLOW_ALL_USERS=true for open access."
  204. )
  205. def _check_saved_token(token: str) -> Optional[DiscordBotCheck]:
  206. from tools.discord_tool import DiscordAPIError
  207. try:
  208. return check_bot_token(token) if token else None
  209. except (DiscordAPIError, OSError):
  210. return None
  211. def interactive_setup() -> None:
  212. """Guide the user through Discord bot setup: token (checked live), intents, invite link,
  213. allowlist (defaults to the bot's owner) and home channel. CLI imports are lazy."""
  214. from hermes_cli.cli_output import print_header, print_info, print_success, prompt, prompt_yes_no
  215. from hermes_cli.config import get_env_value, remove_env_value, save_env_value
  216. from hermes_cli.setup_platforms import declines_reconfigure
  217. print_header("Discord")
  218. if declines_reconfigure("Discord", "Reconfigure Discord?", "DISCORD_BOT_TOKEN"):
  219. if not get_env_value("DISCORD_ALLOWED_USERS"):
  220. print_info(
  221. "⚠️ Discord has no user allowlist. With the fail-closed default, "
  222. "messages are denied unless you configure allowed users, roles, "
  223. "or channels, or set DISCORD_ALLOW_ALL_USERS=true."
  224. )
  225. if prompt_yes_no("Add allowed users now?", True):
  226. saved = _check_saved_token(get_env_value("DISCORD_BOT_TOKEN") or "")
  227. _prompt_allowlist(saved, prompt, prompt_yes_no)
  228. return
  229. for line in (
  230. "1. Open https://discord.com/developers/applications → New Application",
  231. "2. Open the Bot page → Reset Token → copy the token",
  232. "Hermes checks the token, the intents and the invite link for you next.",
  233. "Guide: https://hermes-agent.nousresearch.com/docs/user-guide/messaging/discord",
  234. ):
  235. print_info(line)
  236. token, check = _prompt_checked_token(prompt)
  237. if not token:
  238. return
  239. save_env_value("DISCORD_BOT_TOKEN", token)
  240. print_success("Discord token saved")
  241. if check is None:
  242. print_info("Make sure Message Content Intent is on (Bot page → Privileged Gateway Intents), "
  243. "or Discord will refuse the bot's connection.")
  244. else:
  245. check = _ensure_message_content_intent(token, check, prompt)
  246. _print_invite(check)
  247. _prompt_allowlist(check, prompt, prompt_yes_no)
  248. print()
  249. for line in (
  250. "📬 Home Channel: where Hermes delivers cron job results,",
  251. " cross-platform messages, and notifications.",
  252. " Easiest: type /set-home in a Discord channel once the bot is running.",
  253. " Or paste a channel ID (Developer Mode → right-click a channel → Copy Channel ID).",
  254. ):
  255. print_info(line)
  256. home_channel = prompt("Home channel ID (leave empty to set later with /set-home)").strip()
  257. if home_channel:
  258. save_env_value("DISCORD_HOME_CHANNEL", home_channel)
  259. elif remove_env_value("DISCORD_HOME_CHANNEL"):
  260. print_info("Home channel cleared.")