a6ff0036b5
The DingTalk adapter only ever classified incoming messages as text and did not implement FileDownloader, so files sent to the bot were never saved to the channel's configured knowledge base — unlike WeCom, which worked. Users saw the file received and read, but never stored. Parse file/picture msgtypes in both the webhook and stream paths (set MessageTypeFile/Image, FileName, FileKey=downloadCode, robot_code), and implement DownloadFile: exchange the downloadCode for a temporary URL via robot/messageFiles/download, then fetch it. robotCode comes from the callback (webhook) or the app client ID (stream). Pictures get a MsgID-derived name, mirroring the WeCom adapter.
69 lines
2.0 KiB
Go
69 lines
2.0 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
|
|
dtsdk "github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
|
|
|
|
"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 establishes the stream connection. The underlying SDK's Start is
|
|
// non-blocking: it dials the websocket, spawns its internal read/reconnect
|
|
// loops, and returns once the connection is established (or the attempt fails).
|
|
func (c *LongConnClient) Start(ctx context.Context) error {
|
|
logger.Infof(ctx, "[IM] DingTalk Stream connecting...")
|
|
return c.streamClient.Start(ctx)
|
|
}
|
|
|
|
// Close tears down the stream connection. AutoReconnect is disabled first so
|
|
// that closing the connection does not trigger the SDK's internal reconnect.
|
|
func (c *LongConnClient) Close() {
|
|
c.streamClient.AutoReconnect = false
|
|
c.streamClient.Close()
|
|
}
|
|
|
|
func (c *LongConnClient) onChatBotMessage(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) {
|
|
incoming := streamToIncoming(data, c.clientID)
|
|
|
|
if err := c.handler(ctx, incoming); err != nil {
|
|
logger.Errorf(ctx, "[DingTalk] Handle message error: %v", err)
|
|
}
|
|
|
|
return nil, nil
|
|
}
|