From 39831fb61cfa3fd8a236fe499e7333cf97bff740 Mon Sep 17 00:00:00 2001 From: nullkey Date: Thu, 2 Apr 2026 03:15:51 +0800 Subject: [PATCH] fix(wecom): strip @mention from group chat messages to fix slash commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WeCom AI Bot does not strip @mention from text.content in group chats, causing all slash commands (/stop, /clear, /help) to fail — the content arrives as "@BotName /stop" instead of "/stop". - Add stripAtMentionBasic (stateless) and stripAtMention (with bot name caching) to handle multi-word bot display names - Support bot_name in channel credentials for immediate precision - Apply stripping in both WebSocket and webhook adapters, text and mixed - Add mention_test.go with 21 test cases --- internal/container/container.go | 1 + internal/im/wecom/longconn.go | 97 +++++++++++++++-- internal/im/wecom/mention_test.go | 154 +++++++++++++++++++++++++++ internal/im/wecom/webhook_adapter.go | 11 +- 4 files changed, 254 insertions(+), 9 deletions(-) create mode 100644 internal/im/wecom/mention_test.go diff --git a/internal/container/container.go b/internal/container/container.go index 4614a01e..7f4b3ee1 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -1009,6 +1009,7 @@ func registerIMAdapterFactories(imService *imPkg.Service) { client := wecom.NewLongConnClient( getString(creds, "bot_id"), getString(creds, "bot_secret"), + getString(creds, "bot_name"), msgHandler, ) diff --git a/internal/im/wecom/longconn.go b/internal/im/wecom/longconn.go index c8bda37e..20b236e1 100644 --- a/internal/im/wecom/longconn.go +++ b/internal/im/wecom/longconn.go @@ -136,15 +136,24 @@ type LongConnClient struct { // the previously displayed text, so we must send the full accumulated text. streamBufsMu sync.Mutex streamBufs map[string]*strings.Builder + + // botDisplayName caches the bot's display name for @mention stripping. + // Set from credentials "bot_name", or learned from double-space messages. + botDisplayName atomic.Value // string } // NewLongConnClient creates a WeCom long connection client. -func NewLongConnClient(botID, secret string, handler MessageHandler) *LongConnClient { - return &LongConnClient{ +// botName is the bot's display name for @mention stripping; empty to auto-detect. +func NewLongConnClient(botID, secret, botName string, handler MessageHandler) *LongConnClient { + c := &LongConnClient{ botID: botID, secret: secret, handler: handler, } + if botName != "" { + c.botDisplayName.Store(botName) + } + return c } // Start connects and runs the long connection loop. It reconnects automatically on failure. @@ -475,7 +484,8 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) { chatType := im.ChatTypeDirect chatID := "" - if msg.ChatType == "group" { + isGroup := msg.ChatType == "group" + if isGroup { chatType = im.ChatTypeGroup chatID = msg.ChatID } @@ -490,6 +500,12 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) { switch msg.MsgType { case "text": + // WeCom does not strip @mention in group chat; strip it so slash + // commands (/stop, /clear) are recognized. + textContent := msg.Text.Content + if isGroup { + textContent = c.stripAtMention(textContent) + } incoming = &im.IncomingMessage{ Platform: im.PlatformWeCom, MessageType: im.MessageTypeText, @@ -497,7 +513,7 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) { UserName: msg.From.UserID, ChatID: chatID, ChatType: chatType, - Content: strings.TrimSpace(msg.Text.Content), + Content: strings.TrimSpace(textContent), MessageID: msg.MsgID, Extra: map[string]string{"req_id": reqID}, } @@ -558,7 +574,7 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) { case "mixed": // Extract text parts for QA content, and detect if any images are present - incoming = convertMixedMessage(&msg, chatID, chatType, reqID) + incoming = c.convertMixedMessage(&msg, chatID, chatType, reqID) if incoming == nil { logger.Infof(ctx, "[WeCom] Ignoring empty mixed message") return @@ -588,7 +604,8 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) { // convertMixedMessage converts a WeCom mixed (text+image) message. // Extracts all text content for QA; if there's only images, treat as image message. -func convertMixedMessage(msg *botMessage, chatID string, chatType im.ChatType, reqID string) *im.IncomingMessage { +func (c *LongConnClient) convertMixedMessage(msg *botMessage, chatID string, chatType im.ChatType, reqID string) *im.IncomingMessage { + isGroup := chatType == im.ChatTypeGroup var textParts []string var firstImageURL string var firstImageAESKey string @@ -596,7 +613,11 @@ func convertMixedMessage(msg *botMessage, chatID string, chatType im.ChatType, r for _, item := range msg.Mixed.MsgItem { switch item.MsgType { case "text": - if t := strings.TrimSpace(item.Text.Content); t != "" { + t := strings.TrimSpace(item.Text.Content) + if isGroup { + t = c.stripAtMention(t) + } + if t != "" { textParts = append(textParts, t) } case "image": @@ -651,6 +672,68 @@ func (c *LongConnClient) closeConn() { } } +// stripAtMentionBasic removes a leading "@Name" prefix from group chat content. +// Strategies: double-space split → heuristic (space + "/" or CJK) → first @word. +// Used directly by the webhook adapter (stateless) and as the base for +// LongConnClient.stripAtMention (stateful). +func stripAtMentionBasic(content string) string { + content = strings.TrimSpace(content) + if !strings.HasPrefix(content, "@") { + return content + } + // Some WeCom clients insert two spaces between @mention and user text. + if idx := strings.Index(content, " "); idx > 0 { + return strings.TrimSpace(content[idx+2:]) + } + // Heuristic: bot names are ASCII words; user content starts with "/" + // or non-ASCII (CJK). Scan for the transition. + for i := 1; i < len(content); i++ { + if content[i] == ' ' && i+1 < len(content) { + if next := content[i+1]; next == '/' || next >= 0x80 { + return strings.TrimSpace(content[i+1:]) + } + } + } + // Fallback: strip first @word. + if idx := strings.Index(content, " "); idx > 0 { + return strings.TrimSpace(content[idx+1:]) + } + return content +} + +// stripAtMention removes the leading "@BotName" prefix from group chat messages. +// Bot names may contain spaces (e.g., "WeKnora Bot"), so this adds two strategies +// on top of stripAtMentionBasic: (1) double-space split with bot-name learning, +// (2) cached/configured bot name prefix match. +// Concurrent calls are safe; atomic.Value races are benign (same bot name). +func (c *LongConnClient) stripAtMention(content string) string { + content = strings.TrimSpace(content) + if !strings.HasPrefix(content, "@") { + return content + } + + // Strategy 1: double-space separator. Learn bot name on first occurrence + // (skip if already cached to avoid false positives from user double-spaces). + if idx := strings.Index(content, " "); idx > 0 { + botName := content[1:idx] // between "@" and " " + if cached, _ := c.botDisplayName.Load().(string); cached == "" && botName != "" { + c.botDisplayName.Store(botName) + } + return strings.TrimSpace(content[idx+2:]) + } + + // Strategy 2: cached/configured bot name with word-boundary check. + if name, _ := c.botDisplayName.Load().(string); name != "" { + prefix := "@" + name + if strings.HasPrefix(content, prefix) && (len(content) == len(prefix) || content[len(prefix)] == ' ') { + return strings.TrimSpace(content[len(prefix):]) + } + } + + // Strategy 3: delegate to stateless helper (heuristic scan + first-@word fallback). + return stripAtMentionBasic(content) +} + func (c *LongConnClient) writeJSON(v interface{}) error { c.mu.Lock() defer c.mu.Unlock() diff --git a/internal/im/wecom/mention_test.go b/internal/im/wecom/mention_test.go new file mode 100644 index 00000000..51887fc5 --- /dev/null +++ b/internal/im/wecom/mention_test.go @@ -0,0 +1,154 @@ +package wecom + +import ( + "testing" +) + +func TestStripAtMentionBasic(t *testing.T) { + tests := []struct { + name string + content string + want string + }{ + {"no mention", "hello world", "hello world"}, + {"empty string", "", ""}, + {"mention only no content", "@Bot", "@Bot"}, + {"single-word bot double-space", "@Bot /stop", "/stop"}, + {"single-word bot single-space", "@Bot /stop", "/stop"}, + {"single-word bot double-space chinese", "@Bot 你好世界", "你好世界"}, + {"multi-word bot double-space", "@WeKnora Bot /stop", "/stop"}, + {"multi-word bot double-space chinese", "@WeKnora Bot 什么是上下文工程", "什么是上下文工程"}, + {"multi-word bot single-space command", "@WeKnora Bot /stop", "/stop"}, + {"multi-word bot single-space chinese", "@WeKnora Bot 什么是老登", "什么是老登"}, + {"leading whitespace", " @Bot hello ", "hello"}, + {"double-space in user content", "@Bot hello world", "hello world"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := stripAtMentionBasic(tt.content) + if got != tt.want { + t.Errorf("stripAtMentionBasic(%q) = %q, want %q", tt.content, got, tt.want) + } + }) + } +} + +func TestLongConnClient_StripAtMention(t *testing.T) { + t.Run("learns bot name from double-space then handles single-space", func(t *testing.T) { + c := &LongConnClient{} + + // First message: double-space → learn "WeKnora Bot" + got := c.stripAtMention("@WeKnora Bot 什么是上下文工程") + if got != "什么是上下文工程" { + t.Errorf("first message: got %q, want %q", got, "什么是上下文工程") + } + + // Verify bot name was cached + if name, _ := c.botDisplayName.Load().(string); name != "WeKnora Bot" { + t.Errorf("cached bot name = %q, want %q", name, "WeKnora Bot") + } + + // Second message: single-space → should use cached name + got = c.stripAtMention("@WeKnora Bot /stop") + if got != "/stop" { + t.Errorf("second message: got %q, want %q", got, "/stop") + } + + // Single-space with chinese content + got = c.stripAtMention("@WeKnora Bot 什么是B+树") + if got != "什么是B+树" { + t.Errorf("chinese single-space: got %q, want %q", got, "什么是B+树") + } + }) + + t.Run("preconfigured bot name", func(t *testing.T) { + c := &LongConnClient{} + c.botDisplayName.Store("WeKnora Bot") + + // Single-space should work immediately without learning + got := c.stripAtMention("@WeKnora Bot /stop") + if got != "/stop" { + t.Errorf("got %q, want %q", got, "/stop") + } + }) + + t.Run("cached name must not partial-match a longer bot name", func(t *testing.T) { + c := &LongConnClient{} + c.botDisplayName.Store("Bot") + + // "@BotX /stop" should NOT match cached "Bot" — "BotX" is a different name. + // Falls through to Strategy 3 (strip first @word). + got := c.stripAtMention("@BotX /stop") + if got != "/stop" { + t.Errorf("got %q, want %q", got, "/stop") + } + }) + + t.Run("NewLongConnClient with bot name", func(t *testing.T) { + c := NewLongConnClient("id", "secret", "My Bot", nil) + + got := c.stripAtMention("@My Bot /help") + if got != "/help" { + t.Errorf("got %q, want %q", got, "/help") + } + }) + + t.Run("does not overwrite cached name from user double-spaces", func(t *testing.T) { + c := &LongConnClient{} + c.botDisplayName.Store("Bot") + + // User content has double space — should NOT overwrite "Bot" with "Bot hello" + got := c.stripAtMention("@Bot hello world") + if got != "hello world" { + t.Errorf("got %q, want %q", got, "hello world") + } + + // Cached name should still be "Bot" + if name, _ := c.botDisplayName.Load().(string); name != "Bot" { + t.Errorf("cached bot name = %q, want %q", name, "Bot") + } + }) + + t.Run("no mention passthrough", func(t *testing.T) { + c := &LongConnClient{} + got := c.stripAtMention("hello world") + if got != "hello world" { + t.Errorf("got %q, want %q", got, "hello world") + } + }) + + t.Run("empty string", func(t *testing.T) { + c := &LongConnClient{} + got := c.stripAtMention("") + if got != "" { + t.Errorf("got %q, want %q", got, "") + } + }) + + t.Run("cold start single-space command", func(t *testing.T) { + c := &LongConnClient{} + // No cached name, single space → heuristic detects " /" boundary + got := c.stripAtMention("@WeKnora Bot /stop") + if got != "/stop" { + t.Errorf("got %q, want %q", got, "/stop") + } + }) + + t.Run("cold start single-space chinese", func(t *testing.T) { + c := &LongConnClient{} + // No cached name, single space → heuristic detects non-ASCII boundary + got := c.stripAtMention("@WeKnora Bot 什么是老登") + if got != "什么是老登" { + t.Errorf("got %q, want %q", got, "什么是老登") + } + }) + + t.Run("cold start all-ascii content falls back to first word", func(t *testing.T) { + c := &LongConnClient{} + // No cached name, all ASCII → heuristic can't find boundary, strips first @word + got := c.stripAtMention("@WeKnora Bot hello") + if got != "Bot hello" { + t.Errorf("got %q, want %q", got, "Bot hello") + } + }) +} diff --git a/internal/im/wecom/webhook_adapter.go b/internal/im/wecom/webhook_adapter.go index 5c55bc4e..b088cc43 100644 --- a/internal/im/wecom/webhook_adapter.go +++ b/internal/im/wecom/webhook_adapter.go @@ -167,13 +167,20 @@ func (a *WebhookAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, err // Determine chat type chatType := im.ChatTypeDirect chatID := "" - if msg.ChatID != "" { + isGroup := msg.ChatID != "" + if isGroup { chatType = im.ChatTypeGroup chatID = msg.ChatID } switch msg.MsgType { case "text": + // Strip @mention in group chat (same issue as long connection mode). + // Webhook adapter has no persistent state, so use the standalone helper. + textContent := msg.Content + if isGroup { + textContent = stripAtMentionBasic(textContent) + } return &im.IncomingMessage{ Platform: im.PlatformWeCom, MessageType: im.MessageTypeText, @@ -181,7 +188,7 @@ func (a *WebhookAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, err UserName: msg.FromUserName, ChatID: chatID, ChatType: chatType, - Content: strings.TrimSpace(msg.Content), + Content: strings.TrimSpace(textContent), MessageID: msg.MsgID, }, nil