feat(dingtalk): support image questions with vision models

This commit is contained in:
姚章浩
2026-07-15 13:54:34 +08:00
parent 9645de64a1
commit 1b0b0fb8ed
7 changed files with 498 additions and 25 deletions
+151 -19
View File
@@ -9,7 +9,11 @@ import (
"encoding/json"
"fmt"
"io"
"mime"
"net"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
"sync"
@@ -33,15 +37,18 @@ const dingtalkConvTypeGroup = "2"
// Compile-time checks.
var (
_ im.Adapter = (*Adapter)(nil)
_ im.StreamSender = (*Adapter)(nil)
_ im.Adapter = (*Adapter)(nil)
_ im.StreamSender = (*Adapter)(nil)
_ im.FileDownloader = (*Adapter)(nil)
)
// Adapter implements im.Adapter for DingTalk.
type Adapter struct {
clientID string
clientSecret string
cardTemplateID string // optional: enables AI card streaming when set
clientID string
clientSecret string
cardTemplateID string // optional: enables AI card streaming when set
messageFileDownloadURL string
allowInsecureDownload bool // tests only; production requires HTTPS
// accessToken cache
tokenMu sync.RWMutex
@@ -114,19 +121,20 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
// DingTalk callback message structure.
type callbackMessage struct {
ConversationID string `json:"conversationId"`
ConversationType string `json:"conversationType"`
MsgID string `json:"msgId"`
Msgtype string `json:"msgtype"`
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"`
ConversationID string `json:"conversationId"`
ConversationType string `json:"conversationType"`
MsgID string `json:"msgId"`
Msgtype string `json:"msgtype"`
Text *textContent `json:"text"`
Content json.RawMessage `json:"content"`
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 {
@@ -170,6 +178,20 @@ func parseCallbackMessage(msg *callbackMessage) *im.IncomingMessage {
if msg.Text != nil {
content = strings.TrimSpace(msg.Text.Content)
}
messageType := im.MessageTypeText
fileKey := ""
fileName := ""
if strings.EqualFold(msg.Msgtype, "picture") {
var picture struct {
DownloadCode string `json:"downloadCode"`
}
if json.Unmarshal(msg.Content, &picture) == nil && strings.TrimSpace(picture.DownloadCode) != "" {
messageType = im.MessageTypeImage
fileKey = strings.TrimSpace(picture.DownloadCode)
fileName = msg.MsgID + ".png"
content = ""
}
}
return &im.IncomingMessage{
Platform: im.PlatformDingtalk,
@@ -178,14 +200,124 @@ func parseCallbackMessage(msg *callbackMessage) *im.IncomingMessage {
ChatID: chatID,
ChatType: chatType,
MessageID: msg.MsgID,
MessageType: im.MessageTypeText,
MessageType: messageType,
Content: content,
FileKey: fileKey,
FileName: fileName,
Extra: map[string]string{
"session_webhook": msg.SessionWebhook,
},
}
}
const dingtalkMessageFileDownloadURL = "https://api.dingtalk.com/v1.0/robot/messageFiles/download"
func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
if msg == nil || strings.TrimSpace(msg.FileKey) == "" {
return nil, "", fmt.Errorf("download code is required")
}
token, err := a.getAccessToken(ctx)
if err != nil {
return nil, "", fmt.Errorf("get access token: %w", err)
}
body, err := json.Marshal(map[string]string{
"downloadCode": msg.FileKey,
"robotCode": a.clientID,
})
if err != nil {
return nil, "", fmt.Errorf("marshal message file request: %w", err)
}
apiURL := a.messageFileDownloadURL
if apiURL == "" {
apiURL = dingtalkMessageFileDownloadURL
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(body))
if err != nil {
return nil, "", fmt.Errorf("create message file 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 nil, "", fmt.Errorf("request message file URL: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return nil, "", fmt.Errorf("dingtalk message file API returned %d", resp.StatusCode)
}
var result struct {
DownloadURL string `json:"downloadUrl"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil {
return nil, "", fmt.Errorf("decode message file response: %w", err)
}
if err := validateDingTalkDownloadURL(result.DownloadURL, a.allowInsecureDownload); err != nil {
return nil, "", err
}
downloadReq, err := http.NewRequestWithContext(ctx, http.MethodGet, result.DownloadURL, nil)
if err != nil {
return nil, "", fmt.Errorf("create image download request: %w", err)
}
downloadClient := *httpClient
downloadClient.CheckRedirect = func(req *http.Request, _ []*http.Request) error {
return validateDingTalkDownloadURL(req.URL.String(), a.allowInsecureDownload)
}
downloadResp, err := downloadClient.Do(downloadReq)
if err != nil {
return nil, "", fmt.Errorf("download dingtalk image: %w", err)
}
if downloadResp.StatusCode < http.StatusOK || downloadResp.StatusCode >= http.StatusMultipleChoices {
downloadResp.Body.Close()
return nil, "", fmt.Errorf("dingtalk image download returned %d", downloadResp.StatusCode)
}
contentType := strings.ToLower(strings.TrimSpace(strings.Split(downloadResp.Header.Get("Content-Type"), ";")[0]))
if msg.MessageType == im.MessageTypeImage && !strings.HasPrefix(contentType, "image/") {
downloadResp.Body.Close()
return nil, "", fmt.Errorf("dingtalk picture response is not an image")
}
return downloadResp.Body, dingtalkDownloadedFileName(downloadResp, msg, contentType), nil
}
func validateDingTalkDownloadURL(rawURL string, allowInsecure bool) error {
u, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || u.Hostname() == "" || u.User != nil {
return fmt.Errorf("invalid dingtalk download URL")
}
if allowInsecure {
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("invalid dingtalk download URL scheme")
}
return nil
}
if u.Scheme != "https" {
return fmt.Errorf("dingtalk download URL must use HTTPS")
}
if ip := net.ParseIP(u.Hostname()); ip != nil && (ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified()) {
return fmt.Errorf("dingtalk download URL points to a private address")
}
return nil
}
func dingtalkDownloadedFileName(resp *http.Response, msg *im.IncomingMessage, contentType string) string {
if _, params, err := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); err == nil {
if name := filepath.Base(strings.TrimSpace(params["filename"])); name != "" && name != "." && name != ".." {
return name
}
}
if msg != nil && strings.TrimSpace(msg.FileName) != "" {
return filepath.Base(msg.FileName)
}
ext := ".bin"
if extensions, _ := mime.ExtensionsByType(contentType); len(extensions) > 0 {
ext = extensions[0]
}
if msg != nil && msg.MessageID != "" {
return msg.MessageID + ext
}
return "dingtalk-file" + ext
}
// ── Send reply ──
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {