dingtalk

package
v1.2.61 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 24, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

钉钉群机器人消息发送包

这是一个用于向钉钉群发送消息的 Go 语言包,支持多种消息类型。

功能特性

  • ✅ 文本消息
  • ✅ Markdown 消息
  • ✅ 链接消息
  • ✅ ActionCard 消息(单按钮/多按钮)
  • ✅ FeedCard 消息(多条链接展示)
  • ✅ 支持 @人功能(text、markdown类型完全支持,其他类型为扩展预留)
  • ✅ 加签安全验证
  • ✅ 完善的错误处理
  • ✅ 详细的日志记录

@人功能说明

根据钉钉官方文档:

  • text(文本)markdown 类型消息完全支持@人功能
  • ⚠️ link(链接)actionCardfeedCard 类型消息官方不支持@人功能

本包为所有消息类型都提供了@人参数,对于官方不支持的类型,@人字段会被发送但可能不会生效。这样设计是为了:

  1. 保持API的一致性
  2. 如果钉钉未来支持这些类型的@人功能,代码无需修改即可使用

安装

go get gitee.com/hexug/go-tools/msgbot/dingtalk

快速开始

1. 创建客户端
import "gitee.com/hexug/go-tools/msgbot/dingtalk"

// 创建默认客户端
client := dingtalk.NewClient()

// 或创建指定日志级别的客户端
client := dingtalk.NewClientWithLogLevel(dingtalk.LogLevelDebug)
2. 使用加签方式(推荐)

钉钉机器人支持三种安全设置方式:自定义关键词、加签、IP地址。推荐使用加签方式,更加安全。

// 原始webhook和secret
webhook := "https://oapi.dingtalk.com/robot/send?access_token=xxx"
secret := "SECxxxxxxxxxxxx" // 创建机器人时获得的加签密钥

// 生成带签名的URL
signedURL, err := dingtalk.GenerateSignedURL(webhook, secret)
if err != nil {
    log.Fatal(err)
}

// 使用签名后的URL发送消息
ctx := context.Background()
err = client.SendWebhookTextMessage(ctx, signedURL, "这是一条测试消息")
3. 发送文本消息
ctx := context.Background()
webhookUrl := "YOUR_DINGTALK_WEBHOOK_URL"

// 简单文本消息
err := client.SendWebhookTextMessage(ctx, webhookUrl, "这是一条测试消息")

// 带@功能的文本消息
req := &dingtalk.SendTextRequest{
    Webhook:   webhookUrl,
    Content:   "这是一条测试消息,@所有人",
    AtMobiles: []string{"13800138000"},
    IsAtAll:   true,
}
err := client.SendWebhookTextMessageV2(ctx, req)
3. 发送文本消息
ctx := context.Background()
webhookUrl := "YOUR_DINGTALK_WEBHOOK_URL"

// 简单文本消息
err := client.SendWebhookTextMessage(ctx, webhookUrl, "这是一条测试消息")

// 带@功能的文本消息
req := &dingtalk.SendTextRequest{
    Webhook:   webhookUrl,
    Content:   "这是一条测试消息,@所有人",
    AtMobiles: []string{"13800138000"},
    IsAtAll:   true,
}
err := client.SendWebhookTextMessageV2(ctx, req)
4. 发送 Markdown 消息
markdown := `## 测试标题
这是一条测试Markdown消息

### 功能列表
- 功能1
- 功能2
- 功能3

**加粗文本** *斜体文本*`

// 简单Markdown消息
err := client.SendWebhookMarkdownMessage(ctx, webhookUrl, "测试标题", markdown)

// 带@功能的Markdown消息
req := &dingtalk.SendMarkdownRequest{
    Webhook:   webhookUrl,
    Title:     "测试标题",
    Text:      markdown,
    AtMobiles: []string{"13800138000"},
    IsAtAll:   false,
}
err := client.SendWebhookMarkdownMessageV2(ctx, req)
5. 发送链接消息
// 简单链接消息
err := client.SendWebhookLinkMessage(
    ctx,
    webhookUrl,
    "消息标题",
    "消息内容描述",
    "https://www.example.com",
    "https://example.com/image.png", // 图片URL(可选)
)

// 使用请求对象
req := &dingtalk.SendLinkRequest{
    Webhook:    webhookUrl,
    Title:      "消息标题",
    Text:       "消息内容描述",
    MessageUrl: "https://www.example.com",
    PicUrl:     "https://example.com/image.png",
}
err := client.SendWebhookLinkMessageV2(ctx, req)
6. 发送包含代码块的 Markdown 消息
// JSON代码块
data := map[string]interface{}{
    "name": "张三",
    "age":  30,
}
jsonBytes, _ := json.MarshalIndent(data, "", "  ")
markdown := fmt.Sprintf("## 数据\n\n```json\n%s\n```", string(jsonBytes))
err := client.SendWebhookMarkdownMessage(ctx, webhookUrl, "数据展示", markdown)

// Go代码块
goCode, _ := os.ReadFile("main.go")
markdown := fmt.Sprintf("## 代码\n\n```go\n%s\n```", string(goCode))
err := client.SendWebhookMarkdownMessage(ctx, webhookUrl, "代码展示", markdown)
7. 发送 ActionCard 消息

ActionCard 消息支持单按钮和多按钮两种模式。

// 单按钮模式
text := `#### 系统维护通知

![screenshot](https://example.com/image.png)

### 重要提醒
- 系统将于今晚22:00进行维护
- 预计维护时间:2小时

**请提前保存工作!**`

err := client.SendWebhookActionCardMessage(
    ctx,
    webhookUrl,
    "系统维护通知",
    text,
    "查看详情",
    "https://www.example.com",
    "0", // 0-按钮竖直排列,1-按钮横向排列
)

// 多按钮模式
btns := []*dingtalk.WebhookActionCardButton{
    {
        Title:     "查看需求",
        ActionURL: "https://www.example.com/requirements",
    },
    {
        Title:     "查看设计",
        ActionURL: "https://www.example.com/design",
    },
}

err := client.SendWebhookActionCardMessageV2(
    ctx,
    webhookUrl,
    "项目进度报告",
    text,
    btns,
    "1", // 按钮横向排列
)

// 使用请求对象(推荐)
req := &dingtalk.SendActionCardRequest{
    Webhook:        webhookUrl,
    Title:          "版本更新通知",
    Text:           text,
    SingleTitle:    "立即体验",
    SingleURL:      "https://www.example.com",
    BtnOrientation: "0",
}
err := client.SendWebhookActionCardMessageV3(ctx, req)
8. 发送 FeedCard 消息

FeedCard 消息可以展示多条链接信息,每条信息包含标题、链接和图片。

// 基本用法
links := []*dingtalk.WebhookFeedCardLink{
    {
        Title:      "技术博客:Go语言最佳实践",
        MessageURL: "https://www.example.com/blog/go",
        PicURL:     "https://example.com/image1.png",
    },
    {
        Title:      "新闻:Go 1.21 正式发布",
        MessageURL: "https://www.example.com/news/go-1.21",
        PicURL:     "https://example.com/image2.png",
    },
}

err := client.SendWebhookFeedCardMessage(ctx, webhookUrl, links)

// 使用请求对象(推荐)
req := &dingtalk.SendFeedCardRequest{
    Webhook: webhookUrl,
    Links:   links,
}
err := client.SendWebhookFeedCardMessageV2(ctx, req)

消息类型说明

文本消息
  • 支持纯文本内容
  • 支持 @指定用户或 @所有人
Markdown 消息
  • 支持标准 Markdown 语法
  • 支持代码块(json, go, python 等)
  • 支持 @指定用户或 @所有人
  • 需要提供标题和内容
链接消息
  • 支持标题、描述、跳转链接
  • 可选图片展示
ActionCard 消息
  • 支持 Markdown 格式内容
  • 支持单按钮模式:一个按钮,点击跳转到指定链接
  • 支持多按钮模式:多个按钮,每个按钮可跳转不同链接
  • 按钮可选择竖直排列或横向排列
  • 适用于通知、审批、选择等场景
FeedCard 消息
  • 支持展示多条链接信息
  • 每条信息包含标题、链接和图片
  • 适用于新闻聚合、文章推荐等场景
  • 用户点击可跳转到对应链接

错误处理

所有发送方法都会返回 error,建议进行错误处理:

err := client.SendWebhookTextMessage(ctx, webhookUrl, "测试消息")
if err != nil {
    log.Printf("发送消息失败: %v", err)
    return
}
log.Println("发送消息成功")

获取 Webhook 地址

  1. 在钉钉群中添加自定义机器人
  2. 选择"自定义"机器人类型
  3. 配置安全设置(关键词、加签或IP地址)
  4. 复制生成的 Webhook 地址

注意事项

  1. 安全设置:钉钉机器人需要配置安全设置,支持三种方式:
    • 加签(推荐):使用 GenerateSignedURL 方法生成带签名的URL
    • 自定义关键词:消息内容必须包含设置的关键词
    • IP地址:仅允许指定IP地址访问
  2. 频率限制:钉钉机器人有频率限制,每个机器人每分钟最多发送20条消息
  3. 内容长度:建议单条消息内容不要过长,避免显示不完整
  4. @功能:使用@功能时,需要提供正确的手机号或用户ID
  5. 签名有效期:使用加签方式时,签名有效期为1小时,超时需要重新生成

测试

运行测试前,请先在 sendmsg_test.go 中配置实际的 Webhook 地址:

const testWebhookUrl = "YOUR_DINGTALK_WEBHOOK_URL"

然后运行测试:

# 运行所有测试
go test -v

# 运行指定测试
go test -v -run TestClient_SendWebhookTextMessage

依赖

  • gitee.com/hexug/go-reqx/rest - HTTP 客户端
  • gitee.com/hexug/go-tools/logger - 日志库

参考文档

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateSignedURL

func GenerateSignedURL(webhook string, secret string) (string, error)

GenerateSignedURL 生成带签名的钉钉 Webhook URL 钉钉机器人安全设置中的"加签"方式需要使用此方法 参数:

  • webhook: 原始的 Webhook 地址
  • secret: 机器人的加签密钥

返回:

  • string: 带签名参数的完整 URL
  • error: 生成失败时返回错误信息

示例:

webhook := "https://oapi.dingtalk.com/robot/send?access_token=xxx"
secret := "SECxxxxxxxxxxxx"
signedURL, err := GenerateSignedURL(webhook, secret)

Types

type Client

type Client struct {
	Log *logger.MyLogger
	// contains filtered or unexported fields
}

Client 钉钉群机器人客户端 主要用于通过 Webhook 发送消息到群聊

func NewClient

func NewClient() *Client

NewClient 创建新的钉钉客户端 返回一个配置好的客户端实例,用于发送消息

func NewClientWithLogLevel

func NewClientWithLogLevel(level LogLevel) *Client

NewClientWithLogLevel 创建指定日志级别的钉钉客户端

func (*Client) SendWebhookActionCardMessage

func (c *Client) SendWebhookActionCardMessage(ctx context.Context, webhook, title, text, singleTitle, singleURL string, btnOrientation ...string) error

SendWebhookActionCardMessage 发送 ActionCard 消息(单按钮模式) 参数:

  • ctx: 上下文
  • webhook: Webhook 地址
  • title: 首屏会话透出的展示内容
  • text: Markdown 格式的消息内容
  • singleTitle: 按钮标题
  • singleURL: 按钮跳转链接
  • btnOrientation: 按钮排列方式,"0"-竖直排列,"1"-横向排列(可选,默认"0")
  • at: @人信息(可选,注意:钉钉官方actionCard类型不支持@人,此参数为扩展预留)

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookActionCardMessageV2

func (c *Client) SendWebhookActionCardMessageV2(ctx context.Context, webhook, title, text string, btns []*WebhookActionCardButton, btnOrientation ...string) error

SendWebhookActionCardMessageV2 发送 ActionCard 消息(多按钮模式) 参数:

  • ctx: 上下文
  • webhook: Webhook 地址
  • title: 首屏会话透出的展示内容
  • text: Markdown 格式的消息内容
  • btns: 按钮列表
  • btnOrientation: 按钮排列方式,"0"-竖直排列,"1"-横向排列(可选,默认"0")

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookActionCardMessageV3

func (c *Client) SendWebhookActionCardMessageV3(ctx context.Context, req *SendActionCardRequest) error

SendWebhookActionCardMessageV3 发送 ActionCard 消息(使用请求对象) 参数:

  • ctx: 上下文
  • req: ActionCard 消息请求参数

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookFeedCardMessage

func (c *Client) SendWebhookFeedCardMessage(ctx context.Context, webhook string, links []*WebhookFeedCardLink) error

SendWebhookFeedCardMessage 发送 FeedCard 消息 参数:

  • ctx: 上下文
  • webhook: Webhook 地址
  • links: 链接列表
  • at: @人信息(可选,注意:钉钉官方feedCard类型不支持@人,此参数为扩展预留)

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookFeedCardMessageV2

func (c *Client) SendWebhookFeedCardMessageV2(ctx context.Context, req *SendFeedCardRequest) error

SendWebhookFeedCardMessageV2 发送 FeedCard 消息(使用请求对象) 参数:

  • ctx: 上下文
  • req: FeedCard 消息请求参数

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookLinkMessage

func (c *Client) SendWebhookLinkMessage(ctx context.Context, webhookUrl string, title string, text string, messageUrl string, picUrl string) error

SendWebhookLinkMessage 通过 Webhook 发送链接消息到钉钉群 参数:

  • ctx: 上下文,用于控制请求超时和取消
  • webhookUrl: 群机器人的 Webhook 地址
  • title: 消息标题
  • text: 消息内容
  • messageUrl: 点击消息跳转的URL
  • picUrl: 图片URL(可选)

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookLinkMessageV2

func (c *Client) SendWebhookLinkMessageV2(ctx context.Context, req *SendLinkRequest) error

SendWebhookLinkMessageV2 通过 Webhook 发送链接消息到钉钉群(使用请求对象) 参数:

  • ctx: 上下文,用于控制请求超时和取消
  • req: 发送链接消息请求,包含完整的配置参数

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookMarkdownMessage

func (c *Client) SendWebhookMarkdownMessage(ctx context.Context, webhookUrl string, title string, text string) error

SendWebhookMarkdownMessage 通过 Webhook 发送 Markdown 消息到钉钉群 参数:

  • ctx: 上下文,用于控制请求超时和取消
  • webhookUrl: 群机器人的 Webhook 地址
  • title: 首屏会话透出的展示内容
  • text: Markdown 格式的消息内容

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookMarkdownMessageV2

func (c *Client) SendWebhookMarkdownMessageV2(ctx context.Context, req *SendMarkdownRequest) error

SendWebhookMarkdownMessageV2 通过 Webhook 发送 Markdown 消息到钉钉群(支持@功能) 参数:

  • ctx: 上下文,用于控制请求超时和取消
  • req: 发送Markdown消息请求,包含完整的配置参数

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookTextMessage

func (c *Client) SendWebhookTextMessage(ctx context.Context, webhookUrl string, content string) error

SendWebhookTextMessage 通过 Webhook 发送文本消息到钉钉群 参数:

  • ctx: 上下文,用于控制请求超时和取消
  • webhookUrl: 群机器人的 Webhook 地址
  • content: 要发送的文本内容

返回:

  • error: 发送失败时返回错误信息

func (*Client) SendWebhookTextMessageV2

func (c *Client) SendWebhookTextMessageV2(ctx context.Context, req *SendTextRequest) error

SendWebhookTextMessageV2 通过 Webhook 发送文本消息到钉钉群(支持@功能) 参数:

  • ctx: 上下文,用于控制请求超时和取消
  • req: 发送文本消息请求,包含完整的配置参数

返回:

  • error: 发送失败时返回错误信息

type LogLevel

type LogLevel int
const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
	LogLevelFatal
	LogLevelPanic
)

type SendActionCardRequest

type SendActionCardRequest struct {
	Webhook        string                     // Webhook地址
	Title          string                     // 首屏会话透出的展示内容
	Text           string                     // Markdown格式的消息
	SingleTitle    string                     // 单个按钮的标题(单按钮模式)
	SingleURL      string                     // 单个按钮的跳转链接(单按钮模式)
	BtnOrientation string                     // 按钮排列方式:0-按钮竖直排列,1-按钮横向排列
	Btns           []*WebhookActionCardButton // 按钮列表(多按钮模式)
	AtMobiles      []string                   // 被@人的手机号(注意:钉钉官方actionCard类型不支持@人,此字段为扩展预留)
	AtUserIds      []string                   // 被@人的用户userid(注意:钉钉官方actionCard类型不支持@人,此字段为扩展预留)
	IsAtAll        bool                       // 是否@所有人(注意:钉钉官方actionCard类型不支持@人,此字段为扩展预留)
}

SendActionCardRequest 发送ActionCard消息请求参数

type SendFeedCardRequest

type SendFeedCardRequest struct {
	Webhook   string                 // Webhook地址
	Links     []*WebhookFeedCardLink // 链接列表
	AtMobiles []string               // 被@人的手机号(注意:钉钉官方feedCard类型不支持@人,此字段为扩展预留)
	AtUserIds []string               // 被@人的用户userid(注意:钉钉官方feedCard类型不支持@人,此字段为扩展预留)
	IsAtAll   bool                   // 是否@所有人(注意:钉钉官方feedCard类型不支持@人,此字段为扩展预留)
}

SendFeedCardRequest 发送FeedCard消息请求参数

type SendLinkRequest

type SendLinkRequest struct {
	Webhook    string   // Webhook地址
	Title      string   // 消息标题
	Text       string   // 消息内容
	MessageUrl string   // 点击消息跳转的URL
	PicUrl     string   // 图片URL(可选)
	AtMobiles  []string // 被@人的手机号(注意:钉钉官方link类型不支持@人,此字段为扩展预留)
	AtUserIds  []string // 被@人的用户userid(注意:钉钉官方link类型不支持@人,此字段为扩展预留)
	IsAtAll    bool     // 是否@所有人(注意:钉钉官方link类型不支持@人,此字段为扩展预留)
}

SendLinkRequest 发送链接消息请求参数

type SendMarkdownRequest

type SendMarkdownRequest struct {
	Webhook   string   // Webhook地址
	Title     string   // 首屏会话透出的展示内容
	Text      string   // Markdown格式的消息内容
	AtMobiles []string // 被@人的手机号
	AtUserIds []string // 被@人的用户userid
	IsAtAll   bool     // 是否@所有人
}

SendMarkdownRequest 发送Markdown消息请求参数

type SendTextRequest

type SendTextRequest struct {
	Webhook   string   // Webhook地址
	Content   string   // 文本内容
	AtMobiles []string // 被@人的手机号
	AtUserIds []string // 被@人的用户userid
	IsAtAll   bool     // 是否@所有人
}

SendTextRequest 发送文本消息请求参数

type WebhookActionCardButton

type WebhookActionCardButton struct {
	Title     string `json:"title"`     // 按钮标题
	ActionURL string `json:"actionURL"` // 点击按钮触发的URL
}

WebhookActionCardButton ActionCard按钮

type WebhookActionCardContent

type WebhookActionCardContent struct {
	Title          string                     `json:"title"`                    // 首屏会话透出的展示内容
	Text           string                     `json:"text"`                     // Markdown格式的消息
	SingleTitle    string                     `json:"singleTitle,omitempty"`    // 单个按钮的标题
	SingleURL      string                     `json:"singleURL,omitempty"`      // 单个按钮的跳转链接
	BtnOrientation string                     `json:"btnOrientation,omitempty"` // 按钮排列方式:0-按钮竖直排列,1-按钮横向排列
	Btns           []*WebhookActionCardButton `json:"btns,omitempty"`           // 按钮列表
}

WebhookActionCardContent Webhook ActionCard消息内容

type WebhookActionCardMessage

type WebhookActionCardMessage struct {
	MsgType    string                    `json:"msgtype"`      // 消息类型,固定为 "actionCard"
	ActionCard *WebhookActionCardContent `json:"actionCard"`   // ActionCard内容
	At         *WebhookAt                `json:"at,omitempty"` // @人信息(注意:钉钉官方actionCard类型不支持@人,此字段为扩展预留)
}

WebhookActionCardMessage Webhook ActionCard消息请求体

type WebhookAt

type WebhookAt struct {
	AtMobiles []string `json:"atMobiles,omitempty"` // 被@人的手机号
	AtUserIds []string `json:"atUserIds,omitempty"` // 被@人的用户userid
	IsAtAll   bool     `json:"isAtAll,omitempty"`   // 是否@所有人
}

WebhookAt @人信息

type WebhookFeedCardContent

type WebhookFeedCardContent struct {
	Links []*WebhookFeedCardLink `json:"links"` // 链接列表
}

WebhookFeedCardContent Webhook FeedCard消息内容

type WebhookFeedCardLink struct {
	Title      string `json:"title"`      // 单条信息文本
	MessageURL string `json:"messageURL"` // 点击单条信息到跳转链接
	PicURL     string `json:"picURL"`     // 单条信息后面图片的URL
}

WebhookFeedCardLink FeedCard链接项

type WebhookFeedCardMessage

type WebhookFeedCardMessage struct {
	MsgType  string                  `json:"msgtype"`      // 消息类型,固定为 "feedCard"
	FeedCard *WebhookFeedCardContent `json:"feedCard"`     // FeedCard内容
	At       *WebhookAt              `json:"at,omitempty"` // @人信息(注意:钉钉官方feedCard类型不支持@人,此字段为扩展预留)
}

WebhookFeedCardMessage Webhook FeedCard消息请求体

type WebhookLinkContent

type WebhookLinkContent struct {
	Title      string `json:"title"`            // 消息标题
	Text       string `json:"text"`             // 消息内容,如果太长只会部分展示
	MessageUrl string `json:"messageUrl"`       // 点击消息跳转的URL
	PicUrl     string `json:"picUrl,omitempty"` // 图片URL
}

WebhookLinkContent Webhook 链接消息内容

type WebhookLinkMessage

type WebhookLinkMessage struct {
	MsgType string              `json:"msgtype"`      // 消息类型,固定为 "link"
	Link    *WebhookLinkContent `json:"link"`         // 链接内容
	At      *WebhookAt          `json:"at,omitempty"` // @人信息(注意:钉钉官方link类型不支持@人,此字段为扩展预留)
}

WebhookLinkMessage Webhook 链接消息请求体

type WebhookMarkdownContent

type WebhookMarkdownContent struct {
	Title string `json:"title"` // 首屏会话透出的展示内容
	Text  string `json:"text"`  // Markdown格式的消息内容
}

WebhookMarkdownContent Webhook Markdown消息内容

type WebhookMarkdownMessage

type WebhookMarkdownMessage struct {
	MsgType  string                  `json:"msgtype"`  // 消息类型,固定为 "markdown"
	Markdown *WebhookMarkdownContent `json:"markdown"` // Markdown内容
	At       *WebhookAt              `json:"at"`       // @人信息
}

WebhookMarkdownMessage Webhook Markdown消息请求体

type WebhookResponse

type WebhookResponse struct {
	ErrCode int    `json:"errcode"` // 错误码,0表示成功
	ErrMsg  string `json:"errmsg"`  // 错误信息
}

WebhookResponse Webhook响应结构

type WebhookTextContent

type WebhookTextContent struct {
	Content string `json:"content"` // 文本内容
}

WebhookTextContent Webhook文本消息内容

type WebhookTextMessage

type WebhookTextMessage struct {
	MsgType string              `json:"msgtype"` // 消息类型,固定为 "text"
	Text    *WebhookTextContent `json:"text"`    // 文本内容
	At      *WebhookAt          `json:"at"`      // @人信息
}

WebhookTextMessage Webhook文本消息请求体

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL