dingtalk.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package public
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "net/http"
  6. )
  7. // 接收的消息体
  8. type ReceiveMsg struct {
  9. ConversationID string `json:"conversationId"`
  10. AtUsers []struct {
  11. DingtalkID string `json:"dingtalkId"`
  12. } `json:"atUsers"`
  13. ChatbotUserID string `json:"chatbotUserId"`
  14. MsgID string `json:"msgId"`
  15. SenderNick string `json:"senderNick"`
  16. IsAdmin bool `json:"isAdmin"`
  17. SenderStaffId string `json:"senderStaffId"`
  18. SessionWebhookExpiredTime int64 `json:"sessionWebhookExpiredTime"`
  19. CreateAt int64 `json:"createAt"`
  20. ConversationType string `json:"conversationType"`
  21. SenderID string `json:"senderId"`
  22. ConversationTitle string `json:"conversationTitle"`
  23. IsInAtList bool `json:"isInAtList"`
  24. SessionWebhook string `json:"sessionWebhook"`
  25. Text Text `json:"text"`
  26. RobotCode string `json:"robotCode"`
  27. Msgtype string `json:"msgtype"`
  28. }
  29. // 发送的消息体
  30. type SendMsg struct {
  31. Text Text `json:"text"`
  32. Msgtype string `json:"msgtype"`
  33. At At `json:"at"`
  34. }
  35. // 消息内容
  36. type Text struct {
  37. Content string `json:"content"`
  38. }
  39. // at 内容
  40. type At struct {
  41. AtUserIds []string `json:"atUserIds"`
  42. }
  43. // 发消息给钉钉
  44. func (r ReceiveMsg) ReplyText(msg string, staffId string) (statuscode int, err error) {
  45. // 定义消息
  46. msgtmp := &SendMsg{Text: Text{Content: msg}, Msgtype: "text", At: At{AtUserIds: []string{staffId}}}
  47. data, err := json.Marshal(msgtmp)
  48. if err != nil {
  49. return 0, err
  50. }
  51. req, err := http.NewRequest("POST", r.SessionWebhook, bytes.NewBuffer(data))
  52. if err != nil {
  53. return 0, err
  54. }
  55. req.Header.Add("Accept", "*/*")
  56. req.Header.Add("Content-Type", "application/json")
  57. client := &http.Client{}
  58. resp, err := client.Do(req)
  59. if err != nil {
  60. return 0, err
  61. }
  62. defer resp.Body.Close()
  63. return resp.StatusCode, nil
  64. }