forked from fiatjaf/lntxbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
508 lines (466 loc) · 13.8 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
package main
import (
"context"
"encoding/json"
"errors"
"net/url"
"strconv"
"strings"
"unicode/utf8"
"github.com/bwmarrin/discordgo"
"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
)
log := log.With().Interface("origin", ctx.Value("origin")).Logger()
// defaults from ctx
var origin string
if iorigin := ctx.Value("origin"); iorigin != nil {
origin, _ = iorigin.(string)
}
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
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)
origin = "telegram"
}
// only discord
var linkTo DiscordMessageID
var discordMessage *discordgo.Message
var emojiReaction string
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:
if utf8.RuneCountInString(text) == 1 {
emojiReaction = thing
origin = "discord"
} else {
text = thing
}
case *tgbotapi.CallbackQuery:
callbackQuery = thing
origin = "telegram"
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 DiscordMessageID:
linkTo = thing
origin = "discord"
case int:
replyToId = thing
case *tgbotapi.Message:
telegramMessage = thing
origin = "telegram"
case *discordgo.Message:
discordMessage = thing
origin = "discord"
case *TelegramCopyMessage:
copyMessage = thing
origin = "telegram"
case TelegramCopyMessage:
copyMessage = &thing
origin = "telegram"
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()
// get origin from user if not present
if origin == "" && target != nil {
if origin == "telegram" &&
target.TelegramChatId == 0 && target.DiscordChannelId != "" {
origin = "discord"
} else if origin == "discord" &&
target.DiscordChannelId == "" && target.TelegramChatId != 0 {
origin = "telegram"
}
}
// build text with params
if text == "" && template != "" {
// fallback locale to user or group
if locale == "" && group != nil {
locale = group.Locale
}
if locale == "" && 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
var groupId = chatId // may be zero if not given
if group != nil {
groupId = group.TelegramId
}
var useGroup = (spammy && !hasExplicitTarget && groupId != 0) ||
(forceSpammy && groupId != 0) ||
(groupId != 0 && target == nil)
// origin can be "api", "background", "external"
if origin != "telegram" && origin != "discord" {
// here we try to determine where to notify the user
// this is only used when he is not interacting with the bot directly
if useGroup {
origin = "telegram"
// TODO discord group
} else if target.TelegramChatId != 0 {
origin = "telegram"
} else if target.DiscordChannelId != "" {
origin = "discord"
} else {
log.Error().Msg("can't send message, user has no chat ids")
return nil
}
}
// build the message to send
switch origin {
case "telegram":
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
}
case "discord":
var reference = linkTo
if reference == "" && discordMessage != nil {
reference = discordIDFromMessage(discordMessage)
}
if emojiReaction != "" {
// we're sending an emoji reaction
if reference == "" {
log.Error().Msg("trying to send a reaction without a reference")
return
}
// send emoji
err := discord.MessageReactionAdd(
reference.Channel(), reference.Message(), emojiReaction)
if err != nil {
log.Warn().Err(err).Str("emoji", text).
Msg("failed to react with emoji")
return
}
return linkTo
} else if documentURL != "" {
// for documentURLs we behave differently as embeds won't work
// TODO
} else {
// we're sending a message or edit
text = convertToDiscord(text)
if linkTo != "" {
text += "\n" + linkTo.URL()
}
// build the embed object to send
// TODO use simple messages if there just one line of text?
embed := &discordgo.MessageEmbed{
Description: text,
}
if pictureURL != "" {
embed.Image = &discordgo.MessageEmbedImage{URL: pictureURL}
}
if commandName := ctx.Value("command"); commandName != nil {
embed.Title = commandName.(string)
}
if edit && reference != "" {
// editing
if justAppend {
if discordMessage != nil {
text = discordMessage.Embeds[0].Description + " " + text
} else {
log.Error().Msg("can't append to a message with only its id")
return
}
}
// send edit
message, err := discord.ChannelMessageEditEmbed(
linkTo.Channel(), linkTo.Message(), embed)
if err != nil {
log.Warn().Err(err).Msg("failed to send discord message")
}
return discordIDFromMessage(message)
} else {
var channelId string
if group != nil {
spamChannelId, _ := getGuildMetadata(group.DiscordGuildId)
message := ctx.Value("message").(*discordgo.Message)
if spammy {
// send to the same channel it came from
channelId = message.ChannelID
} else if (message.ChannelID == spamChannelId) ||
(target.DiscordChannelId == "" && spamChannelId != "") {
// send to the #commands or #lntxbot
channelId = spamChannelId
} else {
// send to user privately
channelId = target.DiscordChannelId
}
} else {
// send to user privately
channelId = target.DiscordChannelId
}
// send message
message, err := discord.ChannelMessageSendEmbed(channelId, embed)
if err != nil {
log.Warn().Err(err).Msg("failed to send discord message")
return
}
return discordIDFromMessage(message)
}
}
}
return nil
}
func removeKeyboardButtons(ctx context.Context) {
send(ctx, EDIT, &tgbotapi.InlineKeyboardMarkup{
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{},
})
}