dingtalk_robot_node.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package nodes
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gogf/gf/encoding/gjson"
  6. "github.com/gogf/gf/os/grpool"
  7. "net/http"
  8. "sparrow/pkg/protocol"
  9. "sparrow/pkg/ruleEngine"
  10. "sparrow/pkg/server"
  11. "sparrow/pkg/utils"
  12. "sync"
  13. )
  14. type DingTalkRobotNode struct {
  15. pool *grpool.Pool
  16. config *DingTalkRobotNodeConfig
  17. client *utils.HttpClient
  18. bufPool sync.Pool
  19. }
  20. type DingTalkRobotNodeConfig struct {
  21. WebHook string `json:"webhook"` // webhook
  22. }
  23. func (d *DingTalkRobotNode) Init(ctx ruleEngine.Context, config string) error {
  24. fmt.Printf("初始化钉钉机器人节点---------------\n")
  25. d.pool = grpool.New(10)
  26. if config == "" {
  27. d.config = &DingTalkRobotNodeConfig{
  28. WebHook: "http://localhost:8899/test",
  29. }
  30. } else {
  31. c := new(DingTalkRobotNodeConfig)
  32. err := json.Unmarshal([]byte(config), c)
  33. if err != nil {
  34. return err
  35. }
  36. d.config = c
  37. }
  38. client := utils.NewHttpClient()
  39. client.SetLogger(server.Log)
  40. d.client = client
  41. return nil
  42. }
  43. func (d *DingTalkRobotNode) OnMessage(ctx ruleEngine.Context, message *protocol.Message) error {
  44. fmt.Printf("执行钉钉机器人节点--------------\n")
  45. body, err := d.newBody(message)
  46. if body == nil {
  47. return nil
  48. } else if err != nil {
  49. return err
  50. }
  51. fmt.Printf("webhook:-----------%s\n", d.config.WebHook)
  52. req, err := d.client.Post(d.config.WebHook, "application/json", gjson.New(body))
  53. return d.pool.Add(func() {
  54. if err != nil {
  55. server.Log.Errorf("请求出错%s", err.Error())
  56. return
  57. }
  58. if req != nil && req.Response() != nil {
  59. defer req.Close()
  60. if req.Response().StatusCode == http.StatusOK {
  61. ctx.TellSuccess(message)
  62. }
  63. }
  64. })
  65. }
  66. func (d *DingTalkRobotNode) newBody(message *protocol.Message) (body map[string]interface{}, err error) {
  67. msg := map[string]interface{}{
  68. "content": message.AlarmMessage,
  69. }
  70. body = map[string]interface{}{
  71. "msgtype": "text",
  72. "text": msg,
  73. }
  74. fmt.Printf("message222222:-----------%s\n", body)
  75. return body, nil
  76. }