Files
dobotai-platform/internal/channels/dingtalk/handler.go
T
2026-07-20 18:21:47 +08:00

197 lines
6.1 KiB
Go

package dingtalk
import (
"context"
"errors"
"fmt"
"log"
"strings"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
)
const (
msgTypeText = "text"
msgTypePicture = "picture"
conversationTypeDirect = "1"
conversationTypeGroup = "2"
replyTitle = "DobotAI"
unsupportedMessageReply = "当前版本暂仅支持文字消息。"
qaErrorReply = "抱歉,当前暂时无法完成回答,请稍后重试。"
imageErrorReply = "图片识别暂时不可用,请稍后重试或发送文字。"
imageQuery = "请描述并分析这张图片。"
)
type TenantConfig struct {
TenantKey string
Channel string
}
type BotCallback struct {
ConversationType string
ConversationID string
Msgtype string
MsgID string
SenderNick string
SenderStaffID string
SenderID string
IsInAtList bool
SessionWebhook string
Text string
DownloadCode string
}
type QAAsker interface {
Ask(ctx context.Context, req core.QARequest) (core.QAResult, error)
}
type MarkdownSender interface {
SendMarkdown(ctx context.Context, webhookURL, title, text string) error
}
type ImageDownloader interface {
Download(ctx context.Context, downloadCode string) (core.ImageInput, error)
}
type Handler struct {
cfg TenantConfig
qa QAAsker
reply MarkdownSender
downloader ImageDownloader
}
// NewHandler accepts at most one image downloader. A nil/omitted downloader
// keeps text ingress available while picture messages fail closed.
func NewHandler(cfg TenantConfig, qa QAAsker, reply MarkdownSender, downloaders ...ImageDownloader) (*Handler, error) {
if strings.TrimSpace(cfg.TenantKey) == "" {
return nil, errors.New("dingtalk handler: tenant key is required")
}
if strings.TrimSpace(cfg.Channel) == "" {
return nil, errors.New("dingtalk handler: channel is required")
}
if qa == nil {
return nil, errors.New("dingtalk handler: QA asker is required")
}
if reply == nil {
return nil, errors.New("dingtalk handler: markdown sender is required")
}
if len(downloaders) > 1 {
return nil, errors.New("dingtalk handler: at most one image downloader is allowed")
}
var downloader ImageDownloader
if len(downloaders) == 1 {
downloader = downloaders[0]
}
return &Handler{cfg: cfg, qa: qa, reply: reply, downloader: downloader}, nil
}
func (h *Handler) Handle(ctx context.Context, cb BotCallback) error {
// Admission comes first: a group message without @ must have zero side effects.
if cb.ConversationType == conversationTypeGroup && !cb.IsInAtList {
return nil
}
// Validate the only reply destination before downloading media or spending a
// model call. Webhook errors never include its query string.
webhookURL := strings.TrimSpace(cb.SessionWebhook)
if webhookURL == "" {
return errors.New("dingtalk handler: sessionWebhook is required to reply")
}
if err := ValidateWebhookURL(webhookURL); err != nil {
return fmt.Errorf("dingtalk handler: invalid sessionWebhook: %w", err)
}
if strings.TrimSpace(cb.MsgID) == "" {
return errors.New("dingtalk handler: msgId is required")
}
externalUserID := strings.TrimSpace(cb.SenderStaffID)
if externalUserID == "" {
externalUserID = strings.TrimSpace(cb.SenderID)
}
if externalUserID == "" {
return errors.New("dingtalk handler: sender staffId/senderId is required")
}
req := core.QARequest{
TenantKey: h.cfg.TenantKey,
Channel: h.cfg.Channel,
ExternalUserID: externalUserID,
ExternalMessageID: strings.TrimSpace(cb.MsgID),
SenderName: cb.SenderNick,
}
switch cb.ConversationType {
case conversationTypeGroup:
if strings.TrimSpace(cb.ConversationID) == "" {
return errors.New("dingtalk handler: conversationId is required for group messages")
}
req.ConversationType = core.ConversationGroup
req.ExternalChatID = strings.TrimSpace(cb.ConversationID)
default:
req.ConversationType = core.ConversationDirect
}
switch strings.ToLower(strings.TrimSpace(cb.Msgtype)) {
case msgTypeText:
req.Query = strings.TrimSpace(cb.Text)
if req.Query == "" {
return errors.New("dingtalk handler: text message content is empty")
}
case msgTypePicture:
if strings.TrimSpace(cb.DownloadCode) == "" {
log.Printf("DingTalk image preparation failed: stage=missing_download_code")
return h.sendReply(ctx, webhookURL, imageErrorReply)
}
if h.downloader == nil {
log.Printf("DingTalk image preparation failed: stage=downloader_unavailable")
return h.sendReply(ctx, webhookURL, imageErrorReply)
}
image, err := h.downloader.Download(ctx, strings.TrimSpace(cb.DownloadCode))
if err != nil {
log.Printf("DingTalk image preparation failed: stage=%s", imageFailureStage(err))
return h.sendReply(ctx, webhookURL, imageErrorReply)
}
req.Query = imageQuery
req.Images = []core.ImageInput{image}
default:
return h.sendReply(ctx, webhookURL, unsupportedMessageReply)
}
result, err := h.qa.Ask(ctx, req)
if err != nil {
if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil {
return replyErr
}
return nil
}
return h.sendReply(ctx, webhookURL, result.Answer)
}
func imageFailureStage(err error) string {
message := strings.ToLower(err.Error())
switch {
case strings.Contains(message, "oauth"):
return "oauth"
case strings.Contains(message, "api"):
return "file_api"
case strings.Contains(message, "unsafe") || strings.Contains(message, "destination"):
return "unsafe_url"
case strings.Contains(message, "format") || strings.Contains(message, "image data") || strings.Contains(message, "dimensions") || strings.Contains(message, "size limit"):
return "image_validation"
case strings.Contains(message, "request") || strings.Contains(message, "http") || strings.Contains(message, "read"):
return "image_fetch"
default:
return "unknown"
}
}
func (h *Handler) sendReply(ctx context.Context, webhookURL, text string) error {
if strings.TrimSpace(webhookURL) == "" {
return errors.New("dingtalk handler: sessionWebhook is required to reply")
}
if err := h.reply.SendMarkdown(ctx, webhookURL, replyTitle, text); err != nil {
return fmt.Errorf("dingtalk handler: send reply: %w", err)
}
return nil
}