1 回答

TA貢獻2011條經驗 獲得超2個贊
這里沒有錯bytes.NewBuffer() 。從 slack 的角度來看,它只識別“文本”字段提供的消息。你需要重新設計你的SlackRequestBody結構。當您使用 Webhook API 發送消息時,您的請求正文應遵循slack.
POST https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
Content-type: application/json
{
"text": ...
"blocks": ...
"attachments": ...
"thread_ts": ...
"mrkdwn": ...
... ... ...
}
所以,你的SlackRequestBody結構應該是這樣的:
package main
import (
"encoding/json"
"fmt"
"time"
)
type SlackRequestBody struct {
Text string `json:"text"`
Blocks []Block `json:"blocks,omitempty"`
ThreadTimestamp string `json:"thread_ts,omitempty"`
Mrkdwn bool `json:"mrkdwn,omitempty"`
}
type Block struct {
BlockID string `json:"block_id,omitempty"`
Type string `json:"type"`
Text Text `json:"text"`
}
type Text struct {
Type string `json:"type"`
Text string `json:"text"`
}
func main() {
var payload = &SlackRequestBody{
Text: "Your message",
Blocks: []Block{
{
Type: "section",
Text: Text{
Type: "plain_text",
Text: "User Name: XXXX",
},
BlockID: "username",
},
{
Type: "section",
Text: Text{
Type: "plain_text",
Text: "Event Time: " + time.Now().String(),
},
BlockID: "eventTime",
},
},
}
data, err := json.Marshal(payload)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
去游樂場
輸出:
{
"text":"Your message",
"blocks":[
{
"block_id":"username",
"type":"section",
"text":{
"type":"plain_text",
"text":"User Name: XXXX"
}
},
{
"block_id":"eventTime",
"type":"section",
"text":{
"type":"plain_text",
"text":"Event Time: 2020-03-29 14:11:33.533827881 +0600 +06 m=+0.000078203"
}
}
]
}
我會推薦你使用 slack 的官方go 客戶端。它將提供更大的靈活性??鞓肪幋a。
- 1 回答
- 0 關注
- 130 瀏覽
添加回答
舉報