Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
Add im channel Mattermost
Austin Xia463f40fadcc1
diff --git "a/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md" "b/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md"index 7d907f9e8..1632e8ca6 100644--- "a/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md"+++ "b/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md"@@ -1,6 +1,6 @@# IM 集成开发文档-WeKnora 的 IM 集成模块将企业即时通讯平台(企业微信、飞书、Slack、Telegram、钉钉)接入 WeKnora 知识问答管道,支持在 IM 中直接向 AI 提问并获得实时流式回答。+WeKnora 的 IM 集成模块将企业即时通讯平台(企业微信、飞书、Slack、Telegram、钉钉、Mattermost)接入 WeKnora 知识问答管道,支持在 IM 中直接向 AI 提问并获得实时流式回答。IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置通过前端 Agent 编辑器管理,存储在数据库中。@@ -12,6 +12,7 @@ IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置- [Slack 接入](#slack-接入)- [Telegram 接入](#telegram-接入)- [钉钉接入](#钉钉接入)+ - [Mattermost 接入](#mattermost-接入)- [前端管理](#前端管理)- [架构总览](#架构总览)- [数据模型](#数据模型)@@ -25,6 +26,7 @@ IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置- [Slack](#slack)- [Telegram](#telegram)- [钉钉 (DingTalk)](#钉钉-dingtalk)+ - [Mattermost](#mattermost)- [斜杠指令系统](#斜杠指令系统)- [QA 队列与限流](#qa-队列与限流)- [流式输出机制](#流式输出机制)@@ -466,6 +468,49 @@ curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \2. **消息接收地址**:粘贴从 WeKnora 复制的回调地址3. 钉钉会通过 HmacSHA256 签名验证回调请求+---++### Mattermost 接入++Mattermost 为**自建部署**,当前仅支持 **Webhook** 模式:**出站 Webhook(Outgoing Webhook)** 将用户消息 POST 到 WeKnora,Bot 通过 **REST API v4** 发回频道/线程回复。与 Slack Events API 类似,回调需快速返回 `200`,实际回答由 Bot Token 异步调用接口完成。++> 需要公网或内网可达的回调 URL(Mattermost 服务器能访问 WeKnora 的 `/api/v1/im/callback/{channel_id}`)。若 WeKnora 在内网,请在 Mattermost 中配置 [Trusted Internal Connections](https://docs.mattermost.com/configure/environment-configuration-settings.html) 或将回调地址加入允许列表。++#### 第一步:创建 Bot 账户并获取 Token++1. 在 Mattermost 中创建专用 Bot 账户(或使用个人账户的 **Personal Access Token**,不推荐生产环境)。+2. 为 Bot 授予在目标频道/团队发消息、读取文件等所需权限(若需将用户上传的文件写入知识库,需能下载附件)。+3. 在 **Profile → Security → Personal Access Tokens**(或 Bot 设置)生成 Token,复制保存为 **Bot Token**。++#### 第二步:创建 Outgoing Webhook++1. 打开 **产品菜单 → 集成 → 出站 Webhook**(若不可见,需系统管理员在 **系统控制台 → 集成** 中启用出站 Webhook)。+2. 点击 **Add Outgoing Webhook**,填写标题与描述。+3. **Content Type** 建议选择 **application/json**(也支持 `application/x-www-form-urlencoded`,WeKnora 两种均可解析)。+4. 选择触发频道,或配置**触发词**(与频道组合规则以 Mattermost 说明为准)。+5. **Callback URLs** 先留空或填占位;保存后在 WeKnora 创建渠道后会得到正式地址。+6. 保存后复制页面上的 **Token**(出站 Webhook 密钥),即 **Outgoing Webhook Token**。++#### 第三步:在 WeKnora 中添加 IM 渠道++1. 进入 Agent 编辑器 → **IM 集成** → **添加渠道**。+2. 填写配置:+ - **平台**:选择「Mattermost」+ - **接入模式**:固定为 **Webhook**(选择 Mattermost 后界面会禁用 WebSocket)+ - **输出模式**:流式输出 / 完整输出(流式通过编辑帖子实现)+ - **Site URL**:Mattermost 站点根地址,如 `https://mattermost.example.com`(无尾部 `/`)+ - **Bot Token**:上一步生成的 Token+ - **Outgoing Webhook Token**:出站 Webhook 页面复制的 Token(用于校验回调,且参与 `bot_identity` 去重)+ - **Bot User ID**(可选):Bot 在 Mattermost 中的用户 ID;填写后可忽略 Bot 自身触发的回调,避免自回复循环+3. 保存后,复制渠道卡片上的 **回调地址**,回到 Mattermost 出站 Webhook 配置,将 **Callback URLs** 设为该地址并保存。++#### 第四步:验证++在绑定频道发送触发出站 Webhook 的消息,应收到 WeKnora 的回复;回复默认出现在**触发帖所在线程**(使用 Mattermost 的 `root_id` 与触发 `post_id` 对齐)。++**参考文档:** [Outgoing webhooks](https://developers.mattermost.com/integrate/webhooks/outgoing/)++---## 前端管理@@ -475,7 +520,7 @@ IM 渠道在 Agent 编辑器的 **IM 集成** 标签页中管理(仅编辑模### 渠道列表每个渠道以卡片形式展示,包含:-- **平台标识**:企业微信(绿色)/ 飞书(蓝色)/ Slack(紫色)/ Telegram(蓝色)/ 钉钉(蓝色)+- **平台标识**:企业微信(绿色)/ 飞书(蓝色)/ Slack(紫色)/ Telegram(蓝色)/ 钉钉(蓝色)/ Mattermost(蓝色)- **渠道名称**:用户自定义- **接入模式**:WebSocket / Webhook- **输出模式**:流式输出 / 完整输出@@ -511,6 +556,17 @@ IM 渠道在 Agent 编辑器的 **IM 集成** 标签页中管理(仅编辑模│ │ │ │ │ │ ││ ─────┼─────────────┼─────────────┼──────────────┼─────────────┼──────── ││ └─────────────┼─────────────┼──────────────┘─────────────┘ │+│ │ │+│ ┌────┴────────────┐ │+│ │ Mattermost │ Webhook-only │+│ └────────┬────────┘ │+│ ▼ │+│ ┌────────────────┐ │+│ │ Mattermost │ │+│ │ Adapter │ │+│ └────────┬────────┘ │+│ │ │+│ ──────────────────┴────────────────────────────────────────────────────││ ▼ ││ ┌──────────────────────────────────┐ ││ │ im.Service │ 服务编排层 │@@ -559,7 +615,7 @@ CREATE TABLE im_channels (id VARCHAR(36) PRIMARY KEY,tenant_id BIGINT NOT NULL,agent_id VARCHAR(36) NOT NULL, -- 绑定的 Agent ID- platform VARCHAR(20) NOT NULL, -- 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk'+ platform VARCHAR(20) NOT NULL, -- 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost'name VARCHAR(255) NOT NULL DEFAULT '',enabled BOOLEAN NOT NULL DEFAULT true,mode VARCHAR(20) NOT NULL DEFAULT 'websocket', -- 'webhook' | 'websocket'@@ -587,6 +643,9 @@ CREATE TABLE im_channels (| Telegram | Webhook | `bot_token`, `secret_token`(可选) || 钉钉 | WebSocket | `client_id`, `client_secret`, `card_template_id`(可选) || 钉钉 | Webhook | `client_id`, `client_secret`, `card_template_id`(可选) |+| Mattermost | Webhook(唯一支持) | `site_url`, `bot_token`, `outgoing_token`(必填);`bot_user_id`(可选,过滤机器人自身消息) |++`mattermost` 渠道的 `mode` 在数据库中固定为 `webhook`(创建时若未指定,服务端与模型钩子会默认 `webhook`)。`bot_identity` 形如 `mattermost:wh:{outgoing_token}`,用于防止同一出站 Webhook 重复绑定多个渠道。### im_channel_sessions 表@@ -626,7 +685,7 @@ CREATE TABLE im_channels (### IMChannel — IM 渠道-每个 IM 渠道代表一个 IM 平台机器人与 WeKnora Agent 的绑定关系。一个 Agent 可以绑定多个渠道(如同时接入企业微信、飞书和 Slack),同一平台也可以创建多个渠道(如不同的企业微信机器人)。+每个 IM 渠道代表一个 IM 平台机器人与 WeKnora Agent 的绑定关系。一个 Agent 可以绑定多个渠道(如同时接入企业微信、飞书、Slack 与 Mattermost),同一平台也可以创建多个渠道(如不同的企业微信机器人)。渠道有一个计算字段 `BotIdentity`,由平台类型、模式和核心凭证推导,用于防止同一机器人被重复创建。@@ -638,7 +697,7 @@ CREATE TABLE im_channels (```gotype IncomingMessage struct {- Platform Platform // "wecom" | "feishu" | "slack" | "telegram" | "dingtalk"+ Platform Platform // "wecom" | "feishu" | "slack" | "telegram" | "dingtalk" | "mattermost"MessageType MessageType // "text" | "file" | "image"UserID string // 平台用户标识UserName string // 显示名 (可选)@@ -1127,6 +1186,59 @@ EndStream:---+### Mattermost++仅支持 **Webhook** 模式:Mattermost **Outgoing Webhook** 将请求体 POST 到 WeKnora 统一回调地址;适配器实现 `Adapter`、`StreamSender`、`FileDownloader`(标准库 HTTP 调用 REST API,无第三方 SDK)。++#### Webhook 模式(Outgoing Webhook)++```+Mattermost 服务器 ──HTTP POST──▶ /api/v1/im/callback/{channel_id}+ │+ 校验 body 中 token = outgoing_token+ 解析 JSON 或 x-www-form-urlencoded+ │+ 通过 REST API v4 回复(Bearer Bot Token)+```++- **安全校验:** 请求体中的 `token` 必须与渠道凭证中的 `outgoing_token` 一致(创建渠道时工厂会校验 `outgoing_token` 非空)。+- **载荷格式:** 支持 `application/json` 与 `application/x-www-form-urlencoded`(与 [官方文档](https://developers.mattermost.com/integrate/webhooks/outgoing/) 一致)。+- **机器人过滤:** 若配置了 `bot_user_id`,且 `user_id` 与之相同,则返回 `nil` 消息,避免自激。+- **线程回复:** `IncomingMessage.Extra` 中保存 `thread_root_id`(有 `root_id` 时用其值,否则用触发帖 `post_id`);`SendReply` / `CreatePost` 时设置 `root_id`,使回复出现在同一线程。+- **消息去重:** `MessageID` 使用触发帖的 `post_id`。+- **文件消息:** 若载荷含 `file_ids`,取首个文件 ID 作为 `FileKey`;`DownloadFile` 先 `GET /api/v4/files/{id}/info` 再 `GET /api/v4/files/{id}` 下载内容。++#### 流式回复++与 Slack 类似,通过**编辑同一条帖子**展示累积全文:++```+StartStream:+ 1. POST /api/v4/posts → 创建占位帖(如「正在思考...」),得到 post id++SendStreamChunk:+ 2. PUT /api/v4/posts/{post_id}/patch → Patch message 字段(累积全文)++EndStream:+ 3. 最后一次 Patch,与 SendStreamChunk 相同逻辑+```++流式刷新间隔由 Service 侧 `streamFlushInterval`(300ms)批量合并,以降低编辑频率、减轻 API 压力。++#### URL 验证++Mattermost 出站 Webhook 无 Slack/Feishu 类 challenge 流程,`HandleURLVerification` 恒为 `false`。++#### 源码文件++| 文件 | 职责 |+|------|------|+| `internal/im/mattermost/adapter.go` | 出站 Webhook 解析、Token 校验、发帖/补丁流式、文件下载 |+| `internal/im/mattermost/client.go` | REST v4:`CreatePost`、`PatchPostMessage`、文件 info/下载 |+| `internal/im/mattermost/form_parse.go` | 表单编码 body 与 `file_ids` 辅助解析 |++---+## 斜杠指令系统IM 渠道支持斜杠指令(Slash Commands),用户在聊天中输入 `/指令名` 即可触发,无需经过 QA 管道,且不受限流约束。@@ -1300,6 +1412,7 @@ QA 管道 ──chunk──chunk──chunk──▶ EventBus| 企业微信 Webhook | PicUrl 直接下载 或 MediaId 临时素材 API || 企业微信 WebSocket | 加密附件 URL + per-message AES 密钥解密 || Telegram | getFile API 获取文件路径 + HTTPS 下载(支持文档和图片) |+| Mattermost | `GET /api/v4/files/{file_id}/info` + `GET /api/v4/files/{file_id}`(Bearer Bot Token) |---diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.tsindex 3e4a534eb..33dbb4702 100644--- a/frontend/src/api/agent/index.ts+++ b/frontend/src/api/agent/index.ts@@ -182,7 +182,7 @@ export interface IMChannel {id: string;tenant_id?: number;agent_id: string;- platform: 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk';+ platform: 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost';name: string;enabled: boolean;mode: 'webhook' | 'websocket';diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vueindex c7ea6d28d..802c1be0a 100644--- a/frontend/src/components/IMChannelPanel.vue+++ b/frontend/src/components/IMChannelPanel.vue@@ -91,6 +91,7 @@<t-radio-button value="slack">{{ $t('agentEditor.im.slack') }}</t-radio-button><t-radio-button value="telegram">{{ $t('agentEditor.im.telegram') }}</t-radio-button><t-radio-button value="dingtalk">{{ $t('agentEditor.im.dingtalk') }}</t-radio-button>+ <t-radio-button value="mattermost">{{ $t('agentEditor.im.mattermost') }}</t-radio-button></t-radio-group></div>@@ -104,10 +105,11 @@<div class="form-item"><label class="form-label">{{ $t('agentEditor.im.mode') }}</label><t-radio-group v-model="formData.mode">- <t-radio-button value="websocket">WebSocket</t-radio-button>+ <t-radio-button value="websocket" :disabled="formData.platform === 'mattermost'">WebSocket</t-radio-button><t-radio-button value="webhook">Webhook</t-radio-button></t-radio-group>- <p class="form-hint">{{ $t('agentEditor.im.modeHint') }}</p>+ <p v-if="formData.platform === 'mattermost'" class="form-hint">{{ $t('agentEditor.im.mattermostModeHint') }}</p>+ <p v-else class="form-hint">{{ $t('agentEditor.im.modeHint') }}</p></div><!-- Output mode -->@@ -283,13 +285,50 @@<p class="form-hint">{{ $t('agentEditor.im.dingtalkCardTemplateIdHint') }}</p></div></template>++ <!-- Mattermost credentials -->+ <template v-if="formData.platform === 'mattermost'">+ <div class="platform-link-hint">+ <t-icon name="jump" class="hint-link-icon" />+ <a href="https://developers.mattermost.com/integrate/webhooks/outgoing/" target="_blank" rel="noopener noreferrer" class="hint-link">+ {{ $t('agentEditor.im.mattermostConsole') }}+ </a>+ <span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>+ </div>+ <div class="form-item">+ <label class="form-label">Site URL</label>+ <t-input v-model="formData.credentials.site_url" placeholder="https://mattermost.example.com" />+ </div>+ <div class="form-item">+ <label class="form-label">Bot Token</label>+ <t-input v-model="formData.credentials.bot_token" type="password" placeholder="Bot Token" />+ </div>+ <div class="form-item">+ <label class="form-label">Outgoing Webhook Token</label>+ <t-input v-model="formData.credentials.outgoing_token" type="password" placeholder="Token from Outgoing Webhook" />+ </div>+ <div class="form-item">+ <label class="form-label">Bot User ID</label>+ <t-input v-model="formData.credentials.bot_user_id" placeholder="Optional — filter bot self-messages" />+ </div>+ <div class="form-item mattermost-post-main-row">+ <div class="mattermost-post-main-label">+ <label class="form-label">{{ $t('agentEditor.im.mattermostPostToMain') }}</label>+ <t-switch+ :value="!!formData.credentials.post_to_main"+ @change="(v: boolean) => { formData.credentials.post_to_main = v }"+ />+ </div>+ <p class="form-hint">{{ $t('agentEditor.im.mattermostPostToMainHint') }}</p>+ </div>+ </template></div></t-dialog></div></template><script setup lang="ts">-import { ref, onMounted } from 'vue';+import { ref, onMounted, watch } from 'vue';import { useI18n } from 'vue-i18n';import { MessagePlugin } from 'tdesign-vue-next';import { listIMChannels, createIMChannel, updateIMChannel, deleteIMChannel, toggleIMChannel } from '@/api/agent';@@ -313,7 +352,7 @@ const knowledgeBases = ref<{ id: string; name: string }[]>([]);const defaultCredentials = (): Record<string, any> => ({});const formData = ref({- platform: 'wecom' as 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk',+ platform: 'wecom' as 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost',name: '',mode: 'websocket' as 'webhook' | 'websocket',output_mode: 'stream' as 'stream' | 'full',@@ -326,6 +365,18 @@ function platformLabel(platform: string): string {return t(key);}+watch(+ () => formData.value.platform,+ (p) => {+ if (p === 'mattermost') {+ formData.value.mode = 'webhook';+ if (typeof formData.value.credentials.post_to_main !== 'boolean') {+ formData.value.credentials.post_to_main = false;+ }+ }+ },+);+async function loadChannels() {loading.value = true;try {@@ -343,16 +394,29 @@ async function loadChannels() {}function getCallbackUrl(channel: IMChannel): string {- const base = window.location.origin;+ const base = import.meta.env.VITE_IS_DOCKER ? window.location.origin : 'http://127.0.0.1:8080';return `${base}/api/v1/im/callback/${channel.id}`;}async function copyUrl(channel: IMChannel) {+ const text = getCallbackUrl(channel);try {- await navigator.clipboard.writeText(getCallbackUrl(channel));+ await navigator.clipboard.writeText(text);MessagePlugin.success(t('common.copySuccess'));} catch {- MessagePlugin.error(t('common.copyFailed'));+ const el = document.createElement('textarea');+ el.value = text;+ el.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0';+ document.body.appendChild(el);+ el.focus();+ el.select();+ const ok = document.execCommand('copy');+ document.body.removeChild(el);+ if (ok) {+ MessagePlugin.success(t('common.copySuccess'));+ } else {+ MessagePlugin.error(t('common.copyFailed'));+ }}}@@ -572,6 +636,11 @@ onMounted(() => {background: rgba(23, 126, 251, 0.08);color: #177efb;}++ &.mattermost {+ background: rgba(25, 42, 77, 0.08);+ color: #192a4d;+ }}.channel-name {@@ -661,6 +730,20 @@ onMounted(() => {}}+.mattermost-post-main-row {+ .mattermost-post-main-label {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;++ .form-label {+ margin-bottom: 0;+ flex: 1;+ }+ }+}+.form-divider {height: 1px;background: var(--td-component-stroke);diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex bda756b0e..c162d0242 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -3208,12 +3208,13 @@ export default {},im: {title: 'IM Integration',- description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Slack, Telegram and DingTalk',+ description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Slack, Telegram, DingTalk, and Mattermost',wecom: 'WeCom',feishu: 'Feishu',slack: 'Slack',telegram: 'Telegram',dingtalk: 'DingTalk',+ mattermost: 'Mattermost',addChannel: 'Add Channel',editChannel: 'Edit Channel',deleteConfirm: 'Are you sure you want to delete this channel? This action cannot be undone.',@@ -3235,6 +3236,11 @@ export default {dingtalkConsole: 'DingTalk Open Platform',dingtalkCardTemplateId: 'Card Template ID (optional)',dingtalkCardTemplateIdHint: 'Create an AI Card template at open-dev.dingtalk.com/fe/card to enable streaming output with typewriter effect',+ mattermostConsole: 'Mattermost integrations',+ mattermostModeHint: 'Mattermost only supports Webhook mode (outgoing webhook + bot token).',+ mattermostPostToMain: 'Post replies in channel timeline',+ mattermostPostToMainHint:+ 'When on, bot replies are new top-level posts in the channel. When off (default), they stay in the thread and the main view only shows “N replies”.',modeHint: 'WebSocket is recommended for easier setup',consoleTip: 'to get credentials',fileKnowledgeBase: 'File Storage Knowledge Base',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex f0e5bfe08..84a117146 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -3237,12 +3237,13 @@ export default {},im: {title: "IM 통합",- description: "에이전트를 WeCom, Feishu, Slack, Telegram, DingTalk 등 인스턴트 메시징 플랫폼에 연결",+ description: "에이전트를 WeCom, Feishu, Slack, Telegram, DingTalk, Mattermost 등 인스턴트 메시징 플랫폼에 연결",wecom: "WeCom",feishu: "Feishu",slack: "Slack",telegram: "Telegram",dingtalk: "DingTalk",+ mattermost: "Mattermost",addChannel: "채널 추가",editChannel: "채널 편집",deleteConfirm: "이 채널을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",@@ -3264,6 +3265,11 @@ export default {dingtalkConsole: "DingTalk 개발 플랫폼",dingtalkCardTemplateId: "카드 템플릿 ID (선택 사항)",dingtalkCardTemplateIdHint: "open-dev.dingtalk.com/fe/card에서 AI 카드 템플릿을 만들면 타자기 효과 스트리밍 출력이 활성화됩니다",+ mattermostConsole: "Mattermost 통합",+ mattermostModeHint: "Mattermost는 Webhook(아웃고잉 웹훅 + 봇 토큰)만 지원합니다.",+ mattermostPostToMain: "답변을 채널 메인 타임라인에 표시",+ mattermostPostToMainHint:+ "켜면 봇 답변이 채널의 새 최상위 게시물로 올라갑니다. 끄면(기본) 스레드 답변이며 메인 화면에는 「N개 답변」만 보입니다.",modeHint: "WebSocket 방식이 설정이 더 간편하여 권장됩니다",consoleTip: "자격 증명 정보를 가져오세요",fileKnowledgeBase: "파일 저장 지식 베이스",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex a4caaafbd..ea476532b 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -2870,12 +2870,13 @@ export default {},im: {title: 'Интеграция IM',- description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom, Feishu, Slack, Telegram и DingTalk',+ description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom, Feishu, Slack, Telegram, DingTalk и Mattermost',wecom: 'WeCom',feishu: 'Feishu',slack: 'Slack',telegram: 'Telegram',dingtalk: 'DingTalk',+ mattermost: 'Mattermost',addChannel: 'Добавить канал',editChannel: 'Редактировать канал',deleteConfirm: 'Вы уверены, что хотите удалить этот канал? Это действие не может быть отменено.',@@ -2897,6 +2898,11 @@ export default {dingtalkConsole: 'Платформа DingTalk',dingtalkCardTemplateId: 'ID шаблона карточки (необязательно)',dingtalkCardTemplateIdHint: 'Создайте шаблон AI-карточки на open-dev.dingtalk.com/fe/card для потоковой передачи с эффектом печатной машинки',+ mattermostConsole: 'Интеграции Mattermost',+ mattermostModeHint: 'Mattermost поддерживает только режим Webhook (исходящий вебхук + токен бота).',+ mattermostPostToMain: 'Ответы в основной ленте канала',+ mattermostPostToMainHint:+ 'Включено — ответы бота как новые сообщения в канале. Выключено (по умолчанию) — ответы в ветке, в основном окне только «N ответов».',modeHint: 'Рекомендуется WebSocket — проще настроить',consoleTip: 'для получения учётных данных',fileKnowledgeBase: 'База знаний для файлов',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex c09b0536f..9f2c11c31 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -3183,12 +3183,13 @@ export default {},im: {title: "IM 集成",- description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram和钉钉",+ description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram、钉钉和 Mattermost",wecom: "企业微信",feishu: "飞书",slack: "Slack",telegram: "Telegram",dingtalk: "钉钉",+ mattermost: "Mattermost",addChannel: "添加渠道",editChannel: "编辑渠道",deleteConfirm: "确定删除该渠道?删除后无法恢复。",@@ -3210,6 +3211,11 @@ export default {dingtalkConsole: "钉钉开放平台",dingtalkCardTemplateId: "卡片模板 ID(可选)",dingtalkCardTemplateIdHint: "在 open-dev.dingtalk.com/fe/card 创建 AI 卡片模板,启用后支持打字机效果的流式输出",+ mattermostConsole: "Mattermost 集成说明",+ mattermostModeHint: "Mattermost 仅支持 Webhook(出站 Webhook + Bot Token)。",+ mattermostPostToMain: "回复显示在频道主时间线",+ mattermostPostToMainHint:+ "开启后 Bot 回复作为频道内新帖子;关闭(默认)则作为原消息的线程回复,主窗口仅显示「N 条回复」。",modeHint: "推荐使用 WebSocket 方式接入,配置更简单",consoleTip: "前往获取凭证信息",fileKnowledgeBase: "文件保存知识库",diff --git a/internal/container/container.go b/internal/container/container.goindex c38fa9ff2..cc9281a94 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -56,6 +56,7 @@ import (imPkg "github.com/Tencent/WeKnora/internal/im""github.com/Tencent/WeKnora/internal/im/dingtalk""github.com/Tencent/WeKnora/internal/im/feishu"+ "github.com/Tencent/WeKnora/internal/im/mattermost""github.com/Tencent/WeKnora/internal/im/slack""github.com/Tencent/WeKnora/internal/im/telegram""github.com/Tencent/WeKnora/internal/im/wecom"@@ -1171,6 +1172,40 @@ func registerIMAdapterFactories(imService *imPkg.Service) {}})+ // Register Mattermost adapter factory (outgoing webhook + REST API).+ imService.RegisterAdapterFactory("mattermost", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {+ creds, err := parseCredentials(channel.Credentials)+ if err != nil {+ return nil, nil, fmt.Errorf("parse mattermost credentials: %w", err)+ }++ mode := channel.Mode+ if mode == "" {+ mode = "webhook"+ }+ if mode != "webhook" {+ return nil, nil, fmt.Errorf("unsupported mattermost mode: %s (only webhook is supported)", mode)+ }++ siteURL := getString(creds, "site_url")+ botToken := getString(creds, "bot_token")+ outgoingToken := getString(creds, "outgoing_token")+ botUserID := getString(creds, "bot_user_id")++ if outgoingToken == "" {+ return nil, nil, fmt.Errorf("mattermost outgoing_token is required")+ }++ client, err := mattermost.NewClient(siteURL, botToken)+ if err != nil {+ return nil, nil, err+ }++ postReplyToMain := credentialBool(creds, "post_to_main")+ adapter := mattermost.NewAdapter(client, outgoingToken, botUserID, postReplyToMain)+ return adapter, func() {}, nil+ })+// Load and start all enabled channels from databaseif err := imService.LoadAndStartChannels(); err != nil {logger.Warnf(ctx, "[IM] Failed to load channels from database: %v", err)@@ -1198,3 +1233,24 @@ func getString(creds map[string]interface{}, key string) string {}return ""}++// credentialBool reads a boolean from JSON credentials (bool, string "true"/"1", or non-zero number).+func credentialBool(creds map[string]interface{}, key string) bool {+ v, ok := creds[key]+ if !ok {+ return false+ }+ switch x := v.(type) {+ case bool:+ return x+ case string:+ s := strings.TrimSpace(strings.ToLower(x))+ return s == "true" || s == "1" || s == "yes"+ case float64:+ return x != 0+ case int:+ return x != 0+ default:+ return false+ }+}diff --git a/internal/handler/im.go b/internal/handler/im.goindex bae73da32..98b7e48d9 100644--- a/internal/handler/im.go+++ b/internal/handler/im.go@@ -12,7 +12,9 @@ import ()// validIMPlatforms is the set of supported IM platforms.-var validIMPlatforms = map[string]bool{"wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true}+var validIMPlatforms = map[string]bool{+ "wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true, "mattermost": true,+}// IMHandler handles IM platform callback requests and channel CRUD.type IMHandler struct {@@ -57,7 +59,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {}if !validIMPlatforms[req.Platform] {- c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram' or 'dingtalk'"})+ c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram', 'dingtalk' or 'mattermost'"})return}@@ -76,7 +78,11 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {channel.Enabled = *req.Enabled}if channel.Mode == "" {- channel.Mode = "websocket"+ if channel.Platform == "mattermost" {+ channel.Mode = "webhook"+ } else {+ channel.Mode = "websocket"+ }}if channel.OutputMode == "" {channel.OutputMode = "stream"@@ -265,6 +271,8 @@ func (h *IMHandler) IMCallback(c *gin.Context) {return}+ logger.Infof(ctx, "[IM] Callback received platform=%s path_channel_id=%s", channel.Platform, channelID)+// Handle URL verificationif adapter.HandleURLVerification(c) {return@@ -287,6 +295,11 @@ func (h *IMHandler) IMCallback(c *gin.Context) {// If nil, it's a non-message event - just acknowledgeif msg == nil {+ if channel.Platform == "mattermost" {+ logger.Infof(ctx, "[IM] Mattermost callback ignored (no message): path_channel_id=%s — check: (1) trigger word must be the *first word* of the post; (2) if channel+trigger are both set, post must be in that channel; (3) bot_user_id must not match the sender", channelID)+ } else {+ logger.Infof(ctx, "[IM] Callback parsed no message to process platform=%s path_channel_id=%s", channel.Platform, channelID)+ }c.JSON(http.StatusOK, gin.H{"success": true})return}diff --git a/internal/im/adapter.go b/internal/im/adapter.goindex b8925ac4b..7a7acd52d 100644--- a/internal/im/adapter.go+++ b/internal/im/adapter.go@@ -11,11 +11,12 @@ import (type Platform stringconst (- PlatformWeCom Platform = "wecom"- PlatformFeishu Platform = "feishu"- PlatformSlack Platform = "slack"- PlatformTelegram Platform = "telegram"- PlatformDingtalk Platform = "dingtalk"+ PlatformWeCom Platform = "wecom"+ PlatformFeishu Platform = "feishu"+ PlatformSlack Platform = "slack"+ PlatformTelegram Platform = "telegram"+ PlatformDingtalk Platform = "dingtalk"+ PlatformMattermost Platform = "mattermost")// MessageType identifies the kind of IM message.diff --git a/internal/im/mattermost/adapter.go b/internal/im/mattermost/adapter.gonew file mode 100644index 000000000..affe30bd8--- /dev/null+++ b/internal/im/mattermost/adapter.go@@ -0,0 +1,341 @@+package mattermost++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "strings"+ "sync"++ "github.com/gin-gonic/gin"++ "github.com/Tencent/WeKnora/internal/im"+ "github.com/Tencent/WeKnora/internal/logger"+)++// Compile-time checks.+var (+ _ im.Adapter = (*Adapter)(nil)+ _ im.StreamSender = (*Adapter)(nil)+ _ im.FileDownloader = (*Adapter)(nil)+)++const (+ extraKeyThreadRoot = "thread_root_id"+ extraKeyChannelID = "channel_id"+)++// Adapter implements im integration for Mattermost (outgoing webhook inbound + REST outbound).+type Adapter struct {+ client *Client+ outgoingToken string+ botUserID string+ // postReplyToMain: when true, bot replies are new top-level channel posts (visible in main timeline).+ // When false (default), replies use root_id tied to the trigger post so they appear in Mattermost threads.+ postReplyToMain bool+}++// NewAdapter creates a Mattermost adapter.+func NewAdapter(client *Client, outgoingToken, botUserID string, postReplyToMain bool) *Adapter {+ return &Adapter{+ client: client,+ outgoingToken: strings.TrimSpace(outgoingToken),+ botUserID: strings.TrimSpace(botUserID),+ postReplyToMain: postReplyToMain,+ }+}++// outgoingPayload matches Mattermost outgoing webhook parameters (JSON or form).+type outgoingPayload struct {+ Token string `json:"token"`+ UserID string `json:"user_id"`+ UserName string `json:"user_name"`+ ChannelID string `json:"channel_id"`+ PostID string `json:"post_id"`+ Text string `json:"text"`+ RootID string `json:"root_id"`+ FileIDsRaw json.RawMessage `json:"file_ids"`+}++func (a *Adapter) Platform() im.Platform {+ return im.PlatformMattermost+}++func (a *Adapter) HandleURLVerification(c *gin.Context) bool {+ return false+}++func (a *Adapter) VerifyCallback(c *gin.Context) error {+ bodyBytes, err := io.ReadAll(c.Request.Body)+ if err != nil {+ return fmt.Errorf("read body: %w", err)+ }+ c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))++ payload, err := parseOutgoingBody(c.Request.Header.Get("Content-Type"), bodyBytes)+ if err != nil {+ return fmt.Errorf("parse outgoing payload: %w", err)+ }++ if a.outgoingToken != "" && payload.Token != a.outgoingToken {+ return fmt.Errorf("invalid outgoing webhook token")+ }++ return nil+}++func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {+ bodyBytes, err := io.ReadAll(c.Request.Body)+ if err != nil {+ return nil, fmt.Errorf("read body: %w", err)+ }+ c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))++ payload, err := parseOutgoingBody(c.Request.Header.Get("Content-Type"), bodyBytes)+ if err != nil {+ return nil, err+ }++ if a.botUserID != "" && payload.UserID == a.botUserID {+ logger.Infof(c.Request.Context(), "[Mattermost] Skip callback: user_id matches bot_user_id (avoid self-reply loop)")+ return nil, nil+ }++ if strings.TrimSpace(payload.Text) == "" && len(parseFileIDs(payload.FileIDsRaw)) == 0 {+ logger.Infof(c.Request.Context(), "[Mattermost] Skip callback: empty text and no file_ids")+ return nil, nil+ }++ var threadRoot string+ if a.postReplyToMain {+ threadRoot = ""+ } else {+ threadRoot = payload.RootID+ if threadRoot == "" {+ threadRoot = payload.PostID+ }+ }++ msg := &im.IncomingMessage{+ Platform: im.PlatformMattermost,+ UserID: payload.UserID,+ UserName: payload.UserName,+ ChatID: payload.ChannelID,+ ChatType: im.ChatTypeGroup,+ Content: strings.TrimSpace(payload.Text),+ MessageID: payload.PostID,+ Extra: map[string]string{+ extraKeyThreadRoot: threadRoot,+ extraKeyChannelID: payload.ChannelID,+ },+ }++ fileIDs := parseFileIDs(payload.FileIDsRaw)+ if len(fileIDs) > 0 {+ msg.MessageType = im.MessageTypeFile+ msg.FileKey = fileIDs[0]+ if len(fileIDs) > 1 {+ msg.Extra["file_ids"] = strings.Join(fileIDs, ",")+ }+ } else {+ msg.MessageType = im.MessageTypeText+ }++ return msg, nil+}++func parseOutgoingBody(contentType string, body []byte) (*outgoingPayload, error) {+ ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))++ switch {+ case ct == "application/json" || strings.HasSuffix(ct, "+json"):+ var p outgoingPayload+ if err := json.Unmarshal(body, &p); err != nil {+ return nil, err+ }+ return &p, nil++ case ct == "application/x-www-form-urlencoded" || ct == "":+ // Parse as form (Mattermost default for some configs).+ values, err := parseFormBody(body)+ if err != nil {+ return nil, err+ }+ p := &outgoingPayload{+ Token: values.Get("token"),+ UserID: values.Get("user_id"),+ UserName: values.Get("user_name"),+ ChannelID: values.Get("channel_id"),+ PostID: values.Get("post_id"),+ Text: values.Get("text"),+ RootID: values.Get("root_id"),+ }+ if f := values.Get("file_ids"); f != "" {+ p.FileIDsRaw = json.RawMessage(jsonArrayFromCSV(f))+ }+ return p, nil++ default:+ // Try JSON fallback for unknown types.+ var p outgoingPayload+ if err := json.Unmarshal(body, &p); err == nil && (p.Token != "" || p.ChannelID != "") {+ return &p, nil+ }+ return nil, fmt.Errorf("unsupported content-type: %s", contentType)+ }+}++func parseFileIDs(raw json.RawMessage) []string {+ if len(raw) == 0 {+ return nil+ }+ var arr []string+ if err := json.Unmarshal(raw, &arr); err == nil {+ return arr+ }+ var s string+ if err := json.Unmarshal(raw, &s); err == nil && s != "" {+ return splitFileIDs(s)+ }+ return nil+}++func splitFileIDs(s string) []string {+ parts := strings.Split(s, ",")+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ p = strings.TrimSpace(p)+ if p != "" {+ out = append(out, p)+ }+ }+ return out+}++func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {+ channelID := incoming.ChatID+ if channelID == "" {+ channelID = incoming.Extra[extraKeyChannelID]+ }+ if channelID == "" {+ return fmt.Errorf("missing channel_id")+ }++ threadRoot := ""+ if incoming.Extra != nil {+ threadRoot = incoming.Extra[extraKeyThreadRoot]+ }++ _, err := a.client.CreatePost(ctx, channelID, threadRoot, reply.Content)+ return err+}++type mmStreamState struct {+ mu sync.Mutex+ content strings.Builder+ postID string+ channel string+}++var (+ mmStreamsMu sync.Mutex+ mmStreams = map[string]*mmStreamState{}+)++func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {+ channelID := incoming.ChatID+ if channelID == "" {+ channelID = incoming.Extra[extraKeyChannelID]+ }+ threadRoot := ""+ if incoming.Extra != nil {+ threadRoot = incoming.Extra[extraKeyThreadRoot]+ }++ postID, err := a.client.CreatePost(ctx, channelID, threadRoot, "正在思考...")+ if err != nil {+ return "", err+ }++ streamID := channelID + ":" + postID+ mmStreamsMu.Lock()+ mmStreams[streamID] = &mmStreamState{postID: postID, channel: channelID}+ mmStreamsMu.Unlock()++ logger.Infof(ctx, "[Mattermost] Streaming started: stream_id=%s", streamID)+ return streamID, nil+}++func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {+ if content == "" {+ return nil+ }++ mmStreamsMu.Lock()+ state, ok := mmStreams[streamID]+ mmStreamsMu.Unlock()+ if !ok {+ return fmt.Errorf("unknown stream ID: %s", streamID)+ }++ state.mu.Lock()+ state.content.WriteString(content)+ full := state.content.String()+ postID := state.postID+ state.mu.Unlock()++ if err := a.client.PatchPostMessage(ctx, postID, full); err != nil {+ logger.Warnf(ctx, "[Mattermost] Patch post failed: %v", err)+ }+ return nil+}++func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {+ mmStreamsMu.Lock()+ state, ok := mmStreams[streamID]+ delete(mmStreams, streamID)+ mmStreamsMu.Unlock()++ if !ok {+ return nil+ }++ state.mu.Lock()+ full := state.content.String()+ postID := state.postID+ state.mu.Unlock()++ if err := a.client.PatchPostMessage(ctx, postID, full); err != nil {+ logger.Warnf(ctx, "[Mattermost] EndStream patch failed: %v", err)+ }+ logger.Infof(ctx, "[Mattermost] Streaming ended: post_id=%s", postID)+ return nil+}++func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {+ if msg.FileKey == "" {+ return nil, "", fmt.Errorf("file_key is required")+ }++ info, err := a.client.GetFileInfo(ctx, msg.FileKey)+ if err != nil {+ return nil, "", fmt.Errorf("file info: %w", err)+ }++ name := info.Name+ if name == "" {+ name = msg.FileName+ }+ if name == "" {+ name = msg.FileKey+ }++ rc, err := a.client.GetFileReader(ctx, msg.FileKey)+ if err != nil {+ return nil, "", err+ }++ return rc, name, nil+}diff --git a/internal/im/mattermost/client.go b/internal/im/mattermost/client.gonew file mode 100644index 000000000..58c90f555--- /dev/null+++ b/internal/im/mattermost/client.go@@ -0,0 +1,182 @@+package mattermost++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"+)++// Client calls Mattermost REST API v4.+type Client struct {+ baseURL string+ httpClient *http.Client+ token string+}++// NewClient builds an API client. siteURL is the Mattermost server root (e.g. https://mm.example.com).+func NewClient(siteURL, botToken string) (*Client, error) {+ siteURL = strings.TrimSpace(siteURL)+ siteURL = strings.TrimRight(siteURL, "/")+ if siteURL == "" {+ return nil, fmt.Errorf("site_url is required")+ }+ if strings.TrimSpace(botToken) == "" {+ return nil, fmt.Errorf("bot_token is required")+ }+ return &Client{+ baseURL: siteURL + "/api/v4",+ httpClient: &http.Client{+ Timeout: 60 * time.Second,+ },+ token: strings.TrimSpace(botToken),+ }, nil+}++func (c *Client) authHeader(req *http.Request) {+ req.Header.Set("Authorization", "Bearer "+c.token)+ req.Header.Set("Content-Type", "application/json")+}++// CreatePost creates a channel post. rootID is the thread root post id (empty for new top-level post).+func (c *Client) CreatePost(ctx context.Context, channelID, rootID, message string) (postID string, err error) {+ body := map[string]string{+ "channel_id": channelID,+ "message": message,+ }+ if rootID != "" {+ body["root_id"] = rootID+ }+ payload, err := json.Marshal(body)+ if err != nil {+ return "", err+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/posts", bytes.NewReader(payload))+ if err != nil {+ return "", err+ }+ c.authHeader(req)++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return "", err+ }+ defer resp.Body.Close()++ respBody, _ := io.ReadAll(resp.Body)+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ if resp.StatusCode == http.StatusForbidden {+ return "", fmt.Errorf("mattermost create post: 403 forbidden — add the bot user to this Mattermost channel (Channel menu → Members → Add); body=%s", truncateForErr(respBody))+ }+ return "", fmt.Errorf("mattermost create post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))+ }++ var created struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(respBody, &created); err != nil {+ return "", fmt.Errorf("decode create post: %w", err)+ }+ if created.ID == "" {+ return "", fmt.Errorf("mattermost create post: empty id")+ }+ return created.ID, nil+}++// PatchPostMessage updates a post's message field.+func (c *Client) PatchPostMessage(ctx context.Context, postID, message string) error {+ payload, err := json.Marshal(map[string]string{"message": message})+ if err != nil {+ return err+ }++ url := fmt.Sprintf("%s/posts/%s/patch", c.baseURL, postID)+ req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(payload))+ if err != nil {+ return err+ }+ c.authHeader(req)++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ respBody, _ := io.ReadAll(resp.Body)+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return fmt.Errorf("mattermost patch post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))+ }+ return nil+}++// FileInfo holds metadata from GET /files/{id}/info.+type FileInfo struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Size int64 `json:"size"`+}++// GetFileInfo fetches file metadata.+func (c *Client) GetFileInfo(ctx context.Context, fileID string) (*FileInfo, error) {+ url := fmt.Sprintf("%s/files/%s/info", c.baseURL, fileID)+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return nil, err+ }+ c.authHeader(req)+ req.Header.Del("Content-Type")++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ respBody, _ := io.ReadAll(resp.Body)+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return nil, fmt.Errorf("mattermost file info: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))+ }++ var info FileInfo+ if err := json.Unmarshal(respBody, &info); err != nil {+ return nil, fmt.Errorf("decode file info: %w", err)+ }+ return &info, nil+}++// GetFileReader opens a download stream for file content.+func (c *Client) GetFileReader(ctx context.Context, fileID string) (io.ReadCloser, error) {+ url := fmt.Sprintf("%s/files/%s", c.baseURL, fileID)+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return nil, err+ }+ c.authHeader(req)+ req.Header.Del("Content-Type")++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ body, _ := io.ReadAll(resp.Body)+ resp.Body.Close()+ return nil, fmt.Errorf("mattermost get file: status=%d body=%s", resp.StatusCode, truncateForErr(body))+ }+ return resp.Body, nil+}++func truncateForErr(b []byte) string {+ const max = 512+ s := string(b)+ if len(s) > max {+ return s[:max] + "..."+ }+ return s+}diff --git a/internal/im/mattermost/form_parse.go b/internal/im/mattermost/form_parse.gonew file mode 100644index 000000000..4226c5acd--- /dev/null+++ b/internal/im/mattermost/form_parse.go@@ -0,0 +1,27 @@+package mattermost++import (+ "encoding/json"+ "fmt"+ "net/url"+)++func parseFormBody(body []byte) (url.Values, error) {+ values, err := url.ParseQuery(string(body))+ if err != nil {+ return nil, fmt.Errorf("parse form: %w", err)+ }+ return values, nil+}++func jsonArrayFromCSV(csv string) []byte {+ parts := splitFileIDs(csv)+ if len(parts) == 0 {+ return []byte("[]")+ }+ b, err := json.Marshal(parts)+ if err != nil {+ return []byte("[]")+ }+ return b+}diff --git a/internal/im/types.go b/internal/im/types.goindex bf4ab55c3..94754b149 100644--- a/internal/im/types.go+++ b/internal/im/types.go@@ -39,7 +39,11 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error {ch.ID = uuid.New().String()}if ch.Mode == "" {- ch.Mode = "websocket"+ if ch.Platform == "mattermost" {+ ch.Mode = "webhook"+ } else {+ ch.Mode = "websocket"+ }}if ch.OutputMode == "" {ch.OutputMode = "stream"@@ -104,6 +108,10 @@ func (ch *IMChannel) computeBotIdentity() string {if clientID := str("client_id"); clientID != "" {return "dingtalk:" + clientID}+ case "mattermost":+ if tok := str("outgoing_token"); tok != "" {+ return "mattermost:wh:" + tok+ }}return ""}