dingtalk.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. DINGTALK_NAME = "dingtalk"
  13. )
  14. type OptionsDingtalk struct {
  15. AccessToken string `envconfig:"ACCESS_TOKEN"`
  16. }
  17. type dingtalk struct {
  18. opt *OptionsDingtalk
  19. }
  20. var _ beaconfire.BeaconFire = &dingtalk{}
  21. func NewDingtalk(opt *OptionsDingtalk) *dingtalk {
  22. return &dingtalk{
  23. opt: opt,
  24. }
  25. }
  26. func (c dingtalk) Name() string {
  27. return DINGTALK_NAME
  28. }
  29. func (c *dingtalk) Send(bp *beaconfire.BeaconParam) error {
  30. msgType := _DINGTALK_DEFAULT_MSGTYPE
  31. url := fmt.Sprintf("%s?access_token=%s", _DINGTALK_ENDPOINT, c.opt.AccessToken)
  32. content := bp.FormatMarkdown()
  33. values := map[string]interface{}{
  34. "msgtype": msgType,
  35. msgType: map[string]interface{}{
  36. "content": content,
  37. },
  38. "at": map[string]interface{}{
  39. "atUserIds": bp.To,
  40. "isAtAll": false,
  41. },
  42. }
  43. jsonBuffer, err := json.Marshal(values)
  44. if err != nil {
  45. return err
  46. }
  47. res, err := beaconfire.PostJson(url, jsonBuffer)
  48. if err != nil {
  49. return err
  50. }
  51. var r map[string]interface{}
  52. err = json.Unmarshal(res, &r)
  53. if err != nil {
  54. return err
  55. }
  56. // DEBUG
  57. fmt.Printf("dingtalk: %+v\n", r)
  58. return nil
  59. }