forked from olhodedeus/Redlol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilities.lua
1270 lines (1119 loc) · 38.1 KB
/
utilities.lua
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local serpent = require 'serpent'
local config = require 'config'
local api = require 'methods'
local ltn12 = require 'ltn12'
local HTTPS = require 'ssl.https'
local HTTP = require'socket.http'
local JSON = require('dkjson')
-- utilities.lua
-- Functions shared among plugins.
local utilities = {}
-- Escape markdown for Telegram. This function makes non-clickable usernames,
-- hashtags, commands, links and emails, if only_markup flag isn't setted.
function string:escape(only_markup)
if not only_markup then
-- insert word joiner
self = self:gsub('([@#/.])(%w)', '%1\xE2\x81\xA0%2')
end
return self:gsub('[*_`[]', '\\%0')
end
function string:escape_html()
self = self:gsub('&', '&')
self = self:gsub('"', '"')
self = self:gsub('<', '<'):gsub('>', '>')
return self
end
function utilities.load_data(filename)
local f = io.open(filename)
if f then
local s = f:read('*all')
f:close()
return JSON.decode(s)
else
return {}
end
end
function utilities.save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Obtém coordenadas para um local. Usado por gMaps.lua, time.lua, weather.lua
function utilities.get_coords(input)
local url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' .. URL.escape(input)
local jstr, res = HTTP.request(url)
if res ~= 200 then
return config.errors.connection
end
local jdat = JSON.decode(jstr)
if jdat.status == 'ZERO_RESULTS' then
return config.errors.results
end
return {
lat = jdat.results[1].geometry.location.lat,
lon = jdat.results[1].geometry.location.lng
}
end
function utilities.spairs(t, order)
-- Recolhe as chaves
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- Se a função informar a ordem, classificar por ele passando a tabela e as chaves a, b,
-- caso contrário, apenas ordenar as chave
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- Retornar a função iterator
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
-- Remove specified formating or all markdown. This function useful for put
-- names into message. It seems not possible send arbitrary text via markdown.
function string:escape_hard(ft)
if ft == 'bold' then
return self:gsub('%*', '')
elseif ft == 'italic' then
return self:gsub('_', '')
elseif ft == 'fixed' then
return self:gsub('`', '')
elseif ft == 'link' then
return self:gsub(']', '')
else
return self:gsub('[*_`[%]]', '')
end
end
function utilities.is_allowed(action, chat_id, user_obj)
--[[ACTION
"hammer": hammering functions (/ban, /kick, /tempban, /warn, /nowarn, /status, /user)
"config": managing the group settings (read: /config command)
"texts": getting the basic informations of the group (/rules, /adminlis, /modlist, #extras)]]
if not user_obj.mod and not user_obj.admin then return end
if user_obj.admin then return true end
local status = db:hget('chat:'..chat_id..':modsettings', action) or config.chat_settings['modsettings'][action]
--true: requires admin
return status == 'yes'
end
function utilities.is_mod(chat_id, user_id)
if type(chat_id) == 'table' then
local msg = chat_id
if msg.from.admin then
return true
else
chat_id = msg.chat.id
user_id = msg.from.id
local set = 'chat:'..chat_id..':mods'
return db:sismember(set, user_id)
end
else
if utilities.is_admin(chat_id, user_id) then
return true
else
local set = 'chat:'..chat_id..':mods'
return db:sismember(set, user_id)
end
end
end
function utilities.is_superadmin(user_id)
for i=1, #config.superadmins do
if tonumber(user_id) == config.superadmins[i] then
return true
end
end
return false
end
function utilities.bot_is_admin(chat_id)
local status = api.getChatMember(chat_id, bot.id).result.status
if not(status == 'administrator') then
return false
else
return true
end
end
function utilities.is_admin_request(msg)
local res = api.getChatMember(msg.chat.id, msg.from.id)
if not res then
return false, false
end
local status = res.result.status
if status == 'creator' or status == 'administrator' then
return true, true
else
return false, true
end
end
-- Returns the admin status of the user. The first argument can be the message,
-- then the function checks the rights of the sender in the incoming chat.
function utilities.is_admin(chat_id, user_id)
if type(chat_id) == 'table' then
local msg = chat_id
chat_id = msg.chat.id
user_id = msg.from.id
end
local set = 'cache:chat:'..chat_id..':admins'
if not db:exists(set) then
utilities.cache_adminlist(chat_id, res)
end
return db:sismember(set, user_id)
end
function utilities.is_admin2(chat_id, user_id)
local res = api.getChatMember(chat_id, user_id)
if not res then
return false, false
end
local status = res.result.status
if status == 'creator' or status == 'administrator' then
return true, true
else
return false, true
end
end
function utilities.is_owner_request(msg)
local status = api.getChatMember(msg.chat.id, msg.from.id).result.status
if status == 'creator' then
return true
else
return false
end
end
function utilities.is_owner(chat_id, user_id)
if type(chat_id) == 'table' then
local msg = chat_id
chat_id = msg.chat.id
user_id = msg.from.id
end
local hash = 'cache:chat:'..chat_id..':owner'
local owner_id, res = nil, true
repeat
owner_id = db:get(hash)
if not owner_id then
res = utilities.cache_adminlist(chat_id)
end
until owner_id or not res
if owner_id then
if tonumber(owner_id) == tonumber(user_id) then
return true
end
end
return false
end
function utilities.is_owner2(chat_id, user_id)
local status = api.getChatMember(chat_id, user_id).result.status
if status == 'creator' then
return true
else
return false
end
end
function utilities.add_role(chat_id, user_obj)
user_obj.admin = utilities.is_admin(chat_id, user_obj.id)
user_obj.mod = utilities.is_mod(chat_id, user_obj.id)
return user_obj
end
function utilities.cache_adminlist(chat_id)
local res, code = api.getChatAdministrators(chat_id)
if not res then
return false, code
end
local set = 'cache:chat:'..chat_id..':admins'
for _, admin in pairs(res.result) do
if admin.status == 'creator' then
db:set('cache:chat:'..chat_id..':owner', admin.user.id)
end
db:sadd(set, admin.user.id)
utilities.demote(chat_id, admin.user.id)
end
db:expire(set, config.bot_settings.cache_time.adminlist)
return true, #res.result or 0
end
function utilities.get_cached_admins_list(chat_id, second_try)
local hash = 'cache:chat:'..chat_id..':admins'
local list = db:smembers(hash)
if not list or not next(list) then
utilities.cache_adminlist(chat_id)
if not second_try then
return utilities.get_cached_admins_list(chat_id, true)
else
return false
end
else
return list
end
end
function utilities.is_blocked_global(id)
if db:sismember('bot:blocked', id) then
return true
else
return false
end
end
function string:trim() -- Trims whitespace from a string.
local s = self:gsub('^%s*(.-)%s*$', '%1')
return s
end
function utilities.dump(...)
for _, value in pairs{...} do
print(serpent.block(value, {comment=false}))
end
end
function utilities.vtext(...)
local lines = {}
for _, value in pairs{...} do
table.insert(lines, serpent.block(value, {comment=false}))
end
return table.concat(lines, '\n')
end
function utilities.download_to_file(url, file_path)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
options.redirect = false
response = {HTTPS.request(options)}
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return false, code end
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path, code
end
function utilities.telegram_file_link(res)
--res = table returned by getFile()
return "https://api.telegram.org/file/bot"..config.api_token.."/"..res.result.file_path
end
function utilities.deeplink_constructor(chat_id, what)
return 'https://telegram.me/'..bot.username..'?start='..chat_id..'_'..what
end
function table.clone(t)
local new_t = {}
local i, v = next(t, nil)
while i do
new_t[i] = v
i, v = next(t, i)
end
return new_t
end
function utilities.get_date(timestamp)
if not timestamp then
timestamp = os.time()
end
return os.date('%d/%m/%y', timestamp)
end
-- Resolves username. Returns ID of user if it was early stored in date base.
-- Argument username must begin with symbol @ (commercial 'at')
function utilities.resolve_user(username)
assert(username:byte(1) == string.byte('@'))
local stored_id = tonumber(db:hget('bot:usernames', username:lower()))
if not stored_id then return false end
local user_obj = api.getChat(stored_id)
if not user_obj then
return stored_id
else
if not user_obj.result.username then return stored_id end
end
-- User could change his username
if username ~= '@' .. user_obj.result.username:lower() then
if user_obj.result.username then
-- Update it if it exists
db:hset('bot:usernames', user_obj.result.username:lower(), user_obj.result.id)
end
-- And return false because this user not the same that asked
return false
end
assert(stored_id == user_obj.result.id)
return user_obj.result.id
end
function utilities.get_sm_error_string(code)
local hyperlinks_text = _('More info [here](https://telegram.me/GB_tutorials/12)')
local descriptions = {
[109] = _("Inline link formatted incorrectly. Check the text between brackets -> \\[]()\n%s"):format(hyperlinks_text),
[141] = _("Inline link formatted incorrectly. Check the text between brackets -> \\[]()\n%s"):format(hyperlinks_text),
[142] = _("Inline link formatted incorrectly. Check the text between brackets -> \\[]()\n%s"):format(hyperlinks_text),
[112] = _("This text breaks the markdown.\n"
.. "More info about a proper use of markdown "
.. "[here](https://telegram.me/GB_tutorials/10) and [here](https://telegram.me/GB_tutorials/12)."),
[118] = _('This message is too long. Max lenght allowed by Telegram: 4000 characters'),
[146] = _('One of the URLs that should be placed in an inline button seems to be invalid (not an URL). Please check it'),
[137] = _("One of the inline buttons you are trying to set is missing the URL"),
[149] = _("One of the inline buttons you are trying to set doesn't have a name"),
[115] = _("Please input a text")
}
return descriptions[code] or _("Text not valid: unknown formatting error")
end
function string:escape_magic()
self = self:gsub('%%', '%%%%')
self = self:gsub('%-', '%%-')
self = self:gsub('%?', '%%?')
return self
end
function utilities.reply_markup_from_text(text)
local clean_text = text
local n = 0
local reply_markup = {inline_keyboard={}}
for label, url in text:gmatch("{{(.-)}{(.-)}}") do
clean_text = clean_text:gsub('{{'..label:escape_magic()..'}{'..url:escape_magic()..'}}', '')
if label and url and n < 3 then
local line = {{text = label, url = url}}
table.insert(reply_markup.inline_keyboard, line)
end
n = n + 1
end
if not next(reply_markup.inline_keyboard) then reply_markup = nil end
return reply_markup, clean_text
end
function utilities.demote(chat_id, user_id)
chat_id, user_id = tonumber(chat_id), tonumber(user_id)
db:del(('chat:%d:mod:%d'):format(chat_id, user_id))
local removed = db:srem('chat:'..chat_id..':mods', user_id)
return removed == 1
end
function utilities.get_media_type(msg)
if msg.photo then
return 'photo'
elseif msg.video then
return 'video'
elseif msg.audio then
return 'audio'
elseif msg.voice then
return 'voice'
elseif msg.document then
if msg.document.mime_type == 'video/mp4' then
return 'gif'
else
return 'document'
end
elseif msg.sticker then
return 'sticker'
elseif msg.contact then
return 'contact'
elseif msg.location then
return 'location'
elseif msg.game then
return 'game'
elseif msg.venue then
return 'venue'
else
return false
end
end
function utilities.get_media_id(msg)
if msg.photo then
return msg.photo[#msg.photo].file_id, 'photo'
elseif msg.document then
return msg.document.file_id
elseif msg.video then
return msg.video.file_id, 'video'
elseif msg.audio then
return msg.audio.file_id
elseif msg.voice then
return msg.voice.file_id, 'voice'
elseif msg.sticker then
return msg.sticker.file_id
else
return false, 'The message has not a media file_id'
end
end
function utilities.migrate_chat_info(old, new, on_request)
if not old or not new then
return false
end
for hash_name, hash_content in pairs(config.chat_settings) do
local old_t = db:hgetall('chat:'..old..':'..hash_name)
if next(old_t) then
for key, val in pairs(old_t) do
db:hset('chat:'..new..':'..hash_name, key, val)
end
end
end
for _, hash_name in pairs(config.chat_hashes) do
local old_t = db:hgetall('chat:'..old..':'..hash_name)
if next(old_t) then
for key, val in pairs(old_t) do
db:hset('chat:'..new..':'..hash_name, key, val)
end
end
end
for i=1, #config.chat_sets do
local old_t = db:smembers('chat:'..old..':'..config.chat_sets[i])
if next(old_t) then
db:sadd('chat:'..new..':'..config.chat_sets[i], table.unpack(old_t))
end
end
if on_request then
api.sendReply(msg, 'Should be done')
end
end
-- Perform substitution of placeholders in the text according given the message.
-- The second argument can be the flag to avoid the escape, if it's set, the
-- markdown escape isn't performed. In any case the following arguments are
-- considered as the sequence of strings - names of placeholders. If
-- placeholders to replacing are specified, this function processes only them,
-- otherwise it processes all available placeholders.
function string:replaceholders(msg, ...)
if msg.new_chat_member then
msg.from = msg.new_chat_member
elseif msg.left_chat_member then
msg.from = msg.left_chat_member
end
local tail_arguments = {...}
-- check that the second argument is a boolean and true
local non_escapable = tail_arguments[1] == true
local replace_map
if non_escapable then
replace_map = {
name = msg.from.first_name,
surname = msg.from.last_name and msg.from.last_name or '',
username = msg.from.username and '@'..msg.from.username or '-',
id = msg.from.id,
title = msg.chat.title,
rules = utilities.deeplink_constructor(msg.chat.id, 'rules'),
}
-- remove flag about escaping
table.remove(tail_arguments, 1)
else
replace_map = {
name = msg.from.first_name:escape(),
surname = msg.from.last_name and msg.from.last_name:escape() or '',
username = msg.from.username and '@'..msg.from.username:escape() or '-',
id = msg.from.id,
title = msg.chat.title:escape(),
rules = utilities.deeplink_constructor(msg.chat.id, 'rules'),
}
end
local substitutions = next(tail_arguments) and {} or replace_map
for _, placeholder in pairs(tail_arguments) do
substitutions[placeholder] = replace_map[placeholder]
end
return self:gsub('$(%w+)', substitutions)
end
function utilities.to_supergroup(msg)
local old = msg.chat.id
local new = msg.migrate_to_chat_id
local done = utilities.migrate_chat_info(old, new, false)
if done then
utilities.remGroup(old, true, 'to supergroup')
api.sendMessage(new, '(_service notification: migration of the group executed_)', true)
end
end
-- Return user mention for output a text
function utilities.getname_final(user)
return utilities.getname_link(user.first_name, user.username) or '<code>'..user.first_name:escape_html()..'</code>'
end
-- Return link to user profile or false, if he doesn't have login
function utilities.getname_link(name, username)
if not name or not username then return nil end
username = username:gsub('@', '')
return ('<a href="%s">%s</a>'):format('https://telegram.me/'..username, name:escape_html())
end
function utilities.bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
function utilities.telegram_file_link(res)
--res = table returned by getFile()
return "https://api.telegram.org/file/bot"..config.bot_api_key.."/"..res.result.file_path
end
function utilities.is_silentmode_on(chat_id)
local hash = 'chat:'..chat_id..':settings'
local res = db:hget(hash, 'Silent')
if res and res == 'on' then
return true
else
return false
end
end
function utilities.getRules(chat_id)
local hash = 'chat:'..chat_id..':info'
local rules = db:hget(hash, 'rules')
if not rules then
return _("-*empty*-")
else
return rules
end
end
function utilities.getAdminlist(chat_id)
local list, code = api.getChatAdministrators(chat_id)
if not list then
return false, code
end
local creator = ''
local adminlist = ''
local count = 1
for i,admin in pairs(list.result) do
local name
local s = ' ├ '
if admin.status == 'administrator' or admin.status == 'moderator' then
name = admin.user.first_name
if admin.user.username then
name = ('<a href="telegram.me/%s">%s</a>'):format(admin.user.username, name:escape_html())
else
name = name:escape_html()
end
if count + 1 == #list.result then s = ' └ ' end
adminlist = adminlist..s..name..'\n'
count = count + 1
elseif admin.status == 'creator' then
creator = admin.user.first_name
if admin.user.username then
creator = ('<a href="telegram.me/%s">%s</a>'):format(admin.user.username, creator:escape_html())
else
creator = creator:escape_html()
end
end
end
if adminlist == '' then adminlist = '-' end
if creator == '' then creator = '-' end
return _("<b>👤 Creator</b>\n└ %s\n\n<b>👥 Admins</b> (%d)\n%s"):format(creator, #list.result - 1, adminlist)
end
local function get_list_name(chat_id, user_id)
local user = db:hgetall(('chat:%d:mod:%d'):format(chat_id, tonumber(user_id)))
return utilities.getname_final(user) or 'x'
end
function utilities.getModlist(chat_id)
local mods = db:smembers('chat:'..chat_id..':mods')
local text
if not next(mods) then
return false, _("<i>Empty moderators list</i>")
else
local list_name
local modlist = {}
local s = ' ├ '
text = _("<b>👥 Moderators</b>\n")
for i=1, #mods do
list_name = get_list_name(chat_id, mods[i]) --mods[i] -> string
if i == #mods then s = ' └ ' end
table.insert(modlist, s..list_name)
end
text = text..table.concat(modlist, '\n')
return true, text
end
end
local function sort_funct(a, b)
print(a, b)
return a:gsub('#', '') < b:gsub('#', '') end
function utilities.getExtraList(chat_id)
local hash = 'chat:'..chat_id..':extra'
local commands = db:hkeys(hash)
if not next(commands) then
return _("No commands set")
else
local lines = {}
for i, k in ipairs(commands) do
table.insert(lines, (k:escape(true)))
end
return _("List of *custom commands*:\n") .. table.concat(lines, '\n')
end
end
-- alteração extrap
local function sort_funct(a, b)
print(a, b)
return a:gsub('/', '') < b:gsub('/', '') end
function utilities.getExtraList(chat_id)
local hash = 'chat:'..chat_id..':extrap'
local commands = db:hkeys(hash)
if not next(commands) then
return _("No commands set")
else
local lines = {}
for i, k in ipairs(commands) do
table.insert(lines, (k:escape(true)))
end
return _("List of *custom commands*:\n") .. table.concat(lines, '\n')
end
end
--fimalteração extrap
function utilities.getSettings(chat_id)
local hash = 'chat:'..chat_id..':settings'
local lang = db:get('lang:'..chat_id) or 'pt_BR' -- group language
local message = _("Current settings for *the group*:\n\n")
.. _("*Language*: %s\n"):format(config.available_languages[lang])
--build the message
local strings = {
Welcome = _("Welcome message"),
Goodbye = _("Goodbye message"),
Extra = _("Extra"),
Extrap = _("Extrap"),
Flood = _("Anti-flood"),
Antibot = _("Ban bots"),
Silent = _("Silent mode"),
Rules = _("Rules"),
Arab = _("Arab"),
Rtl = _("RTL"),
Reports = _("Reports"),
Welbut = _("Welcome button")
}
for key, default in pairs(config.chat_settings['settings']) do
local off_icon, on_icon = '🚫', '✅'
if utilities.is_info_message_key(key) then
off_icon, on_icon = '👤', '👥'
end
local db_val = db:hget(hash, key)
if not db_val then db_val = default end
if db_val == 'off' then
message = message .. string.format('%s: %s\n', strings[key], off_icon)
else
message = message .. string.format('%s: %s\n', strings[key], on_icon)
end
end
--build the char settings lines
hash = 'chat:'..chat_id..':char'
off_icon, on_icon = '🚫', '✅'
for key, default in pairs(config.chat_settings['char']) do
db_val = db:hget(hash, key)
if not db_val then db_val = default end
if db_val == 'off' then
message = message .. string.format('%s: %s\n', strings[key], off_icon)
else
message = message .. string.format('%s: %s\n', strings[key], on_icon)
end
end
--build the "welcome" line
hash = 'chat:'..chat_id..':welcome'
local type = db:hget(hash, 'type')
if type == 'media' then
message = message .. _("*Welcome type*: `GIF / sticker`\n")
elseif type == 'custom' then
message = message .. _("*Welcome type*: `custom message`\n")
elseif type == 'no' then
message = message .. _("*Welcome type*: `default message`\n")
end
local warnmax_std = (db:hget('chat:'..chat_id..':warnsettings', 'max')) or config.chat_settings['warnsettings']['max']
local warnmax_media = (db:hget('chat:'..chat_id..':warnsettings', 'mediamax')) or config.chat_settings['warnsettings']['mediamax']
return message .. _("Warns (`standard`): *%s*\n"):format(warnmax_std)
.. _("Warns (`media`): *%s*\n\n"):format(warnmax_media)
.. _("✅ = _enabled / allowed_\n")
.. _("🚫 = _disabled / not allowed_\n")
.. _("👥 = _sent in group (always for admins)_\n")
.. _("👤 = _sent in private_")
end
function utilities.changeSettingStatus(chat_id, field)
local turned_off = {
reports = _("@admin command disabled"),
welcome = _("Welcome message won't be displayed from now"),
goodbye = _("Goodbye message won't be displayed from now"),
extra = _("#extra commands are now available only for moderator"),
extrap = _("#extra commands are now available only for moderator"),
flood = _("Anti-flood is now off"),
rules = _("/rules will reply in private (for users)"),
silent = _("Silent mode is now off"),
preview = _("Links preview disabled"),
welbut = _("Welcome message without a button for the rules")
}
local turned_on = {
reports = _("@admin command enabled"),
welcome = _("Welcome message will be displayed"),
goodbye = _("Goodbye message will be displayed"),
extra = _("#extra commands are now available for all"),
extrap = _("#extra commands are now available for all"),
flood = _("Anti-flood is now on"),
rules = _("/rules will reply in the group (with everyone)"),
silent = _("Silent mode is now on"),
preview = _("Links preview enabled"),
welbut = _("The welcome message will have a button for the rules")
}
local hash = 'chat:'..chat_id..':settings'
local now = db:hget(hash, field)
if now == 'on' then
db:hset(hash, field, 'off')
return turned_off[field:lower()]
else
db:hset(hash, field, 'on')
if field:lower() == 'goodbye' then
local r = api.getChatMembersCount(chat_id)
if r and r.result > 50 then
return _("This setting is enabled, but the goodbye message won't be displayed in large groups, "
.. "because I can't see service messages about left members"), true
end
end
return turned_on[field:lower()]
end
end
function utilities.changeMediaStatus(chat_id, media, new_status)
local old_status = db:hget('chat:'..chat_id..':media', media)
local new_status_icon
if new_status == 'next' then
if not old_status then
new_status = 'ok'
new_status_icon = '✅'
elseif old_status == 'ok' then
new_status = 'notok'
new_status_icon = '❌'
elseif old_status == 'notok' then
new_status = 'ok'
new_status_icon = '✅'
end
end
db:hset('chat:'..chat_id..':media', media, new_status)
return _("New status = %s"):format(new_status_icon), true
end
function utilities.sendStartMe(msg)
local keyboard = {inline_keyboard = {{{text = _("Start me"), url = 'https://telegram.me/'..bot.username}}}}
api.sendMessage(msg.chat.id, _("_Please message me first so I can message you_"), true, keyboard)
end
function utilities.initGroup(chat_id)
for set, setting in pairs(config.chat_settings) do
local hash = 'chat:'..chat_id..':'..set
for field, value in pairs(setting) do
db:hset(hash, field, value)
end
end
utilities.cache_adminlist(chat_id, api.getChatAdministrators(chat_id)) --init admin cache
--save group id
db:sadd('bot:groupsid', chat_id)
--remove the group id from the list of dead groups
db:srem('bot:groupsid:removed', chat_id)
end
local function remRealm(chat_id)
if db:exists('realm:'..chat_id..':subgroups') then
local subgroups = db:hgetall('realm:'..chat_id..':subgroups')
if next(subgroups) then
for subgroup_id, _ in pairs(subgroups) do
db:del('chat:'..subgroup_id..':realm')
end
end
db:del('realm:'..chat_id..':subgroups')
return true
end
db:srem('bot:realms', chat_id)
end
local function empty_modlist(chat_id)
local set = 'chat:'..chat_id..':mods'
local mods = db:smembers(set)
if next(mods) then
local hash = ('chat:%d:mod:%d'):format(tonumber(chat_id), tonumber(mods[i]))
for i=1, #mods do
db:del(hash)
end
end
db:del(set)
end
function utilities.remGroup(chat_id, full, converted_to_realm)
if not converted_to_realm then
--remove group id
db:srem('bot:groupsid', chat_id)
--add to the removed groups list
db:sadd('bot:groupsid:removed', chat_id)
--remove the owner cached
db:del('cache:chat:'..chat_id..':owner')
--remove the realm data: the group is not being converted to realm -> remove all the info
remRealm(chat_id)
end
for set,field in pairs(config.chat_settings) do
db:del('chat:'..chat_id..':'..set)
end
db:del('cache:chat:'..chat_id..':admins') --delete the cache
db:hdel('bot:logchats', chat_id) --delete the associated log chat
db:del('chat:'..chat_id..':pin') --delete the msg id of the (maybe) pinned message
db:del('chat:'..chat_id..':userlast')
db:hdel('bot:chats:latsmsg', chat_id)
db:hdel('bot:chatlogs', chat_id) --log channel
--if chat_id has a realm
if db:exists('chat:'..chat_id..':realm') then
local realm_id = db:get('chat:'..chat_id..':realm') --get the realm id
db:hdel('realm:'..realm_id..':subgroups', chat_id) --remove the group from the realm subgroups
db:del('chat:'..chat_id..':realm') --remove the key with the group realm
end
if full or converted_to_realm then
for i=1, #config.chat_hashes do
db:del('chat:'..chat_id..':'..config.chat_hashes[i])
end
for i=1, #config.chat_sets do
db:del('chat:'..chat_id..':'..config.chat_sets[i])
end
if db:exists('chat:'..chat_id..':mods') then
empty_modlist(chat_id)
end
db:del('lang:'..chat_id)
end
end
function utilities.getnames_complete(msg, blocks)
local admin, kicked
admin = utilities.getname_link(msg.from.first_name, msg.from.username) or ("<code>%s</code>"):format(msg.from.first_name:escape_html())
if msg.reply then
kicked = utilities.getname_link(msg.reply.from.first_name, msg.reply.from.username) or ("<code>%s</code>"):format(msg.reply.from.first_name:escape_html())
elseif msg.text:match(config.cmd..'%w%w%w%w?%w?%s(@[%w_]+)%s?') then
local username = msg.text:match('%s(@[%w_]+)')
kicked = username
elseif msg.mention_id then
for _, entity in pairs(msg.entities) do
if entity.user then
kicked = '<code>'..entity.user.first_name:escape_html()..'</code>'
end
end
elseif msg.text:match(config.cmd..'%w%w%w%w?%w?%s(%d+)') then
local id = msg.text:match(config.cmd..'%w%w%w%w?%w?%s(%d+)')
kicked = '<code>'..id..'</code>'
end
return admin, kicked
end
function utilities.get_user_id(msg, blocks)
--if no user id: returns false and the msg id of the translation for the problem
if not msg.reply and not blocks[2] then
return false, _("Reply to someone")
else
if msg.reply then
if msg.reply.new_chat_member then
msg.reply.from = msg.reply.new_chat_member
end
return msg.reply.from.id
elseif msg.text:match(config.cmd..'%w%w%w%w?%w?%w?%s(@[%w_]+)%s?') then
local username = msg.text:match('%s(@[%w_]+)')
local id = utilities.resolve_user(username)