feat(im): add DingTalk platform integration
Add DingTalk bot adapter supporting both webhook (HmacSHA256 signature verification) and Stream mode (via official dingtalk-stream-sdk-go), with sessionWebhook/OpenAPI reply fallback and AccessToken caching.
This commit is contained in:
@@ -182,7 +182,7 @@ export interface IMChannel {
|
||||
id: string;
|
||||
tenant_id?: number;
|
||||
agent_id: string;
|
||||
platform: 'wecom' | 'feishu' | 'slack' | 'telegram';
|
||||
platform: 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk';
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
mode: 'webhook' | 'websocket';
|
||||
|
||||
@@ -90,6 +90,7 @@
|
||||
<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-button value="telegram">{{ $t('agentEditor.im.telegram') }}</t-radio-button>
|
||||
<t-radio-button value="dingtalk">{{ $t('agentEditor.im.dingtalk') }}</t-radio-button>
|
||||
</t-radio-group>
|
||||
</div>
|
||||
|
||||
@@ -259,6 +260,24 @@
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<!-- DingTalk credentials -->
|
||||
<template v-if="formData.platform === 'dingtalk'">
|
||||
<div class="platform-link-hint">
|
||||
<t-icon name="jump" class="hint-link-icon" />
|
||||
<a href="https://open.dingtalk.com/" target="_blank" rel="noopener noreferrer" class="hint-link">
|
||||
{{ $t('agentEditor.im.dingtalkConsole') }}
|
||||
</a>
|
||||
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label">Client ID (AppKey)</label>
|
||||
<t-input v-model="formData.credentials.client_id" placeholder="Client ID / AppKey" />
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label">Client Secret (AppSecret)</label>
|
||||
<t-input v-model="formData.credentials.client_secret" type="password" placeholder="Client Secret / AppSecret" />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</t-dialog>
|
||||
</div>
|
||||
@@ -289,7 +308,7 @@ const knowledgeBases = ref<{ id: string; name: string }[]>([]);
|
||||
const defaultCredentials = (): Record<string, any> => ({});
|
||||
|
||||
const formData = ref({
|
||||
platform: 'wecom' as 'wecom' | 'feishu' | 'slack' | 'telegram',
|
||||
platform: 'wecom' as 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk',
|
||||
name: '',
|
||||
mode: 'websocket' as 'webhook' | 'websocket',
|
||||
output_mode: 'stream' as 'stream' | 'full',
|
||||
@@ -544,6 +563,10 @@ onMounted(() => {
|
||||
color: #26a6db;
|
||||
}
|
||||
|
||||
&.dingtalk {
|
||||
background: rgba(23, 126, 251, 0.08);
|
||||
color: #177efb;
|
||||
}
|
||||
}
|
||||
|
||||
.channel-name {
|
||||
|
||||
@@ -3182,11 +3182,12 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: 'IM Integration',
|
||||
description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Slack and Telegram',
|
||||
description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Slack, Telegram and DingTalk',
|
||||
wecom: 'WeCom',
|
||||
feishu: 'Feishu',
|
||||
slack: 'Slack',
|
||||
telegram: 'Telegram',
|
||||
dingtalk: 'DingTalk',
|
||||
addChannel: 'Add Channel',
|
||||
editChannel: 'Edit Channel',
|
||||
deleteConfirm: 'Are you sure you want to delete this channel? This action cannot be undone.',
|
||||
@@ -3205,6 +3206,7 @@ export default {
|
||||
feishuConsole: 'Feishu Open Platform',
|
||||
slackConsole: 'Slack API Console',
|
||||
telegramConsole: 'Telegram BotFather',
|
||||
dingtalkConsole: 'DingTalk Open Platform',
|
||||
modeHint: 'WebSocket is recommended for easier setup',
|
||||
consoleTip: 'to get credentials',
|
||||
fileKnowledgeBase: 'File Storage Knowledge Base',
|
||||
|
||||
@@ -3212,11 +3212,12 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: "IM 통합",
|
||||
description: "에이전트를 WeCom, Feishu, Slack, Telegram 등 인스턴트 메시징 플랫폼에 연결",
|
||||
description: "에이전트를 WeCom, Feishu, Slack, Telegram, DingTalk 등 인스턴트 메시징 플랫폼에 연결",
|
||||
wecom: "WeCom",
|
||||
feishu: "Feishu",
|
||||
slack: "Slack",
|
||||
telegram: "Telegram",
|
||||
dingtalk: "DingTalk",
|
||||
addChannel: "채널 추가",
|
||||
editChannel: "채널 편집",
|
||||
deleteConfirm: "이 채널을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
|
||||
@@ -3235,6 +3236,7 @@ export default {
|
||||
feishuConsole: "Feishu 개발 플랫폼",
|
||||
slackConsole: "Slack API 콘솔",
|
||||
telegramConsole: "Telegram BotFather",
|
||||
dingtalkConsole: "DingTalk 개발 플랫폼",
|
||||
modeHint: "WebSocket 방식이 설정이 더 간편하여 권장됩니다",
|
||||
consoleTip: "자격 증명 정보를 가져오세요",
|
||||
fileKnowledgeBase: "파일 저장 지식 베이스",
|
||||
|
||||
@@ -2845,11 +2845,12 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: 'Интеграция IM',
|
||||
description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom, Feishu, Slack и Telegram',
|
||||
description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom, Feishu, Slack, Telegram и DingTalk',
|
||||
wecom: 'WeCom',
|
||||
feishu: 'Feishu',
|
||||
slack: 'Slack',
|
||||
telegram: 'Telegram',
|
||||
dingtalk: 'DingTalk',
|
||||
addChannel: 'Добавить канал',
|
||||
editChannel: 'Редактировать канал',
|
||||
deleteConfirm: 'Вы уверены, что хотите удалить этот канал? Это действие не может быть отменено.',
|
||||
@@ -2868,6 +2869,7 @@ export default {
|
||||
feishuConsole: 'Платформа Feishu',
|
||||
slackConsole: 'Консоль Slack API',
|
||||
telegramConsole: 'Telegram BotFather',
|
||||
dingtalkConsole: 'Платформа DingTalk',
|
||||
modeHint: 'Рекомендуется WebSocket — проще настроить',
|
||||
consoleTip: 'для получения учётных данных',
|
||||
fileKnowledgeBase: 'База знаний для файлов',
|
||||
|
||||
@@ -3157,11 +3157,12 @@ export default {
|
||||
},
|
||||
im: {
|
||||
title: "IM 集成",
|
||||
description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack和Telegram",
|
||||
description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack、Telegram和钉钉",
|
||||
wecom: "企业微信",
|
||||
feishu: "飞书",
|
||||
slack: "Slack",
|
||||
telegram: "Telegram",
|
||||
dingtalk: "钉钉",
|
||||
addChannel: "添加渠道",
|
||||
editChannel: "编辑渠道",
|
||||
deleteConfirm: "确定删除该渠道?删除后无法恢复。",
|
||||
@@ -3180,6 +3181,7 @@ export default {
|
||||
feishuConsole: "飞书开放平台",
|
||||
slackConsole: "Slack API 控制台",
|
||||
telegramConsole: "Telegram BotFather",
|
||||
dingtalkConsole: "钉钉开放平台",
|
||||
modeHint: "推荐使用 WebSocket 方式接入,配置更简单",
|
||||
consoleTip: "前往获取凭证信息",
|
||||
fileKnowledgeBase: "文件保存知识库",
|
||||
|
||||
@@ -31,6 +31,7 @@ require (
|
||||
github.com/minio/minio-go/v7 v7.0.91
|
||||
github.com/neo4j/neo4j-go-driver/v6 v6.0.0-alpha.1
|
||||
github.com/ollama/ollama v0.11.4
|
||||
github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1
|
||||
github.com/panjf2000/ants/v2 v2.11.3
|
||||
github.com/parquet-go/parquet-go v0.25.0
|
||||
github.com/pganalyze/pg_query_go/v6 v6.1.0
|
||||
|
||||
@@ -2211,6 +2211,8 @@ github.com/ollama/ollama v0.11.4/go.mod h1:9+1//yWPsDE2u+l1a5mpaKrYw4VdnSsRU3ioq
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||
github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1 h1:Lb/Uzkiw2Ugt2Xf03J5wmv81PdkYOiWbI8CNBi1boC8=
|
||||
github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1/go.mod h1:ln3IqPYYocZbYvl9TAOrG/cxGR9xcn4pnZRLdCTEGEU=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||
|
||||
@@ -54,6 +54,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/handler"
|
||||
"github.com/Tencent/WeKnora/internal/handler/session"
|
||||
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/slack"
|
||||
"github.com/Tencent/WeKnora/internal/im/telegram"
|
||||
@@ -1133,6 +1134,44 @@ func registerIMAdapterFactories(imService *imPkg.Service) {
|
||||
}
|
||||
})
|
||||
|
||||
// Register DingTalk adapter factory
|
||||
imService.RegisterAdapterFactory("dingtalk", 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 dingtalk credentials: %w", err)
|
||||
}
|
||||
|
||||
clientID := getString(creds, "client_id")
|
||||
clientSecret := getString(creds, "client_secret")
|
||||
|
||||
mode := channel.Mode
|
||||
if mode == "" {
|
||||
mode = "websocket"
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case "webhook":
|
||||
adapter := dingtalk.NewWebhookAdapter(clientID, clientSecret)
|
||||
return adapter, nil, nil
|
||||
|
||||
case "websocket":
|
||||
client := dingtalk.NewLongConnClient(clientID, clientSecret, msgHandler)
|
||||
|
||||
wsCtx, wsCancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
|
||||
logger.Errorf(context.Background(), "[IM] DingTalk stream stopped for channel %s: %v", channel.ID, err)
|
||||
}
|
||||
}()
|
||||
|
||||
adapter := dingtalk.NewAdapter(client, clientID, clientSecret)
|
||||
return adapter, wsCancel, nil
|
||||
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unsupported dingtalk 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)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
// validIMPlatforms is the set of supported IM platforms.
|
||||
var validIMPlatforms = map[string]bool{"wecom": true, "feishu": true, "slack": true, "telegram": true}
|
||||
var validIMPlatforms = map[string]bool{"wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true}
|
||||
|
||||
// IMHandler handles IM platform callback requests and channel CRUD.
|
||||
type IMHandler struct {
|
||||
@@ -57,7 +57,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' or 'telegram'"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram' or 'dingtalk'"})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ const (
|
||||
PlatformFeishu Platform = "feishu"
|
||||
PlatformSlack Platform = "slack"
|
||||
PlatformTelegram Platform = "telegram"
|
||||
PlatformDingtalk Platform = "dingtalk"
|
||||
)
|
||||
|
||||
// MessageType identifies the kind of IM message.
|
||||
|
||||
@@ -0,0 +1,422 @@
|
||||
package dingtalk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// httpClient is a shared HTTP client with a reasonable timeout for DingTalk API calls.
|
||||
var httpClient = &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
// Compile-time checks.
|
||||
var (
|
||||
_ im.Adapter = (*Adapter)(nil)
|
||||
_ im.StreamSender = (*Adapter)(nil)
|
||||
)
|
||||
|
||||
// Adapter implements im.Adapter for DingTalk.
|
||||
type Adapter struct {
|
||||
clientID string
|
||||
clientSecret string
|
||||
client *LongConnClient // nil for webhook mode
|
||||
|
||||
// accessToken cache
|
||||
tokenMu sync.RWMutex
|
||||
token string
|
||||
tokenExpAt time.Time
|
||||
}
|
||||
|
||||
// NewWebhookAdapter creates a DingTalk adapter for HTTP callback mode.
|
||||
func NewWebhookAdapter(clientID, clientSecret string) *Adapter {
|
||||
return &Adapter{
|
||||
clientID: clientID,
|
||||
clientSecret: clientSecret,
|
||||
}
|
||||
}
|
||||
|
||||
// NewAdapter creates a DingTalk adapter backed by a stream client.
|
||||
func NewAdapter(client *LongConnClient, clientID, clientSecret string) *Adapter {
|
||||
return &Adapter{
|
||||
clientID: clientID,
|
||||
clientSecret: clientSecret,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Adapter) Platform() im.Platform {
|
||||
return im.PlatformDingtalk
|
||||
}
|
||||
|
||||
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
|
||||
return false // DingTalk does not use URL verification challenges.
|
||||
}
|
||||
|
||||
// VerifyCallback verifies the DingTalk webhook signature (HmacSHA256).
|
||||
func (a *Adapter) VerifyCallback(c *gin.Context) error {
|
||||
if a.clientSecret == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
timestamp := c.GetHeader("Timestamp")
|
||||
sign := c.GetHeader("Sign")
|
||||
if timestamp == "" || sign == "" {
|
||||
return fmt.Errorf("missing timestamp or sign header")
|
||||
}
|
||||
|
||||
// Check timestamp is within 1 hour
|
||||
ts, err := strconv.ParseInt(timestamp, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid timestamp: %w", err)
|
||||
}
|
||||
diff := time.Now().UnixMilli() - ts
|
||||
if diff > 3600*1000 || diff < -3600*1000 {
|
||||
return fmt.Errorf("timestamp expired")
|
||||
}
|
||||
|
||||
// Verify HMAC-SHA256 signature
|
||||
stringToSign := timestamp + "\n" + a.clientSecret
|
||||
h := hmac.New(sha256.New, []byte(a.clientSecret))
|
||||
h.Write([]byte(stringToSign))
|
||||
expectedSign := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
|
||||
if !hmac.Equal([]byte(sign), []byte(expectedSign)) {
|
||||
return fmt.Errorf("invalid signature")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DingTalk callback message structure.
|
||||
type callbackMessage struct {
|
||||
ConversationID string `json:"conversationId"`
|
||||
ConversationType string `json:"conversationType"` // "1" = single, "2" = group
|
||||
MsgID string `json:"msgId"`
|
||||
Msgtype string `json:"msgtype"` // "text", "picture", "richText", "file"
|
||||
Text *textContent `json:"text"`
|
||||
SenderNick string `json:"senderNick"`
|
||||
SenderStaffId string `json:"senderStaffId"`
|
||||
SenderID string `json:"senderId"`
|
||||
SessionWebhook string `json:"sessionWebhook"`
|
||||
RobotCode string `json:"robotCode"`
|
||||
AtUsers []atUser `json:"atUsers"`
|
||||
IsInAtList bool `json:"isInAtList"`
|
||||
ChatbotCorpId string `json:"chatbotCorpId"`
|
||||
}
|
||||
|
||||
type textContent struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type atUser struct {
|
||||
DingtalkID string `json:"dingtalkId"`
|
||||
StaffID string `json:"staffId"`
|
||||
}
|
||||
|
||||
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))
|
||||
|
||||
var msg callbackMessage
|
||||
if err := json.Unmarshal(bodyBytes, &msg); err != nil {
|
||||
return nil, fmt.Errorf("parse callback: %w", err)
|
||||
}
|
||||
|
||||
return parseCallbackMessage(&msg), nil
|
||||
}
|
||||
|
||||
func parseCallbackMessage(msg *callbackMessage) *im.IncomingMessage {
|
||||
chatType := im.ChatTypeDirect
|
||||
chatID := ""
|
||||
if msg.ConversationType == "2" {
|
||||
chatType = im.ChatTypeGroup
|
||||
chatID = msg.ConversationID
|
||||
}
|
||||
|
||||
userID := msg.SenderStaffId
|
||||
if userID == "" {
|
||||
userID = msg.SenderID
|
||||
}
|
||||
|
||||
content := ""
|
||||
if msg.Text != nil {
|
||||
content = strings.TrimSpace(msg.Text.Content)
|
||||
}
|
||||
|
||||
incoming := &im.IncomingMessage{
|
||||
Platform: im.PlatformDingtalk,
|
||||
UserID: userID,
|
||||
UserName: msg.SenderNick,
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
MessageID: msg.MsgID,
|
||||
MessageType: im.MessageTypeText,
|
||||
Content: content,
|
||||
Extra: map[string]string{
|
||||
"session_webhook": msg.SessionWebhook,
|
||||
},
|
||||
}
|
||||
|
||||
return incoming
|
||||
}
|
||||
|
||||
// ── Send reply ──
|
||||
|
||||
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
// Prefer sessionWebhook for simplicity
|
||||
sessionWebhook := ""
|
||||
if incoming.Extra != nil {
|
||||
sessionWebhook = incoming.Extra["session_webhook"]
|
||||
}
|
||||
|
||||
if sessionWebhook != "" {
|
||||
return a.replyViaSessionWebhook(ctx, sessionWebhook, reply.Content)
|
||||
}
|
||||
|
||||
// Fallback to OpenAPI
|
||||
return a.replyViaOpenAPI(ctx, incoming, reply.Content)
|
||||
}
|
||||
|
||||
func (a *Adapter) replyViaSessionWebhook(ctx context.Context, webhookURL, content string) error {
|
||||
body := map[string]interface{}{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]string{
|
||||
"title": "Reply",
|
||||
"text": content,
|
||||
},
|
||||
}
|
||||
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal reply: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send reply: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("dingtalk sessionWebhook returned %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) replyViaOpenAPI(ctx context.Context, incoming *im.IncomingMessage, content string) error {
|
||||
token, err := a.getAccessToken(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get access token: %w", err)
|
||||
}
|
||||
|
||||
msgParam, err := json.Marshal(map[string]string{"title": "Reply", "text": content})
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal msgParam: %w", err)
|
||||
}
|
||||
|
||||
var apiURL string
|
||||
body := map[string]interface{}{
|
||||
"robotCode": a.clientID,
|
||||
"msgKey": "sampleMarkdown",
|
||||
"msgParam": string(msgParam),
|
||||
}
|
||||
|
||||
if incoming.ChatType == im.ChatTypeGroup {
|
||||
apiURL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
|
||||
body["openConversationId"] = incoming.ChatID
|
||||
} else {
|
||||
apiURL = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
|
||||
body["userIds"] = []string{incoming.UserID}
|
||||
}
|
||||
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal body: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-acs-dingtalk-access-token", token)
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send reply: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("dingtalk OpenAPI returned %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getAccessToken returns a cached or fresh DingTalk access token.
|
||||
func (a *Adapter) getAccessToken(ctx context.Context) (string, error) {
|
||||
a.tokenMu.RLock()
|
||||
if a.token != "" && time.Now().Before(a.tokenExpAt) {
|
||||
token := a.token
|
||||
a.tokenMu.RUnlock()
|
||||
return token, nil
|
||||
}
|
||||
a.tokenMu.RUnlock()
|
||||
|
||||
a.tokenMu.Lock()
|
||||
defer a.tokenMu.Unlock()
|
||||
|
||||
// Double check after acquiring write lock
|
||||
if a.token != "" && time.Now().Before(a.tokenExpAt) {
|
||||
return a.token, nil
|
||||
}
|
||||
|
||||
body := map[string]string{
|
||||
"appKey": a.clientID,
|
||||
"appSecret": a.clientSecret,
|
||||
}
|
||||
jsonBody, _ := json.Marshal(body)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://api.dingtalk.com/v1.0/oauth2/accessToken",
|
||||
bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("dingtalk accessToken returned %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
ExpireIn int64 `json:"expireIn"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return "", fmt.Errorf("decode token response: %w", err)
|
||||
}
|
||||
if result.AccessToken == "" {
|
||||
return "", fmt.Errorf("empty access token from dingtalk")
|
||||
}
|
||||
|
||||
a.token = result.AccessToken
|
||||
// Refresh 5 minutes before expiry
|
||||
a.tokenExpAt = time.Now().Add(time.Duration(result.ExpireIn)*time.Second - 5*time.Minute)
|
||||
|
||||
return a.token, nil
|
||||
}
|
||||
|
||||
// ── StreamSender implementation ──
|
||||
// DingTalk does not support editing messages in place. We accumulate content
|
||||
// and send the full reply at EndStream via sessionWebhook.
|
||||
|
||||
type streamState struct {
|
||||
mu sync.Mutex
|
||||
content strings.Builder
|
||||
sessionWebhook string
|
||||
}
|
||||
|
||||
var (
|
||||
streamsMu sync.Mutex
|
||||
dStreams = map[string]*streamState{}
|
||||
)
|
||||
|
||||
func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
|
||||
sessionWebhook := ""
|
||||
if incoming.Extra != nil {
|
||||
sessionWebhook = incoming.Extra["session_webhook"]
|
||||
}
|
||||
|
||||
streamID := fmt.Sprintf("dt:%s:%s", incoming.UserID, incoming.MessageID)
|
||||
|
||||
streamsMu.Lock()
|
||||
dStreams[streamID] = &streamState{
|
||||
sessionWebhook: sessionWebhook,
|
||||
}
|
||||
streamsMu.Unlock()
|
||||
|
||||
logger.Infof(ctx, "[DingTalk] 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
|
||||
}
|
||||
|
||||
streamsMu.Lock()
|
||||
state, ok := dStreams[streamID]
|
||||
streamsMu.Unlock()
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown stream ID: %s", streamID)
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
state.content.WriteString(content)
|
||||
state.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
|
||||
streamsMu.Lock()
|
||||
state, ok := dStreams[streamID]
|
||||
delete(dStreams, streamID)
|
||||
streamsMu.Unlock()
|
||||
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
fullContent := state.content.String()
|
||||
state.mu.Unlock()
|
||||
|
||||
if state.sessionWebhook != "" {
|
||||
if err := a.replyViaSessionWebhook(ctx, state.sessionWebhook, fullContent); err != nil {
|
||||
logger.Warnf(ctx, "[DingTalk] Failed to end stream: %v", err)
|
||||
}
|
||||
} else {
|
||||
// Fallback to OpenAPI
|
||||
if err := a.replyViaOpenAPI(ctx, incoming, fullContent); err != nil {
|
||||
logger.Warnf(ctx, "[DingTalk] Failed to end stream via OpenAPI: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[DingTalk] Streaming ended: stream_id=%s", streamID)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package dingtalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
dtsdk "github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
|
||||
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// MessageHandler is called when an IM message is received via stream connection.
|
||||
type MessageHandler func(ctx context.Context, msg *im.IncomingMessage) error
|
||||
|
||||
// LongConnClient manages a DingTalk Stream mode connection.
|
||||
type LongConnClient struct {
|
||||
clientID string
|
||||
clientSecret string
|
||||
handler MessageHandler
|
||||
streamClient *dtsdk.StreamClient
|
||||
}
|
||||
|
||||
// NewLongConnClient creates a DingTalk stream client.
|
||||
func NewLongConnClient(clientID, clientSecret string, handler MessageHandler) *LongConnClient {
|
||||
cli := dtsdk.NewStreamClient(
|
||||
dtsdk.WithAppCredential(&dtsdk.AppCredentialConfig{
|
||||
ClientId: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
}),
|
||||
)
|
||||
|
||||
c := &LongConnClient{
|
||||
clientID: clientID,
|
||||
clientSecret: clientSecret,
|
||||
handler: handler,
|
||||
streamClient: cli,
|
||||
}
|
||||
|
||||
cli.RegisterChatBotCallbackRouter(c.onChatBotMessage)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// Start begins the stream connection. It blocks until ctx is cancelled.
|
||||
func (c *LongConnClient) Start(ctx context.Context) error {
|
||||
logger.Infof(ctx, "[IM] DingTalk Stream connecting...")
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- c.streamClient.Start(ctx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case err := <-errCh:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (c *LongConnClient) onChatBotMessage(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) {
|
||||
chatType := im.ChatTypeDirect
|
||||
chatID := ""
|
||||
if data.ConversationType == "2" {
|
||||
chatType = im.ChatTypeGroup
|
||||
chatID = data.ConversationId
|
||||
}
|
||||
|
||||
userID := data.SenderStaffId
|
||||
if userID == "" {
|
||||
userID = data.SenderId
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(data.Text.Content)
|
||||
|
||||
incoming := &im.IncomingMessage{
|
||||
Platform: im.PlatformDingtalk,
|
||||
UserID: userID,
|
||||
UserName: data.SenderNick,
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
MessageID: data.MsgId,
|
||||
MessageType: im.MessageTypeText,
|
||||
Content: content,
|
||||
Extra: map[string]string{
|
||||
"session_webhook": data.SessionWebhook,
|
||||
},
|
||||
}
|
||||
|
||||
if err := c.handler(ctx, incoming); err != nil {
|
||||
logger.Errorf(ctx, "[DingTalk] Handle message error: %v", err)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
@@ -100,6 +100,10 @@ func (ch *IMChannel) computeBotIdentity() string {
|
||||
}
|
||||
return "telegram:" + botToken
|
||||
}
|
||||
case "dingtalk":
|
||||
if clientID := str("client_id"); clientID != "" {
|
||||
return "dingtalk:" + clientID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user