workwx.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package providers
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "git.wenlab.co/joe/beaconfire"
  8. )
  9. // API:
  10. // https://work.weixin.qq.com/api/doc/90000/90136/91770
  11. const (
  12. _WORKWX_ENDPOINT = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send"
  13. _WORKWX_MSGTYPE_MARKDOWN = "markdown" // this type would be lcompatible with others easily
  14. WORKWX_NAME = "workwx"
  15. )
  16. type OptionsWorkwx struct {
  17. Key string // robot key
  18. To []string // mention_list
  19. }
  20. type workwx struct {
  21. opt *OptionsWorkwx
  22. }
  23. var _ beaconfire.BeaconFire = &workwx{}
  24. func NewWorkWx(opt *OptionsWorkwx) *workwx {
  25. return &workwx{
  26. opt: opt,
  27. }
  28. }
  29. func (c *workwx) Name() string {
  30. return WORKWX_NAME
  31. }
  32. func (c *workwx) Send(bp *beaconfire.BeaconParam) error {
  33. msgtype := _WORKWX_MSGTYPE_MARKDOWN
  34. // modify content
  35. content := bp.Content
  36. if msgtype == _WORKWX_MSGTYPE_MARKDOWN {
  37. content = bp.FormatMarkdown()
  38. }
  39. url := fmt.Sprintf("%s?key=%s", _WORKWX_ENDPOINT, c.opt.Key)
  40. values := map[string]interface{}{
  41. "msgtype": msgtype,
  42. msgtype: map[string]interface{}{
  43. "content": content,
  44. "mentioned_list": c.opt.To,
  45. },
  46. }
  47. jsonBuffer, err := json.Marshal(values)
  48. if err != nil {
  49. return err
  50. }
  51. data, err := beaconfire.PostJson(url, jsonBuffer)
  52. if err != nil {
  53. return err
  54. }
  55. var res struct {
  56. ErrorCode int `json:"errorcode"`
  57. ErrMsg string `json:"errmsg"`
  58. }
  59. err = json.NewDecoder(bytes.NewBuffer(data)).Decode(&res)
  60. if err != nil {
  61. return err
  62. }
  63. if res.ErrorCode != 0 {
  64. return errors.New(res.ErrMsg)
  65. }
  66. /**
  67. returns:
  68. {
  69. "errcode":0,
  70. "errmsg":"ok"
  71. }
  72. */
  73. return nil
  74. }