跳到主要内容

go 企业微信机器人实例

· 阅读需 3 分钟
ahKevinXy

在终端某个群组添加机器人之后,创建者可以在机器人详情页看的该机器人特有的webhookurl。开发者可以按以下说明向这个地址发起HTTP POST 请求,即可实现给该群组发送消息 go 语言实现机器人推送消息

  • 使用curl 工具
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa' \
-H 'Content-Type: application/json' \
-d '
{
"msgtype": "text",
"text": {
"content": "hello world"
}
}'

  • 当前自定义机器人支持文本(text)、markdown(markdown)、图片(image)、图文(news)四种消息类型

  • 机器人的text/markdown类型消息支持在content中使用< @userid>扩展语法来@群成员

go 语言实现


package helps

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



// PushMessageToQwx
// @Description: 推送消息到企业微信
// @Author ahKevinXy
// @Date 2023-04-12 10:32:59
func PushMessageToQwx(mp map[string]interface{}, noticeUrl string) {

request, i, err := MakeHttpRequest("POST", noticeUrl, mp, nil)
if err != nil {
return
}
fmt.Println(request, i, err, "处理结果")
}

const (
POST = "POST"
GET = "GET"
PUT = "PUT"
PATCH = "PATCH"
)

// MakeHttpRequest
// @Description: HTTP请求
// @Author ahKevinXy
// @Date 2022-11-08 16:49:40
func MakeHttpRequest(method, url string, entity map[string]interface{}, jar *cookiejar.Jar) (string, int, error) {
var body io.Reader
var err error

if entity != nil {
switch method {
case POST, PUT, PATCH:
b, err := json.Marshal(entity)
if err != nil {
return "", 0, err
}

b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)

body = bytes.NewBuffer(b)

case GET:
if len(entity) > 0 {
params := make([]string, len(entity))
index := 0
for k, v := range entity {
_v := fmt.Sprintf("%v", v)
params[index] = fmt.Sprintf("%s=%v", k, _v)
index++
}
queryStr := strings.Join(params, "&")
url = fmt.Sprintf("%s?%s", url, queryStr)
}
}
}

req, err := http.NewRequest(method, url, body)
if err != nil {

return "", 0, err
}
if entity != nil && (method == POST || method == PUT || method == PATCH) {
req.Header.Set("Content-Type", "application/json;charset=utf-8")
req.Header.Set("Accept", "application/json")
}
req.Header.Add("Connection", "close")
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5")


client := http.DefaultClient
if jar != nil {
client = &http.Client{
Jar: jar,
}
}

res, err := client.Do(req)
if err != nil {

return "", 0, err
}
defer res.Body.Close()

if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusNoContent {

return "", 0, errors.New("http request failed to call")
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {

return "", 0, errors.New("the response could not be read")
}

return string(resBody), res.StatusCode, nil
}



Loading Comments...