dingding.go 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package robot
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. )
  9. type DingTalkRobotMessage struct {
  10. ConversationID string `json:"conversationId"` // 会话 ID
  11. AtUsers []AtUser `json:"atUsers"` // @ 的人列表
  12. ChatbotCorpID string `json:"chatbotCorpId"` // 机器人企业 ID
  13. ChatbotUserID string `json:"chatbotUserId"` // 机器人用户 ID
  14. MsgID string `json:"msgId"` // 消息 ID
  15. SenderNick string `json:"senderNick"` // 发送者昵称
  16. IsAdmin bool `json:"isAdmin"` // 是否管理员
  17. SenderStaffID string `json:"senderStaffId"` // 发送者员工 ID
  18. SessionWebhookExpiredTime int64 `json:"sessionWebhookExpiredTime"` // 会话 Webhook 过期时间(毫秒时间戳)
  19. CreateAt int64 `json:"createAt"` // 创建时间(毫秒时间戳)
  20. SenderCorpID string `json:"senderCorpId"` // 发送者企业 ID
  21. ConversationType string `json:"conversationType"` // 会话类型(1: 单聊,2: 群聊)
  22. SenderID string `json:"senderId"` // 发送者 ID
  23. ConversationTitle string `json:"conversationTitle"` // 会话标题
  24. IsInAtList bool `json:"isInAtList"` // 是否在@列表中
  25. SessionWebhook string `json:"sessionWebhook"` // 会话 Webhook
  26. Text Text `json:"text"` // 消息
  27. MsgType string `json:"msgtype"` // 消息类型
  28. }
  29. // AtUser @的用户信息
  30. type AtUser struct {
  31. DingtalkID string `json:"dingtalkId"` // 钉钉 ID
  32. StaffID string `json:"staffId"` // 员工 ID
  33. }
  34. // 文本消息结构体
  35. type Text struct {
  36. Content string `json:"content"` // 消息内容
  37. }
  38. type Markdown struct {
  39. Title string `json:"title"`
  40. Text string `json:"text"`
  41. }
  42. // 钉钉回复消息的请求体结构体
  43. type DingReplyMsg struct {
  44. MsgType string `json:"msgtype"`
  45. Text Text `json:"text"`
  46. Markdown Markdown `json:"markdown"`
  47. }
  48. func SendReplyMsg(webhookUrl string, reply DingReplyMsg) error {
  49. // 序列化为 JSON
  50. jsonData, err := json.Marshal(reply)
  51. if err != nil {
  52. return fmt.Errorf("序列化消息失败:%v", err)
  53. }
  54. // 发送 POST 请求
  55. resp, err := http.Post(
  56. webhookUrl,
  57. "application/json",
  58. bytes.NewBuffer(jsonData),
  59. )
  60. if err != nil {
  61. return fmt.Errorf("发送请求失败:%v", err)
  62. }
  63. defer resp.Body.Close()
  64. // 读取响应结果
  65. respBody, _ := io.ReadAll(resp.Body)
  66. fmt.Printf("钉钉回复接口响应:%s\n", string(respBody))
  67. return nil
  68. }