1. 程式人生 > 程式設計 >Go語言實現釘釘傳送通知

Go語言實現釘釘傳送通知

具體程式碼如下所示:

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
  }
  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,err
  }
  timestamp = Key[0]
  sign = Key[1]
  return timestamp,nil
}
func SendDingMsg(msg string) {
  //請求地址模板
  timestamp,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語言實現釘釘傳送通知,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!