-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.go
112 lines (100 loc) · 2.5 KB
/
telegram.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
111
112
package telegram // import "github.com/robertgzr/joe-telegram-adapter"
import (
"fmt"
"strconv"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
func parseChatID(channel string) (int64, error) {
chatID, err := strconv.ParseInt(channel, 10, 64)
if err != nil {
return -1, fmt.Errorf("failed to parse chat id: %v", err)
}
return chatID, nil
}
func formatChatID(chatID int64) string {
return strconv.FormatInt(chatID, 10)
}
func (a *TelegramAdapter) SendPhoto(channel string, photo interface{}, caption string) error {
chatID, err := parseChatID(channel)
if err != nil {
return err
}
var cfg tgbotapi.PhotoConfig
fileID, ok := photo.(string)
if ok {
cfg = tgbotapi.NewPhotoShare(chatID, fileID)
} else {
cfg = tgbotapi.NewPhotoUpload(chatID, photo)
}
if caption != "" {
cfg.Caption = caption
}
_, err = a.BotAPI.Send(cfg)
return err
}
func (a *TelegramAdapter) SendGIF(channel string, gif interface{}, caption string) error {
chatID, err := parseChatID(channel)
if err != nil {
return err
}
var cfg tgbotapi.AnimationConfig
fileID, ok := gif.(string)
if ok {
cfg = tgbotapi.NewAnimationShare(chatID, fileID)
} else {
cfg = tgbotapi.NewAnimationUpload(chatID, gif)
}
if caption != "" {
cfg.Caption = caption
}
_, err = a.BotAPI.Send(cfg)
return err
}
func (a *TelegramAdapter) SendSticker(channel string, sticker interface{}) error {
chatID, err := parseChatID(channel)
if err != nil {
return err
}
var cfg tgbotapi.StickerConfig
fileID, ok := sticker.(string)
if ok {
cfg = tgbotapi.NewStickerShare(chatID, fileID)
} else {
cfg = tgbotapi.NewStickerUpload(chatID, sticker)
}
_, err = a.BotAPI.Send(cfg)
return err
}
type (
Callback = func(channel string) error
Button struct {
id string
label string
cb Callback
}
)
func (a *TelegramAdapter) NewButton(label string, cb Callback) Button {
return Button{
id: "_button_" + strings.ToLower(label),
label: label,
cb: cb,
}
}
func (a *TelegramAdapter) SendButtons(channel, text string, buttons ...Button) error {
chatID, err := parseChatID(channel)
if err != nil {
return err
}
var buttonRow []tgbotapi.InlineKeyboardButton
for _, button := range buttons {
a.callbacks[button.id] = button.cb
buttonRow = append(buttonRow,
tgbotapi.NewInlineKeyboardButtonData(button.label, button.id))
}
msg := tgbotapi.NewMessage(chatID, text)
msg.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(buttonRow...))
_, err = a.BotAPI.Send(msg)
return err
}