feat(IM): support both websocket/webhook mode im channel for slack
Signed-off-by: joeyczheng <joeyczheng@tencent.com>
This commit is contained in:
@@ -182,7 +182,7 @@ export interface IMChannel {
|
||||
id: string;
|
||||
tenant_id?: number;
|
||||
agent_id: string;
|
||||
platform: 'wecom' | 'feishu';
|
||||
platform: 'wecom' | 'feishu' | 'slack';
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
mode: 'webhook' | 'websocket';
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<div class="channel-info-top">
|
||||
<div class="channel-main">
|
||||
<span class="platform-badge" :class="channel.platform">
|
||||
{{ channel.platform === 'wecom' ? $t('agentEditor.im.wecom') : $t('agentEditor.im.feishu') }}
|
||||
{{ channel.platform === 'wecom' ? $t('agentEditor.im.wecom') : channel.platform === 'feishu' ? $t('agentEditor.im.feishu') : $t('agentEditor.im.slack') }}
|
||||
</span>
|
||||
<span class="channel-name">{{ channel.name || $t('agentEditor.im.unnamed') }}</span>
|
||||
</div>
|
||||
@@ -88,6 +88,7 @@
|
||||
<t-radio-group v-model="formData.platform" :disabled="!!editingChannel">
|
||||
<t-radio-button value="wecom">{{ $t('agentEditor.im.wecom') }}</t-radio-button>
|
||||
<t-radio-button value="feishu">{{ $t('agentEditor.im.feishu') }}</t-radio-button>
|
||||
<t-radio-button value="slack">{{ $t('agentEditor.im.slack') }}</t-radio-button>
|
||||
</t-radio-group>
|
||||
</div>
|
||||
|
||||
@@ -204,6 +205,37 @@
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<!-- Slack credentials -->
|
||||
<template v-if="formData.platform === 'slack'">
|
||||
<div class="platform-link-hint">
|
||||
<t-icon name="jump" class="hint-link-icon" />
|
||||
<a href="https://api.slack.com/apps" target="_blank" rel="noopener noreferrer" class="hint-link">
|
||||
{{ $t('agentEditor.im.slackConsole') }}
|
||||
</a>
|
||||
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
|
||||
</div>
|
||||
<template v-if="formData.mode === 'websocket'">
|
||||
<div class="form-item">
|
||||
<label class="form-label">App Token</label>
|
||||
<t-input v-model="formData.credentials.app_token" type="password" placeholder="xapp-..." />
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label">Bot Token</label>
|
||||
<t-input v-model="formData.credentials.bot_token" type="password" placeholder="xoxb-..." />
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="form-item">
|
||||
<label class="form-label">Bot Token</label>
|
||||
<t-input v-model="formData.credentials.bot_token" type="password" placeholder="xoxb-..." />
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label">Signing Secret</label>
|
||||
<t-input v-model="formData.credentials.signing_secret" type="password" placeholder="Signing Secret" />
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
</t-dialog>
|
||||
</div>
|
||||
@@ -234,7 +266,7 @@ const knowledgeBases = ref<{ id: string; name: string }[]>([]);
|
||||
const defaultCredentials = (): Record<string, any> => ({});
|
||||
|
||||
const formData = ref({
|
||||
platform: 'wecom' as 'wecom' | 'feishu',
|
||||
platform: 'wecom' as 'wecom' | 'feishu' | 'slack',
|
||||
name: '',
|
||||
mode: 'websocket' as 'webhook' | 'websocket',
|
||||
output_mode: 'stream' as 'stream' | 'full',
|
||||
@@ -420,7 +452,6 @@ onMounted(() => {
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
// --- Channel card (matches share-item pattern) ---
|
||||
.channel-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -474,6 +505,11 @@ onMounted(() => {
|
||||
background: rgba(51, 112, 255, 0.08);
|
||||
color: #3370ff;
|
||||
}
|
||||
|
||||
&.slack {
|
||||
background: rgba(224, 30, 90, 0.08);
|
||||
color: #e01e5a;
|
||||
}
|
||||
}
|
||||
|
||||
.channel-name {
|
||||
@@ -537,7 +573,6 @@ onMounted(() => {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// --- Add button ---
|
||||
.add-btn {
|
||||
margin-top: 4px;
|
||||
|
||||
@@ -548,7 +583,6 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Dialog form (matches share form pattern) ---
|
||||
.dialog-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -607,4 +641,4 @@ onMounted(() => {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
@@ -3174,9 +3174,10 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: 'IM Integration',
|
||||
description: 'Connect agent to instant messaging platforms like WeCom and Feishu',
|
||||
description: 'Connect agent to instant messaging platforms like WeCom, Feishu and Slack',
|
||||
wecom: 'WeCom',
|
||||
feishu: 'Feishu',
|
||||
slack: 'Slack',
|
||||
addChannel: 'Add Channel',
|
||||
editChannel: 'Edit Channel',
|
||||
deleteConfirm: 'Are you sure you want to delete this channel? This action cannot be undone.',
|
||||
@@ -3193,6 +3194,7 @@ export default {
|
||||
docLink: 'Integration Guide',
|
||||
wecomConsole: 'WeCom Admin',
|
||||
feishuConsole: 'Feishu Open Platform',
|
||||
slackConsole: 'Slack API Console',
|
||||
modeHint: 'WebSocket is recommended for easier setup',
|
||||
consoleTip: 'to get credentials',
|
||||
fileKnowledgeBase: 'File Storage Knowledge Base',
|
||||
|
||||
@@ -3204,9 +3204,10 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: "IM 통합",
|
||||
description: "에이전트를 WeCom, Feishu 등 인스턴트 메시징 플랫폼에 연결",
|
||||
description: "에이전트를 WeCom, Feishu, Slack 등 인스턴트 메시징 플랫폼에 연결",
|
||||
wecom: "WeCom",
|
||||
feishu: "Feishu",
|
||||
slack: "Slack",
|
||||
addChannel: "채널 추가",
|
||||
editChannel: "채널 편집",
|
||||
deleteConfirm: "이 채널을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
|
||||
@@ -3223,6 +3224,7 @@ export default {
|
||||
docLink: "통합 가이드 보기",
|
||||
wecomConsole: "WeCom 관리 콘솔",
|
||||
feishuConsole: "Feishu 개발 플랫폼",
|
||||
slackConsole: "Slack API 콘솔",
|
||||
modeHint: "WebSocket 방식이 설정이 더 간편하여 권장됩니다",
|
||||
consoleTip: "자격 증명 정보를 가져오세요",
|
||||
fileKnowledgeBase: "파일 저장 지식 베이스",
|
||||
|
||||
@@ -2837,9 +2837,10 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: 'Интеграция IM',
|
||||
description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom и Feishu',
|
||||
description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom, Feishu и Slack',
|
||||
wecom: 'WeCom',
|
||||
feishu: 'Feishu',
|
||||
slack: 'Slack',
|
||||
addChannel: 'Добавить канал',
|
||||
editChannel: 'Редактировать канал',
|
||||
deleteConfirm: 'Вы уверены, что хотите удалить этот канал? Это действие не может быть отменено.',
|
||||
@@ -2856,6 +2857,7 @@ export default {
|
||||
docLink: 'Руководство по интеграции',
|
||||
wecomConsole: 'Консоль WeCom',
|
||||
feishuConsole: 'Платформа Feishu',
|
||||
slackConsole: 'Консоль Slack API',
|
||||
modeHint: 'Рекомендуется WebSocket — проще настроить',
|
||||
consoleTip: 'для получения учётных данных',
|
||||
fileKnowledgeBase: 'База знаний для файлов',
|
||||
|
||||
@@ -3149,9 +3149,10 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: "IM 集成",
|
||||
description: "将智能体接入即时通讯平台,支持企业微信和飞书",
|
||||
description: "将智能体接入即时通讯平台,支持企业微信、飞书和Slack",
|
||||
wecom: "企业微信",
|
||||
feishu: "飞书",
|
||||
slack: "Slack",
|
||||
addChannel: "添加渠道",
|
||||
editChannel: "编辑渠道",
|
||||
deleteConfirm: "确定删除该渠道?删除后无法恢复。",
|
||||
@@ -3168,6 +3169,7 @@ export default {
|
||||
docLink: "查看接入文档",
|
||||
wecomConsole: "企业微信管理后台",
|
||||
feishuConsole: "飞书开放平台",
|
||||
slackConsole: "Slack API 控制台",
|
||||
modeHint: "推荐使用 WebSocket 方式接入,配置更简单",
|
||||
consoleTip: "前往获取凭证信息",
|
||||
fileKnowledgeBase: "文件保存知识库",
|
||||
|
||||
@@ -22,7 +22,7 @@ require (
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1
|
||||
github.com/google/jsonschema-go v0.4.2
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/hibiken/asynq v0.25.1
|
||||
github.com/larksuite/oapi-sdk-go/v3 v3.5.3
|
||||
github.com/mark3labs/mcp-go v0.43.0
|
||||
@@ -38,6 +38,7 @@ require (
|
||||
github.com/redis/go-redis/v9 v9.14.0
|
||||
github.com/sashabaranov/go-openai v1.40.5
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/slack-go/slack v0.18.0-rc2
|
||||
github.com/spf13/viper v1.20.1
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/swaggo/files v1.0.1
|
||||
|
||||
@@ -1759,6 +1759,8 @@ github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn
|
||||
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
|
||||
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=
|
||||
@@ -1950,8 +1952,9 @@ github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y=
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI=
|
||||
@@ -2342,6 +2345,8 @@ github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic
|
||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/slack-go/slack v0.18.0-rc2 h1:ZudScaC0YC+kefly8l9lADsthTU4jToudZSIkja1csI=
|
||||
github.com/slack-go/slack v0.18.0-rc2/go.mod h1:P4z6wDzyNaESCa24JMwl81HHUkj8GXYdhJ6HxkMtBys=
|
||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
|
||||
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
|
||||
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
|
||||
|
||||
@@ -55,6 +55,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/handler/session"
|
||||
imPkg "github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/im/feishu"
|
||||
"github.com/Tencent/WeKnora/internal/im/slack"
|
||||
"github.com/Tencent/WeKnora/internal/im/wecom"
|
||||
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
@@ -66,6 +67,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/tracing"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
slackpkg "github.com/slack-go/slack"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
|
||||
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
|
||||
@@ -1051,6 +1053,47 @@ func registerIMAdapterFactories(imService *imPkg.Service) {
|
||||
}
|
||||
})
|
||||
|
||||
// Register Slack adapter factory
|
||||
imService.RegisterAdapterFactory("slack", 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 slack credentials: %w", err)
|
||||
}
|
||||
|
||||
mode := channel.Mode
|
||||
if mode == "" {
|
||||
mode = "websocket"
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case "webhook":
|
||||
api := slackpkg.New(getString(creds, "bot_token"))
|
||||
adapter := slack.NewWebhookAdapter(api, getString(creds, "signing_secret"))
|
||||
return adapter, func() {}, nil
|
||||
|
||||
case "websocket":
|
||||
client := slack.NewLongConnClient(
|
||||
getString(creds, "app_token"),
|
||||
getString(creds, "bot_token"),
|
||||
msgHandler,
|
||||
)
|
||||
|
||||
adapter := slack.NewAdapter(client, client.GetAPI())
|
||||
|
||||
wsCtx, wsCancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
|
||||
logger.Errorf(context.Background(), "[IM] Slack long connection stopped for channel %s: %v", channel.ID, err)
|
||||
}
|
||||
}()
|
||||
|
||||
return adapter, wsCancel, nil
|
||||
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unsupported slack mode: %s", mode)
|
||||
}
|
||||
})
|
||||
|
||||
// Load and start all enabled channels from database
|
||||
if err := imService.LoadAndStartChannels(); err != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to load channels from database: %v", err)
|
||||
|
||||
@@ -53,8 +53,8 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.Platform != "wecom" && req.Platform != "feishu" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom' or 'feishu'"})
|
||||
if req.Platform != "wecom" && req.Platform != "feishu" && req.Platform != "slack" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu' or 'slack'"})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ type Platform string
|
||||
const (
|
||||
PlatformWeCom Platform = "wecom"
|
||||
PlatformFeishu Platform = "feishu"
|
||||
PlatformSlack Platform = "slack"
|
||||
)
|
||||
|
||||
// MessageType identifies the kind of IM message.
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
package slack
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/slack-go/slack"
|
||||
"github.com/slack-go/slack/slackevents"
|
||||
|
||||
"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)
|
||||
)
|
||||
|
||||
// Adapter implements im.Adapter and im.StreamSender for Slack.
|
||||
// It delegates to the Slack LongConnClient for Socket Mode.
|
||||
type Adapter struct {
|
||||
client *LongConnClient
|
||||
api *slack.Client
|
||||
signingSecret string
|
||||
}
|
||||
|
||||
// NewAdapter creates an adapter backed by a Slack long connection client.
|
||||
func NewAdapter(client *LongConnClient, api *slack.Client) *Adapter {
|
||||
return &Adapter{
|
||||
client: client,
|
||||
api: api,
|
||||
}
|
||||
}
|
||||
|
||||
// NewWebhookAdapter creates an adapter for Slack Events API via Webhook.
|
||||
func NewWebhookAdapter(api *slack.Client, signingSecret string) *Adapter {
|
||||
return &Adapter{
|
||||
api: api,
|
||||
signingSecret: signingSecret,
|
||||
}
|
||||
}
|
||||
|
||||
func parseIncomingMessage(user, channel, text, ts string, chatType im.ChatType, files []slack.File) *im.IncomingMessage {
|
||||
content := text
|
||||
if chatType == im.ChatTypeGroup {
|
||||
// Slack mentions are in the format <@U12345678>
|
||||
for strings.HasPrefix(content, "<@") {
|
||||
idx := strings.Index(content, ">")
|
||||
if idx >= 0 {
|
||||
content = strings.TrimSpace(content[idx+1:])
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
msg := &im.IncomingMessage{
|
||||
Platform: im.PlatformSlack,
|
||||
UserID: user,
|
||||
ChatID: channel,
|
||||
ChatType: chatType,
|
||||
Content: strings.TrimSpace(content),
|
||||
MessageID: ts,
|
||||
}
|
||||
|
||||
if len(files) > 0 {
|
||||
file := files[0]
|
||||
msg.FileKey = file.ID
|
||||
msg.FileName = file.Name
|
||||
msg.FileSize = int64(file.Size)
|
||||
msg.Extra = map[string]string{
|
||||
"url_private_download": file.URLPrivateDownload,
|
||||
}
|
||||
if strings.HasPrefix(file.Mimetype, "image/") {
|
||||
msg.MessageType = im.MessageTypeImage
|
||||
} else {
|
||||
msg.MessageType = im.MessageTypeFile
|
||||
}
|
||||
} else {
|
||||
msg.MessageType = im.MessageTypeText
|
||||
}
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
func (a *Adapter) Platform() im.Platform {
|
||||
return im.PlatformSlack
|
||||
}
|
||||
|
||||
func (a *Adapter) VerifyCallback(c *gin.Context) error {
|
||||
if a.signingSecret == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
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))
|
||||
|
||||
sv, err := slack.NewSecretsVerifier(c.Request.Header, a.signingSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new secrets verifier: %w", err)
|
||||
}
|
||||
if _, err := sv.Write(bodyBytes); err != nil {
|
||||
return fmt.Errorf("write body to verifier: %w", err)
|
||||
}
|
||||
if err := sv.Ensure(); err != nil {
|
||||
return fmt.Errorf("verify signature: %w", err)
|
||||
}
|
||||
|
||||
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))
|
||||
|
||||
eventsAPIEvent, err := slackevents.ParseEvent(json.RawMessage(bodyBytes), slackevents.OptionNoVerifyToken())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse event: %w", err)
|
||||
}
|
||||
|
||||
if eventsAPIEvent.Type == slackevents.CallbackEvent {
|
||||
var rawEvent struct {
|
||||
Event struct {
|
||||
Files []slack.File `json:"files"`
|
||||
} `json:"event"`
|
||||
}
|
||||
_ = json.Unmarshal(bodyBytes, &rawEvent)
|
||||
files := rawEvent.Event.Files
|
||||
|
||||
innerEvent := eventsAPIEvent.InnerEvent
|
||||
switch ev := innerEvent.Data.(type) {
|
||||
case *slackevents.AppMentionEvent:
|
||||
threadTs := ev.ThreadTimeStamp
|
||||
if threadTs == "" {
|
||||
threadTs = ev.TimeStamp
|
||||
}
|
||||
return parseIncomingMessage(ev.User, ev.Channel, ev.Text, threadTs, im.ChatTypeGroup, files), nil
|
||||
case *slackevents.MessageEvent:
|
||||
if ev.BotID != "" || (ev.SubType != "" && ev.SubType != "file_share") {
|
||||
return nil, nil
|
||||
}
|
||||
chatType := im.ChatTypeDirect
|
||||
if ev.ChannelType == "channel" || ev.ChannelType == "group" {
|
||||
chatType = im.ChatTypeGroup
|
||||
}
|
||||
threadTs := ev.ThreadTimeStamp
|
||||
if threadTs == "" {
|
||||
threadTs = ev.TimeStamp
|
||||
}
|
||||
return parseIncomingMessage(ev.User, ev.Channel, ev.Text, threadTs, chatType, files), nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
|
||||
bodyBytes, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
|
||||
var body struct {
|
||||
Type string `json:"type"`
|
||||
Challenge string `json:"challenge"`
|
||||
}
|
||||
if err := json.Unmarshal(bodyBytes, &body); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if body.Type == "url_verification" {
|
||||
c.JSON(http.StatusOK, gin.H{"challenge": body.Challenge})
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
channelID := incoming.ChatID
|
||||
if channelID == "" {
|
||||
channelID = incoming.UserID
|
||||
}
|
||||
|
||||
options := []slack.MsgOption{slack.MsgOptionText(reply.Content, false)}
|
||||
if incoming.MessageID != "" {
|
||||
options = append(options, slack.MsgOptionTS(incoming.MessageID))
|
||||
}
|
||||
|
||||
_, _, err := a.api.PostMessageContext(ctx, channelID, options...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("slack post message: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// slackStreamState tracks per-stream accumulated content.
|
||||
type slackStreamState struct {
|
||||
mu sync.Mutex
|
||||
content strings.Builder
|
||||
ts string // The timestamp of the message being updated
|
||||
channel string // The channel ID
|
||||
}
|
||||
|
||||
var (
|
||||
slackStreamsMu sync.Mutex
|
||||
slackStreams = map[string]*slackStreamState{}
|
||||
)
|
||||
|
||||
func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
|
||||
channelID := incoming.ChatID
|
||||
if channelID == "" {
|
||||
channelID = incoming.UserID
|
||||
}
|
||||
|
||||
options := []slack.MsgOption{slack.MsgOptionText("正在思考...", false)}
|
||||
if incoming.MessageID != "" {
|
||||
options = append(options, slack.MsgOptionTS(incoming.MessageID))
|
||||
}
|
||||
|
||||
// Send initial "Thinking..." message
|
||||
_, ts, err := a.api.PostMessageContext(ctx, channelID, options...)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("slack start stream: %w", err)
|
||||
}
|
||||
|
||||
streamID := fmt.Sprintf("%s:%s", channelID, ts)
|
||||
|
||||
slackStreamsMu.Lock()
|
||||
slackStreams[streamID] = &slackStreamState{
|
||||
ts: ts,
|
||||
channel: channelID,
|
||||
}
|
||||
slackStreamsMu.Unlock()
|
||||
|
||||
logger.Infof(ctx, "[Slack] 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
|
||||
}
|
||||
|
||||
slackStreamsMu.Lock()
|
||||
state, ok := slackStreams[streamID]
|
||||
slackStreamsMu.Unlock()
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown stream ID: %s", streamID)
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
state.content.WriteString(content)
|
||||
fullContent := state.content.String()
|
||||
state.mu.Unlock()
|
||||
|
||||
// Update the message
|
||||
logger.Infof(ctx, "[Slack] Updating stream chunk: stream_id=%s, content=%s", streamID, fullContent)
|
||||
_, _, _, err := a.api.UpdateMessageContext(ctx, state.channel, state.ts, slack.MsgOptionText(fullContent, false))
|
||||
if err != nil {
|
||||
// slack has rate limit, so we just log the error
|
||||
// see: https://docs.slack.dev/reference/methods/chat.update/
|
||||
logger.Warnf(ctx, "[Slack] Failed to update stream chunk: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
|
||||
slackStreamsMu.Lock()
|
||||
state, ok := slackStreams[streamID]
|
||||
delete(slackStreams, streamID)
|
||||
slackStreamsMu.Unlock()
|
||||
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
fullContent := state.content.String()
|
||||
state.mu.Unlock()
|
||||
|
||||
_, _, _, err := a.api.UpdateMessageContext(ctx, state.channel, state.ts, slack.MsgOptionText(fullContent, false))
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Slack] Failed to end stream: %v", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Slack] Streaming ended: stream_id=%s", streamID)
|
||||
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")
|
||||
}
|
||||
|
||||
downloadURL := ""
|
||||
if msg.Extra != nil {
|
||||
downloadURL = msg.Extra["url_private_download"]
|
||||
}
|
||||
|
||||
if downloadURL == "" {
|
||||
file, _, _, err := a.api.GetFileInfoContext(ctx, msg.FileKey, 0, 0)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("get file info: %w", err)
|
||||
}
|
||||
downloadURL = file.URLPrivateDownload
|
||||
}
|
||||
|
||||
if downloadURL == "" {
|
||||
return nil, "", fmt.Errorf("no download URL available for file %s", msg.FileKey)
|
||||
}
|
||||
|
||||
pr, pw := io.Pipe()
|
||||
go func() {
|
||||
err := a.api.GetFileContext(ctx, downloadURL, pw)
|
||||
pw.CloseWithError(err)
|
||||
}()
|
||||
|
||||
return pr, msg.FileName, nil
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package slack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/slack-go/slack"
|
||||
"github.com/slack-go/slack/slackevents"
|
||||
"github.com/slack-go/slack/socketmode"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// MessageHandler is called when an IM message is received via long connection.
|
||||
type MessageHandler func(ctx context.Context, msg *im.IncomingMessage) error
|
||||
|
||||
// LongConnClient manages a Slack Socket Mode long connection.
|
||||
type LongConnClient struct {
|
||||
appToken string
|
||||
botToken string
|
||||
handler MessageHandler
|
||||
|
||||
api *slack.Client
|
||||
client *socketmode.Client
|
||||
}
|
||||
|
||||
// NewLongConnClient creates a Slack long connection client.
|
||||
func NewLongConnClient(appToken, botToken string, handler MessageHandler) *LongConnClient {
|
||||
api := slack.New(
|
||||
botToken,
|
||||
slack.OptionAppLevelToken(appToken),
|
||||
)
|
||||
|
||||
client := socketmode.New(
|
||||
api,
|
||||
socketmode.OptionDebug(false), // true for debugging
|
||||
)
|
||||
|
||||
return &LongConnClient{
|
||||
appToken: appToken,
|
||||
botToken: botToken,
|
||||
handler: handler,
|
||||
api: api,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
// GetAPI returns the underlying slack API client.
|
||||
func (c *LongConnClient) GetAPI() *slack.Client {
|
||||
return c.api
|
||||
}
|
||||
|
||||
// Start begins the WebSocket long connection. It blocks until ctx is cancelled.
|
||||
func (c *LongConnClient) Start(ctx context.Context) error {
|
||||
logger.Infof(ctx, "[IM] Slack WebSocket connecting...")
|
||||
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case evt := <-c.client.Events:
|
||||
switch evt.Type {
|
||||
case socketmode.EventTypeConnecting:
|
||||
logger.Infof(ctx, "[Slack] Connecting to Slack with Socket Mode...")
|
||||
case socketmode.EventTypeConnectionError:
|
||||
logger.Errorf(ctx, "[Slack] Connection failed. Retrying later...")
|
||||
case socketmode.EventTypeConnected:
|
||||
logger.Infof(ctx, "[IM] Slack WebSocket connected successfully")
|
||||
case socketmode.EventTypeEventsAPI:
|
||||
eventsAPIEvent, ok := evt.Data.(slackevents.EventsAPIEvent)
|
||||
if !ok {
|
||||
logger.Warnf(ctx, "[Slack] Ignored %+v", evt)
|
||||
continue
|
||||
}
|
||||
|
||||
// Acknowledge the event
|
||||
c.client.Ack(*evt.Request)
|
||||
|
||||
// Handle the event
|
||||
c.handleEvent(ctx, eventsAPIEvent, evt.Request.Payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return c.client.RunContext(ctx)
|
||||
}
|
||||
|
||||
func (c *LongConnClient) handleEvent(ctx context.Context, eventsAPIEvent slackevents.EventsAPIEvent, rawPayload json.RawMessage) {
|
||||
logger.Infof(ctx, "[Slack] Received event type: %s", eventsAPIEvent.Type)
|
||||
switch eventsAPIEvent.Type {
|
||||
case slackevents.CallbackEvent:
|
||||
var rawEvent struct {
|
||||
Event struct {
|
||||
Files []slack.File `json:"files"`
|
||||
} `json:"event"`
|
||||
}
|
||||
_ = json.Unmarshal(rawPayload, &rawEvent)
|
||||
files := rawEvent.Event.Files
|
||||
|
||||
innerEvent := eventsAPIEvent.InnerEvent
|
||||
logger.Infof(ctx, "[Slack] Received inner event type: %s", innerEvent.Type)
|
||||
switch ev := innerEvent.Data.(type) {
|
||||
case *slackevents.AppMentionEvent:
|
||||
logger.Infof(ctx, "[Slack] AppMentionEvent: user=%s channel=%s text=%s", ev.User, ev.Channel, ev.Text)
|
||||
// Handle @bot mention in a channel
|
||||
threadTs := ev.ThreadTimeStamp
|
||||
if threadTs == "" {
|
||||
threadTs = ev.TimeStamp
|
||||
}
|
||||
c.processMessage(ctx, ev.User, ev.Channel, ev.Text, threadTs, im.ChatTypeGroup, files)
|
||||
case *slackevents.MessageEvent:
|
||||
logger.Infof(ctx, "[Slack] MessageEvent: user=%s channel=%s text=%s subtype=%s bot_id=%s", ev.User, ev.Channel, ev.Text, ev.SubType, ev.BotID)
|
||||
if ev.BotID != "" {
|
||||
return
|
||||
}
|
||||
if ev.SubType != "" && ev.SubType != "file_share" {
|
||||
return
|
||||
}
|
||||
|
||||
chatType := im.ChatTypeDirect
|
||||
if ev.ChannelType == "channel" || ev.ChannelType == "group" {
|
||||
chatType = im.ChatTypeGroup
|
||||
}
|
||||
|
||||
threadTs := ev.ThreadTimeStamp
|
||||
if threadTs == "" {
|
||||
threadTs = ev.TimeStamp
|
||||
}
|
||||
|
||||
c.processMessage(ctx, ev.User, ev.Channel, ev.Text, threadTs, chatType, files)
|
||||
default:
|
||||
logger.Warnf(ctx, "[Slack] Unhandled inner event type: %T", innerEvent.Data)
|
||||
}
|
||||
default:
|
||||
logger.Warnf(ctx, "[Slack] Unhandled event type: %s", eventsAPIEvent.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LongConnClient) processMessage(ctx context.Context, user, channel, text, ts string, chatType im.ChatType, files []slack.File) {
|
||||
incoming := parseIncomingMessage(user, channel, text, ts, chatType, files)
|
||||
|
||||
if err := c.handler(ctx, incoming); err != nil {
|
||||
logger.Errorf(ctx, "[Slack] Handle message error: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user