JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(discord): support reaction, direct message and proper session_id parsing on front-end
SushiNinja426b053fe551
diff --git a/docs/assets/images/discord/1_create_new_app.png b/docs/assets/images/discord/1_create_new_app.pngnew file mode 100644index 0000000000..f9c2798ff3Binary files /dev/null and b/docs/assets/images/discord/1_create_new_app.png differdiff --git a/docs/assets/images/discord/2_reset_bot_token.png b/docs/assets/images/discord/2_reset_bot_token.pngnew file mode 100644index 0000000000..c07e4bfa55Binary files /dev/null and b/docs/assets/images/discord/2_reset_bot_token.png differdiff --git a/docs/assets/images/discord/3_set_required_intent.png b/docs/assets/images/discord/3_set_required_intent.pngnew file mode 100644index 0000000000..e80359de17Binary files /dev/null and b/docs/assets/images/discord/3_set_required_intent.png differdiff --git a/docs/assets/images/discord/4_set_guild_install_scope_and_permissions.png b/docs/assets/images/discord/4_set_guild_install_scope_and_permissions.pngnew file mode 100644index 0000000000..fc7f7cf584Binary files /dev/null and b/docs/assets/images/discord/4_set_guild_install_scope_and_permissions.png differdiff --git a/docs/assets/images/discord/5_select_install_methods_and_copy_setup_link.png b/docs/assets/images/discord/5_select_install_methods_and_copy_setup_link.pngnew file mode 100644index 0000000000..31618d1373Binary files /dev/null and b/docs/assets/images/discord/5_select_install_methods_and_copy_setup_link.png differdiff --git a/docs/discord.md b/docs/discord.mdnew file mode 100644index 0000000000..8f04a95bc9--- /dev/null+++ b/docs/discord.md@@ -0,0 +1,186 @@+# Discord 频道接入说明++本文说明如何在 [Discord 开发者平台](https://discord.com/developers/applications) 创建应用与 Bot、开启所需 Intent 与安装方式,并在 JiuwenClaw 的**频道管理**中完成配置。++## 本仓库中的实现++- Python 频道:`jiuwenclaw/channel/discord_channel.py`(基于 discord.py)+- 运行时配置:`config.yaml` 中的 `channels/discord`,或通过 Web 端 **频道管理** → Discord 保存++Bot 使用 **Bot Token** 登录,可在配置的服务器频道与/或私信(DM)中收发消息(也可通过 `block_dm` 关闭私信)。处理过程中会对用户消息尝试添加 👀 反应,与其它频道行为一致。++## 前置条件++- 已注册 Discord 账号+- 具备将 Bot 拉入服务器的权限;若启用用户安装,用户也可通过安装链接使用私信(取决于你在后台的安装设置)++---++## 1. 创建应用++1. 打开 [https://discord.com/developers/applications](https://discord.com/developers/applications)。+2. 点击 **New Application**,填写名称并创建。++++后续 **OAuth2 / 安装** 与 **Bot** 用户均在此应用下配置。++---++## 2. 获取 Bot Token(重置并复制)++1. 左侧进入 **Bot**。+2. 在 **Token** 区域点击 **Reset Token** 并确认。+3. **立即复制 Token** 并妥善保存;重置后 Discord 通常只完整展示一次。++++**安全提示**++- Token 等同于密码,泄露后他人可操控你的 Bot。+- 仅填入 JiuwenClaw 的 Discord 配置或 `config.yaml`,勿提交到代码仓。+- 若怀疑泄露,在同一位置再次 **Reset Token**。++该值对应 JiuwenClaw 中的 **`bot_token`**。++---++## 3. 开启 Message Content Intent++JiuwenClaw 需要读取用户消息的**文本内容**。Discord 要求通过「特权网关 Intent」显式开启。++1. 仍在 **Bot** 页面。+2. 在 **Privileged Gateway Intents** 中打开 **MESSAGE CONTENT INTENT**。+3. 若页面有保存提示,请保存。++++未开启时,Bot 可能在线但无法读取普通消息的文本内容。++---++## 4. 服务器安装:权限范围与 Bot 权限++配置 Bot 被安装进服务器后的能力。JiuwenClaw 典型需要:++- 在目标频道**读取**消息+- **发送**消息(回复用户)+- **读取消息历史**(上下文)+- **添加反应**(例如处理中的 👀)+- **使用应用程序命令**(若你另行使用斜杠命令,可按需勾选)++在开发者后台的 **Installation** 或 **OAuth2 → URL Generator** 等入口(界面可能随 Discord 更新调整)中:++- 勾选 **`bot`** 等所需 **Scopes**(若使用应用命令可勾选 **`applications.commands`**)。+- 勾选与上表一致的 **Bot Permissions**。+- 下方截图中显示了推荐的权限配置,必选内容已标出。++++请以截图与上述能力为准;若菜单名称与截图略有差异,选择等效项即可。++---++## 5. 安装方式与安装 / 设置链接++选择用户或管理员如何安装应用:++- **Guild install(服务器安装)** — 将 Bot 加入指定服务器,需要可分享的安装或邀请链接。+- **User install(用户安装)** — 允许用户为**私信(DM)**安装应用(适合主要走私聊、不固定某个频道)。++在门户中复制生成的 **URL** 或 **Install link**,在浏览器中打开完成授权。++++安装完成后:++- **服务器场景**:将 Bot 放入 JiuwenClaw 要监听的频道(见下文 `guild_id` / `channel_id`)。+- **私信场景**:用户可与 Bot 打开私聊(除非在 JiuwenClaw 中开启 **`block_dm`**)。++---++## 6. JiuwenClaw 需要的 ID++| 配置项 | 获取方式 |+|--------|----------|+| **Application ID** | **General Information** → **APPLICATION ID**,复制。对应 **`application_id`**(建议填写)。 |+| **Guild ID(服务器 ID)** | Discord 用户设置中开启 **开发者模式**(高级)。**右键服务器图标** → **复制服务器 ID**。对应 **`guild_id`**。若仅私信、不限制服务器可留空。 |+| **Channel ID(频道 ID)** | **右键文字频道** → **复制频道 ID**。对应 **`channel_id`**。若仅私信等场景可按需留空。 |++当 **`guild_id`** 与 **`channel_id`** 均填写时,只处理**该服务器下该频道**内的消息;**私信仍可收发**,除非将 **`block_dm`** 设为 `true`。++有一个快速取得 `guild_id` 与 `channel_id` 的小技巧。在 Discord 网页版中打开目标文字频道,并查看浏览器地址栏,URL 格式一般为:+```+https://discord.com/channels/<guild_id>/<channel_id>+```++---++## 7. 在 JiuwenClaw 频道管理中配置++在 Web 端打开 **频道管理** → **Discord** 填写并保存,或直接编辑:++`~/.jiuwenclaw/config/config.yaml`(路径因环境可能不同)++示例:++```yaml+channels:+ discord:+ bot_token: "你的Bot_Token"+ application_id: "你的Application_ID"+ guild_id: "你的服务器ID" # 仅私信场景可留空+ channel_id: "你的频道ID" # 按需留空+ block_dm: false # true 表示不处理私信+ allow_from: [] # 空为不限制;否则填 Discord 用户 ID 列表+ enabled: true+```++| 字段 | 说明 |+|------|------|+| `bot_token` | **必填**,来自第 2 步。 |+| `application_id` | **General Information** 中的应用 ID。 |+| `guild_id` | 限定服务器;仅 DM 时可不填。 |+| `channel_id` | 限定频道;可与 DM 并存时按需填写。 |+| `block_dm` | `true` 时忽略所有私信。 |+| `allow_from` | 用户白名单;空表示不限制(仍需能向 Bot 发消息)。 |+| `enabled` | 是否启用 Discord 频道。 |++---++## 8. 验证++1. 确认 Bot 在服务器中在线,或用户侧可与 Bot 私信。+2. 在已配置频道或私信中发送一条短消息。+3. 若 Bot 在该场景下有 **添加反应** 权限,用户消息上应出现 👀;模型与下游配置正确时,应收到智能体回复。++---++## 故障排查++### Bot 在线但没有回复++- 确认已开启 **MESSAGE CONTENT INTENT**。+- 确认 **`enabled: true`** 且 **`bot_token`** 正确。+- 检查 **`guild_id` / `channel_id`**:二者都填时,仅监听该频道内消息。+- 若配置了 **`allow_from`**,当前用户的 Discord 用户 ID 须在列表中(或改为空列表)。++### 无法添加 👀 反应++- 在该频道为 Bot 所在角色勾选 **添加反应(Add Reactions)** 权限(或通过频道权限覆盖)。++### 私信不可用++- 若需用户私信使用,需要在Discord进行 **User install**。+- JiuwenClaw 中确认 **`block_dm`** 为 `false`。+- 用户安装后通常需在 Bot 资料页选择 **发消息** 打开 DM。++### 模型或下游 API 报错++Discord 连通与模型配置相互独立。若出现模型 HTTP 错误,请检查 `.env` 与模型相关配置并重启应用(与其它频道文档说明一致)。++---++## 相关文档++- 简要字段说明:[频道.md](频道.md) 中的 Discord 小节diff --git a/docs/discord_en.md b/docs/discord_en.mdnew file mode 100644index 0000000000..839dc368de--- /dev/null+++ b/docs/discord_en.md@@ -0,0 +1,186 @@+# Discord Channel Setup++This guide walks through creating a Discord application and bot in the [Discord Developer Portal](https://discord.com/developers/applications), enabling the intents and install options JiuwenClaw needs, and wiring the bot into **Channel Management** in JiuwenClaw.++## What This Repo Uses++- Python channel: `jiuwenclaw/channel/discord_channel.py` (discord.py)+- Runtime config: `channels/discord` in your `config.yaml` (or the web UI **Channel Management** → Discord)++The bot connects with your **Bot Token**, receives messages in configured guild channels and/or DMs (unless you turn off DMs), and can add a 👀 reaction while processing, similar to other channels.++## Prerequisites++- A Discord account+- Permission to add bots to a server (or users can install the app for DMs, depending on your install settings)++---++## 1. Create an application++1. Open [https://discord.com/developers/applications](https://discord.com/developers/applications).+2. Click **New Application**, choose a name, and create it.++++You will use this application for both **OAuth2 / installation** and the **Bot** user.++---++## 2. Get the Bot Token (reset and copy)++1. In the left sidebar, open **Bot**.+2. Under **Token**, use **Reset Token** and confirm.+3. **Copy the token immediately** and store it somewhere safe. Discord shows it only once after a reset.++++**Security**++- Treat the token like a password. Anyone with it can control your bot.+- Paste it into JiuwenClaw’s Discord settings or `config.yaml`; do not commit it to git.+- If it leaks, reset the token again in the same place.++You will map this value to **`bot_token`** in JiuwenClaw.++---++## 3. Enable Message Content Intent++JiuwenClaw reads the text of messages your bot receives. Discord requires an explicit privileged intent for that.++1. Stay on the **Bot** page.+2. Under **Privileged Gateway Intents**, turn on **MESSAGE CONTENT INTENT**.+3. Save changes if the portal prompts you.++++Without this, the bot may connect but will not see normal message text content.++---++## 4. Guild install: scopes and bot permissions++Configure how the bot is installed into servers and what it can do there. Typical needs for JiuwenClaw:++- **Read** messages in the channels you care about+- **Send** messages (replies)+- **Read message history** (context)+- **Add reactions** (e.g. 👀 while processing)+- **Use slash commands** (optional, if you use them elsewhere)++In the Developer Portal, use the installation / OAuth2 tools (e.g. **Installation** or **OAuth2 → URL Generator**, depending on the current UI) to select:++- Scopes such as **`bot`** (and **`applications.commands`** if you use application commands).+- Bot permissions that match the list above.+- Screenshot attached below shows the recommended permissions, the mandatory ones are marked.++++Exact labels may move between **Installation**, **OAuth2**, and **Bot** sections as Discord updates the portal; align your choices with the screenshot and the capabilities above.++---++## 5. Install methods and setup / invite link++Choose how users or admins can add the app:++- **Guild install** — add the bot to a server (you need a shareable install or invite URL).+- **User install** — allows users to add the app for **direct messages** (useful if you want DM-only usage without a fixed guild channel).++Copy the **generated URL** or **Install link** from the portal and open it in a browser to complete authorization.++++After installation:++- For **server** use: place the bot in a channel JiuwenClaw will listen to (see `guild_id` / `channel_id` below).+- For **DM** use: users can open a private message with the bot (if not blocked by **`block_dm`** in JiuwenClaw).++---++## 6. IDs you need for JiuwenClaw++| Value | Where to find it |+|--------|------------------|+| **Application ID** | **General Information** → **APPLICATION ID** (copy). Maps to **`application_id`** (optional but recommended). |+| **Guild ID** | Discord: enable **Developer Mode** (Settings → App Settings → Advanced). Right‑click the **server icon** → **Copy Server ID**. Maps to **`guild_id`**. Leave empty if you only use DMs and do not restrict to one server. |+| **Channel ID** | Right‑click the **text channel** → **Copy Channel ID**. Maps to **`channel_id`**. Leave empty to rely on DM-only or broader routing per your deployment. |++If both **`guild_id`** and **`channel_id`** are set, the bot handles messages **only in that channel** on that server, while **DMs can still work** unless **`block_dm`** is enabled.++A trick to get `guild_id` and `channel_id` easily is to check the url to a channel, since the format would be:+```+https://discord.com/channels/<guild_id>/<channel_id>+```++---++## 7. Configure Discord in JiuwenClaw (Channel Management)++Open the JiuwenClaw web UI → **Channel Management** → **Discord**, or edit:++`~/.jiuwenclaw/config/config.yaml` (path may differ on your machine)++Example:++```yaml+channels:+ discord:+ bot_token: "YOUR_BOT_TOKEN"+ application_id: "YOUR_APPLICATION_ID"+ guild_id: "YOUR_GUILD_ID" # optional if DM-only+ channel_id: "YOUR_CHANNEL_ID" # optional if DM-only+ block_dm: false # set true to ignore DMs+ allow_from: [] # empty = all users; else list Discord user IDs+ enabled: true+```++| Field | Purpose |+|--------|---------|+| `bot_token` | **Required.** From step 2. |+| `application_id` | Application ID from **General Information**. |+| `guild_id` | Restrict handling to one server; optional for DM-focused setups. |+| `channel_id` | Restrict handling to one channel in that server; optional with DMs. |+| `block_dm` | If `true`, ignore direct messages. |+| `allow_from` | Allow-list of Discord user IDs; empty allows everyone who can message the bot. |+| `enabled` | Turn the Discord channel on. |++---++## 8. Verify++1. Ensure the bot is online in the server or available in DMs.+2. Send a short message in the configured channel or in DM.+3. You should see a 👀 reaction on the user message (if the bot has **Add Reactions** in that context), then a reply from your agent pipeline when the model and tools are configured correctly.++---++## Troubleshooting++### Bot online but no replies++- Confirm **MESSAGE CONTENT INTENT** is enabled.+- Confirm **`enabled: true`** and **`bot_token`** are correct.+- Check **`guild_id` / `channel_id`**: messages outside the configured channel are ignored when those are set.+- If using **`allow_from`**, your Discord user ID must be listed (or leave the list empty).++### Cannot add 👀 reaction++- Grant the bot **Add Reactions** in the channel (channel overrides or role permissions).++### DMs not working++- Perform **User install** in Discord.+- In JiuwenClaw, ensure **`block_dm`** is `false`.+- Users may need to open the bot’s profile and **Message** after installing.++### LLM or downstream errors++Discord delivery is separate from model configuration. If you see HTTP errors from the model API, fix `.env` / model settings and restart the app (same idea as other channels).++---++## Related++- Short overview and field table: [频道.md](频道.md) (Discord section)diff --git "a/docs/\351\242\221\351\201\223.md" "b/docs/\351\242\221\351\201\223.md"index c4ccab7198..df0c4b32f0 100644--- "a/docs/\351\242\221\351\201\223.md"+++ "b/docs/\351\242\221\351\201\223.md"@@ -424,10 +424,13 @@ channels:当前版本已经支持 Discord 频道接入。在「频道管理」中配置并启用 Discord Bot,也可以手动编辑 `config.yaml`。+**分步图文(开发者后台创建 Bot、Intent、安装链接、频道管理)见 [discord.md](discord.md)。**+- `bot_token`- `application_id`- `guild_id`- `channel_id`+- `block_dm`- `allow_from`- `enabled`@@ -440,11 +443,12 @@ channels:application_id: "Application ID"guild_id: "目标服务器 Guild ID"channel_id: "目标频道 Channel ID"+ block_dm: falseallow_from: []- enabled: false+ enabled: true``````-## 使用说明+## 简略使用说明1. 在 Discord Developer Portal 创建 Bot,获取 `bot_token`。2. 在 Bot 页签开启 **Message Content Intent**。@@ -459,5 +463,6 @@ channels:| `application_id` | 应用 ID(可选,建议填写) || `guild_id` | 仅监听指定服务器(可选,留空表示不限制) || `channel_id` | 仅监听/回复指定频道(可选,留空按消息上下文回复) |+| `block_dm` | 为 `true` 时不处理私信(DM) || `allow_from` | 允许访问的 Discord 用户 ID 列表,空列表表示允许所有 || `enabled` | 是否启用 Discord 频道 |diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex 09bbb87db8..463d5beec7 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -1743,6 +1743,7 @@ async def _run() -> None:guild_id=str(discord_conf.get("guild_id") or "").strip(),channel_id=str(discord_conf.get("channel_id") or "").strip(),allow_from=discord_conf.get("allow_from") or [],+ block_dm=(str(discord_conf.get("block_dm")).lower() in ["true", "1"]) or False,)discord_channel = DiscordChannel(discord_config, _DummyBus())channel_manager.register_channel(discord_channel)diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex 7dbb2ac319..e465b44402 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -473,6 +473,7 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: stguild_id=str(discord_conf.get("guild_id") or "").strip(),channel_id=str(discord_conf.get("channel_id") or "").strip(),allow_from=discord_conf.get("allow_from") or [],+ block_dm=(str(discord_conf.get("block_dm")).lower() in ["true", "1"]) or False,)discord_channel = DiscordChannel(discord_config, _DummyBus())channel_manager.register_channel(discord_channel)diff --git a/jiuwenclaw/channel/discord_channel.py b/jiuwenclaw/channel/discord_channel.pyindex 4abe2c59af..ee4d66ed56 100644--- a/jiuwenclaw/channel/discord_channel.py+++ b/jiuwenclaw/channel/discord_channel.py@@ -1,9 +1,7 @@"""Discord channel implementation based on discord.py."""-from __future__ import annotations--import loggingimport asyncio+import loggingimport timefrom dataclasses import dataclass, fieldfrom typing import Any, Callable@@ -29,6 +27,7 @@ class DiscordChannelConfig:application_id: str = ""guild_id: str = ""channel_id: str = ""+ block_dm: bool = Falseallow_from: list[str] = field(default_factory=list)@@ -71,6 +70,7 @@ class DiscordChannel(BaseChannel):intents = discord.Intents.default()intents.guilds = Trueintents.messages = True+ intents.dm_messages = Trueintents.message_content = Trueapp_id: int | None = None@@ -154,21 +154,37 @@ class DiscordChannel(BaseChannel):if channel is None:return+ author_name = str(getattr(message.author, "name", "") or "")+ author_nickname = str(getattr(message.author, "global_name", "") or "")guild_id = str(getattr(guild, "id", "") or "")channel_id = str(getattr(channel, "id", "") or "")cfg_guild = (self.config.guild_id or "").strip()cfg_channel = (self.config.channel_id or "").strip()-- if cfg_guild:- if not guild_id or guild_id != cfg_guild:+ # Guild/channel filters apply only to server messages. DMs have no guild+ if guild_id: # message from server+ if cfg_guild and guild_id != cfg_guild:+ return+ if cfg_channel and channel_id != cfg_channel:return- if cfg_channel and channel_id != cfg_channel:+ elif self.config.block_dm: # blocked direct message+ logger.info(+ "Discord direct message ignored, from user %s (name=%s, id=%s)", author_nickname, author_name, author_id+ )+ await self._add_reaction_emoji(message, emoji="🚫")returntext = str(getattr(message, "content", "") or "").strip()if not text:return+ add_emoji_exception = await self._add_reaction_emoji(message, emoji="👀")+ if add_emoji_exception is not None:+ logger.error(+ "Discord add reaction to message from user %s (name=%s, id=%s) failed: %s",+ author_nickname, author_name, author_id, add_emoji_exception,+ )+ del add_emoji_exception+session_id = f"discord_{channel_id}_{author_id}"req = Message(id=str(getattr(message, "id", f"discord-{int(time.time() * 1000)}")),@@ -181,8 +197,8 @@ class DiscordChannel(BaseChannel):req_method=ReqMethod.CHAT_SEND,metadata={"discord_user_id": author_id,- "discord_username": str(getattr(message.author, "name", "") or ""),- "discord_global_name": str(getattr(message.author, "global_name", "") or ""),+ "discord_username": author_name,+ "discord_global_name": author_nickname,"discord_channel_id": channel_id,"discord_channel_name": str(getattr(channel, "name", "") or ""),"discord_guild_id": guild_id,@@ -234,6 +250,14 @@ class DiscordChannel(BaseChannel):return msg.payload.strip()return ""+ @staticmethod+ async def _add_reaction_emoji(message: Any, emoji: str = "👀") -> Exception | None:+ try:+ await message.add_reaction(emoji)+ return None+ except Exception as e:+ return e+def get_metadata(self) -> ChannelMetadata:return ChannelMetadata(channel_id=self.channel_id,diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex 29104c5274..8ee7246414 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -181,6 +181,7 @@ channels:enabled: falsediscord:# Discord Bot 配置(当前版本仅支持参数管理)+ # 可与用户私聊(DM):仍受 allow_from 约束# Bot Token(Discord Developer Portal -> Bot)bot_token:# Application ID(Discord Developer Portal -> General Information)@@ -191,6 +192,8 @@ channels:channel_id:# 用户白名单(Discord user_id),为空则允许所有用户allow_from: []+ # 是否关闭私信功能+ block_dm: falseenabled: falsewhatsapp:# WhatsApp 配置(通过本地 Baileys bridge)diff --git a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsxindex ac92e011ed..6ccd1bd6f2 100644--- a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx+++ b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx@@ -93,6 +93,7 @@ type DiscordConfig = {application_id: string;guild_id: string;channel_id: string;+ block_dm: boolean;allow_from: string[];};@@ -102,6 +103,7 @@ type DiscordDraft = {application_id: string;guild_id: string;channel_id: string;+ block_dm: boolean;allow_from: string;};@@ -191,6 +193,7 @@ const DEFAULT_DISCORD_CONF: DiscordConfig = {application_id: '',guild_id: '',channel_id: '',+ block_dm: false,allow_from: [],};@@ -447,6 +450,14 @@ function isSensitiveDiscordField(field: keyof DiscordDraft): boolean {return field === 'bot_token';}+/** Match backend discord_conf bool parsing (true / 1 / "true" / "1"). */+function parseDiscordBoolFlag(value: unknown): boolean {+ if (value === true || value === 1) return true;+ if (value === false || value === 0) return false;+ const s = String(value).trim().toLowerCase();+ return s === 'true' || s === '1';+}+function normalizeDiscordConfig(input: unknown): DiscordConfig {if (!input || typeof input !== 'object') {return DEFAULT_DISCORD_CONF;@@ -462,6 +473,7 @@ function normalizeDiscordConfig(input: unknown): DiscordConfig {application_id: String(data.application_id ?? '').trim(),guild_id: String(data.guild_id ?? '').trim(),channel_id: String(data.channel_id ?? '').trim(),+ block_dm: parseDiscordBoolFlag(data.block_dm),allow_from: allowFrom,};}@@ -473,6 +485,7 @@ function draftFromDiscordConfig(conf: DiscordConfig): DiscordDraft {application_id: conf.application_id,guild_id: conf.guild_id,channel_id: conf.channel_id,+ block_dm: conf.block_dm,allow_from: conf.allow_from.join('\n'),};}@@ -484,6 +497,7 @@ function buildDiscordPayload(draft: DiscordDraft): Record<string, unknown> {application_id: draft.application_id.trim(),guild_id: draft.guild_id.trim(),channel_id: draft.channel_id.trim(),+ block_dm: draft.block_dm,allow_from: normalizeAllowFromText(draft.allow_from),};}@@ -936,6 +950,7 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {baseDraft.application_id !== discordDraft.application_id ||baseDraft.guild_id !== discordDraft.guild_id ||baseDraft.channel_id !== discordDraft.channel_id ||+ baseDraft.block_dm !== discordDraft.block_dm ||normalizeAllowFromText(baseDraft.allow_from).join('\n') !== normalizeAllowFromText(discordDraft.allow_from).join('\n'));}, [discordConfig, discordDraft]);@@ -2000,6 +2015,26 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {</button></td></tr>+ <tr className="border-t border-border first:border-t-0 even:bg-secondary/10">+ <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">block_dm</td>+ <td className="px-4 py-2.5 align-middle">+ <button+ type="button"+ role="switch"+ aria-checked={discordDraft.block_dm}+ onClick={() => handleDiscordFieldChange('block_dm', !discordDraft.block_dm)}+ className={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none ${+ discordDraft.block_dm ? 'bg-ok' : 'bg-secondary'+ }`}+ >+ <span+ className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ${+ discordDraft.block_dm ? 'translate-x-4' : 'translate-x-0'+ }`}+ />+ </button>+ </td>+ </tr>{(['bot_token', 'application_id', 'guild_id', 'channel_id'] as const).map((field) => (<tr key={field} className="border-t border-border first:border-t-0 even:bg-secondary/10"><td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{field}</td>@@ -2009,7 +2044,13 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {type={isSensitiveDiscordField(field) && !discordVisibleFields[field] ? 'password' : 'text'}value={discordDraft[field]}onChange={(e) => handleDiscordFieldChange(field, e.target.value)}- placeholder={t('channels.placeholders.configValue')}+ placeholder={+ field === 'guild_id'+ ? t('channels.placeholders.discordGuildId')+ : field === 'channel_id'+ ? t('channels.placeholders.discordChannelId')+ : t('channels.placeholders.configValue')+ }className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent ${isSensitiveDiscordField(field) ? 'pr-10' : ''}`}diff --git a/jiuwenclaw/web/src/components/SessionsPanel/index.tsx b/jiuwenclaw/web/src/components/SessionsPanel/index.tsxindex cde1168993..d9bffd6001 100644--- a/jiuwenclaw/web/src/components/SessionsPanel/index.tsx+++ b/jiuwenclaw/web/src/components/SessionsPanel/index.tsx@@ -42,6 +42,15 @@ function isPlausibleDate(date: Date): boolean {return year >= 2020 && year <= 2100;}+/** Shorten Discord IDs for list labels*/+function shortenDiscordIDForLabel(id: string): string {+ const s = id.trim();+ if (s.length <= 12) {+ return s;+ }+ return `${s.slice(0, 4)}…${s.slice(-4)}`;+}+function parseSessionDisplayLabel(sessionId: string, t: (key: string, options?: Record<string, unknown>) => string): string {if (!sessionId) return t('sessions.unknownSession');@@ -78,6 +87,17 @@ function parseSessionDisplayLabel(sessionId: string, t: (key: string, options?:return rawBody ? `${t('sessions.prefixes.heartbeat')}-${rawBody}` : t('sessions.prefixes.heartbeat');}+ // discord_{channel_id}_{user_id} from Discord Channel (not hex timestamps)+ if (sessionId.startsWith('discord_')) {+ const parts = sessionId.split('_');+ const discordLabel = t('sessions.prefixes.discord');+ if (parts.length >= 3) {+ const ch = shortenDiscordIDForLabel(parts[1]);+ const user = shortenDiscordIDForLabel(parts[2]);+ return `${discordLabel}-${ch}/${user}`;+ }+ }+// 解析会话ID中可能包含的时间戳格式,如 YYYYMMDD_HHMMSS_xxxxconst timestampRegex = /(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})/;const match = sessionId.match(timestampRegex);diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.jsonindex 0a358efe7a..7fd38366e5 100644--- a/jiuwenclaw/web/src/i18n/locales/en.json+++ b/jiuwenclaw/web/src/i18n/locales/en.json@@ -116,6 +116,7 @@"xiaoyi": "Xiaoyi","dingtalk": "DingTalk","wecom": "WeCom",+ "discord": "Discord","heartbeat": "Heartbeat","unknown": "Unknown"},@@ -272,7 +273,7 @@"feishuSubtitle": "Configure Lark channel service settings","discordTitle": "Discord Channel Configuration","discordSubtitle": "Configure Discord bot service settings",- "discordHint": "Discord Bot messaging is supported. Enable Message Content Intent in Developer Portal and set the target channel.",+ "discordHint": "Discord Bot messaging is supported. Enable Message Content Intent in Developer Portal and optionally set the target channel, the block_dm toggle can be used to block direct message.","telegramTitle": "Telegram Channel Configuration","telegramSubtitle": "Configure Telegram Bot service settings","whatsappTitle": "WhatsApp Channel Configuration",@@ -300,7 +301,9 @@"telegramUserIds": "One Telegram user_id per line (comma-separated is also supported)","whatsappJids": "One WhatsApp JID per line (comma-separated is also supported)","wecomDefaultChatId": "userid or chatid (group)",- "wecomDefaultChatIdHint": "Target for heartbeat/scheduled push. Leave empty to use last chatid"+ "wecomDefaultChatIdHint": "Target for heartbeat/scheduled push. Leave empty to use last chatid",+ "discordGuildId": "Enter the Discord server ID (direct message still works without this)",+ "discordChannelId": "Enter the Discord server's channel ID (direct message still works without this)"},"saved": {"feishu": "Lark settings saved",diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.jsonindex 111ae5e0e2..61928ced5b 100644--- a/jiuwenclaw/web/src/i18n/locales/zh.json+++ b/jiuwenclaw/web/src/i18n/locales/zh.json@@ -116,6 +116,7 @@"xiaoyi": "小艺","dingtalk": "钉钉","wecom": "企业微信",+ "discord": "Discord","heartbeat": "心跳","unknown": "未知"},@@ -272,7 +273,7 @@"feishuSubtitle": "配置飞书频道服务相关参数","discordTitle": "Discord 频道参数配置","discordSubtitle": "配置 Discord Bot 服务相关参数",- "discordHint": "支持 Discord Bot 消息收发,请确保已在开发者后台开启 Message Content Intent 并配置目标频道。",+ "discordHint": "支持 Discord Bot 消息收发,请确保已在开发者后台开启 Message Content Intent 并配置目标频道,可使用block_dm开关屏蔽私信。","telegramTitle": "Telegram 频道参数配置","telegramSubtitle": "配置 Telegram Bot 服务相关参数","whatsappTitle": "WhatsApp 频道参数配置",@@ -300,7 +301,9 @@"telegramUserIds": "每行一个 Telegram user_id(也支持逗号分隔)","whatsappJids": "每行一个 WhatsApp JID(也支持逗号分隔)","wecomDefaultChatId": "userid 或 chatid(群聊)",- "wecomDefaultChatIdHint": "心跳/定时推送目标。不填则自动使用最近一次聊天的 chatid"+ "wecomDefaultChatIdHint": "心跳/定时推送目标。不填则自动使用最近一次聊天的 chatid",+ "discordGuildId": "请填入Discord的服务器ID(留空则仅接收私信)",+ "discordChannelId": "请填入Discord服务器的频道ID(留空则仅接收私信)"},"saved": {"feishu": "飞书配置已保存",