Go实现Zabbix企业微信机器人告警

发布时间 2023-11-12 18:05:34作者: 实践哥

企业微信
应用通知的程序相对复杂点,见上篇文章
机器人告警相对简单点,只需一个url即可
企业微信里创建一个机器人
注意机器人的url,后续程序中需要使用
直接上程序sjgzbx_machine.go

package main

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

    "gopkg.in/ini.v1"
)

type MACHINEMESSAGES struct {
    Msgtype string `json:"msgtype"`
    Text    struct {
        Content string `json:"content"`
    } `json:"text"`
}

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 + "/machine.ini")
    if err != nil {
        fmt.Println(err)
    }
    machineurl := cfg.Section("").Key("machineurl").String()
    send_url := machineurl
    client := &http.Client{}
    msg := MACHINEMESSAGES{
        Msgtype: "text",
        Text: struct {
            Content string `json:"content"`
        }{Content: args[2]},
    }
    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))

}

配置文件与二进程文件放一个目录machine.ini

machineurl=xxx

程序说明
接收两个参数,第一个参数作废,发的信息就是第二个参数

zabbix媒介两个参数

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

视频操作
https://www.bilibili.com/video/BV1dC4y177kS/