dingding.go 1.26 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
package dingding

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

var (
	ROBOTWEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=5207fd753d28661ea0716ea0ef5b9e9e0aea392c9a148307c0b186e3d09b4aec"
	HILO         = "hilo:"
)

type dingResponse struct {
	Errcode int
	Errmsg  string
}
type dingtextMessage struct {
	MsgType string         `json:"msgtype"`
	Text    dingtextParams `json:"text"`
	At      dingdingAt     `json:"at"`
}

type dingtextParams struct {
	Content string `json:"content"`
}

// At at struct
type dingdingAt struct {
	AtMobiles []string `json:"atMobiles"`
	IsAtAll   bool     `json:"isAtAll"`
}

func SendDingRobot(url string, content string, isAtAll bool) error {
	msg := dingtextMessage{MsgType: "text", Text: dingtextParams{Content: HILO + content}, At: dingdingAt{IsAtAll: isAtAll}}
	m, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	resp, err := http.Post(url, "application/json", bytes.NewReader(m))
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	var dr dingResponse
	err = json.Unmarshal(data, &dr)
	if err != nil {
		return err
	}
	if dr.Errcode != 0 {
		return fmt.Errorf("dingrobot send failed: %v", dr.Errmsg)
	}
	return nil
}