-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsend.go
110 lines (100 loc) · 2.32 KB
/
send.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"bytes"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
var errAudio = errors.New("auido or chat_id fields missing")
type audioMsg struct {
chatID int64
title string
audio string
performer string
thumb string
duration int
yurl string
}
// 由于使用的api库不支持sendAudio的时候传thumb,这里重写了一个
func sendAudio(bot *tgbotapi.BotAPI, msg audioMsg) error {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// set file
if msg.audio != "" {
if err := addFileToWriter(writer, "audio", msg.audio); err != nil {
return err
}
} else {
return errAudio
}
if msg.thumb != "" {
if err := addFileToWriter(writer, "thumb", msg.thumb); err != nil {
return err
}
}
// set params
if msg.chatID != 0 {
if err := writer.WriteField("chat_id", fmt.Sprintf("%d", msg.chatID)); err != nil {
return err
}
} else {
return errAudio
}
if msg.title != "" {
if err := writer.WriteField("title", msg.title); err != nil {
return err
}
caption := fmt.Sprintf(`<a href="%s">🈲</a> %s`, msg.yurl, msg.title)
if err := writer.WriteField("caption", caption); err != nil {
return err
}
if err := writer.WriteField("parse_mode", tgbotapi.ModeHTML); err != nil {
return err
}
}
if msg.performer != "" {
if err := writer.WriteField("performer", msg.performer); err != nil {
return err
}
}
if msg.duration != 0 {
if err := writer.WriteField("duration", fmt.Sprintf("%d", msg.duration)); err != nil {
return err
}
}
if err := writer.Close(); err != nil {
return err
}
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendAudio", bot.Token)
req, err := http.NewRequest("POST", url, body)
if err != nil {
return err
}
req.Header.Add("Content-Type", writer.FormDataContentType())
resp, err := bot.Client.Do(req)
if err != nil {
return err
}
if resp.StatusCode == http.StatusInternalServerError {
return errHTTP
}
return nil
}
func addFileToWriter(writer *multipart.Writer, fieldName string, file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
part, err := writer.CreateFormFile(fieldName, filepath.Base(file))
if err != nil {
return err
}
_, err = io.Copy(part, f)
return err
}