-
Notifications
You must be signed in to change notification settings - Fork 26
/
message.go
357 lines (327 loc) · 9.63 KB
/
message.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package main
import (
"context"
"encoding/json"
"errors"
"net/url"
"strconv"
"strings"
"github.com/fiatjaf/lntxbot/t"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
type MessageModifier string
const (
EDIT MessageModifier = "EDIT"
APPEND MessageModifier = "APPEND"
WITHALERT MessageModifier = "WITHALERT"
FORCESPAMMY MessageModifier = "FORCESPAMMY"
)
type TelegramCopyMessage struct {
ChatID int64
MessageID int
}
func send(ctx context.Context, things ...interface{}) (id interface{}) {
var (
edit bool
text string
template t.Key
pictureURL string
justAppend bool
documentURL string
templateData t.T
)
// defaults from ctx
var target *User
if itarget := ctx.Value("initiator"); itarget != nil {
if ftarget, ok := itarget.(*User); ok {
target = ftarget
}
}
var group *GroupChat
if igroup := ctx.Value("group"); igroup != nil {
if fgroup, ok := igroup.(GroupChat); ok {
group = &fgroup
}
}
var forceSpammy bool
var hasExplicitTarget bool
var spammy bool = true
if ispammy := ctx.Value("spammy"); ispammy != nil {
spammy = ispammy.(bool)
}
var locale string
if ilocale := ctx.Value("locale"); ilocale != nil {
locale = ilocale.(string)
}
// only telegram
var (
alert bool
chatId int64
keyboard *tgbotapi.InlineKeyboardMarkup
replyToId int // will be sent in reply to this -- or if editing will edit this
forceReply *tgbotapi.ForceReply
copyMessage *TelegramCopyMessage
callbackQuery *tgbotapi.CallbackQuery
telegramMessage *tgbotapi.Message // unless this is provided, this has precedence in edition priotiry
mustSendAnActualMessage bool
)
if icb := ctx.Value("callbackQuery"); icb != nil {
callbackQuery = icb.(*tgbotapi.CallbackQuery)
}
for _, ithing := range things {
switch thing := ithing.(type) {
case *User:
target = thing
mustSendAnActualMessage = true
hasExplicitTarget = true
case User:
target = &thing
mustSendAnActualMessage = true
hasExplicitTarget = true
case *GroupChat:
group = thing
mustSendAnActualMessage = true
case GroupChat:
group = &thing
mustSendAnActualMessage = true
case int64:
chatId = thing
mustSendAnActualMessage = true
case t.Key:
template = thing
case t.T:
templateData = thing
case string:
text = thing
case *tgbotapi.CallbackQuery:
callbackQuery = thing
case *url.URL:
spl := strings.Split(thing.Path, ".")
ext := spl[len(spl)-1]
if strings.HasPrefix(thing.Path, "/qr/") ||
ext == "png" || ext == "jpg" || ext == "jpeg" {
pictureURL = thing.String()
} else {
documentURL = thing.String()
}
case *tgbotapi.InlineKeyboardMarkup:
keyboard = thing
// if telegram, this will be ignored
case *tgbotapi.ForceReply:
forceReply = thing
// if not telegram, this will be ignored
case int:
replyToId = thing
case tgbotapi.Message:
telegramMessage = &thing
case *tgbotapi.Message:
telegramMessage = thing
case *TelegramCopyMessage:
copyMessage = thing
case TelegramCopyMessage:
copyMessage = &thing
case MessageModifier:
switch thing {
case WITHALERT:
alert = true
case FORCESPAMMY:
spammy = true
forceSpammy = true
case EDIT:
edit = true
case APPEND:
edit = true
justAppend = true
}
case nil:
// ignore
default:
log.Debug().Interface("param", ithing).Msg("unrecognized param on send()")
}
}
log := log.With().Str("key", string(template)).Stringer("user", target).
Bool("alert", alert).Bool("spammy", spammy).Bool("edit", edit).
Bool("append", justAppend).Bool("keyboard", keyboard != nil).
Bool("cb", callbackQuery != nil).Stringer("group", group).
Logger()
// build text with params
if text == "" && template != "" {
// fallback locale to user
if target != nil {
locale = target.Locale
}
ctx = context.WithValue(ctx, "locale", locale)
text = translateTemplate(ctx, template, templateData)
text = strings.TrimSpace(text)
}
// either a user or a group must be a target (or there should be a callback)
if target == nil && group == nil && callbackQuery == nil {
log.Error().Msg("no target user or group for message")
return nil
}
// determine if we're going to send to the group or in private
groupId := chatId // may be zero if not given
if group != nil {
groupId = group.TelegramId
}
useGroup := (spammy && !hasExplicitTarget && groupId != 0) ||
(forceSpammy && groupId != 0) ||
(groupId != 0 && target == nil)
// use group locale then
if useGroup && locale == "" && group != nil {
locale = group.Locale
}
// build the message to send
if callbackQuery != nil && !edit && !mustSendAnActualMessage {
// it's a reply to a callbackQuery
bot.AnswerCallbackQuery(tgbotapi.CallbackConfig{
CallbackQueryID: callbackQuery.ID,
Text: text,
ShowAlert: alert,
})
return nil
} else {
// it's a message (or a call to edit a message)
values := url.Values{
"parse_mode": {"HTML"},
"disable_web_page_preview": {"true"},
}
if keyboard != nil {
jkeyboard, _ := json.Marshal(keyboard)
values.Set("reply_markup", string(jkeyboard))
} else if forceReply != nil {
jforceReply, _ := json.Marshal(forceReply)
values.Set("reply_markup", string(jforceReply))
}
if useGroup {
// send to group instead of the the user
values.Set("chat_id", strconv.FormatInt(groupId, 10))
} else {
// send to user
values.Set("chat_id", strconv.FormatInt(target.TelegramChatId, 10))
}
// editing
canEdit := (telegramMessage != nil) || (replyToId != 0) ||
(callbackQuery != nil && callbackQuery.InlineMessageID != "") ||
(callbackQuery != nil && callbackQuery.Message.MessageID != 0)
var method string
if edit && canEdit {
if callbackQuery != nil {
if callbackQuery.Message != nil {
values.Set("chat_id", strconv.FormatInt(
callbackQuery.Message.Chat.ID, 10))
values.Set("message_id", strconv.Itoa(
callbackQuery.Message.MessageID))
if justAppend || text == "" {
if messageHasCaption(callbackQuery.Message) {
text = callbackQuery.Message.Caption + " " + text
method = "editMessageCaption"
values.Set("caption", text)
} else {
text = callbackQuery.Message.Text + " " + text
method = "editMessageText"
values.Set("text", text)
}
} else if messageHasCaption(callbackQuery.Message) {
method = "editMessageCaption"
values.Set("caption", text)
} else if text == "" && values.Get("reply_markup") != "" {
method = "editMessageReplyMarkup"
}
} else if callbackQuery.InlineMessageID != "" {
values.Del("chat_id")
values.Set("inline_message_id", callbackQuery.InlineMessageID)
if callbackQuery.Message != nil && justAppend {
text = callbackQuery.Message.Text + " " + text
}
if text == "" && values.Get("reply_markup") != "" {
method = "editMessageReplyMarkup"
}
}
} else if telegramMessage != nil {
values.Set("chat_id", strconv.FormatInt(
telegramMessage.Chat.ID, 10))
values.Set("message_id", strconv.Itoa(telegramMessage.MessageID))
if justAppend || text == "" {
if messageHasCaption(telegramMessage) {
text = telegramMessage.Caption + " " + text
method = "editMessageCaption"
values.Set("caption", text)
} else {
text = telegramMessage.Text + " " + text
method = "editMessageText"
values.Set("text", text)
}
} else if messageHasCaption(telegramMessage) {
method = "editMessageCaption"
values.Set("caption", text)
} else if text == "" && values.Get("reply_markup") != "" {
method = "editMessageReplyMarkup"
}
} else if replyToId != 0 {
values.Set("message_id", strconv.Itoa(replyToId))
if justAppend {
log.Error().Msg("can't append to a message with only its id")
return
}
}
if method == "" {
method = "editMessageText"
values.Set("text", text)
}
} else {
// not editing, can add pictures and reply_to targets
if replyToId != 0 {
values.Set("reply_to_message_id", strconv.Itoa(replyToId))
} else if telegramMessage != nil {
values.Set("reply_to_message_id", strconv.Itoa(
telegramMessage.MessageID))
}
if copyMessage != nil {
method = "copyMessage"
values.Set("from_chat_id", strconv.FormatInt(
copyMessage.ChatID, 10))
values.Set("message_id", strconv.Itoa(copyMessage.MessageID))
} else if pictureURL == "" && documentURL == "" {
method = "sendMessage"
values.Set("text", text)
} else if pictureURL != "" {
values.Set("photo", pictureURL)
values.Set("caption", text)
method = "sendPhoto"
} else if documentURL != "" {
method = "sendDocument"
values.Set("document", documentURL)
values.Set("caption", text)
}
}
log = log.With().Str("method", method).Str("chat_id", values.Get("chat_id")).
Bool("using-group", useGroup).
Logger()
// send message
resp, err := bot.MakeRequest(method, values)
if err == nil && !resp.Ok {
err = errors.New(resp.Description)
}
if err != nil {
if err.Error() == "Bad Request: replied message not found" {
values.Del("reply_to_message_id")
resp, err = bot.MakeRequest(method, values)
}
if err != nil {
log.Warn().Err(err).Msg("error sending message to telegram")
return
}
}
// extract resulting message id to return
var c tgbotapi.Message
json.Unmarshal(resp.Result, &c)
return c.MessageID
}
return nil
}
func removeKeyboardButtons(ctx context.Context) {
send(ctx, EDIT, &tgbotapi.InlineKeyboardMarkup{
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{},
})
}