钉钉机器人
javascript
js
const token = ""
const secret = ""
async function get_timestamp_sign(secret) {
async function hmac_sha256_b64(secret, data) {
const encoder = new TextEncoder()
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
)
const mac = await crypto.subtle.sign("HMAC", key, encoder.encode(data))
return encodeURIComponent(btoa(String.fromCharCode(...new Uint8Array(mac))))
}
let timestamp = Date.now()
return {
sign: await hmac_sha256_b64(secret, `${timestamp}\n${secret}`),
timestamp: timestamp
}
}
async function makeResponse(request) {
let ua = request.headers.get("User-Agent")
let data = await get_timestamp_sign(secret)
let content = await request.clone().text()
var raw = JSON.stringify({
"msgtype": "markdown",
"markdown": {
"title": "from workers api",
"text": content + "\n\n \n\n[Sent by] " + ua
}
})
var requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: raw,
redirect: 'follow'
};
let url = `https://oapi.dingtalk.com/robot/send?access_token=${token}×tamp=${data.timestamp}&sign=${data.sign}`
await fetch(url, requestOptions)
return new Response("SUCCESS")
}
addEventListener("fetch", event => {
const request = event.request
const url = new URL(request.url)
const prefix = "/zbot"
if (url.pathname.startsWith(prefix)) {
event.respondWith(makeResponse(request))
} else{
event.respondWith(new Response("FAILED"))
}
})
golang
go
package utils
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func SendBotMessage(message string, token string) {
url := "https://oapi.dingtalk.com/robot/send?access_token=" + token
method := "POST"
payload := strings.NewReader(`{"msgtype":"text","text":{"content":"` + message + `"}}`)
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
_, err = ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
}