首页 > 其他分享 >go发送飞书机器人webhook

go发送飞书机器人webhook

时间:2024-09-24 11:46:14浏览次数:9  
标签:logsign string err title text 机器人 webhook json go

package controllers

import (
"PrometheusAlert/models"
"bytes"
"crypto/tls"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"

"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)

type FSMessage struct {
Title string `json:"title"`
Text string `json:"text"`
}

func PostToFS(title, text, Fsurl, userEmail, logsign string) string {
open := beego.AppConfig.String("open-feishu")
if open != "1" {
logs.Info(logsign, "[feishu]", "飞书接口未配置未开启状态,请先配置open-feishu为1")
return "飞书接口未配置未开启状态,请先配置open-feishu为1"
}
RTstring := ""
if strings.Contains(Fsurl, "/v2/") {
RTstring = PostToFeiShuv2(title, text, Fsurl, userEmail, logsign)
} else {
RTstring = PostToFeiShu(title, text, Fsurl, logsign)
}
return RTstring
}

func PostToFeiShu(title, text, Fsurl, logsign string) string {
u := FSMessage{Title: title, Text: text}

b := new(bytes.Buffer)
json.NewEncoder(b).Encode(u)
logs.Info(logsign, "[feishu]", b)
var tr *http.Transport
if proxyUrl := beego.AppConfig.String("proxy"); proxyUrl != "" {
proxy := func(_ *http.Request) (*url.URL, error) {
return url.Parse(proxyUrl)
}
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Proxy: proxy,
}
} else {
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
client := &http.Client{Transport: tr}
res, err := client.Post(Fsurl, "application/json", b)
if err != nil {
logs.Error(logsign, "[feishu]", err.Error())
}
defer res.Body.Close()
result, err := ioutil.ReadAll(res.Body)
if err != nil {
logs.Error(logsign, "[feishu]", err.Error())
}
models.AlertToCounter.WithLabelValues("feishu").Add(1)
ChartsJson.Feishu += 1
logs.Info(logsign, "[feishu]", string(result))
return string(result)
}

type Conf struct {
WideScreenMode bool `json:"wide_screen_mode"`
EnableForward bool `json:"enable_forward"`
}

type Te struct {
Content string `json:"content"`
Tag string `json:"tag"`
}

type Element struct {
Tag string `json:"tag"`
Text Te `json:"text"`
Content string `json:"content"`
Elements []Element `json:"elements"`
}

type Titles struct {
Content string `json:"content"`
Tag string `json:"tag"`
}

type Headers struct {
Title Titles `json:"title"`
Template string `json:"template"`
}

type Cards struct {
Config Conf `json:"config"`
Elements []Element `json:"elements"`
Header Headers `json:"header"`
}

type FSMessagev2 struct {
MsgType string `json:"msg_type"`
Email string `json:"email"` //@所使用字段
Card Cards `json:"card"`
}

type TenantAccessMeg struct {
AppId string `json:"app_id"`
AppSecret string `json:"app_secret"`
}

type TenantAccessResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
TenantAccessToken string `json:"tenant_access_token"`
}

func PostToFeiShuv2(title, text, Fsurl, userOpenId, logsign string) string {
var color string
if strings.Count(text, "resolved") > 0 && strings.Count(text, "firing") > 0 {
color = "orange"
} else if strings.Count(text, "resolved") > 0 {
color = "green"
} else {
color = "red"
}

SendContent := text
if userOpenId != "" {
OpenIds := strings.Split(userOpenId, ",")
OpenIdtext := ""
for _, OpenId := range OpenIds {
OpenIdtext += "<at user_id=" + OpenId + " id=" + OpenId + "></at>"
}
SendContent += OpenIdtext
}

u := FSMessagev2{
MsgType: "interactive",
Email: "[email protected]",
Card: Cards{
Config: Conf{
WideScreenMode: true,
EnableForward: true,
},
Header: Headers{
Title: Titles{
Content: title,
Tag: "plain_text",
},
Template: color,
},
Elements: []Element{
Element{
Tag: "div",
Text: Te{
Content: SendContent,
Tag: "lark_md",
},
},
{
Tag: "hr",
},
{
Tag: "note",
Elements: []Element{
{
Content: title,
Tag: "lark_md",
},
},
},
},
},
}

b := new(bytes.Buffer)
json.NewEncoder(b).Encode(u)
logs.Info(logsign, "[feishuv2]", b)
var tr *http.Transport
if proxyUrl := beego.AppConfig.String("proxy"); proxyUrl != "" {
proxy := func(_ *http.Request) (*url.URL, error) {
return url.Parse(proxyUrl)
}
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Proxy: proxy,
}
} else {
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
client := &http.Client{Transport: tr}
res, err := client.Post(Fsurl, "application/json", b)
if err != nil {
logs.Error(logsign, "[feishuv2]", title+": "+err.Error())
}
defer res.Body.Close()
result, err := ioutil.ReadAll(res.Body)
if err != nil {
logs.Error(logsign, "[feishuv2]", title+": "+err.Error())
}
models.AlertToCounter.WithLabelValues("feishu").Add(1)
ChartsJson.Feishu += 1
logs.Info(logsign, "[feishuv2]", title+": "+string(result))
return string(result)
}

标签:logsign,string,err,title,text,机器人,webhook,json,go
From: https://www.cnblogs.com/cheyunhua/p/18428853

相关文章

  • go flag的常用设置
    packagemainimport("bytes""encoding/json""flag""fmt""io/ioutil""net/http""os")varZabbixTarget,ZabbixMessage,ZabbixType,PrometheusAlertUrlstringvarhelp......
  • go基础-16.文件操作
    文件读取一次性读取byteData,_:=os.ReadFile("go_study/hello.txt")fmt.Println(string(byteData))获取当前go文件的路径可以通过获取当前go文件的路径,然后用相对于当前go文件的路径去打开文件//GetCurrentFilePath获取当前文件路径funcGetCurrentFilePath()string......
  • go基础-19.网络编程
    TCP传输控制协议(TCP,TransmissionControlProtocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议如何保证连接可靠呢?(面试常考题)三次握手四次挥手服务端packagemainimport("fmt""io""net")funcmain(){//创建tcp的监听地址tcpAddr,_:=......
  • go基础-18.反射
    类型判断判断一个变量是否是结构体,切片,mappackagemainimport("fmt""reflect")funcrefType(objany){typeObj:=reflect.TypeOf(obj)fmt.Println(typeObj,typeObj.Kind())//去判断具体的类型switchtypeObj.Kind(){casereflect.Slice:fm......
  • go基础-20.部署
    go项目的部署特别简单,编写完成之后,只需要执行gobuild即可打包为可执行文件注意,这个操作是不同平台不一样的windows下打包就是exe文件,linux下打包就是二进制文件打包命令gobuild打当前目录下的main包,注意,只能有一个main函数的包gobuildxxx.go打当前目录下,xxx.go的......
  • go基础-3.基本数据类型
    go语言的基本数据类型有整数形浮点型复数布尔字符串整数型go语言的整数类型,具体细分有很多varn1uint8=2varn2uint16=2varn3uint32=2varn4uint64=2varn5uint=2varn6int8=2varn7int16=2varn8int32=2varn9int64=2va......
  • go基础-2.变量定义与输入输出
    变量定义标准的变量定义packagemainimport"fmt"funcmain(){//先定义,再赋值varnamestringname="枫枫"fmt.Println(name)//var变量名类型="变量值"varuserNamestring="枫枫"fmt.Println(userName)}如果一个变量定义了......
  • go基础-5.判断语句
    if语句以年龄为例,输入的年龄在某一个区间,就输出对应的提示信息<=0未出生1-18未成年18-35青年>=35中年很明显,这是一个多选一的情况我们有很多中方式来实现中断式packagemainimport"fmt"funcmain(){fmt.Println("请输入你的年龄:")varagei......
  • go基础-4.数组、切片、map
    数组数组(Array)是一种非常常见的数据类型,几乎所有的计算机编程语言中都会用到它数组里的元素必须全部为同一类型,要嘛全部是字符串,要嘛全部是整数声明数组时,必须指定其长度或者大小packagemainimport"fmt"funcmain(){vararray[3]int=[3]int{1,2,3}fmt.Pr......
  • go基础-7.函数和指针
    函数是一段封装了特定功能的可重用代码块,用于执行特定的任务或计算函数接受输入(参数)并产生输出(返回值)函数定义packagemainimport"fmt"//使用func关键字定义一个函数funcsayHello(){fmt.Println("hello")}funcmain(){//函数()调用函数sayHello()}......