feat: add message push function call
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type barkResponse struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type Bark struct {
|
||||
PushKey string
|
||||
Archive string
|
||||
Group string
|
||||
Sound string
|
||||
Icon string
|
||||
Level string
|
||||
URL string
|
||||
Key string
|
||||
IV string
|
||||
}
|
||||
|
||||
func (b *Bark) Request(title, content string) ([]byte, error) {
|
||||
data := map[string]interface{}{
|
||||
"title": title,
|
||||
"body": content,
|
||||
}
|
||||
if b.Archive != "" {
|
||||
data["isArchive"] = b.Archive
|
||||
}
|
||||
if b.Group != "" {
|
||||
data["group"] = b.Group
|
||||
}
|
||||
if b.Sound != "" {
|
||||
data["sound"] = b.Sound
|
||||
}
|
||||
if b.Icon != "" {
|
||||
data["icon"] = b.Icon
|
||||
}
|
||||
if b.Level != "" {
|
||||
data["level"] = b.Level
|
||||
}
|
||||
if b.URL != "" {
|
||||
data["url"] = b.URL
|
||||
}
|
||||
|
||||
var postData interface{}
|
||||
url := b.getURL()
|
||||
|
||||
if b.Key != "" && b.IV != "" {
|
||||
// Use encryption
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ciphertext, err := b.encryptPayload(string(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encryption failed: %v", err)
|
||||
}
|
||||
postData = map[string]interface{}{
|
||||
"ciphertext": ciphertext,
|
||||
"device_key": b.PushKey,
|
||||
"sound": b.Sound,
|
||||
}
|
||||
// When using encryption, use the push endpoint if PushKey is just a key
|
||||
if !strings.HasPrefix(b.PushKey, "http") {
|
||||
url = "https://api.day.app/push"
|
||||
}
|
||||
} else {
|
||||
// Normal request
|
||||
postData = data
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(postData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r barkResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
|
||||
if r.Code != 200 {
|
||||
return body, fmt.Errorf("bark response error: %s", string(body))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (b *Bark) getURL() string {
|
||||
pushKey := b.PushKey
|
||||
if strings.HasPrefix(pushKey, "http") {
|
||||
return pushKey
|
||||
}
|
||||
return fmt.Sprintf("https://api.day.app/%s", pushKey)
|
||||
}
|
||||
|
||||
func (b *Bark) encryptPayload(payload string) (string, error) {
|
||||
key := []byte(b.Key)
|
||||
iv := []byte(b.IV)
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
paddedPayload := b.pkcs7Pad([]byte(payload), aes.BlockSize)
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
ciphertext := make([]byte, len(paddedPayload))
|
||||
mode.CryptBlocks(ciphertext, paddedPayload)
|
||||
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
func (b *Bark) pkcs7Pad(data []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(data)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(data, padtext...)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CustomWebhook struct {
|
||||
Webhook string
|
||||
Body string
|
||||
}
|
||||
|
||||
var Client = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
func (cw *CustomWebhook) Request(url string, msg string) ([]byte, error) {
|
||||
resp, err := Client.Post(url, "application/json", bytes.NewBuffer([]byte(msg)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(resp.Body)
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return body, err
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type response struct {
|
||||
Code int `json:"errcode"`
|
||||
Msg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
type Dtalk struct {
|
||||
AccessToken string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (t *Dtalk) Request(msg interface{}) ([]byte, error) {
|
||||
b, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.Post(t.getURL(), "application/json", bytes.NewBuffer(b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(resp.Body)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r response
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
if r.Code != 0 {
|
||||
return body, fmt.Errorf("response error: %s", string(body))
|
||||
}
|
||||
return body, err
|
||||
}
|
||||
|
||||
// SendMessageText Function to send message
|
||||
func (t *Dtalk) SendMessageText(text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "text",
|
||||
"text": map[string]string{
|
||||
"content": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 添加@功能
|
||||
if len(at) > 0 {
|
||||
atMobiles := []string{}
|
||||
isAtAll := false
|
||||
|
||||
for _, mobile := range at {
|
||||
if mobile == "all" || mobile == "@all" {
|
||||
isAtAll = true
|
||||
} else {
|
||||
atMobiles = append(atMobiles, mobile)
|
||||
}
|
||||
}
|
||||
|
||||
msg["at"] = map[string]interface{}{
|
||||
"atMobiles": atMobiles,
|
||||
"isAtAll": isAtAll,
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *Dtalk) SendMessageMarkdown(title, text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]string{
|
||||
"title": title,
|
||||
"text": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 添加@功能
|
||||
if len(at) > 0 {
|
||||
atMobiles := []string{}
|
||||
isAtAll := false
|
||||
|
||||
for _, mobile := range at {
|
||||
if mobile == "all" || mobile == "@all" {
|
||||
isAtAll = true
|
||||
} else {
|
||||
atMobiles = append(atMobiles, mobile)
|
||||
}
|
||||
}
|
||||
|
||||
msg["at"] = map[string]interface{}{
|
||||
"atMobiles": atMobiles,
|
||||
"isAtAll": isAtAll,
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *Dtalk) hmacSha256(stringToSign string, secret string) string {
|
||||
h := hmac.New(sha256.New, []byte(secret))
|
||||
h.Write([]byte(stringToSign))
|
||||
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func (t *Dtalk) getURL() string {
|
||||
wh := "https://oapi.dingtalk.com/robot/send?access_token=" + t.AccessToken
|
||||
timestamp := time.Now().UnixNano() / 1e6
|
||||
stringToSign := fmt.Sprintf("%d\n%s", timestamp, t.Secret)
|
||||
sign := t.hmacSha256(stringToSign, t.Secret)
|
||||
url := fmt.Sprintf("%s×tamp=%d&sign=%s", wh, timestamp, sign)
|
||||
return url
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gopkg.in/gomail.v2"
|
||||
)
|
||||
|
||||
type EmailMessage struct {
|
||||
Server string
|
||||
Port int
|
||||
Account string
|
||||
Passwd string
|
||||
FromName string
|
||||
GM *gomail.Dialer
|
||||
}
|
||||
|
||||
func (e *EmailMessage) Init(host string, port int, account string, passwd string, fromName string) {
|
||||
e.Server = host
|
||||
e.Port = port
|
||||
e.Account = account
|
||||
e.Passwd = passwd
|
||||
e.FromName = fromName
|
||||
e.GM = gomail.NewDialer(host, port, account, passwd)
|
||||
}
|
||||
|
||||
func (e *EmailMessage) SendTextMessage(toEmail string, title string, content string) string {
|
||||
m := gomail.NewMessage()
|
||||
if e.FromName != "" {
|
||||
m.SetAddressHeader("From", e.Account, e.FromName)
|
||||
} else {
|
||||
m.SetHeader("From", e.Account)
|
||||
}
|
||||
m.SetHeader("To", toEmail)
|
||||
m.SetHeader("Subject", title)
|
||||
m.SetBody("text/html", content)
|
||||
|
||||
if err := e.GM.DialAndSend(m); err != nil {
|
||||
return fmt.Sprintf("邮件发送失败: %s", err)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (e *EmailMessage) SendHtmlMessage(toEmail string, title string, content string) string {
|
||||
return e.SendTextMessage(toEmail, title, content)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type feishuResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
type Feishu struct {
|
||||
AccessToken string
|
||||
Secret string
|
||||
}
|
||||
|
||||
// genSign 生成飞书签名
|
||||
func (f *Feishu) genSign(timestamp int64) string {
|
||||
if f.Secret == "" {
|
||||
return ""
|
||||
}
|
||||
stringToSign := fmt.Sprintf("%v\n%s", timestamp, f.Secret)
|
||||
h := hmac.New(sha256.New, []byte(stringToSign))
|
||||
signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
return signature
|
||||
}
|
||||
|
||||
// SendMessageText 发送文本消息
|
||||
func (f *Feishu) SendMessageText(content string, atMobiles ...string) ([]byte, error) {
|
||||
timestamp := time.Now().Unix()
|
||||
sign := f.genSign(timestamp)
|
||||
|
||||
msg := map[string]interface{}{
|
||||
"timestamp": strconv.FormatInt(timestamp, 10),
|
||||
"sign": sign,
|
||||
"msg_type": "text",
|
||||
"content": map[string]interface{}{
|
||||
"text": content,
|
||||
},
|
||||
}
|
||||
|
||||
return f.send(msg)
|
||||
}
|
||||
|
||||
// SendMessageMarkdown 发送 Markdown 消息
|
||||
func (f *Feishu) SendMessageMarkdown(title, content string, atMobiles ...string) ([]byte, error) {
|
||||
timestamp := time.Now().Unix()
|
||||
sign := f.genSign(timestamp)
|
||||
|
||||
// 处理 @ 人员
|
||||
atContent := ""
|
||||
if len(atMobiles) > 0 {
|
||||
for _, mobile := range atMobiles {
|
||||
if mobile == "all" {
|
||||
atContent += "<at user_id=\"all\">所有人</at>"
|
||||
} else {
|
||||
atContent += fmt.Sprintf("<at user_id=\"%s\"></at>", mobile)
|
||||
}
|
||||
}
|
||||
content = atContent + "\n" + content
|
||||
}
|
||||
|
||||
msg := map[string]interface{}{
|
||||
"timestamp": strconv.FormatInt(timestamp, 10),
|
||||
"sign": sign,
|
||||
"msg_type": "interactive",
|
||||
"card": map[string]interface{}{
|
||||
"header": map[string]interface{}{
|
||||
"title": map[string]interface{}{
|
||||
"tag": "plain_text",
|
||||
"content": title,
|
||||
},
|
||||
},
|
||||
"elements": []map[string]interface{}{
|
||||
{
|
||||
"tag": "markdown",
|
||||
"content": content,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return f.send(msg)
|
||||
}
|
||||
|
||||
// send 发送请求
|
||||
func (f *Feishu) send(msg map[string]interface{}) ([]byte, error) {
|
||||
url := fmt.Sprintf("https://open.feishu.cn/open-apis/bot/v2/hook/%s", f.AccessToken)
|
||||
|
||||
jsonData, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("JSON序列化失败: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建请求失败: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("发送请求失败: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取响应失败: %v", err)
|
||||
}
|
||||
|
||||
var result feishuResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return body, fmt.Errorf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
if result.Code != 0 {
|
||||
return body, fmt.Errorf("飞书返回错误: %s", result.Msg)
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type gotifyResponse struct {
|
||||
Id int `json:"id"`
|
||||
Message string `json:"message"`
|
||||
ErrorCode int `json:"errorCode"`
|
||||
}
|
||||
|
||||
type Gotify struct {
|
||||
Url string
|
||||
Token string
|
||||
Priority int
|
||||
}
|
||||
|
||||
func (g *Gotify) Request(title, content string) ([]byte, error) {
|
||||
// Construct the URL with token
|
||||
u, err := url.Parse(fmt.Sprintf("%s/message", g.Url))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("token", g.Token)
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
data := map[string]interface{}{
|
||||
"title": title,
|
||||
"message": content,
|
||||
"priority": g.Priority,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := http.Post(u.String(), "application/json", bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r gotifyResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
|
||||
if r.Id == 0 {
|
||||
return body, fmt.Errorf("gotify response error: %s", string(body))
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Ntfy struct {
|
||||
Url string
|
||||
Topic string
|
||||
Priority string
|
||||
Icon string
|
||||
Token string
|
||||
Username string
|
||||
Password string
|
||||
Actions string
|
||||
}
|
||||
|
||||
func encodeRFC2047(text string) string {
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(text))
|
||||
return fmt.Sprintf("=?utf-8?B?%s?=", encoded)
|
||||
}
|
||||
|
||||
func (n *Ntfy) Request(title, content string) ([]byte, error) {
|
||||
if n.Url == "" {
|
||||
n.Url = "https://ntfy.sh"
|
||||
}
|
||||
url := fmt.Sprintf("%s/%s", n.Url, n.Topic)
|
||||
|
||||
req, err := http.NewRequest("POST", url, bytes.NewBufferString(content))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Title", encodeRFC2047(title))
|
||||
priority := n.Priority
|
||||
if priority == "" {
|
||||
priority = "3"
|
||||
}
|
||||
req.Header.Set("Priority", priority)
|
||||
if n.Icon != "" {
|
||||
req.Header.Set("Icon", n.Icon)
|
||||
}
|
||||
if n.Actions != "" {
|
||||
req.Header.Set("Actions", encodeRFC2047(n.Actions))
|
||||
}
|
||||
|
||||
if n.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+n.Token)
|
||||
} else if n.Username != "" && n.Password != "" {
|
||||
authStr := n.Username + ":" + n.Password
|
||||
encodedAuth := base64.StdEncoding.EncodeToString([]byte(authStr))
|
||||
req.Header.Set("Authorization", "Basic "+encodedAuth)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return body, fmt.Errorf("ntfy response error: %s", string(body))
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PushMe struct {
|
||||
PushKey string
|
||||
URL string
|
||||
Date string
|
||||
Type string
|
||||
}
|
||||
|
||||
func (p *PushMe) Request(title, content string) (string, error) {
|
||||
apiURL := p.URL
|
||||
if apiURL == "" {
|
||||
apiURL = "https://push.i-i.me/"
|
||||
}
|
||||
|
||||
data := url.Values{}
|
||||
data.Set("push_key", p.PushKey)
|
||||
data.Set("title", title)
|
||||
data.Set("content", content)
|
||||
if p.Date != "" {
|
||||
data.Set("date", p.Date)
|
||||
}
|
||||
if p.Type != "" {
|
||||
data.Set("type", p.Type)
|
||||
}
|
||||
|
||||
resp, err := http.Post(apiURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if resp.StatusCode == 200 && string(body) == "success" {
|
||||
return string(body), nil
|
||||
}
|
||||
|
||||
return string(body), fmt.Errorf("PushMe response error: %s", string(body))
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type qywxResponse struct {
|
||||
Code int `json:"errcode"`
|
||||
Msg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
type QyWeiXin struct {
|
||||
AccessToken string
|
||||
}
|
||||
|
||||
func (t *QyWeiXin) Request(msg interface{}) ([]byte, error) {
|
||||
b, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.Post(t.getURL(), "application/json", bytes.NewBuffer(b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(resp.Body)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r qywxResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
if r.Code != 0 {
|
||||
return body, fmt.Errorf("response error: %s", string(body))
|
||||
}
|
||||
return body, err
|
||||
}
|
||||
|
||||
// SendMessageText Function to send message
|
||||
func (t *QyWeiXin) SendMessageText(text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "text",
|
||||
"text": map[string]interface{}{
|
||||
"content": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 添加@功能
|
||||
// 企业微信支持两种@方式:
|
||||
// 1. mentioned_list: userid列表或"@all"
|
||||
// 2. mentioned_mobile_list: 手机号列表
|
||||
if len(at) > 0 {
|
||||
mentionedList := []string{}
|
||||
mentionedMobileList := []string{}
|
||||
|
||||
for _, item := range at {
|
||||
if item == "@all" || item == "all" {
|
||||
mentionedList = append(mentionedList, "@all")
|
||||
} else if len(item) == 11 && item[0] == '1' {
|
||||
// 判断是否为手机号(简单判断:11位且以1开头)
|
||||
mentionedMobileList = append(mentionedMobileList, item)
|
||||
} else {
|
||||
// 否则当作userid处理
|
||||
mentionedList = append(mentionedList, item)
|
||||
}
|
||||
}
|
||||
|
||||
textContent := msg["text"].(map[string]interface{})
|
||||
if len(mentionedList) > 0 {
|
||||
textContent["mentioned_list"] = mentionedList
|
||||
}
|
||||
if len(mentionedMobileList) > 0 {
|
||||
textContent["mentioned_mobile_list"] = mentionedMobileList
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *QyWeiXin) SendMessageMarkdown(title, text string, at ...string) ([]byte, error) {
|
||||
msg := map[string]interface{}{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]interface{}{
|
||||
"content": text,
|
||||
},
|
||||
}
|
||||
|
||||
// 企业微信Markdown消息不支持@功能,但可以在内容中手动添加
|
||||
// 如果需要@功能,建议使用text类型
|
||||
|
||||
resp, err := t.Request(msg)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *QyWeiXin) getURL() string {
|
||||
url := "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + t.AccessToken
|
||||
return url
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
type telegramResponse struct {
|
||||
Ok bool `json:"ok"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type Telegram struct {
|
||||
BotToken string
|
||||
ChatID string
|
||||
ApiHost string // 可选的自定义API地址(优先级最高)
|
||||
ProxyURL string // 可选的代理地址,支持 http://、https://、socks5:// 格式
|
||||
}
|
||||
|
||||
func (t *Telegram) Request(params map[string]interface{}) ([]byte, error) {
|
||||
apiURL := t.getAPIURL()
|
||||
|
||||
// 构建请求体
|
||||
data := url.Values{}
|
||||
for key, value := range params {
|
||||
data.Set(key, fmt.Sprintf("%v", value))
|
||||
}
|
||||
|
||||
// 创建 HTTP 客户端
|
||||
client := t.getHTTPClient()
|
||||
|
||||
resp, err := client.Post(apiURL, "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
// 忽略关闭错误
|
||||
}
|
||||
}(resp.Body)
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r telegramResponse
|
||||
err = json.Unmarshal(body, &r)
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
|
||||
if !r.Ok {
|
||||
return body, fmt.Errorf("telegram api error: %s", r.Description)
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// SendMessageText 发送文本消息
|
||||
func (t *Telegram) SendMessageText(text string) ([]byte, error) {
|
||||
params := map[string]interface{}{
|
||||
"chat_id": t.ChatID,
|
||||
"text": text,
|
||||
"disable_web_page_preview": "true",
|
||||
}
|
||||
|
||||
return t.Request(params)
|
||||
}
|
||||
|
||||
// SendMessageMarkdown 发送Markdown格式消息
|
||||
func (t *Telegram) SendMessageMarkdown(text string) ([]byte, error) {
|
||||
params := map[string]interface{}{
|
||||
"chat_id": t.ChatID,
|
||||
"text": text,
|
||||
"parse_mode": "Markdown",
|
||||
"disable_web_page_preview": "true",
|
||||
}
|
||||
|
||||
return t.Request(params)
|
||||
}
|
||||
|
||||
// SendMessageHTML 发送HTML格式消息
|
||||
func (t *Telegram) SendMessageHTML(text string) ([]byte, error) {
|
||||
params := map[string]interface{}{
|
||||
"chat_id": t.ChatID,
|
||||
"text": text,
|
||||
"parse_mode": "HTML",
|
||||
"disable_web_page_preview": "true",
|
||||
}
|
||||
|
||||
return t.Request(params)
|
||||
}
|
||||
|
||||
func (t *Telegram) getAPIURL() string {
|
||||
// 自定义 API 地址优先级最高
|
||||
if t.ApiHost != "" {
|
||||
return fmt.Sprintf("%s/bot%s/sendMessage", t.ApiHost, t.BotToken)
|
||||
}
|
||||
return fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", t.BotToken)
|
||||
}
|
||||
|
||||
// getHTTPClient 获取配置了代理的 HTTP 客户端
|
||||
func (t *Telegram) getHTTPClient() *http.Client {
|
||||
client := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
// 如果配置了代理且没有自定义 API 地址,则使用代理
|
||||
// 自定义 API 地址优先级更高,通常用于自建代理服务器
|
||||
if t.ProxyURL != "" && t.ApiHost == "" {
|
||||
proxyURL, err := url.Parse(t.ProxyURL)
|
||||
if err == nil {
|
||||
// 判断是否为 SOCKS5 代理
|
||||
if strings.HasPrefix(strings.ToLower(t.ProxyURL), "socks5://") {
|
||||
// 使用 SOCKS5 代理
|
||||
dialer, err := t.createSOCKS5Dialer(proxyURL)
|
||||
if err == nil {
|
||||
client.Transport = &http.Transport{
|
||||
DialContext: dialer.DialContext,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 使用 HTTP/HTTPS 代理
|
||||
client.Transport = &http.Transport{
|
||||
Proxy: http.ProxyURL(proxyURL),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
// createSOCKS5Dialer 创建 SOCKS5 代理拨号器
|
||||
func (t *Telegram) createSOCKS5Dialer(proxyURL *url.URL) (proxy.ContextDialer, error) {
|
||||
// 解析代理地址
|
||||
host := proxyURL.Host
|
||||
|
||||
// 检查是否有认证信息
|
||||
var auth *proxy.Auth
|
||||
if proxyURL.User != nil {
|
||||
password, _ := proxyURL.User.Password()
|
||||
auth = &proxy.Auth{
|
||||
User: proxyURL.User.Username(),
|
||||
Password: password,
|
||||
}
|
||||
}
|
||||
|
||||
// 创建基础拨号器
|
||||
baseDialer := &net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}
|
||||
|
||||
// 创建 SOCKS5 拨号器
|
||||
dialer, err := proxy.SOCKS5("tcp", host, auth, baseDialer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 转换为 ContextDialer
|
||||
contextDialer, ok := dialer.(proxy.ContextDialer)
|
||||
if !ok {
|
||||
return nil, errors.New("failed to convert to ContextDialer")
|
||||
}
|
||||
|
||||
return contextDialer, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2"
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/message"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type WeChatOFAccount struct {
|
||||
AppID string
|
||||
AppSecret string
|
||||
ToUser string
|
||||
TemplateID string
|
||||
URL string
|
||||
}
|
||||
|
||||
// 使用内存缓存进行token的存储
|
||||
var memory = cache.NewMemory()
|
||||
|
||||
func (cw *WeChatOFAccount) Send(title string, content string) (string, error) {
|
||||
wc := wechat.NewWechat()
|
||||
cfg := &offConfig.Config{
|
||||
AppID: cw.AppID,
|
||||
AppSecret: cw.AppSecret,
|
||||
Cache: memory,
|
||||
}
|
||||
officialAccount := wc.GetOfficialAccount(cfg)
|
||||
|
||||
// 获取 Access Token
|
||||
_, err := officialAccount.GetAccessToken()
|
||||
if err != nil {
|
||||
logrus.Errorf("获取access token失败:%s", err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
msgData := make(map[string]*message.TemplateDataItem)
|
||||
msgData["content"] = &message.TemplateDataItem{
|
||||
Value: content,
|
||||
}
|
||||
msgData["title"] = &message.TemplateDataItem{
|
||||
Value: title,
|
||||
//Color: "#173177",
|
||||
}
|
||||
|
||||
// 创建模板消息
|
||||
templateMessage := &message.TemplateMessage{
|
||||
ToUser: cw.ToUser,
|
||||
TemplateID: cw.TemplateID,
|
||||
URL: cw.URL,
|
||||
Data: msgData,
|
||||
}
|
||||
|
||||
// 发送模板消息
|
||||
_, err = officialAccount.GetTemplate().Send(templateMessage)
|
||||
if err != nil {
|
||||
logrus.Errorf("发送模板消息失败: %s", err)
|
||||
return "", err
|
||||
}
|
||||
//logrus.Infof("模板消息发送成功。 消息ID: %d", msgID)
|
||||
return "", nil
|
||||
}
|
||||
Reference in New Issue
Block a user