ai-week/qywechat/send.go

51 lines
1.4 KiB
Go
Raw Normal View History

2024-05-01 20:03:20 +08:00
package qywechat
import (
2024-05-02 21:04:26 +08:00
"encoding/json"
"fmt"
"io"
2024-05-01 20:03:20 +08:00
"log"
"net/http"
2024-05-02 21:04:26 +08:00
"strings"
2024-05-01 20:03:20 +08:00
)
//企业微信机器人发送
const webhookURL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7b50e0c4-8a35-4f29-b652-25e1d6142c2b"
func Send(repContent string) {
// 替换为你的企业微信机器人Webhook URL
2024-05-02 21:04:26 +08:00
jsonData, err := json.Marshal(repContent)
if err != nil {
fmt.Println("转换为JSON时出错:", err)
return
}
repContent = string(jsonData)
// 去掉最后三个字符和第一个引号
repContent = repContent[:len(repContent)-3]
repContent = repContent[1:]
fmt.Println(repContent)
2024-05-01 20:03:20 +08:00
// 创建消息体
2024-05-02 21:04:26 +08:00
repContent = fmt.Sprintf(`{"msgtype": "text", "text": {"content": "%s"}}`, repContent)
2024-05-01 20:03:20 +08:00
2024-05-02 21:04:26 +08:00
//repContent = strings.Replace(repContent, "\\", "", 9)
//lastIndex := strings.LastIndex(repContent, "\\")
//if lastIndex != -1 {
// repContent = repContent[:lastIndex] + repContent[lastIndex+1:]
//}
2024-05-01 20:03:20 +08:00
// 发送HTTP POST请求到企业微信机器人Webhook
2024-05-02 21:04:26 +08:00
fmt.Println(repContent)
resp, err := http.Post(webhookURL, "application/json", strings.NewReader(repContent))
2024-05-01 20:03:20 +08:00
if err != nil {
log.Printf("发送企业微信机器人失败,错误是: %v", err)
2024-05-01 20:03:20 +08:00
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("发送企业微信机器人失败,错误是: %v", err)
}
log.Printf("发送企业微信机器人完成,状态码为:%v返回体为%v", resp.StatusCode, string(body))
2024-05-01 20:03:20 +08:00
}