Skip to content

The agent that grows with you

fix(discord): setup survives rich-text pastes, keeps existing allowed users, and states the intent failure correctly

teknium1f785deb26179
diff --git a/.env.example b/.env.example
index 36ac9b529b8..bff3fa2d235 100644
--- a/.env.example
+++ b/.env.example
@@ -379,7 +379,7 @@ BROWSER_INACTIVITY_TIMEOUT=120
# Guide: https://hermes-agent.nousresearch.com/docs/user-guide/messaging/discord
#
# Bot Token - https://discord.com/developers/applications → your app → Bot → Reset Token
-# (Also on the Bot page: turn ON "Message Content Intent", or the bot sees blank messages.)
+# (Also on the Bot page: turn ON "Message Content Intent", or Discord refuses the connection.)
# DISCORD_BOT_TOKEN=
# DISCORD_ALLOWED_USERS= # Comma-separated Discord user IDs (or usernames)
# DISCORD_ALLOWED_ROLES= # Optional: comma-separated role IDs (anyone with the role)
diff --git a/plugins/platforms/discord/onboarding.py b/plugins/platforms/discord/onboarding.py
index ea50cd6ad6a..aa848dbf158 100644
--- a/plugins/platforms/discord/onboarding.py
+++ b/plugins/platforms/discord/onboarding.py
@@ -1,7 +1,7 @@
"""Discord onboarding: check a bot token against Discord and walk the user through setup.
The Developer Portal is where Discord setup goes wrong: a token copied from the wrong page, the
-Message Content Intent left off (the bot connects and sees empty messages), an invite URL built
+Message Content Intent left off (Discord then refuses the bot's connection), an invite URL built
by hand, and Developer Mode just to learn your own user ID. ``GET /applications/@me`` with the
bot token answers all of it at once — the token works, which intents are on, how many servers the
bot is in, and who owns the application — so the CLI wizard and the dashboard/Desktop check route
@@ -137,13 +137,18 @@ def _prompt_checked_token(prompt) -> tuple[str, Optional[DiscordBotCheck]]:
"""A token Discord accepted (with its check), an unverifiable one (offline: ``None`` check),
or ``("", None)`` when the user gave up."""
from hermes_cli.cli_output import print_error, print_success, print_warning
+ from hermes_cli.config import _check_non_ascii_credential
from tools.discord_tool import DiscordAPIError
for _attempt in range(3):
- token = _prompt_discord_bot_token(prompt).strip()
+ # Same stripping save_env_value applies, done first: a non-ASCII paste can't go in an HTTP header.
+ token = _check_non_ascii_credential("DISCORD_BOT_TOKEN", _prompt_discord_bot_token(prompt)).strip()
if not token:
return "", None
try:
check = check_bot_token(token)
+ except ValueError: # whitespace/control characters inside the paste: not a header-safe token
+ print_error("That isn't a bot token (it contains a line break). Copy it again from the Bot page.")
+ continue
except DiscordAPIError as exc:
if exc.status == 401:
print_error("Discord rejected that token. On the Bot page click Reset Token, "
@@ -166,7 +171,7 @@ def _ensure_message_content_intent(token: str, check: DiscordBotCheck, prompt) -
for _attempt in range(5):
if check.message_content:
break
- print_warning("Message Content Intent is OFF: the bot would receive every message with the text blank.")
+ print_warning("Message Content Intent is OFF: Discord will refuse the bot's connection until it's on.")
print_info(f" Turn it on here: {check.bot_settings_url}")
print_info(" (Privileged Gateway Intents → Message Content Intent → Save Changes)")
if prompt("Press Enter once it's saved to re-check, or type 'skip'").strip().lower() == "skip":
@@ -196,16 +201,19 @@ def _print_invite(check: DiscordBotCheck) -> None:
def _prompt_allowlist(check: Optional[DiscordBotCheck], prompt, prompt_yes_no) -> None:
from hermes_cli.cli_output import print_info, print_success
- from hermes_cli.config import save_env_value
+ from hermes_cli.config import get_env_value, save_env_value
print()
print_info("🔒 Security: only allowlisted Discord users can talk to your bot.")
- allowed: list = []
- if check and check.owners:
+ # Reconfiguring keeps whoever is already allowed; the wizard only adds.
+ allowed = _clean_discord_user_ids(get_env_value("DISCORD_ALLOWED_USERS") or "")
+ if allowed:
+ print_info(f" Already allowed: {', '.join(allowed)}")
+ if check and check.owners and not all(uid in allowed for uid, _name in check.owners):
who = ", ".join(f"@{name}" for _uid, name in check.owners)
question = (f"Allow yourself ({who}) to talk to the bot?" if len(check.owners) == 1
else f"Allow your team ({who}) to talk to the bot?")
if prompt_yes_no(question, True):
- allowed = [uid for uid, _name in check.owners]
+ allowed += [uid for uid, _name in check.owners if uid not in allowed]
print_info(" Others need their Discord user ID: Settings → Advanced → Developer Mode,")
print_info(" then right-click their name → Copy User ID. Usernames work too.")
raw = prompt("Other allowed users (comma-separated, Enter to skip)" if allowed
@@ -267,7 +275,7 @@ def interactive_setup() -> None:
print_success("Discord token saved")
if check is None:
print_info("Make sure Message Content Intent is on (Bot page → Privileged Gateway Intents), "
- "or the bot will see blank messages.")
+ "or Discord will refuse the bot's connection.")
else:
check = _ensure_message_content_intent(token, check, prompt)
_print_invite(check)
diff --git a/tests/gateway/test_discord_plugin_setup.py b/tests/gateway/test_discord_plugin_setup.py
index bc341003536..34b35f312f2 100644
--- a/tests/gateway/test_discord_plugin_setup.py
+++ b/tests/gateway/test_discord_plugin_setup.py
@@ -20,11 +20,17 @@ def _offline(_token):
raise OSError("offline")
-def _patch_setup_io(monkeypatch, prompts, saved, removed, existing, infos=None, yes=False, check=_offline):
+def _patch_setup_io(monkeypatch, prompts, saved, removed, existing, infos=None, yes=False, check=_offline,
+ writes=None):
prompt_iter = iter(prompts)
monkeypatch.setattr(onboarding, "check_bot_token", check)
monkeypatch.setattr(config_mod, "get_env_value", lambda key: existing.get(key, ""))
- monkeypatch.setattr(config_mod, "save_env_value", lambda k, v: saved.update({k: v}))
+ def _save(key, value):
+ if writes is not None:
+ writes.append((key, value))
+ saved[key] = value
+
+ monkeypatch.setattr(config_mod, "save_env_value", _save)
def _remove(key):
removed.append(key)
@@ -44,9 +50,9 @@ def _patch_setup_io(monkeypatch, prompts, saved, removed, existing, infos=None,
# Discord prompts: bot_token (password), allowed_users, home_channel.
-_PROMPTS_NONEMPTY = ["«redacted:discord-bot-token»", "", "123456789012345678"]
-_PROMPTS_BLANK = ["«redacted:discord-bot-token»", "", ""]
-_PROMPTS_WHITESPACE = ["«redacted:discord-bot-token»", "", " "]
+_PROMPTS_NONEMPTY = ["fake-bot-token.part2.part3", "", "123456789012345678"]
+_PROMPTS_BLANK = ["fake-bot-token.part2.part3", "", ""]
+_PROMPTS_WHITESPACE = ["fake-bot-token.part2.part3", "", " "]
class TestDiscordHomeChannelClear:
@@ -68,24 +74,26 @@ class TestDiscordHomeChannelClear:
class TestDiscordTokenCheckedWithDiscord:
- """The wizard asks Discord about the pasted token: a rejected token is never saved, and an
- accepted one yields the invite link and an allowlist seeded with the bot's owner."""
+ """The wizard asks Discord about the pasted token: a rejected token is never written, and an
+ accepted one yields the invite link and adds the bot's owner to whoever is already allowed."""
- def test_rejected_token_reprompts_and_owner_is_allowlisted(self, monkeypatch, tmp_path):
+ def test_rejected_token_never_written_and_owner_added_to_allowlist(self, monkeypatch, tmp_path):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
standin = DiscordStandin().start()
try:
monkeypatch.setattr(discord_tool, "DISCORD_API_BASE", standin.api_base)
- saved, removed, infos, errors = {}, [], [], []
- _patch_setup_io(monkeypatch, ["not.the.token", TOKEN, "", ""], saved, removed,
- existing={}, infos=infos, yes=True, check=_real_check)
+ saved, removed, infos, errors, writes = {}, [], [], [], []
+ # A rejected token, then the real one pasted with rich-text curly quotes around it.
+ prompts = ["not.the.token", f"\u201c{TOKEN}\u201d", "", ""]
+ _patch_setup_io(monkeypatch, prompts, saved, removed, existing={"DISCORD_ALLOWED_USERS": "999"},
+ infos=infos, yes=True, check=_real_check, writes=writes)
monkeypatch.setattr(cli_output_mod, "print_error", lambda *a, **_kw: errors.append(" ".join(map(str, a))))
interactive_setup()
finally:
standin.stop()
- assert saved["DISCORD_BOT_TOKEN"] == TOKEN
assert any("rejected" in e for e in errors)
- assert saved["DISCORD_ALLOWED_USERS"] == "1" # the stand-in application's owner
+ assert [v for k, v in writes if k == "DISCORD_BOT_TOKEN"] == [TOKEN]
+ assert saved["DISCORD_ALLOWED_USERS"] == "999,1" # existing entry kept, stand-in owner added
invite = next(line.strip() for line in infos if "oauth2/authorize" in line)
assert f"client_id={APP_ID}" in invite and f"permissions={onboarding.INVITE_PERMISSIONS}" in invite
@@ -97,7 +105,7 @@ class TestDiscordTokenShapeGuard:
def test_numeric_app_id_reprompts_then_accepts_real_token(self, monkeypatch, tmp_path):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
saved, removed, errors = {}, [], []
- real_token = "«redacted»." + "part2.part3"
+ real_token = "fake-bot-token." + "part2.part3"
_patch_setup_io(
monkeypatch,
["1234567890123456789", real_token, "", ""],
diff --git a/website/docs/user-guide/messaging/discord.md b/website/docs/user-guide/messaging/discord.md
index 5a4c8c62830..d458cc253f5 100644
--- a/website/docs/user-guide/messaging/discord.md
+++ b/website/docs/user-guide/messaging/discord.md
@@ -136,7 +136,7 @@ If you prefer to keep your bot private (Public Bot = OFF), you **must** use the
## Step 3: Enable Privileged Gateway Intents
-This is the most critical step in the entire setup. Without the correct intents enabled, your bot will connect to Discord but **will not be able to read message content**.
+This is the most critical step in the entire setup. Hermes always asks Discord for message content, so if **Message Content Intent** is off, Discord **refuses the bot's connection** and the bot never comes online.
On the **Bot** page, scroll down to **Privileged Gateway Intents**. You'll see three toggles:
@@ -148,11 +148,11 @@ On the **Bot** page, scroll down to **Privileged Gateway Intents**. You'll see t
**Enable both Server Members Intent and Message Content Intent** by toggling them **ON**.
-- Without **Message Content Intent**, your bot receives message events but the message text is empty — the bot literally cannot see what you typed.
+- Without **Message Content Intent**, Discord rejects the connection; `gateway.log` shows "Discord rejected the connection because privileged Gateway Intents are not enabled".
- Without **Server Members Intent**, the bot cannot resolve usernames for the allowed users list and may fail to identify who is messaging it.
:::warning[This is the #1 reason Discord bots don't work]
-If your bot is online but never responds to messages, the **Message Content Intent** is almost certainly disabled. Go back to the [Developer Portal](https://discord.com/developers/applications), select your application → Bot → Privileged Gateway Intents, and make sure **Message Content Intent** is toggled ON. Click **Save Changes**.
+If your bot stays offline and `gateway.log` mentions privileged Gateway Intents, the **Message Content Intent** is disabled. Go back to the [Developer Portal](https://discord.com/developers/applications), select your application → Bot → Privileged Gateway Intents, and make sure **Message Content Intent** is toggled ON. Click **Save Changes**.
:::
**Regarding server count:**
@@ -863,7 +863,7 @@ Refreshing the directory (`/channels refresh` on platforms that expose it, or a
### Bot is online but not responding to messages
-**Cause**: Either Message Content Intent is disabled, or Discord auth is failing closed because no access policy is configured.
+**Cause**: Usually Discord auth is failing closed because no access policy is configured. (A disabled Message Content Intent keeps the bot offline instead; see Step 3.)
**Fix**: