workwx.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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
  18. }
  19. type workwx struct {
  20. opt *OptionsWorkwx
  21. }
  22. var _ beaconfire.BeaconFire = &workwx{}
  23. func NewWorkWx(opt *OptionsWorkwx) *workwx {
  24. return &workwx{
  25. opt: opt,
  26. }
  27. }
  28. func (c *workwx) Name() string {
  29. return WORKWX_NAME
  30. }
  31. func (c *workwx) Send(bp *beaconfire.BeaconParam) error {
  32. msgtype := _WORKWX_MSGTYPE_MARKDOWN
  33. // modify content
  34. content := bp.Content
  35. if msgtype == _WORKWX_MSGTYPE_MARKDOWN {
  36. content = bp.FormatMarkdown()
  37. }
  38. url := fmt.Sprintf("%s?key=%s", _WORKWX_ENDPOINT, c.opt.Key)
  39. values := map[string]interface{}{
  40. "msgtype": msgtype,
  41. msgtype: map[string]interface{}{
  42. "content": content,
  43. "mentioned_list": bp.To,
  44. },
  45. }
  46. jsonBuffer, err := json.Marshal(values)
  47. if err != nil {
  48. return err
  49. }
  50. data, err := beaconfire.PostJson(url, jsonBuffer)
  51. if err != nil {
  52. return err
  53. }
  54. var res struct {
  55. ErrorCode int `json:"errorcode"`
  56. ErrMsg string `json:"errmsg"`
  57. }
  58. err = json.NewDecoder(bytes.NewBuffer(data)).Decode(&res)
  59. if err != nil {
  60. return err
  61. }
  62. if res.ErrorCode != 0 {
  63. return errors.New(res.ErrMsg)
  64. }
  65. /**
  66. returns:
  67. {
  68. "errcode":0,
  69. "errmsg":"ok"
  70. }
  71. */
  72. return nil
  73. }