mirror of
https://github.com/YspCoder/clawgo.git
synced 2026-04-12 06:17:31 +08:00
feat: add multi-account weixin channel
This commit is contained in:
@@ -188,6 +188,12 @@ func gatewayCmd() {
|
||||
if whatsAppBridge != nil {
|
||||
registryServer.SetWhatsAppBridge(whatsAppBridge, embeddedWhatsAppBridgeBasePath)
|
||||
}
|
||||
if rawWeixin, ok := channelManager.GetChannel("weixin"); ok {
|
||||
if weixinChannel, ok := rawWeixin.(*channels.WeixinChannel); ok {
|
||||
weixinChannel.SetConfigPath(getConfigPath())
|
||||
registryServer.SetWeixinChannel(weixinChannel)
|
||||
}
|
||||
}
|
||||
registryServer.SetCronHandler(func(action string, args map[string]interface{}) (interface{}, error) {
|
||||
getStr := func(k string) string {
|
||||
v, _ := args[k].(string)
|
||||
@@ -424,6 +430,14 @@ func gatewayCmd() {
|
||||
registryServer.SetWorkspacePath(cfg.WorkspacePath())
|
||||
registryServer.SetLogFilePath(cfg.LogFilePath())
|
||||
registryServer.SetWhatsAppBridge(whatsAppBridge, embeddedWhatsAppBridgeBasePath)
|
||||
if rawWeixin, ok := channelManager.GetChannel("weixin"); ok {
|
||||
if weixinChannel, ok := rawWeixin.(*channels.WeixinChannel); ok {
|
||||
weixinChannel.SetConfigPath(getConfigPath())
|
||||
registryServer.SetWeixinChannel(weixinChannel)
|
||||
}
|
||||
} else {
|
||||
registryServer.SetWeixinChannel(nil)
|
||||
}
|
||||
sentinelService.Stop()
|
||||
sentinelService = sentinel.NewService(
|
||||
getConfigPath(),
|
||||
|
||||
@@ -145,6 +145,13 @@
|
||||
"inbound_message_id_dedupe_ttl_seconds": 600,
|
||||
"inbound_content_dedupe_window_seconds": 12,
|
||||
"outbound_dedupe_window_seconds": 12,
|
||||
"weixin": {
|
||||
"enabled": false,
|
||||
"base_url": "https://ilinkai.weixin.qq.com",
|
||||
"default_bot_id": "",
|
||||
"accounts": [],
|
||||
"allow_from": []
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "YOUR_TELEGRAM_BOT_TOKEN",
|
||||
|
||||
@@ -53,6 +53,7 @@ type Server struct {
|
||||
onToolsCatalog func() interface{}
|
||||
whatsAppBridge *channels.WhatsAppBridgeService
|
||||
whatsAppBase string
|
||||
weixinChannel *channels.WeixinChannel
|
||||
oauthFlowMu sync.Mutex
|
||||
oauthFlows map[string]*providers.OAuthPendingFlow
|
||||
extraRoutesMu sync.RWMutex
|
||||
@@ -109,6 +110,10 @@ func (s *Server) SetWhatsAppBridge(service *channels.WhatsAppBridgeService, base
|
||||
s.whatsAppBase = strings.TrimSpace(basePath)
|
||||
}
|
||||
|
||||
func (s *Server) SetWeixinChannel(ch *channels.WeixinChannel) {
|
||||
s.weixinChannel = ch
|
||||
}
|
||||
|
||||
func (s *Server) handleWhatsAppBridgeWS(w http.ResponseWriter, r *http.Request) {
|
||||
if s.whatsAppBridge == nil {
|
||||
http.Error(w, "whatsapp bridge unavailable", http.StatusServiceUnavailable)
|
||||
@@ -190,6 +195,12 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
mux.HandleFunc("/api/whatsapp/status", s.handleWebUIWhatsAppStatus)
|
||||
mux.HandleFunc("/api/whatsapp/logout", s.handleWebUIWhatsAppLogout)
|
||||
mux.HandleFunc("/api/whatsapp/qr.svg", s.handleWebUIWhatsAppQR)
|
||||
mux.HandleFunc("/api/weixin/status", s.handleWebUIWeixinStatus)
|
||||
mux.HandleFunc("/api/weixin/login/start", s.handleWebUIWeixinLoginStart)
|
||||
mux.HandleFunc("/api/weixin/login/cancel", s.handleWebUIWeixinLoginCancel)
|
||||
mux.HandleFunc("/api/weixin/qr.svg", s.handleWebUIWeixinQR)
|
||||
mux.HandleFunc("/api/weixin/accounts/remove", s.handleWebUIWeixinAccountRemove)
|
||||
mux.HandleFunc("/api/weixin/accounts/default", s.handleWebUIWeixinAccountDefault)
|
||||
mux.HandleFunc("/api/upload", s.handleWebUIUpload)
|
||||
mux.HandleFunc("/api/cron", s.handleWebUICron)
|
||||
mux.HandleFunc("/api/skills", s.handleWebUISkills)
|
||||
@@ -1318,6 +1329,227 @@ func (s *Server) webUIWhatsAppStatusPayload(ctx context.Context) (map[string]int
|
||||
}, http.StatusOK
|
||||
}
|
||||
|
||||
func (s *Server) handleWebUIWeixinStatus(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
payload, code := s.webUIWeixinStatusPayload(r.Context())
|
||||
writeJSONStatus(w, code, payload)
|
||||
}
|
||||
|
||||
func (s *Server) handleWebUIWeixinLoginStart(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if s.weixinChannel == nil {
|
||||
http.Error(w, "weixin channel unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if _, err := s.weixinChannel.StartLogin(r.Context()); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
payload, code := s.webUIWeixinStatusPayload(r.Context())
|
||||
writeJSONStatus(w, code, payload)
|
||||
}
|
||||
|
||||
func (s *Server) handleWebUIWeixinLoginCancel(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if s.weixinChannel == nil {
|
||||
http.Error(w, "weixin channel unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
LoginID string `json:"login_id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid json body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !s.weixinChannel.CancelPendingLogin(body.LoginID) {
|
||||
http.Error(w, "login_id not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
payload, code := s.webUIWeixinStatusPayload(r.Context())
|
||||
writeJSONStatus(w, code, payload)
|
||||
}
|
||||
|
||||
func (s *Server) handleWebUIWeixinQR(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
payload, code := s.webUIWeixinStatusPayload(r.Context())
|
||||
if code != http.StatusOK {
|
||||
http.Error(w, "qr unavailable", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
qrCode := ""
|
||||
loginID := strings.TrimSpace(r.URL.Query().Get("login_id"))
|
||||
if loginID != "" && s.weixinChannel != nil {
|
||||
if pending := s.weixinChannel.PendingLoginByID(loginID); pending != nil {
|
||||
qrCode = fallbackString(pending.QRCodeImgContent, pending.QRCode)
|
||||
}
|
||||
}
|
||||
if qrCode == "" {
|
||||
pendingItems, _ := payload["pending_logins"].([]interface{})
|
||||
if len(pendingItems) > 0 {
|
||||
if pending, ok := pendingItems[0].(map[string]interface{}); ok {
|
||||
qrCode = fallbackString(stringFromMap(pending, "qr_code_img_content"), stringFromMap(pending, "qr_code"))
|
||||
}
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(qrCode) == "" {
|
||||
http.Error(w, "qr unavailable", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
qrImage, err := qr.Encode(strings.TrimSpace(qrCode), qr.M)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/svg+xml")
|
||||
_, _ = io.WriteString(w, renderQRCodeSVG(qrImage, 8, 24))
|
||||
}
|
||||
|
||||
func (s *Server) handleWebUIWeixinAccountRemove(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if s.weixinChannel == nil {
|
||||
http.Error(w, "weixin channel unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
BotID string `json:"bot_id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid json body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.weixinChannel.RemoveAccount(body.BotID); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
payload, code := s.webUIWeixinStatusPayload(r.Context())
|
||||
writeJSONStatus(w, code, payload)
|
||||
}
|
||||
|
||||
func (s *Server) handleWebUIWeixinAccountDefault(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if s.weixinChannel == nil {
|
||||
http.Error(w, "weixin channel unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
BotID string `json:"bot_id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid json body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.weixinChannel.SetDefaultAccount(body.BotID); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
payload, code := s.webUIWeixinStatusPayload(r.Context())
|
||||
writeJSONStatus(w, code, payload)
|
||||
}
|
||||
|
||||
func (s *Server) webUIWeixinStatusPayload(ctx context.Context) (map[string]interface{}, int) {
|
||||
cfg, err := s.loadConfig()
|
||||
if err != nil {
|
||||
return map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": err.Error(),
|
||||
}, http.StatusInternalServerError
|
||||
}
|
||||
weixinCfg := cfg.Channels.Weixin
|
||||
if s.weixinChannel == nil {
|
||||
return map[string]interface{}{
|
||||
"ok": false,
|
||||
"enabled": weixinCfg.Enabled,
|
||||
"base_url": weixinCfg.BaseURL,
|
||||
"error": "weixin channel unavailable",
|
||||
}, http.StatusOK
|
||||
}
|
||||
pendingLogins, err := s.weixinChannel.RefreshLoginStatuses(ctx)
|
||||
if err != nil {
|
||||
return map[string]interface{}{
|
||||
"ok": false,
|
||||
"enabled": weixinCfg.Enabled,
|
||||
"base_url": weixinCfg.BaseURL,
|
||||
"error": err.Error(),
|
||||
}, http.StatusOK
|
||||
}
|
||||
accounts := s.weixinChannel.ListAccounts()
|
||||
pendingPayload := make([]map[string]interface{}, 0, len(pendingLogins))
|
||||
for _, pending := range pendingLogins {
|
||||
pendingPayload = append(pendingPayload, map[string]interface{}{
|
||||
"login_id": pendingString(pending, "login_id"),
|
||||
"qr_code": pendingString(pending, "qr_code"),
|
||||
"qr_code_img_content": pendingString(pending, "qr_code_img_content"),
|
||||
"status": pendingString(pending, "status"),
|
||||
"last_error": pendingString(pending, "last_error"),
|
||||
"updated_at": pendingString(pending, "updated_at"),
|
||||
"qr_available": pending != nil && strings.TrimSpace(fallbackString(pending.QRCodeImgContent, pending.QRCode)) != "",
|
||||
})
|
||||
}
|
||||
var firstPending *channels.WeixinPendingLogin
|
||||
if len(pendingLogins) > 0 {
|
||||
firstPending = pendingLogins[0]
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"ok": true,
|
||||
"enabled": weixinCfg.Enabled,
|
||||
"base_url": fallbackString(weixinCfg.BaseURL, "https://ilinkai.weixin.qq.com"),
|
||||
"pending_logins": pendingPayload,
|
||||
"pending_login": map[string]interface{}{
|
||||
"login_id": pendingString(firstPending, "login_id"),
|
||||
"qr_code": pendingString(firstPending, "qr_code"),
|
||||
"qr_code_img_content": pendingString(firstPending, "qr_code_img_content"),
|
||||
"status": pendingString(firstPending, "status"),
|
||||
"last_error": pendingString(firstPending, "last_error"),
|
||||
"updated_at": pendingString(firstPending, "updated_at"),
|
||||
"qr_available": firstPending != nil && strings.TrimSpace(fallbackString(firstPending.QRCodeImgContent, firstPending.QRCode)) != "",
|
||||
},
|
||||
"accounts": accounts,
|
||||
}, http.StatusOK
|
||||
}
|
||||
|
||||
func (s *Server) loadConfig() (*cfgpkg.Config, error) {
|
||||
configPath := strings.TrimSpace(s.configPath)
|
||||
if configPath == "" {
|
||||
@@ -1768,6 +2000,28 @@ func fallbackString(value, fallback string) string {
|
||||
return strings.TrimSpace(fallback)
|
||||
}
|
||||
|
||||
func pendingString(item *channels.WeixinPendingLogin, key string) string {
|
||||
if item == nil {
|
||||
return ""
|
||||
}
|
||||
switch strings.TrimSpace(key) {
|
||||
case "login_id":
|
||||
return strings.TrimSpace(item.LoginID)
|
||||
case "qr_code":
|
||||
return strings.TrimSpace(item.QRCode)
|
||||
case "qr_code_img_content":
|
||||
return strings.TrimSpace(item.QRCodeImgContent)
|
||||
case "status":
|
||||
return strings.TrimSpace(item.Status)
|
||||
case "last_error":
|
||||
return strings.TrimSpace(item.LastError)
|
||||
case "updated_at":
|
||||
return strings.TrimSpace(item.UpdatedAt)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleWebUICron(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
|
||||
@@ -3,7 +3,10 @@ package channels
|
||||
import "sort"
|
||||
|
||||
func CompiledChannelKeys() []string {
|
||||
out := make([]string, 0, 7)
|
||||
out := make([]string, 0, 8)
|
||||
if weixinCompiled {
|
||||
out = append(out, "weixin")
|
||||
}
|
||||
if telegramCompiled {
|
||||
out = append(out, "telegram")
|
||||
}
|
||||
|
||||
@@ -92,6 +92,28 @@ func (m *Manager) initChannels() error {
|
||||
}
|
||||
}
|
||||
|
||||
if m.config.Channels.Weixin.Enabled {
|
||||
if len(m.config.Channels.Weixin.Accounts) == 0 && strings.TrimSpace(m.config.Channels.Weixin.BotToken) == "" {
|
||||
logger.WarnCF("channels", 0, map[string]interface{}{
|
||||
"channel": "weixin",
|
||||
"error": "missing accounts",
|
||||
})
|
||||
} else {
|
||||
weixin, err := NewWeixinChannel(m.config.Channels.Weixin, m.bus)
|
||||
if err != nil {
|
||||
logger.ErrorCF("channels", 0, map[string]interface{}{
|
||||
logger.FieldChannel: "weixin",
|
||||
logger.FieldError: err.Error(),
|
||||
})
|
||||
} else {
|
||||
m.channels["weixin"] = weixin
|
||||
logger.InfoCF("channels", 0, map[string]interface{}{
|
||||
logger.FieldChannel: "weixin",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if m.config.Channels.WhatsApp.Enabled {
|
||||
if m.config.Channels.WhatsApp.BridgeURL == "" {
|
||||
logger.WarnC("channels", logger.C0009)
|
||||
@@ -415,6 +437,12 @@ func (m *Manager) GetEnabledChannels() []string {
|
||||
return names
|
||||
}
|
||||
|
||||
func (m *Manager) GetChannel(name string) (Channel, bool) {
|
||||
cur, _ := m.snapshot.Load().(map[string]Channel)
|
||||
ch, ok := cur[strings.TrimSpace(name)]
|
||||
return ch, ok
|
||||
}
|
||||
|
||||
func (m *Manager) SendToChannel(ctx context.Context, channelName, chatID, content string) error {
|
||||
m.mu.RLock()
|
||||
channel, exists := m.channels[channelName]
|
||||
|
||||
1051
pkg/channels/weixin.go
Normal file
1051
pkg/channels/weixin.go
Normal file
File diff suppressed because it is too large
Load Diff
16
pkg/channels/weixin_stub.go
Normal file
16
pkg/channels/weixin_stub.go
Normal file
@@ -0,0 +1,16 @@
|
||||
//go:build omit_weixin
|
||||
|
||||
package channels
|
||||
|
||||
import (
|
||||
"github.com/YspCoder/clawgo/pkg/bus"
|
||||
"github.com/YspCoder/clawgo/pkg/config"
|
||||
)
|
||||
|
||||
type WeixinChannel struct{ disabledChannel }
|
||||
|
||||
const weixinCompiled = false
|
||||
|
||||
func NewWeixinChannel(cfg config.WeixinConfig, bus *bus.MessageBus) (*WeixinChannel, error) {
|
||||
return nil, errChannelDisabled("weixin")
|
||||
}
|
||||
142
pkg/channels/weixin_test.go
Normal file
142
pkg/channels/weixin_test.go
Normal file
@@ -0,0 +1,142 @@
|
||||
//go:build !omit_weixin
|
||||
|
||||
package channels
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/YspCoder/clawgo/pkg/bus"
|
||||
"github.com/YspCoder/clawgo/pkg/config"
|
||||
)
|
||||
|
||||
func TestBuildAndSplitWeixinChatID(t *testing.T) {
|
||||
chatID := buildWeixinChatID("bot-a", "wx-user-1")
|
||||
if chatID != "bot-a|wx-user-1" {
|
||||
t.Fatalf("unexpected composite chat id: %s", chatID)
|
||||
}
|
||||
botID, rawChatID := splitWeixinChatID(chatID)
|
||||
if botID != "bot-a" || rawChatID != "wx-user-1" {
|
||||
t.Fatalf("unexpected split result: %s %s", botID, rawChatID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeixinHandleInboundMessageUsesCompositeSessionChatID(t *testing.T) {
|
||||
mb := bus.NewMessageBus()
|
||||
ch, err := NewWeixinChannel(config.WeixinConfig{
|
||||
BaseURL: "https://ilinkai.weixin.qq.com",
|
||||
Accounts: []config.WeixinAccountConfig{
|
||||
{BotID: "bot-a", BotToken: "token-a"},
|
||||
},
|
||||
}, mb)
|
||||
if err != nil {
|
||||
t.Fatalf("new weixin channel: %v", err)
|
||||
}
|
||||
|
||||
ch.handleInboundMessage("bot-a", weixinInboundMessage{
|
||||
FromUserID: "wx-user-1",
|
||||
ContextToken: "ctx-1",
|
||||
ItemList: []weixinMessageItem{
|
||||
{Type: 1, TextItem: struct {
|
||||
Text string `json:"text"`
|
||||
}{Text: "hello"}},
|
||||
},
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
msg, ok := mb.ConsumeInbound(ctx)
|
||||
if !ok {
|
||||
t.Fatalf("expected inbound message")
|
||||
}
|
||||
if msg.ChatID != "bot-a|wx-user-1" {
|
||||
t.Fatalf("expected composite chat id, got %s", msg.ChatID)
|
||||
}
|
||||
if msg.SessionKey != "weixin:bot-a|wx-user-1" {
|
||||
t.Fatalf("expected composite session key, got %s", msg.SessionKey)
|
||||
}
|
||||
if msg.SenderID != "wx-user-1" {
|
||||
t.Fatalf("expected raw sender id, got %s", msg.SenderID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeixinResolveAccountForCompositeChatID(t *testing.T) {
|
||||
mb := bus.NewMessageBus()
|
||||
ch, err := NewWeixinChannel(config.WeixinConfig{
|
||||
BaseURL: "https://ilinkai.weixin.qq.com",
|
||||
DefaultBotID: "bot-b",
|
||||
Accounts: []config.WeixinAccountConfig{
|
||||
{BotID: "bot-a", BotToken: "token-a", ContextToken: "ctx-a"},
|
||||
{BotID: "bot-b", BotToken: "token-b", ContextToken: "ctx-b"},
|
||||
},
|
||||
}, mb)
|
||||
if err != nil {
|
||||
t.Fatalf("new weixin channel: %v", err)
|
||||
}
|
||||
|
||||
account, rawChatID, contextToken, err := ch.resolveAccountForChat("bot-a|wx-user-7")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve account: %v", err)
|
||||
}
|
||||
if account.cfg.BotID != "bot-a" {
|
||||
t.Fatalf("expected bot-a, got %s", account.cfg.BotID)
|
||||
}
|
||||
if rawChatID != "wx-user-7" {
|
||||
t.Fatalf("expected raw chat id wx-user-7, got %s", rawChatID)
|
||||
}
|
||||
if contextToken != "ctx-a" {
|
||||
t.Fatalf("expected context token ctx-a, got %s", contextToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeixinSetDefaultAccount(t *testing.T) {
|
||||
mb := bus.NewMessageBus()
|
||||
ch, err := NewWeixinChannel(config.WeixinConfig{
|
||||
BaseURL: "https://ilinkai.weixin.qq.com",
|
||||
Accounts: []config.WeixinAccountConfig{
|
||||
{BotID: "bot-a", BotToken: "token-a"},
|
||||
{BotID: "bot-b", BotToken: "token-b"},
|
||||
},
|
||||
}, mb)
|
||||
if err != nil {
|
||||
t.Fatalf("new weixin channel: %v", err)
|
||||
}
|
||||
|
||||
if err := ch.SetDefaultAccount("bot-b"); err != nil {
|
||||
t.Fatalf("set default account: %v", err)
|
||||
}
|
||||
accounts := ch.ListAccounts()
|
||||
if len(accounts) != 2 {
|
||||
t.Fatalf("expected 2 accounts, got %d", len(accounts))
|
||||
}
|
||||
defaultCount := 0
|
||||
for _, account := range accounts {
|
||||
if account.Default {
|
||||
defaultCount++
|
||||
if account.BotID != "bot-b" {
|
||||
t.Fatalf("expected bot-b to be default, got %s", account.BotID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if defaultCount != 1 {
|
||||
t.Fatalf("expected exactly one default account, got %d", defaultCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeixinCancelPendingLogin(t *testing.T) {
|
||||
mb := bus.NewMessageBus()
|
||||
ch, err := NewWeixinChannel(config.WeixinConfig{BaseURL: "https://ilinkai.weixin.qq.com"}, mb)
|
||||
if err != nil {
|
||||
t.Fatalf("new weixin channel: %v", err)
|
||||
}
|
||||
ch.pendingLogins["login-1"] = &WeixinPendingLogin{LoginID: "login-1", QRCode: "code-1", Status: "wait"}
|
||||
ch.loginOrder = []string{"login-1"}
|
||||
|
||||
if ok := ch.CancelPendingLogin("login-1"); !ok {
|
||||
t.Fatalf("expected cancel to succeed")
|
||||
}
|
||||
if got := ch.PendingLogins(); len(got) != 0 {
|
||||
t.Fatalf("expected no pending logins after cancel, got %d", len(got))
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,7 @@ type ChannelsConfig struct {
|
||||
InboundMessageIDDedupeTTLSeconds int `json:"inbound_message_id_dedupe_ttl_seconds" env:"CLAWGO_CHANNELS_INBOUND_MESSAGE_ID_DEDUPE_TTL_SECONDS"`
|
||||
InboundContentDedupeWindowSeconds int `json:"inbound_content_dedupe_window_seconds" env:"CLAWGO_CHANNELS_INBOUND_CONTENT_DEDUPE_WINDOW_SECONDS"`
|
||||
OutboundDedupeWindowSeconds int `json:"outbound_dedupe_window_seconds" env:"CLAWGO_CHANNELS_OUTBOUND_DEDUPE_WINDOW_SECONDS"`
|
||||
Weixin WeixinConfig `json:"weixin"`
|
||||
WhatsApp WhatsAppConfig `json:"whatsapp"`
|
||||
Telegram TelegramConfig `json:"telegram"`
|
||||
Feishu FeishuConfig `json:"feishu"`
|
||||
@@ -187,6 +188,27 @@ type WhatsAppConfig struct {
|
||||
RequireMentionInGroups bool `json:"require_mention_in_groups" env:"CLAWGO_CHANNELS_WHATSAPP_REQUIRE_MENTION_IN_GROUPS"`
|
||||
}
|
||||
|
||||
type WeixinConfig struct {
|
||||
Enabled bool `json:"enabled" env:"CLAWGO_CHANNELS_WEIXIN_ENABLED"`
|
||||
BaseURL string `json:"base_url" env:"CLAWGO_CHANNELS_WEIXIN_BASE_URL"`
|
||||
DefaultBotID string `json:"default_bot_id,omitempty"`
|
||||
Accounts []WeixinAccountConfig `json:"accounts,omitempty"`
|
||||
AllowFrom []string `json:"allow_from" env:"CLAWGO_CHANNELS_WEIXIN_ALLOW_FROM"`
|
||||
BotID string `json:"bot_id,omitempty" env:"CLAWGO_CHANNELS_WEIXIN_BOT_ID"`
|
||||
BotToken string `json:"bot_token,omitempty" env:"CLAWGO_CHANNELS_WEIXIN_BOT_TOKEN"`
|
||||
IlinkUserID string `json:"ilink_user_id,omitempty" env:"CLAWGO_CHANNELS_WEIXIN_ILINK_USER_ID"`
|
||||
ContextToken string `json:"context_token,omitempty" env:"CLAWGO_CHANNELS_WEIXIN_CONTEXT_TOKEN"`
|
||||
GetUpdatesBuf string `json:"get_updates_buf,omitempty" env:"CLAWGO_CHANNELS_WEIXIN_GET_UPDATES_BUF"`
|
||||
}
|
||||
|
||||
type WeixinAccountConfig struct {
|
||||
BotID string `json:"bot_id"`
|
||||
BotToken string `json:"bot_token"`
|
||||
IlinkUserID string `json:"ilink_user_id,omitempty"`
|
||||
ContextToken string `json:"context_token,omitempty"`
|
||||
GetUpdatesBuf string `json:"get_updates_buf,omitempty"`
|
||||
}
|
||||
|
||||
type TelegramConfig struct {
|
||||
Enabled bool `json:"enabled" env:"CLAWGO_CHANNELS_TELEGRAM_ENABLED"`
|
||||
Token string `json:"token" env:"CLAWGO_CHANNELS_TELEGRAM_TOKEN"`
|
||||
@@ -465,6 +487,13 @@ func DefaultConfig() *Config {
|
||||
InboundMessageIDDedupeTTLSeconds: 600,
|
||||
InboundContentDedupeWindowSeconds: 12,
|
||||
OutboundDedupeWindowSeconds: 12,
|
||||
Weixin: WeixinConfig{
|
||||
Enabled: false,
|
||||
BaseURL: "https://ilinkai.weixin.qq.com",
|
||||
DefaultBotID: "",
|
||||
Accounts: []WeixinAccountConfig{},
|
||||
AllowFrom: []string{},
|
||||
},
|
||||
WhatsApp: WhatsAppConfig{
|
||||
Enabled: false,
|
||||
BridgeURL: "",
|
||||
|
||||
@@ -187,6 +187,9 @@ func Validate(cfg *Config) []error {
|
||||
if cfg.Channels.OutboundDedupeWindowSeconds <= 0 {
|
||||
errs = append(errs, fmt.Errorf("channels.outbound_dedupe_window_seconds must be > 0"))
|
||||
}
|
||||
if cfg.Channels.Weixin.Enabled && len(cfg.Channels.Weixin.Accounts) == 0 && strings.TrimSpace(cfg.Channels.Weixin.BotToken) == "" {
|
||||
errs = append(errs, fmt.Errorf("channels.weixin.accounts or channels.weixin.bot_token is required when channels.weixin.enabled=true"))
|
||||
}
|
||||
if cfg.Channels.Telegram.Enabled && cfg.Channels.Telegram.Token == "" {
|
||||
errs = append(errs, fmt.Errorf("channels.telegram.token is required when channels.telegram.enabled=true"))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user