飞书golang 发送机器人结构定义

飞书golang 发送机器人结构定义

在Golang中,可以定义一个结构体来表示飞书(Feishu)机器人的数据。以下是一个简单的示例,展示了如何定义用于发送消息到飞书机器人的结构体:

 
 
package main
 
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
 
// FeishuRobotPayload 表示飞书机器人的消息结构
type FeishuRobotPayload struct {
MsgType string `json:"msg_type"`
Content struct {
Text string `json:"text"`
} `json:"content"`
}
 
// SendFeishuRobotMessage 发送消息到飞书机器人
func SendFeishuRobotMessage(robotURL string, payload *FeishuRobotPayload) error {
payloadBytes, err := json.Marshal(payload)
if err != nil {
return err
}
 
resp, err := http.Post(robotURL, "application/json", bytes.NewBuffer(payloadBytes))
if err != nil {
return err
}
defer resp.Body.Close()
 
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to send message, status code: %d", resp.StatusCode)
}
 
return nil
}
 
func main() {
// 示例:发送文本消息到飞书机器人
robotURL := "https://open.feishu.cn/open-apis/bot/v2/hook/your_robot_hook_url"
message := &FeishuRobotPayload{
MsgType: "text",
Content: struct {
Text string `json:"text"`
}{
Text: "这是一条来自Golang的消息",
},
}
 
err := SendFeishuRobotMessage(robotURL, message)
if err != nil {
fmt.Println("发送消息失败:", err)
} else {
fmt.Println("消息发送成功")
}
}

在这个示例中,我们定义了一个FeishuRobotPayload结构体来表示飞书机器人接受的消息格式。然后我们实现了一个SendFeishuRobotMessage函数,它负责将消息序列化为JSON,并发送到指定的飞书机器人Webhook URL。在main函数中,我们创建了一个消息并调用SendFeishuRobotMessage函数来发送它。

 

 

package main

import (
"Awswork/i18n"
"Awswork/model"
"log"

"bytes"
"crypto/tls"
"encoding/json"
"fmt"
//"github.com/cookieY/yee/logger"
"io"
"net/http"
"os"
"strings"
"text/template"
)

type FeishuRobotPayload struct {
MsgType string `json:"msg_type"`
Content struct {
Text string `json:"text"`
} `json:"content"`
}

type imCryGeneric struct {
Assigned string `json:"assigned"`
WorkId string `json:"work_id"`
Source string `json:"source"`
Username string `json:"username"`
Text string `json:"text"`
}
type SendOrder struct {
Order imCryGeneric `json:"order"`
Status string `json:"status"`
}

//var Commontext = `
//{
// "msgtype": "markdown",
// "markdown": {
// "title": "Yearning",
// "text": "## Yearning工单通知 \n\n **工单编号:** $WORKID\n\n **数据源:** $SOURCE\n\n **工单说明:** $TEXT\n\n **提交人员:** <font color = \"#78beea\">$USER</font> \n \n **下一步操作人:** <font color=\"#fe8696\">$AUDITOR</font> \n \n **平台地址:** [$HOST]($HOST) \n \n **状态:** <font color=\"#1abefa\">$STATE</font> \n \n"
// }
//}

// `
//var Commontext = `{
//"msg_type": "text",
// "content": {
// "text": "🐱‍🏍Yearning工单通知 \n\n 🍳工单编号: $WORKID\n\n 🍭数据源: $SOURCE\n\n ⚓工单说明: $TEXT\n\n 👩‍⚖️提交人员: $USER \n \n 🎗下一步操作人: $AUDITOR \n \n ⛑平台地址: [$HOST]($HOST) \n \n 🎉状态: $STATE \n \n"
// }
//}
//`

var Commontext = JsonToMsg(&SedDingDing)

func JsonToMsg(msg interface{}) string {
data, err := json.MarshalIndent(msg, "", " ")
if err != nil {
fmt.Println(err)
}
return string(data)
}

var Test1 = `
### Yearning工单通知
**工单编号:** {{.Order.WorkId}}

**提交人员:** {{.Order.Username}}

**数据源:** {{.Order.Source}}

**下一步操作人:** {{.Order.Assigned}}

{{ if eq .Order.Assigned "执行成功" }}
**状态:** <font color="#1abefa"> {{.status}} </font>
{{ else }}
**状态:** {{.status }}
{{ end }}
**工单说明:**
> {{.Order.Text}}
`

func TesttempALte(state string, order imCryGeneric) {
//var order imCryGeneric

//if !stateHandler(state) {
// order.Assigned = "无"
//}
msg := SendOrder{
Order: order,
Status: state,
}

t, err := template.New("test").Parse(Test1)
if err != nil {
fmt.Println(err)
}
t.Execute(os.Stdout, &msg)

}

var SedDingDing = FeishuRobotPayload{
MsgType: "text",
Content: struct {
Text string `json:"text"`
}(struct{ Text string }{Text: "### Yearning工单通知 \n\n 工单编号:** $WORKID **\n\n 数据源:** $SOURCE ** \n\n 工单说明: ** $TEXT **\n\n 👩**提交人员:** $USER **\n \n 下一步操作人:** $AUDITOR **\n \n 状态:** $STATE ** \n \n"}),
}

func SendDingMsg(msg model.Message, sv string) {
//请求地址模板

hook := msg.WebHook

if msg.Key != "" {
//hook = Sign(msg.Key, msg.WebHook)
}

fmt.Printf("hook:%v", hook)
fmt.Printf("sv:%v", sv)
req, err := http.NewRequest("POST", hook, strings.NewReader(sv))
if err != nil {
log.Printf("request:", err)
return
}

tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}

client := &http.Client{Transport: tr}
//设置请求头
req.Header.Set("Content-Type", "application/json; charset=utf-8")
//发送请求
resp, err := client.Do(req)

if err != nil {
log.Printf("resp:", err)
return
}
body, _ := io.ReadAll(resp.Body)
log.Printf("resp:%v", string(body))

//关闭请求
defer resp.Body.Close()
}

func dingMsgTplHandler(state string, generic interface{}) string {

var order imCryGeneric

switch v := generic.(type) {
case model.CoreSqlOrder:
order = imCryGeneric{
Assigned: v.Assigned,
WorkId: v.WorkId,
Source: v.Source,
Username: v.Username,
Text: v.Text,
}
case model.CoreQueryOrder:
order = imCryGeneric{
Assigned: v.Assigned,
WorkId: v.WorkId + i18n.DefaultLang.Load(i18n.INFO_QUERY),
Source: i18n.DefaultLang.Load(i18n.ER_QUERY_NO_DATA_SOURCE),
Username: v.Username,
Text: v.Text,
}
}

//if !stateHandler(state) {
// order.Assigned = "无"
//}

//jsonData, _ := json.Marshal(msg)
//fmt.Println(string(jsonData))

//s, _ = RenderTemplate("NAME", Test, msg)
//
//fmt.Println(err)
//return str

text := Commontext

text = strings.Replace(text, "$STATE", state, -1)
text = strings.Replace(text, "$WORKID", order.WorkId, -1)
text = strings.Replace(text, "$SOURCE", order.Source, -1)

text = strings.Replace(text, "$HOST", model.GloOther.Domain, -1)
text = strings.Replace(text, "$USER", order.Username, -1)
text = strings.Replace(text, "$AUDITOR", order.Assigned, -1)
text = strings.Replace(text, "$TEXT", order.Text, -1)

//return text
return text
}

func stateHandler(state string) bool {
switch state {
case i18n.DefaultLang.Load(i18n.INFO_TRANSFERRED_TO_NEXT_AGENT), i18n.DefaultLang.Load(i18n.INFO_SUBMITTED):
return true
}
return false
}
func RenderTemplate(name, defaultStr string, data interface{}) (string, error) {
var out bytes.Buffer
tmpl := template.Must(template.New(name).Parse(defaultStr))
err := tmpl.Execute(os.Stdout, data)
if err != nil {
return "", err
}
return out.String(), nil
}
func main() {
order := imCryGeneric{
Assigned: "cheyunhua",
WorkId: "rtewtwe",
Source: "fdsfsd",
Username: "cheyunhua",
Text: "test",
}
TesttempALte("已提交", order)
//fmt.Println(Test1)
}
posted @ 2024-06-11 17:17  技术颜良  阅读(123)  评论(0编辑  收藏  举报