feat: add WeCom and Feishu IM bot integration

- support webhook and websocket modes for both platforms
- add im_channel_sessions migration for channel-session mapping
- register IM adapters and callback routes
- update config and docker-compose for IM env vars
This commit is contained in:
nullkey
2026-03-15 18:45:53 +08:00
committed by lyingbug
parent 0e8f1b1c81
commit 9fa969fb5c
18 changed files with 2239 additions and 4 deletions
+369
View File
@@ -0,0 +1,369 @@
// Package wecom implements the WeCom (企业微信) IM adapter for WeKnora.
//
// WeCom Smart Bot flow:
// 1. User sends a message to the bot (direct or @mention in group)
// 2. WeCom calls our callback URL with the encrypted message
// 3. We decrypt, parse, and return an immediate response (or stream response)
// 4. For streaming: respond with msgtype="stream", WeCom pulls subsequent chunks via refresh callbacks
//
// Reference: https://developer.work.weixin.qq.com/document/path/101031
package wecom
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"sort"
"strings"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/gin-gonic/gin"
)
var httpClient = &http.Client{Timeout: 10 * time.Second}
// Adapter implements im.Adapter for WeCom.
type Adapter struct {
corpID string
token string
encodingAESKey string
aesKey []byte
agentSecret string
corpAgentID int
// Token cache
tokenMu sync.Mutex
tokenCache string
tokenExpAt time.Time
}
// NewAdapter creates a new WeCom adapter.
func NewAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID int) (*Adapter, error) {
// Decode the AES key from base64
aesKey, err := base64.StdEncoding.DecodeString(encodingAESKey + "=")
if err != nil {
return nil, fmt.Errorf("decode encoding_aes_key: %w", err)
}
return &Adapter{
corpID: corpID,
token: token,
encodingAESKey: encodingAESKey,
aesKey: aesKey,
agentSecret: agentSecret,
corpAgentID: corpAgentID,
}, nil
}
// Platform returns the platform identifier.
func (a *Adapter) Platform() im.Platform {
return im.PlatformWeCom
}
// VerifyCallback verifies the WeCom callback signature.
func (a *Adapter) VerifyCallback(c *gin.Context) error {
timestamp := c.Query("timestamp")
nonce := c.Query("nonce")
msgSignature := c.Query("msg_signature")
// For GET requests (URL verification), use echostr
// For POST requests (message callback), use request body's Encrypt field
var encrypt string
if c.Request.Method == http.MethodGet {
encrypt = c.Query("echostr")
} else {
var body callbackRequestBody
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return fmt.Errorf("read request body: %w", err)
}
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
if err := xml.Unmarshal(bodyBytes, &body); err != nil {
return fmt.Errorf("unmarshal xml body: %w", err)
}
encrypt = body.Encrypt
}
if !a.verifySignature(msgSignature, timestamp, nonce, encrypt) {
return fmt.Errorf("invalid signature")
}
return nil
}
// HandleURLVerification handles the WeCom URL verification (GET request).
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
if c.Request.Method != http.MethodGet {
return false
}
echoStr := c.Query("echostr")
if echoStr == "" {
return false
}
// Decrypt the echostr and return it
decrypted, err := a.decrypt(echoStr)
if err != nil {
logger.Errorf(c.Request.Context(), "[WeCom] Failed to decrypt echostr: %v", err)
c.String(http.StatusBadRequest, "decrypt failed")
return true
}
c.String(http.StatusOK, string(decrypted))
return true
}
// ParseCallback parses a WeCom callback into a unified IncomingMessage.
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
}
var body callbackRequestBody
if err := xml.Unmarshal(bodyBytes, &body); err != nil {
return nil, fmt.Errorf("unmarshal xml: %w", err)
}
// Decrypt the message
decrypted, err := a.decrypt(body.Encrypt)
if err != nil {
return nil, fmt.Errorf("decrypt message: %w", err)
}
var msg wecomMessage
if err := xml.Unmarshal(decrypted, &msg); err != nil {
return nil, fmt.Errorf("unmarshal decrypted message: %w", err)
}
// Only handle text messages
if msg.MsgType != "text" {
logger.Infof(c.Request.Context(), "[WeCom] Ignoring non-text message type: %s", msg.MsgType)
return nil, nil
}
chatType := im.ChatTypeDirect
chatID := ""
content := msg.Content
// Check if this is a group message (has ChatId field in WeCom smart bot callback)
// In group chats, the content may contain @bot mention prefix that should be stripped
if msg.ChatID != "" {
chatType = im.ChatTypeGroup
chatID = msg.ChatID
}
return &im.IncomingMessage{
Platform: im.PlatformWeCom,
UserID: msg.FromUserName,
UserName: msg.FromUserName,
ChatID: chatID,
ChatType: chatType,
Content: strings.TrimSpace(content),
MessageID: msg.MsgID,
}, nil
}
// SendReply sends a reply message via WeCom API.
// For simplicity, this uses the "应用消息" API to proactively send messages.
// A production implementation would integrate with the streaming callback model.
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
// Get access token
accessToken, err := a.getAccessToken(ctx)
if err != nil {
return fmt.Errorf("get access token: %w", err)
}
// Build message payload.
// Note: /cgi-bin/message/send only supports touser/toparty/totag — it does NOT
// support regular group chat IDs (chatid is only for appchat-created groups).
// So for both direct and group messages we reply to the user directly.
payload := map[string]interface{}{
"touser": incoming.UserID,
"msgtype": "markdown",
"agentid": a.corpAgentID,
"markdown": map[string]string{
"content": reply.Content,
},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal payload: %w", err)
}
sendURL := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", accessToken)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, sendURL, bytes.NewReader(payloadBytes))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("send message: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("decode response: %w", err)
}
if result.ErrCode != 0 {
return fmt.Errorf("wecom api error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
return nil
}
// getAccessToken retrieves the WeCom access token with caching.
// WeCom tokens expire in 7200 seconds (2 hours); we cache with a safety margin.
func (a *Adapter) getAccessToken(ctx context.Context) (string, error) {
a.tokenMu.Lock()
defer a.tokenMu.Unlock()
if a.tokenCache != "" && time.Now().Before(a.tokenExpAt) {
return a.tokenCache, nil
}
tokenURL := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
a.corpID, a.agentSecret)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenURL, nil)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request access token: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"` // seconds
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("decode token response: %w", err)
}
if result.ErrCode != 0 {
return "", fmt.Errorf("get token error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
a.tokenCache = result.AccessToken
// Cache with 5-minute safety margin
ttl := time.Duration(result.ExpiresIn) * time.Second
if ttl > 5*time.Minute {
ttl -= 5 * time.Minute
}
a.tokenExpAt = time.Now().Add(ttl)
return a.tokenCache, nil
}
// verifySignature verifies the WeCom callback signature using constant-time comparison.
func (a *Adapter) verifySignature(signature, timestamp, nonce, encrypt string) bool {
parts := []string{a.token, timestamp, nonce, encrypt}
sort.Strings(parts)
combined := strings.Join(parts, "")
hash := sha1.New()
hash.Write([]byte(combined))
computed := fmt.Sprintf("%x", hash.Sum(nil))
return hmac.Equal([]byte(computed), []byte(signature))
}
// decrypt decrypts a WeCom AES-encrypted message.
func (a *Adapter) decrypt(encrypted string) ([]byte, error) {
ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return nil, fmt.Errorf("base64 decode: %w", err)
}
block, err := aes.NewCipher(a.aesKey)
if err != nil {
return nil, fmt.Errorf("new cipher: %w", err)
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("ciphertext too short")
}
iv := a.aesKey[:aes.BlockSize]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
// Remove and verify PKCS#7 padding
padLen := int(ciphertext[len(ciphertext)-1])
if padLen > aes.BlockSize || padLen == 0 || padLen > len(ciphertext) {
return nil, fmt.Errorf("invalid padding")
}
for i := 0; i < padLen; i++ {
if ciphertext[len(ciphertext)-1-i] != byte(padLen) {
return nil, fmt.Errorf("invalid padding")
}
}
plaintext := ciphertext[:len(ciphertext)-padLen]
// WeCom format: random(16) + msg_len(4) + msg + corp_id
if len(plaintext) < 20 {
return nil, fmt.Errorf("plaintext too short")
}
msgLen := binary.BigEndian.Uint32(plaintext[16:20])
if uint32(len(plaintext)) < 20+msgLen {
return nil, fmt.Errorf("message length mismatch")
}
msgBytes := plaintext[20 : 20+msgLen]
// Verify corp_id from plaintext tail
corpIDBytes := plaintext[20+msgLen:]
if string(corpIDBytes) != a.corpID {
return nil, fmt.Errorf("corp_id mismatch: expected %s, got %s", a.corpID, string(corpIDBytes))
}
return msgBytes, nil
}
// callbackRequestBody is the XML structure of a WeCom callback request body.
type callbackRequestBody struct {
XMLName xml.Name `xml:"xml"`
ToUserName string `xml:"ToUserName"`
Encrypt string `xml:"Encrypt"`
AgentID string `xml:"AgentID"`
}
// wecomMessage is the decrypted WeCom message structure.
type wecomMessage struct {
XMLName xml.Name `xml:"xml"`
ToUserName string `xml:"ToUserName"`
FromUserName string `xml:"FromUserName"`
CreateTime int64 `xml:"CreateTime"`
MsgType string `xml:"MsgType"`
Content string `xml:"Content"`
MsgID string `xml:"MsgId"`
AgentID string `xml:"AgentID"`
ChatID string `xml:"ChatId"`
}
+42
View File
@@ -0,0 +1,42 @@
package wecom
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/gin-gonic/gin"
)
// BotAdapter implements im.Adapter for WeCom intelligent bot (long connection mode).
// It delegates SendReply to the WebSocket LongConnClient.
// The webhook methods (VerifyCallback, ParseCallback, HandleURLVerification) are no-ops
// since messages arrive via WebSocket, not HTTP.
type BotAdapter struct {
client *LongConnClient
}
// NewBotAdapter creates an adapter backed by a WeCom long connection client.
func NewBotAdapter(client *LongConnClient) *BotAdapter {
return &BotAdapter{client: client}
}
func (a *BotAdapter) Platform() im.Platform {
return im.PlatformWeCom
}
func (a *BotAdapter) VerifyCallback(c *gin.Context) error {
return fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
}
func (a *BotAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
return nil, fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
}
func (a *BotAdapter) HandleURLVerification(c *gin.Context) bool {
return false
}
func (a *BotAdapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
return a.client.SendReply(ctx, incoming, reply)
}
+353
View File
@@ -0,0 +1,353 @@
// WeCom Intelligent Bot long connection client.
//
// Protocol reference: https://developer.work.weixin.qq.com/document/path/101463
// Node.js SDK reference: https://github.com/WecomTeam/aibot-node-sdk
//
// Flow:
// 1. Connect to wss://openws.work.weixin.qq.com
// 2. Send aibot_subscribe with bot_id + secret
// 3. Receive aibot_msg_callback / aibot_event_callback frames
// 4. Reply via aibot_respond_msg on the same WebSocket
// 5. Heartbeat via ping/pong every 30s
package wecom
import (
"context"
"encoding/json"
"fmt"
"math"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
ws "github.com/gorilla/websocket"
)
const (
wecomWSEndpoint = "wss://openws.work.weixin.qq.com"
cmdSubscribe = "aibot_subscribe"
cmdPing = "ping"
cmdMsgCallback = "aibot_msg_callback"
cmdEventCallback = "aibot_event_callback"
cmdResponse = "aibot_respond_msg"
defaultHeartbeatInterval = 30 * time.Second
defaultReconnectBaseDelay = 1 * time.Second
defaultReconnectMaxDelay = 30 * time.Second
defaultMaxReconnectAttempts = -1 // infinite
)
// wsFrame is the JSON frame exchanged over the WeCom bot WebSocket.
type wsFrame struct {
Cmd string `json:"cmd,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body json.RawMessage `json:"body,omitempty"`
ErrCode int `json:"errcode,omitempty"`
ErrMsg string `json:"errmsg,omitempty"`
}
// botMessage is the body of an aibot_msg_callback frame.
type botMessage struct {
MsgID string `json:"msgid"`
AiBotID string `json:"aibotid"`
ChatID string `json:"chatid"`
ChatType string `json:"chattype"` // "single" or "group"
MsgType string `json:"msgtype"` // "text", "image", "event", ...
CreateTime int64 `json:"create_time"`
From struct {
UserID string `json:"userid"`
} `json:"from"`
Text struct {
Content string `json:"content"`
} `json:"text"`
}
// streamReplyBody is the body for a streaming text reply.
type streamReplyBody struct {
MsgType string `json:"msgtype"`
Stream struct {
ID string `json:"id"`
Finish bool `json:"finish"`
Content string `json:"content"`
} `json:"stream"`
}
// MessageHandler is called when an IM message is received via long connection.
type MessageHandler func(ctx context.Context, msg *im.IncomingMessage) error
// LongConnClient manages a WeCom intelligent bot WebSocket long connection.
type LongConnClient struct {
botID string
secret string
handler MessageHandler
conn *ws.Conn
mu sync.Mutex
closed atomic.Bool
reqSeq atomic.Int64
}
// NewLongConnClient creates a WeCom long connection client.
func NewLongConnClient(botID, secret string, handler MessageHandler) *LongConnClient {
return &LongConnClient{
botID: botID,
secret: secret,
handler: handler,
}
}
// Start connects and runs the long connection loop. It reconnects automatically on failure.
func (c *LongConnClient) Start(ctx context.Context) error {
logger.Infof(ctx, "[IM] WeCom WebSocket connecting (bot_id=%s)...", c.botID)
attempts := 0
for {
if ctx.Err() != nil {
return ctx.Err()
}
err := c.connectAndRun(ctx)
if c.closed.Load() {
return nil
}
if ctx.Err() != nil {
return ctx.Err()
}
attempts++
if defaultMaxReconnectAttempts >= 0 && attempts >= defaultMaxReconnectAttempts {
return fmt.Errorf("max reconnect attempts reached: %w", err)
}
delay := reconnectDelay(attempts)
logger.Warnf(ctx, "[WeCom] Connection lost (%v), reconnecting in %v (attempt %d)...", err, delay, attempts)
select {
case <-time.After(delay):
case <-ctx.Done():
return ctx.Err()
}
}
}
// Stop gracefully closes the connection.
func (c *LongConnClient) Stop() {
c.closed.Store(true)
c.mu.Lock()
defer c.mu.Unlock()
if c.conn != nil {
_ = c.conn.Close()
c.conn = nil
}
}
// SendReply sends a text reply through the WebSocket connection.
// This is used by the IM service to reply to messages in long connection mode.
func (c *LongConnClient) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
reqID, ok := incoming.Extra["req_id"]
if !ok || reqID == "" {
return fmt.Errorf("missing req_id in incoming message extra")
}
// Generate a unique stream ID for this reply
streamID := fmt.Sprintf("stream_%d", c.reqSeq.Add(1))
body := streamReplyBody{MsgType: "stream"}
body.Stream.ID = streamID
body.Stream.Finish = true
body.Stream.Content = reply.Content
bodyBytes, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal reply body: %w", err)
}
frame := wsFrame{
Cmd: cmdResponse,
Headers: map[string]string{"req_id": reqID},
Body: bodyBytes,
}
return c.writeJSON(frame)
}
func (c *LongConnClient) connectAndRun(ctx context.Context) error {
conn, _, err := ws.DefaultDialer.DialContext(ctx, wecomWSEndpoint, nil)
if err != nil {
return fmt.Errorf("dial: %w", err)
}
c.mu.Lock()
c.conn = conn
c.mu.Unlock()
defer func() {
c.mu.Lock()
c.conn = nil
c.mu.Unlock()
_ = conn.Close()
}()
// Authenticate
if err := c.authenticate(ctx); err != nil {
return fmt.Errorf("authenticate: %w", err)
}
logger.Infof(ctx, "[IM] WeCom WebSocket connected successfully (bot_id=%s)", c.botID)
// Start heartbeat
heartbeatCtx, heartbeatCancel := context.WithCancel(ctx)
defer heartbeatCancel()
go c.heartbeatLoop(heartbeatCtx)
// Message receive loop
for {
_, message, err := conn.ReadMessage()
if err != nil {
return fmt.Errorf("read message: %w", err)
}
var frame wsFrame
if err := json.Unmarshal(message, &frame); err != nil {
logger.Warnf(ctx, "[WeCom] Failed to unmarshal frame: %v", err)
continue
}
switch frame.Cmd {
case cmdMsgCallback, cmdEventCallback:
// Detach from connection ctx so in-flight messages survive reconnects.
go c.handleCallback(context.WithoutCancel(ctx), frame)
default:
// pong or other control frames — ignore
}
}
}
func (c *LongConnClient) authenticate(ctx context.Context) error {
authBody, _ := json.Marshal(map[string]string{
"bot_id": c.botID,
"secret": c.secret,
})
reqID := fmt.Sprintf("%s_%d", cmdSubscribe, time.Now().UnixNano())
frame := wsFrame{
Cmd: cmdSubscribe,
Headers: map[string]string{"req_id": reqID},
Body: authBody,
}
if err := c.writeJSON(frame); err != nil {
return fmt.Errorf("send subscribe: %w", err)
}
// Read auth response
c.mu.Lock()
conn := c.conn
c.mu.Unlock()
if conn == nil {
return fmt.Errorf("connection closed")
}
_ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
_, msg, err := conn.ReadMessage()
_ = conn.SetReadDeadline(time.Time{}) // clear deadline
if err != nil {
return fmt.Errorf("read auth response: %w", err)
}
var resp wsFrame
if err := json.Unmarshal(msg, &resp); err != nil {
return fmt.Errorf("unmarshal auth response: %w", err)
}
if resp.ErrCode != 0 {
return fmt.Errorf("auth failed: code=%d msg=%s", resp.ErrCode, resp.ErrMsg)
}
return nil
}
func (c *LongConnClient) heartbeatLoop(ctx context.Context) {
ticker := time.NewTicker(defaultHeartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
reqID := fmt.Sprintf("%s_%d", cmdPing, time.Now().UnixNano())
frame := wsFrame{
Cmd: cmdPing,
Headers: map[string]string{"req_id": reqID},
}
if err := c.writeJSON(frame); err != nil {
logger.Warnf(ctx, "[WeCom] Heartbeat failed: %v", err)
return
}
}
}
}
func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) {
var msg botMessage
if err := json.Unmarshal(frame.Body, &msg); err != nil {
logger.Warnf(ctx, "[WeCom] Failed to unmarshal callback body: %v", err)
return
}
// Only handle text messages for now
if msg.MsgType != "text" {
logger.Infof(ctx, "[WeCom] Ignoring non-text message type: %s", msg.MsgType)
return
}
chatType := im.ChatTypeDirect
chatID := ""
if msg.ChatType == "group" {
chatType = im.ChatTypeGroup
chatID = msg.ChatID
}
// Preserve req_id in Extra for reply routing
reqID := ""
if frame.Headers != nil {
reqID = frame.Headers["req_id"]
}
incoming := &im.IncomingMessage{
Platform: im.PlatformWeCom,
UserID: msg.From.UserID,
UserName: msg.From.UserID,
ChatID: chatID,
ChatType: chatType,
Content: strings.TrimSpace(msg.Text.Content),
MessageID: msg.MsgID,
Extra: map[string]string{"req_id": reqID},
}
if err := c.handler(ctx, incoming); err != nil {
logger.Errorf(ctx, "[WeCom] Handle message error: %v", err)
}
}
func (c *LongConnClient) writeJSON(v interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return fmt.Errorf("connection closed")
}
return c.conn.WriteJSON(v)
}
func reconnectDelay(attempt int) time.Duration {
delay := defaultReconnectBaseDelay * time.Duration(math.Pow(2, float64(attempt-1)))
if delay > defaultReconnectMaxDelay {
delay = defaultReconnectMaxDelay
}
return delay
}