diff --git a/README.md b/README.md
index a9f2f3c..1cf7173 100644
--- a/README.md
+++ b/README.md
@@ -177,13 +177,14 @@ That's it! You have a working AI assistant in 2 minutes.
## 💬 Chat Apps
-Talk to your picoclaw through Telegram
+Talk to your picoclaw through Telegram, Discord, or DingTalk
| Channel | Setup |
|---------|-------|
| **Telegram** | Easy (just a token) |
| **Discord** | Easy (bot token + intents) |
| **QQ** | Easy (AppID + AppSecret) |
+| **DingTalk** | Medium (app credentials) |
Telegram (Recommended)
@@ -295,6 +296,39 @@ picoclaw gateway
```
+
+DingTalk
+
+**1. Create a bot**
+
+- Go to [Open Platform](https://open.dingtalk.com/)
+- Create an internal app
+- Copy Client ID and Client Secret
+
+**2. Configure**
+
+```json
+{
+ "channels": {
+ "dingtalk": {
+ "enabled": true,
+ "client_id": "YOUR_CLIENT_ID",
+ "client_secret": "YOUR_CLIENT_SECRET",
+ "allow_from": []
+ }
+ }
+}
+```
+
+> Set `allow_from` to empty to allow all users, or specify QQ numbers to restrict access.
+
+**3. Run**
+
+```bash
+picoclaw gateway
+```
+
+
## ⚙️ Configuration
Config file: `~/.picoclaw/config.json`
diff --git a/config.example.json b/config.example.json
index 122e9b4..bc5c2bb 100644
--- a/config.example.json
+++ b/config.example.json
@@ -37,6 +37,12 @@
"encrypt_key": "",
"verification_token": "",
"allow_from": []
+ },
+ "dingtalk": {
+ "enabled": false,
+ "client_id": "YOUR_CLIENT_ID",
+ "client_secret": "YOUR_CLIENT_SECRET",
+ "allow_from": []
}
},
"providers": {
diff --git a/go.mod b/go.mod
index b1b6a93..23cfa0e 100644
--- a/go.mod
+++ b/go.mod
@@ -9,6 +9,7 @@ require (
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
github.com/gorilla/websocket v1.5.3
github.com/larksuite/oapi-sdk-go/v3 v3.5.3
+ github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1
github.com/tencent-connect/botgo v0.2.1
golang.org/x/oauth2 v0.35.0
)
@@ -16,11 +17,12 @@ require (
require (
github.com/go-resty/resty/v2 v2.17.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
+ github.com/google/uuid v1.6.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
golang.org/x/crypto v0.48.0 // indirect
- golang.org/x/net v0.49.0 // indirect
+ golang.org/x/net v0.50.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.41.0 // indirect
)
diff --git a/go.sum b/go.sum
index 72fc67a..2f9d5be 100644
--- a/go.sum
+++ b/go.sum
@@ -43,6 +43,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
@@ -66,6 +68,8 @@ github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vv
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
+github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1 h1:Lb/Uzkiw2Ugt2Xf03J5wmv81PdkYOiWbI8CNBi1boC8=
+github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1/go.mod h1:ln3IqPYYocZbYvl9TAOrG/cxGR9xcn4pnZRLdCTEGEU=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@@ -77,8 +81,9 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
+github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/tencent-connect/botgo v0.2.1 h1:+BrTt9Zh+awL28GWC4g5Na3nQaGRWb0N5IctS8WqBCk=
github.com/tencent-connect/botgo v0.2.1/go.mod h1:oO1sG9ybhXNickvt+CVym5khwQ+uKhTR+IhTqEfOVsI=
github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
@@ -118,8 +123,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
-golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
-golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
+golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
+golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
golang.org/x/oauth2 v0.23.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
diff --git a/pkg/channels/dingtalk.go b/pkg/channels/dingtalk.go
new file mode 100644
index 0000000..4114ff6
--- /dev/null
+++ b/pkg/channels/dingtalk.go
@@ -0,0 +1,193 @@
+// PicoClaw - Ultra-lightweight personal AI agent
+// DingTalk channel implementation using Stream Mode
+
+package channels
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "sync"
+
+ "github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
+ "github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
+ "github.com/sipeed/picoclaw/pkg/bus"
+ "github.com/sipeed/picoclaw/pkg/config"
+)
+
+// DingTalkChannel implements the Channel interface for DingTalk (钉钉)
+// It uses WebSocket for receiving messages via stream mode and API for sending
+type DingTalkChannel struct {
+ *BaseChannel
+ config config.DingTalkConfig
+ clientID string
+ clientSecret string
+ streamClient *client.StreamClient
+ ctx context.Context
+ cancel context.CancelFunc
+ // Map to store session webhooks for each chat
+ sessionWebhooks sync.Map // chatID -> sessionWebhook
+}
+
+// NewDingTalkChannel creates a new DingTalk channel instance
+func NewDingTalkChannel(cfg config.DingTalkConfig, messageBus *bus.MessageBus) (*DingTalkChannel, error) {
+ if cfg.ClientID == "" || cfg.ClientSecret == "" {
+ return nil, fmt.Errorf("dingtalk client_id and client_secret are required")
+ }
+
+ base := NewBaseChannel("dingtalk", cfg, messageBus, cfg.AllowFrom)
+
+ return &DingTalkChannel{
+ BaseChannel: base,
+ config: cfg,
+ clientID: cfg.ClientID,
+ clientSecret: cfg.ClientSecret,
+ }, nil
+}
+
+// Start initializes the DingTalk channel with Stream Mode
+func (c *DingTalkChannel) Start(ctx context.Context) error {
+ log.Printf("Starting DingTalk channel (Stream Mode)...")
+
+ c.ctx, c.cancel = context.WithCancel(ctx)
+
+ // Create credential config
+ cred := client.NewAppCredentialConfig(c.clientID, c.clientSecret)
+
+ // Create the stream client with options
+ c.streamClient = client.NewStreamClient(
+ client.WithAppCredential(cred),
+ client.WithAutoReconnect(true),
+ )
+
+ // Register chatbot callback handler (IChatBotMessageHandler is a function type)
+ c.streamClient.RegisterChatBotCallbackRouter(c.onChatBotMessageReceived)
+
+ // Start the stream client
+ if err := c.streamClient.Start(c.ctx); err != nil {
+ return fmt.Errorf("failed to start stream client: %w", err)
+ }
+
+ c.setRunning(true)
+ log.Println("DingTalk channel started (Stream Mode)")
+ return nil
+}
+
+// Stop gracefully stops the DingTalk channel
+func (c *DingTalkChannel) Stop(ctx context.Context) error {
+ log.Println("Stopping DingTalk channel...")
+
+ if c.cancel != nil {
+ c.cancel()
+ }
+
+ if c.streamClient != nil {
+ c.streamClient.Close()
+ }
+
+ c.setRunning(false)
+ log.Println("DingTalk channel stopped")
+ return nil
+}
+
+// Send sends a message to DingTalk via the chatbot reply API
+func (c *DingTalkChannel) Send(ctx context.Context, msg bus.OutboundMessage) error {
+ if !c.IsRunning() {
+ return fmt.Errorf("dingtalk channel not running")
+ }
+
+ // Get session webhook from storage
+ sessionWebhookRaw, ok := c.sessionWebhooks.Load(msg.ChatID)
+ if !ok {
+ return fmt.Errorf("no session_webhook found for chat %s, cannot send message", msg.ChatID)
+ }
+
+ sessionWebhook, ok := sessionWebhookRaw.(string)
+ if !ok {
+ return fmt.Errorf("invalid session_webhook type for chat %s", msg.ChatID)
+ }
+
+ log.Printf("DingTalk message to %s: %s", msg.ChatID, truncateStringDingTalk(msg.Content, 100))
+
+ // Use the session webhook to send the reply
+ return c.SendDirectReply(sessionWebhook, msg.Content)
+}
+
+// onChatBotMessageReceived implements the IChatBotMessageHandler function signature
+// This is called by the Stream SDK when a new message arrives
+// IChatBotMessageHandler is: func(c context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error)
+func (c *DingTalkChannel) onChatBotMessageReceived(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) {
+ // Extract message content from Text field
+ content := data.Text.Content
+ if content == "" {
+ // Try to extract from Content interface{} if Text is empty
+ if contentMap, ok := data.Content.(map[string]interface{}); ok {
+ if textContent, ok := contentMap["content"].(string); ok {
+ content = textContent
+ }
+ }
+ }
+
+ if content == "" {
+ return nil, nil // Ignore empty messages
+ }
+
+ senderID := data.SenderStaffId
+ senderNick := data.SenderNick
+ chatID := senderID
+ if data.ConversationType != "1" {
+ // For group chats
+ chatID = data.ConversationId
+ }
+
+ // Store the session webhook for this chat so we can reply later
+ c.sessionWebhooks.Store(chatID, data.SessionWebhook)
+
+ metadata := map[string]string{
+ "sender_name": senderNick,
+ "conversation_id": data.ConversationId,
+ "conversation_type": data.ConversationType,
+ "platform": "dingtalk",
+ "session_webhook": data.SessionWebhook,
+ }
+
+ log.Printf("DingTalk message from %s (%s): %s", senderNick, senderID, truncateStringDingTalk(content, 50))
+
+ // Handle the message through the base channel
+ c.HandleMessage(senderID, chatID, content, nil, metadata)
+
+ // Return nil to indicate we've handled the message asynchronously
+ // The response will be sent through the message bus
+ return nil, nil
+}
+
+// SendDirectReply sends a direct reply using the session webhook
+func (c *DingTalkChannel) SendDirectReply(sessionWebhook, content string) error {
+ replier := chatbot.NewChatbotReplier()
+
+ // Convert string content to []byte for the API
+ contentBytes := []byte(content)
+ titleBytes := []byte("PicoClaw")
+
+ // Send markdown formatted reply
+ err := replier.SimpleReplyMarkdown(
+ context.Background(),
+ sessionWebhook,
+ titleBytes,
+ contentBytes,
+ )
+
+ if err != nil {
+ return fmt.Errorf("failed to send reply: %w", err)
+ }
+
+ return nil
+}
+
+// truncateStringDingTalk truncates a string to max length for logging (avoiding name collision with telegram.go)
+func truncateStringDingTalk(s string, maxLen int) string {
+ if len(s) <= maxLen {
+ return s
+ }
+ return s[:maxLen]
+}
diff --git a/pkg/channels/manager.go b/pkg/channels/manager.go
index 881ec5b..bf98a4b 100644
--- a/pkg/channels/manager.go
+++ b/pkg/channels/manager.go
@@ -123,6 +123,19 @@ func (m *Manager) initChannels() error {
}
}
+ if m.config.Channels.DingTalk.Enabled && m.config.Channels.DingTalk.ClientID != "" {
+ logger.DebugC("channels", "Attempting to initialize DingTalk channel")
+ dingtalk, err := NewDingTalkChannel(m.config.Channels.DingTalk, m.bus)
+ if err != nil {
+ logger.ErrorCF("channels", "Failed to initialize DingTalk channel", map[string]interface{}{
+ "error": err.Error(),
+ })
+ } else {
+ m.channels["dingtalk"] = dingtalk
+ logger.InfoC("channels", "DingTalk channel enabled successfully")
+ }
+ }
+
logger.InfoCF("channels", "Channel initialization completed", map[string]interface{}{
"enabled_channels": len(m.channels),
})
diff --git a/pkg/config/config.go b/pkg/config/config.go
index 6cdc8b0..5b9c2b5 100644
--- a/pkg/config/config.go
+++ b/pkg/config/config.go
@@ -37,6 +37,7 @@ type ChannelsConfig struct {
Discord DiscordConfig `json:"discord"`
MaixCam MaixCamConfig `json:"maixcam"`
QQ QQConfig `json:"qq"`
+ DingTalk DingTalkConfig `json:"dingtalk"`
}
type WhatsAppConfig struct {
@@ -80,6 +81,13 @@ type QQConfig struct {
AllowFrom []string `json:"allow_from" env:"PICOCLAW_CHANNELS_QQ_ALLOW_FROM"`
}
+type DingTalkConfig struct {
+ Enabled bool `json:"enabled" env:"PICOCLAW_CHANNELS_DINGTALK_ENABLED"`
+ ClientID string `json:"client_id" env:"PICOCLAW_CHANNELS_DINGTALK_CLIENT_ID"`
+ ClientSecret string `json:"client_secret" env:"PICOCLAW_CHANNELS_DINGTALK_CLIENT_SECRET"`
+ AllowFrom []string `json:"allow_from" env:"PICOCLAW_CHANNELS_DINGTALK_ALLOW_FROM"`
+}
+
type ProvidersConfig struct {
Anthropic ProviderConfig `json:"anthropic"`
OpenAI ProviderConfig `json:"openai"`
@@ -160,6 +168,12 @@ func DefaultConfig() *Config {
AppSecret: "",
AllowFrom: []string{},
},
+ DingTalk: DingTalkConfig{
+ Enabled: false,
+ ClientID: "",
+ ClientSecret: "",
+ AllowFrom: []string{},
+ },
},
Providers: ProvidersConfig{
Anthropic: ProviderConfig{},