-
Notifications
You must be signed in to change notification settings - Fork 25
/
group.go
334 lines (282 loc) · 7.88 KB
/
group.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/fiatjaf/lntxbot/t"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
cmap "github.com/orcaman/concurrent-map"
)
// special telegram user ids
const (
CHANNEL_GROUP_POSTER = 10736
CHANNEL_RECEIVER = 777000
GROUP_ANONYMOUS_BOT = 1087968824
)
type KickData struct {
Kind string `json:"kind"`
InvoiceMessage *tgbotapi.Message `json:"invoice_message"`
NotifyMessage *tgbotapi.Message `json:"notify_message"`
JoinMessage *tgbotapi.Message `json:"join_message"`
ChatMemberConfig tgbotapi.ChatMemberConfig `json:"chat_member_config"`
ChatOwner *User `json:"owner"`
TargetId int `json:"new_member_id"`
TargetUsername string `json:"new_member_username"`
Hash string `json:"hash"`
Sats int `json:"sats"`
}
func isChannelOrGroupUser(user *tgbotapi.User) bool {
if user == nil {
return true
}
switch user.ID {
case CHANNEL_RECEIVER, CHANNEL_GROUP_POSTER, GROUP_ANONYMOUS_BOT:
return true
}
return false
}
func interceptMessage(message *tgbotapi.Message) (proceed bool) {
ctx := context.Background()
// check if ticket payments is pending
joinKey := fmt.Sprintf("%d:%d", message.From.ID, message.Chat.ID)
if _, isPending := pendingApproval.Get(joinKey); isPending {
log.Debug().Str("user", message.From.String()).Msg("user pending, can't speak")
return false
}
// check expensiveness
if sats := isExpensive(message.Chat.ID, message.Text); sats != 0 {
// take money out of the poor guy who sent the message
u, err := loadTelegramUser(message.From.ID)
if err != nil {
return false
}
if !u.checkBalanceFor(ctx, int64(sats)*1000, "expensive chat") {
return false
}
owner, err := getChatOwner(message.Chat.ID)
if err != nil {
return true
}
if owner.Id == u.Id {
return true
}
link := fmt.Sprintf("https://t.me/c/%s/%d",
strconv.FormatInt(message.Chat.ID, 10)[4:], message.MessageID)
err = u.sendInternally(ctx, owner, false, int64(sats)*1000, 0,
fmt.Sprintf("Expensive %s.", link), "", "expensive")
if err == nil {
send(ctx, u, t.EXPENSIVENOTIFICATION, t.T{
"Link": link,
"Price": sats,
"Sender": true,
})
send(ctx, owner, t.EXPENSIVENOTIFICATION, t.T{
"Link": link,
"Price": sats,
"Sender": false,
})
return true
}
return false
}
return true
}
/*
ALL GROUP CHAT TELEGRAM IDS ARE NEGATIVE
*/
type GroupChat struct {
TelegramId int64 `db:"telegram_id"`
Locale string `db:"locale"`
Spammy bool `db:"spammy"`
Ticket int `db:"ticket"`
}
const GROUPCHATFIELDS = "coalesce(telegram_id, 0) AS telegram_id, locale, spammy, ticket"
func (g *GroupChat) String() string {
if g == nil {
return "null"
}
if g.TelegramId != 0 {
return fmt.Sprintf("tg:%d", g.TelegramId)
}
return "unknown"
}
func ensureTelegramGroup(telegramId int64, locale string) (g GroupChat, err error) {
err = pg.Get(&g, `
INSERT INTO groupchat AS g (telegram_id, locale)
VALUES (
$1,
CASE WHEN $2 != '' THEN $2 ELSE 'en' END
)
ON CONFLICT (telegram_id)
DO UPDATE
SET locale = CASE WHEN $2 != '' THEN $2 ELSE g.locale END
RETURNING `+GROUPCHATFIELDS+`
`, telegramId, locale)
return
}
func loadTelegramGroup(telegramId int64) (g GroupChat, err error) {
err = pg.Get(&g,
"SELECT "+GROUPCHATFIELDS+" FROM groupchat WHERE telegram_id = $1", telegramId)
return
}
var spammy_cache = cmap.New()
func (g GroupChat) toggleSpammy() (spammy bool, err error) {
err = pg.Get(&spammy, `
UPDATE groupchat AS g SET spammy = NOT g.spammy
WHERE telegram_id = $1
RETURNING spammy
`, g.TelegramId)
spammy_cache.Set(strconv.FormatInt(g.TelegramId, 10), spammy)
return
}
func (g GroupChat) toggleCoinflips() (enabled bool, err error) {
err = pg.Get(&enabled, `
UPDATE groupchat AS g SET coinflips = NOT g.coinflips
WHERE telegram_id = $1
RETURNING coinflips
`, g.TelegramId)
return
}
func (g GroupChat) areCoinflipsEnabled() (enabled bool) {
err := pg.Get(&enabled,
"SELECT coinflips FROM groupchat WHERE telegram_id = $1", g.TelegramId)
if err != nil {
return true
}
return
}
func (g GroupChat) setTicketPrice(sat int) (err error) {
_, err = pg.Exec(`
UPDATE groupchat SET ticket = $2
WHERE telegram_id = $1
`, g.TelegramId, sat)
return
}
type expensiveness struct {
Price int `db:"expensive_price"`
Pattern string `db:"expensive_pattern"`
patternRegex *regexp.Regexp
}
var expensive_cache = cmap.New()
func (g GroupChat) setExpensive(sat int, pattern string) (err error) {
_, err = pg.Exec(`
UPDATE groupchat SET expensive_price = $2, expensive_pattern = $3
WHERE telegram_id = $1
`, g.TelegramId, sat, pattern)
if err != nil {
return err
}
regex, _ := regexp.Compile(pattern)
expensive_cache.Set(strconv.FormatInt(g.TelegramId, 10), expensiveness{
sat, pattern, regex,
})
return
}
func isExpensive(groupTelegramId int64, text string) (price int) {
var expensive expensiveness
if iexpensive, ok := expensive_cache.Get(strconv.FormatInt(groupTelegramId, 10)); ok {
expensive = iexpensive.(expensiveness)
} else {
pg.Get(&expensive, `
SELECT expensive_price, expensive_pattern
FROM groupchat
WHERE telegram_id = $1
`, groupTelegramId)
regex, _ := regexp.Compile(expensive.Pattern)
expensive.patternRegex = regex
expensive_cache.Set(strconv.FormatInt(groupTelegramId, 10), expensive)
}
if expensive.Price == 0 {
return 0
}
if expensive.patternRegex.MatchString(strings.ToLower(text)) {
return expensive.Price
}
return 0
}
func (g GroupChat) setRenamePrice(sat int) (err error) {
_, err = pg.Exec(`
UPDATE groupchat SET renamable = $2
WHERE telegram_id = $1
`, g.TelegramId, sat)
return
}
func (g GroupChat) getRenamePrice() (sat int) {
pg.Get(&sat,
"SELECT renamable FROM groupchat WHERE telegram_id = $1",
g.TelegramId)
return
}
func (g GroupChat) isSpammy() (spammy bool) {
if spammy, ok := spammy_cache.Get(strconv.FormatInt(g.TelegramId, 10)); ok {
return spammy.(bool)
}
err := pg.Get(&spammy,
"SELECT spammy FROM groupchat WHERE telegram_id = $1", g.TelegramId)
if err != nil {
return false
}
spammy_cache.Set(strconv.FormatInt(g.TelegramId, 10), spammy)
return
}
func setLanguage(chatId int64, lang string) (err error) {
if _, languageAvailable := bundle.Translations[lang]; !languageAvailable {
return errors.New("language not available.")
}
table := "account"
field := "telegram_chat_id"
id := chatId
taint := ", manual_locale = true"
if chatId < 0 {
table = "groupchat"
field = "telegram_id"
taint = ""
}
_, err = pg.Exec("UPDATE "+table+" SET locale = $2"+taint+" WHERE "+field+" = $1", id, lang)
return
}
func startKicking() {
data, err := rds.HGetAll("ticket-pending").Result()
if err != nil {
log.Warn().Err(err).Msg("error getting tickets pending")
return
}
ctx := context.WithValue(context.Background(), "origin", "background")
for joinKey, kickdatastr := range data {
var kickdata KickData
err := json.Unmarshal([]byte(kickdatastr), &kickdata)
if err != nil {
log.Warn().Err(err).Msg("failed to unmarshal kickdata from redis")
continue
}
log.Debug().Msg("restarted kick invoice wait")
pendingApproval.Set(joinKey, kickdata)
go waitToKick(ctx, joinKey, kickdata)
}
}
func waitToKick(ctx context.Context, key string, kickdata KickData) {
log.Debug().Str("key", key).Msg("waiting to kick")
select {
case <-waitInvoice(kickdata.Hash):
switch kickdata.Kind {
case "ticket":
ticketPaid(ctx, key, kickdata)
case "fine":
finePaid(ctx, key, kickdata)
}
case <-time.After(15 * time.Minute):
switch kickdata.Kind {
case "ticket":
ticketNotPaid(ctx, key, kickdata)
case "fine":
fineNotPaid(ctx, key, kickdata)
}
case <-waitGeneric(key):
// just to stop this waiter
}
}