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 客户端。它将提供更大的灵活性。快乐编码。
- 1 回答
- 0 关注
- 157 浏览
添加回答
举报
