Files
dobotai-platform/internal/channels/dingtalk/handler.go
T
2026-07-20 13:01:59 +08:00

166 lines
5.1 KiB
Go

package dingtalk
import (
"context"
"errors"
"fmt"
"strings"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
)
const (
// msgTypeText is the DingTalk robot callback message type for text.
msgTypeText = "text"
// conversationTypeDirect is a 1:1 (direct) conversation callback.
conversationTypeDirect = "1"
// conversationTypeGroup is a group conversation callback.
conversationTypeGroup = "2"
// replyTitle is the markdown title used for session webhook replies.
replyTitle = "DobotAI"
// unsupportedMessageReply is sent for non-text messages.
unsupportedMessageReply = "当前版本暂仅支持文字消息。"
// qaErrorReply is sent when the QA backend fails. It must never leak
// internal error details to end users.
qaErrorReply = "抱歉,当前暂时无法完成回答,请稍后重试。"
)
// TenantConfig identifies the tenant + channel this handler serves.
type TenantConfig struct {
TenantKey string
Channel string
}
// BotCallback is the decoded DingTalk robot callback payload for the
// fields the text ingress path needs.
type BotCallback struct {
ConversationType string
ConversationID string
Msgtype string
MsgID string
SenderNick string
SenderStaffID string
SenderID string
IsInAtList bool
SessionWebhook string
Text string
}
// QAAsker answers questions (implemented by the QA service).
type QAAsker interface {
Ask(ctx context.Context, req core.QARequest) (core.QAResult, error)
}
// MarkdownSender sends a markdown reply to a session webhook
// (implemented by WebhookSender).
type MarkdownSender interface {
SendMarkdown(ctx context.Context, webhookURL, title, text string) error
}
// Handler processes DingTalk robot callbacks synchronously.
type Handler struct {
cfg TenantConfig
qa QAAsker
reply MarkdownSender
}
// NewHandler validates its dependencies and returns a Handler.
func NewHandler(cfg TenantConfig, qa QAAsker, reply MarkdownSender) (*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")
}
return &Handler{cfg: cfg, qa: qa, reply: reply}, nil
}
// Handle processes a single bot callback synchronously and returns nil
// once any required reply has been sent (or the message was silently
// ignored). No goroutines are spawned.
func (h *Handler) Handle(ctx context.Context, cb BotCallback) error {
// Group messages that do not @ the bot are silently ignored.
if cb.ConversationType == conversationTypeGroup && !cb.IsInAtList {
return nil
}
// Non-text messages never reach QA; reply with the unsupported notice.
if cb.Msgtype != msgTypeText {
if strings.TrimSpace(cb.SessionWebhook) == "" {
return errors.New("dingtalk handler: sessionWebhook is required to reply")
}
return h.reply.SendMarkdown(ctx, cb.SessionWebhook, replyTitle, unsupportedMessageReply)
}
query := strings.TrimSpace(cb.Text)
if query == "" {
return errors.New("dingtalk handler: text message content is empty")
}
if cb.MsgID == "" {
return errors.New("dingtalk handler: msgId is required")
}
externalUserID := cb.SenderStaffID
if externalUserID == "" {
externalUserID = cb.SenderID
}
if externalUserID == "" {
return errors.New("dingtalk handler: sender staffId/senderId is required")
}
// The session webhook is the only reply channel; fail fast before
// calling QA so a missing webhook never wastes a model call.
if strings.TrimSpace(cb.SessionWebhook) == "" {
return errors.New("dingtalk handler: sessionWebhook is required to reply")
}
req := core.QARequest{
TenantKey: h.cfg.TenantKey,
Channel: h.cfg.Channel,
ExternalUserID: externalUserID,
ExternalMessageID: cb.MsgID,
SenderName: cb.SenderNick,
Query: query,
}
switch cb.ConversationType {
case conversationTypeGroup:
if cb.ConversationID == "" {
return errors.New("dingtalk handler: conversationId is required for group messages")
}
req.ConversationType = core.ConversationGroup
req.ExternalChatID = cb.ConversationID
default:
req.ConversationType = core.ConversationDirect
}
result, err := h.qa.Ask(ctx, req)
if err != nil {
// Never leak internal error details to the user. If the friendly
// reply cannot be delivered, surface that failure instead.
if replyErr := h.sendReply(ctx, cb.SessionWebhook, qaErrorReply); replyErr != nil {
return replyErr
}
return nil
}
return h.sendReply(ctx, cb.SessionWebhook, result.Answer)
}
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
}