dingtalk.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package providers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "git.wenlab.co/joe/beaconfire"
  6. )
  7. // API:
  8. // https://open.dingtalk.com/document/group/custom-robot-access
  9. const (
  10. _DINGTALK_ENDPOINT = "https://oapi.dingtalk.com/robot/send"
  11. _DINGTALK_DEFAULT_MSGTYPE = "markdown" // this type would be lcompatible with others easily
  12. BEACON_NAME_DINGTALK = "dingtalk"
  13. )
  14. type OptionsDingtalk struct {
  15. AccessToken string
  16. To []string // userid
  17. }
  18. type dingtalk struct {
  19. opt *OptionsDingtalk
  20. }
  21. var _ beaconfire.BeaconFire = &dingtalk{}
  22. func NewDingtalk(opt *OptionsDingtalk) *dingtalk {
  23. return &dingtalk{
  24. opt: opt,
  25. }
  26. }
  27. func (c dingtalk) Name() string {
  28. return BEACON_NAME_DINGTALK
  29. }
  30. func (c *dingtalk) Send(bp *beaconfire.BeaconMessage) error {
  31. msgType := _DINGTALK_DEFAULT_MSGTYPE
  32. url := fmt.Sprintf("%s?access_token=%s", _DINGTALK_ENDPOINT, c.opt.AccessToken)
  33. content := bp.FormatMarkdown()
  34. values := map[string]interface{}{
  35. "msgtype": msgType,
  36. msgType: map[string]interface{}{
  37. "content": content,
  38. },
  39. "at": map[string]interface{}{
  40. "atUserIds": c.opt.To,
  41. "isAtAll": false,
  42. },
  43. }
  44. jsonBuffer, err := json.Marshal(values)
  45. if err != nil {
  46. return err
  47. }
  48. res, err := beaconfire.PostJson(url, jsonBuffer)
  49. if err != nil {
  50. return err
  51. }
  52. var r map[string]interface{}
  53. err = json.Unmarshal(res, &r)
  54. if err != nil {
  55. return err
  56. }
  57. // DEBUG
  58. fmt.Printf("dingtalk: %+v\n", r)
  59. return nil
  60. }