欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go语言实现钉钉发送通知

程序员文章站 2022-05-14 15:13:21
具体代码如下所示: package main import ( "bufio" "io" "fmt" "io/ioutil" "os/exec...

具体代码如下所示:

package main
import (
  "bufio"
  "io"
  "fmt"
  "io/ioutil"
  "os/exec"
  "net/http"
  "os"
  "strings"
)
func getkey() (timestamp string ,sign string, err error){
  cmd := exec.command("/bin/python", "/application/scripts/hezhong_host_status/aaa.py")
  stdout , err := cmd.stdoutpipe()
  if err != nil {
   fmt.println("error:can not obtain stdout pipe for command:%s \n", err)
   return timestamp , sign, err
  }
  if err := cmd.start() ; err != nil {
   fmt.println("error:the command is err ",err)
   return timestamp, sign,err
  }
  var key []string
  //读取所有输出
  bytes := bufio.newreader(stdout)
  for {
   line ,err:= bytes.readstring('\n')
   if err == io.eof{
     break
   }
   if err != nil {
     fmt.println("read err:",err)
   }
   key = append(key,line)
  }
  if err := cmd.wait();err!= nil{
   fmt.println("wait",err.error())
   return timestamp, sign ,err
  }
  timestamp = key[0]
  sign = key[1]
  return timestamp ,sign ,nil
}
func senddingmsg(msg string) {
  //请求地址模板
  timestamp , sign , err := getkey()
  if err != nil {
   fmt.println("get key err:",err)
  }
  timestamp = strings.trimright(timestamp, "\n")
  sign = strings.trimright(sign, "\n")
  //timestamp := time.now().unixnano() / 1e6
  //timestamp := int64(1572870805748)
  //sign := "oj5shd3iwcwvicl78k3pgx0tfqnjdfcdzmpxai%2bvrfe%3d"
  webhook := "https://oapi.dingtalk.com/robot/send?access_token=628d11124aef5f9efe2a8c8a6b5afa2b67ab01dxxxxxxxxxxxxxxxxxxxxx&"+ "timestamp=" + timestamp + "&sign=" + sign
  content := `{"msgtype": "text",
   "text": {"content": "`+ msg + `"},
        "at": {
           "atmobiles": [
             "18301371817"
           ],
           "isatall": true
        }
  }`
  //创建一个请求
  req, err := http.newrequest("post", webhook, strings.newreader(content))
  if err != nil {
   fmt.println(err)
  }
  client := &http.client{}
  //设置请求头
  req.header.set("content-type", "application/json")
  req.header.set("user-agent","firefox")
  //发送请求
  resp, err := client.do(req)
  //关闭请求
  defer resp.body.close()
  fmt.println(resp.statuscode)
  body,_ := ioutil.readall(resp.body)
  fmt.println(string(body))
  if err != nil {
   fmt.println("handle error")
  }
}
func main(){
  senddingmsg(os.args[1])
}

辅助python脚本:

#!python 2.7
import time
import hmac
import hashlib
import base64
import urllib
timestamp = long(round(time.time() * 1000))
secret = 'this is secret'
secret_enc = bytes(secret).encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = bytes(string_to_sign).encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.quote_plus(base64.b64encode(hmac_code))
print(timestamp)
print(sign)

总结

以上所述是小编给大家介绍的go语言实现钉钉发送通知,希望对大家有所帮助