Go实现Zabbix企业微信应用通知告警

发布时间 2023-11-11 19:37:08作者: 实践哥

企业微信
https://work.weixin.qq.com/
企业微信->应用管理->创建应用

个人微信也能接收企业微信信息
我的企业 -> 微信插件 -> 扫码关注

特殊说明
之前企业微信只需要调用接口就能实现微信应用通知,最近改版,变得比较复杂
1:需要配置可信IP才能发
2: 配置可信IP前需要先设置可信域名或者设置接收url

上go代码sjgzbx_wechart.go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "path/filepath"

    "gopkg.in/ini.v1"
)

type TOKENJSON struct {
    Access_token string `json:"access_token"`
}

type WECHARTMESSAGES struct {
    Touser  string `json:"touser"`
    Msgtype string `json:"msgtype"`
    Agentid string `json:"agentid"`
    Text    struct {
        Content string `json:"content"`
    } `json:"text"`
}

func get_accesstoken(corpid, corpsecret string) string {
    gettoken_url := "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret
    client := &http.Client{}
    req, _ := client.Get(gettoken_url)
    defer req.Body.Close()
    body, _ := ioutil.ReadAll(req.Body)
    fmt.Printf("\n%q", string(body))
    var mytoken TOKENJSON
    json.Unmarshal([]byte(body), &mytoken)
    return mytoken.Access_token
}

func send_wechart(corpid, corpsecret, agentid, touser, content string) string {
    access_token := get_accesstoken(corpid, corpsecret)
    send_url := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
    client := &http.Client{}
    msg := WECHARTMESSAGES{
        Touser:  touser,
        Msgtype: "text",
        Agentid: agentid,
        Text: struct {
            Content string `json:"content"`
        }{Content: content},
    }
    sed_msg, _ := json.Marshal(msg)
    req, _ := http.NewRequest("POST", send_url, bytes.NewBuffer([]byte(sed_msg)))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("charset", "UTF-8")
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Printf("\n%q", string(body))
    return string(body)
}

func main() {
    args := os.Args
    if len(args) != 3 {
        panic("args len is error")
    }
    ex, err := os.Executable()
    exPath := filepath.Dir(ex)
    cfg, err := ini.Load(exPath + "/wechart.ini")
    if err != nil {
        fmt.Println(err)
    }
    corid := cfg.Section("").Key("corid").String()
    corsecret := cfg.Section("").Key("corsecret").String()
    agentid := cfg.Section("").Key("agentid").String()
    send_wechart(corid, corsecret, agentid, args[1], args[2])
}

配置示例

corid=xxx
corsecret=xxx
agentid=xxx

zabbix传两个参数即可

{ALERT.SENDTO}
{ALERT.SUBJECT} 或者 {ALERT.SUBJECT} {ALERT.MESSAGE}

操作视频地址
https://www.bilibili.com/video/BV1GH4y1z7YB/