-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathmattata.lua
1425 lines (1372 loc) · 64.1 KB
/
mattata.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
--[[
_ _ _
_ __ ___ __ _| |_| |_ __ _| |_ __ _
| '_ ` _ \ / _` | __| __/ _` | __/ _` |
| | | | | | (_| | |_| || (_| | || (_| |
|_| |_| |_|\__,_|\__|\__\__,_|\__\__,_|
v1.5
Copyright 2020 Matthew Hesketh <[email protected]>
See LICENSE for details
]]
local mattata = {}
local https = require('ssl.https')
local ltn12 = require('ltn12')
local json = require('dkjson')
local redis = dofile('libs/redis.lua')
local configuration = require('configuration')
local api = require('telegram-bot-lua.core').configure(configuration.bot_token)
local tools = require('telegram-bot-lua.tools')
local socket = require('socket')
local utils = dofile('libs/utils.lua')
local html = require('htmlEntities')
local plugin_list = {}
local administrative_plugin_list = {}
local inline_plugin_list = {}
function mattata:init()
if mattata.is_reloading then
configuration = require('configuration')
mattata.is_reloading = false
end
self.info = api.info -- Set the bot's information to the object fetched from the Telegram bot API.
mattata.info = api.info
self.plugins = {} -- Make a table for the bot's plugins.
self.api = api
self.tools = tools
self.configuration = configuration
self.beta_plugins = {}
self.chats = {}
self.users = {}
self.replies = {}
for k, v in ipairs(configuration.plugins) do -- Iterate over all of the configured plugins.
local true_path = v
for _, p in pairs(configuration.administrative_plugins) do
if v == p then
true_path = 'administration.' .. v
end
end
for _, p in pairs(configuration.beta_plugins) do
if v == p then
table.insert(self.beta_plugins, v)
end
end
local plugin = require('plugins.' .. true_path) -- Load each plugin.
if not plugin then
error('Invalid plugin: ' .. true_path)
elseif mattata.is_duplicate(configuration.plugins, v) then
error('Duplicate plugin: ' .. v)
end
plugin.is_administrative = true_path:match('^administration%.') and true or false
self.plugins[k] = plugin
self.plugins[k].name = v
if self.beta_plugins[v] then
plugin.is_beta_plugin = true
end
if plugin.init then -- If the plugin has an `init` function, run it.
plugin.init(self, configuration)
end
plugin.is_administrative = (self.plugins[k].name == 'administration' or true_path:match('^administration%.')) and true or false
-- By default, a plugin doesn't have inline functionality; but, if it does, set it to `true` appropriately.
plugin.is_inline = plugin.on_inline_query and true or false
plugin.commands = plugin.commands or {} -- If the plugin hasn't got any commands configured, then set a blank
-- table, so when it comes to iterating over the commands later on, the bot won't encounter any problems.
if plugin.help and not plugin.is_beta_plugin then -- If the plugin has help documentation, then insert it into other tables (where necessary).
if plugin.is_administrative then
table.insert(administrative_plugin_list, plugin.help)
else
table.insert(plugin_list, plugin.help)
if plugin.is_inline then -- If the plugin is inline and has documentation, then insert the documentation into
-- the `inline_plugin_list` table.
table.insert(inline_plugin_list, plugin.help)
end
end
plugin.help = 'Usage:\n' .. plugin.help:gsub('%. (Alias)', '.\n%1') -- Make the plugin's documentation style all nicely unified, for consistency.
end
self.plugin_list = plugin_list
self.inline_plugin_list = inline_plugin_list
self.administrative_plugin_list = administrative_plugin_list
end
print(configuration.connected_message)
local info_message = '\tUsername: @' .. self.info.username .. '\n\tName: ' .. self.info.name .. '\n\tID: ' .. self.info.id
print('\n' .. info_message .. '\n')
if redis:get('mattata:version') ~= configuration.version then
local success = dofile('migrate.lua')
print(success)
end
self.version = configuration.version
-- Make necessary database changes if the version has changed.
if not redis:get('mattata:version') or redis:get('mattata:version') ~= self.version then
redis:set('mattata:version', self.version)
end
self.last_update = self.last_update or 0 -- If there is no last update known, make it 0 so the bot doesn't encounter any problems when it tries to add the necessary increment.
self.last_backup = self.last_backup or os.date('%V')
self.last_cron = self.last_cron or os.date('%M')
self.last_cache = self.last_cache or os.date('%d')
local init_message = '<pre>' .. configuration.connected_message .. '\n\n' .. mattata.escape_html(info_message) .. '\n\n\tPlugins loaded: ' .. #configuration.plugins - #configuration.administrative_plugins .. '\n\tAdministrative plugins loaded: ' .. #configuration.administrative_plugins .. '</pre>'
mattata.send_message(configuration.log_chat, init_message:gsub('\t', ''), 'html')
for _, admin in pairs(configuration.admins) do
mattata.send_message(admin, init_message:gsub('\t', ''), 'html')
end
local shutdown = redis:get('mattata:shutdown')
if shutdown then
local chat_id, message_id = shutdown:match('^(%-?%d+):(%d*)$')
mattata.edit_message_text(chat_id, message_id, 'Successfully rebooted!')
redis:del('mattata:shutdown')
end
return true
end
-- Set a bunch of function aliases, for consistency & compatibility.
for i, v in pairs(api) do
mattata[i] = v
end
for i, v in pairs(tools) do
mattata[i] = v
end
for i, v in pairs(utils) do
if i ~= 'init' then
mattata[i] = v
end
end
function mattata:run(_, token)
-- mattata's main long-polling function which repeatedly checks the Telegram bot API for updates.
-- The objects received in the updates are then further processed through object-specific functions.
token = token or configuration.bot_token
assert(token, 'You need to enter your Telegram bot API token in configuration.lua, or pass it as the second argument when using the mattata:run() function!')
mattata.is_running = mattata.init(self) -- Initialise the bot.
utils.init(self, configuration)
while mattata.is_running do -- Perform the main loop whilst the bot is running.
local success = api.get_updates( -- Check the Telegram bot API for updates.
configuration.updates.timeout,
self.last_update + 1,
configuration.updates.limit,
json.encode(
{
'message',
'edited_message',
'inline_query',
'callback_query'
}
),
configuration.use_beta_endpoint or false
)
if success and success.result then
for _, v in ipairs(success.result) do
self.last_update = v.update_id
self.execution_time = socket.gettime()
if v.message or v.edited_message then
if v.edited_message then
v.message = v.edited_message
v.edited_message = nil
v.message.old_date = v.message.date
v.message.date = v.message.edit_date
v.message.edit_date = nil
v.message.is_edited = true
else
v.message.is_edited = false
end
if v.message.reply_to_message then
v.message.reply = v.message.reply_to_message -- Make the `update.message.reply_to_message`
-- object `update.message.reply` to make any future handling easier.
v.message.reply_to_message = nil -- Delete the old value by setting its value to nil.
end
mattata.on_message(self, v.message)
if configuration.debug then
print(
string.format(
'%s[36m[Update #%s] Message%s from %s to %s: %s%s[0m',
string.char(27),
v.update_id,
v.message.is_edited and ' edit' or '',
v.message.from.id,
v.message.chat.id,
v.message.text,
string.char(27)
)
)
end
elseif v.inline_query then
mattata.on_inline_query(self, v.inline_query)
if configuration.debug then
print(
string.format(
'%s[35m[Update #%s] Inline query from %s%s[0m',
string.char(27),
v.update_id,
v.inline_query.from.id,
string.char(27)
)
)
end
elseif v.callback_query then
if v.callback_query.message and v.callback_query.message.reply_to_message then
v.callback_query.message.reply = v.callback_query.message.reply_to_message
v.callback_query.message.reply_to_message = nil
end
mattata.on_callback_query(self, v.callback_query.message, v.callback_query)
if configuration.debug then
print(
string.format(
'%s[33m[Update #%s] Callback query from %s%s[0m',
string.char(27),
v.update_id,
v.callback_query.from.id,
string.char(27)
)
)
end
end
self.result_time = socket.gettime() - self.execution_time
if configuration.debug then
print('Update #' .. v.update_id .. ' took ' .. self.result_time .. ' seconds to process.')
end
end
else
mattata.log_error('There was an error retrieving updates from the Telegram bot API!')
end
if self.last_backup ~= os.date('%V') then -- If it's been a week since the last backup, perform another backup.
self.last_backup = os.date('%V') -- Set the last backup time to now, since we're
-- now performing one!
print(io.popen('./backup.sh'):read('*all'))
end
if self.last_cron ~= os.date('%M') then -- Perform minutely CRON jobs.
self.last_cron = os.date('%M')
for i = 1, #self.plugins do
local plugin = self.plugins[i]
if plugin and plugin.cron then
local cron_success, res = pcall(function()
plugin.cron(self, configuration)
end)
if not cron_success then
mattata.exception(self, res, 'CRON: ' .. i, configuration.log_chat)
end
end
end
end
if self.last_cache ~= os.date('%d') then -- Reset the bot's cache.
self.last_cache = os.date('%d')
self.chats = {}
self.users = {}
self.replies = {}
end
end
print(self.info.first_name .. ' is shutting down...')
end
function mattata:on_message(message)
-- If the message is old or is missing necessary fields/values, then we'll stop and allow the bot to start processing the next update(s).
-- If the message was sent from a blocklisted chat, then we'll stop because we don't want the bot to respond there.
if not mattata.is_valid(message) then
return false
elseif redis:get('blocklisted_chats:' .. message.chat.id) then
return mattata.leave_chat(message.chat.id)
end
message = mattata.sort_message(message) -- Process the message.
self.is_user_blocklisted, self.is_globally_blocklisted, self.is_globally_banned = mattata.is_user_blocklisted(message)
-- We only want this functionality if the bot owner has been granted API permission to SpamWatch!
self.is_spamwatch_blocklisted = configuration.keys.spamwatch ~= '' and mattata.is_spamwatch_blocklisted(message) or false
if self.is_globally_banned and message.chat.type ~= 'private' then -- Only for the worst of the worst
mattata.ban_chat_member(message.chat.id, message.from.id)
end
local language = require('languages.' .. mattata.get_user_language(message.from.id))
if mattata.is_group(message) and mattata.get_setting(message.chat.id, 'force group language') then
language = require('languages.' .. (mattata.get_value(message.chat.id, 'group language') or 'en_gb'))
end
self.language = language
if mattata.process_spam(message, configuration) then
return false
end
-- Perform the following actions if the user isn't blocklisted.
if not self.is_user_blocklisted then
mattata.process_afk(self, message)
mattata.process_language(self, message)
if message.text then
message = mattata.process_natural_language(self, message)
end
message = mattata.process_stickers(message)
message = mattata.check_links(message, false, true, false, true)
message = mattata.process_deeplinks(message)
-- If the user isn't current AFK, and they say they're going to be right back, we can
-- assume that they are now going to be AFK, so we'll help them out and set them that
-- way by making the message text the /afk command, which will later trigger the plugin.
if (message.text:lower():match('^i?\'?l?l? ?[bg][rt][bg].?$') and not redis:hget('afk:' .. message.from.id, 'since')) then
message.text = '/afk'
end
-- A boolean value to decide later on, whether the message is intended for the current plugin from the iterated table.
message = mattata.process_nicknames(message)
if not self.chats[tostring(message.chat.id)] then
self.chats[tostring(message.chat.id)] = message.chat
self.chats[tostring(message.chat.id)].disabled_plugins = redis:smembers('disabled_plugins:' .. message.chat.id) or {}
end
if message.reply then
if not self.replies[tostring(message.chat.id)] then
self.replies[tostring(message.chat.id)] = {}
end
if not self.replies[tostring(message.chat.id)][tostring(message.message_id)] then
self.replies[tostring(message.chat.id)][tostring(message.message_id)] = message.reply
end
if self.replies[tostring(message.chat.id)][tostring(message.reply.message_id)] then
message.reply.reply = self.replies[tostring(message.chat.id)][tostring(message.reply.message_id)]
end
end
end
self.is_command = false
self.is_command_done = false
self.is_allowed_beta_access = false
self.is_telegram = false
-- If the message is one of those pesky Telegram channel pins, it won't send a service message. We'll trick it.
if message.from.id == 777000 and message.forward_from_chat and message.forward_from_chat.type == 'channel' then
self.is_telegram = true
message.is_service_message = true
message.service_message = 'pinned_message'
message.pinned_message = {
['text'] = message.text,
['date'] = message.date,
['chat'] = message.chat,
['from'] = message.from,
['message_id'] = message.message_id,
['entities'] = message.entities,
['forward_from_message_id'] = message.forward_from_message_id,
['forward_from_chat'] = message.forward_from_chat,
['forward_date'] = message.forward_date
}
end
if message.text:match('^[/!#][%w_]+') and message.chat.type == 'supergroup' then
local command, input = message.text:lower():match('^[/!#]([%w_]+)(.*)$')
local all = redis:hgetall('chat:' .. message.chat.id .. ':aliases')
for alias, original in pairs(all) do
if command == alias then
message.text = '/' .. original .. input
message.is_alias = true
break
end
end
end
-- This is the main loop which iterates over configured plugins and runs the appropriate functions.
for _, plugin in ipairs(self.plugins) do
if not mattata.is_plugin_disabled(self, plugin.name, message) then
if plugin.is_beta_plugin and mattata.is_global_admin(message.from.id) then
self.is_allowed_beta_access = true
end
if not plugin.is_beta_plugin or (plugin.is_beta_plugin and self.is_allowed_beta_access) then
local commands = #plugin.commands or {}
for i = 1, commands do
if message.text:match(plugin.commands[i]) and mattata.is_plugin_allowed(plugin.name, self.is_user_blocklisted, configuration) and not self.is_command_done and not self.is_telegram and (not message.is_edited or mattata.is_global_admin(message.from.id)) then
self.is_command = true
message.command = plugin.commands[i]:match('([%w_%-]+)')
if plugin.on_message then
local old_message = message.text
if mattata.is_global_admin(message.from.id) and message.text:match('^.- && .-$') then
message.text = message.text:match('^(.-) && .-$')
end
local success, result = pcall(function()
return plugin.on_message(self, message, configuration, language)
end)
message.text = old_message
if not success then
mattata.exception(self, result, string.format('%s: %s', message.from.id, message.text), configuration.log_chat)
end
if mattata.get_setting(message.chat.id, 'delete commands') and self.is_command and not redis:sismember('chat:' .. message.chat.id .. ':no_delete', tostring(plugin.name)) and not message.is_natural_language then
mattata.delete_message(message.chat.id, message.message_id)
end
self.is_command_done = true
end
end
end
end
-- Allow plugins to handle new chat participants.
if message.new_chat_members and plugin.on_member_join then
local success, result = pcall(function()
return plugin.on_member_join(self, message, configuration, language)
end)
if not success then
mattata.exception(self, result, string.format('%s: %s', message.from.id, message.text),
configuration.log_chat)
end
end
-- Allow plugins to handle every new message (handy for anti-spam).
if (message.text or message.is_media) and plugin.on_new_message then
local success, result = pcall(function()
return plugin.on_new_message(self, message, configuration, language)
end)
if not success then
mattata.exception(self, result, string.format('%s: %s', message.from.id, message.text or tostring(message.media_type),
configuration.log_chat))
end
end
-- Allow plugins to handle service messages, and pass the type of service message before the message object.
if message.is_service_message and plugin.on_service_message then
local success, result = pcall(function()
return plugin.on_service_message(self, message.service_message:gsub('_', ' '), message, configuration, language)
end)
if not success then
mattata.exception(self, result, string.format('%s: %s', message.from.id, message.text or tostring(message.media_type),
configuration.log_chat))
end
end
end
end
mattata.process_message(self, message)
self.is_done = true
self.is_command_done = false
self.is_ai = false
return
end
function mattata:on_inline_query(inline_query)
if not inline_query.from then
return false, 'No `inline_query.from` object was found!'
elseif redis:get('global_blocklist:' .. inline_query.from.id) then
return false, 'This user is globally blocklisted!'
end
local language = require('languages.' .. mattata.get_user_language(inline_query.from.id))
inline_query.offset = inline_query.offset and tonumber(inline_query.offset) or 0
for _, plugin in ipairs(self.plugins) do
local plugins = plugin.commands or {}
for i = 1, #plugins do
local command = plugin.commands[i]
if not inline_query then
return false, 'No `inline_query` object was found!'
end
if inline_query.query:match(command)
and plugin.on_inline_query
then
local success, result = pcall(
function()
return plugin.on_inline_query(self, inline_query, configuration, language)
end
)
if not success then
local exception = string.format('%s: %s', inline_query.from.id, inline_query.query)
mattata.exception(self, result, exception, configuration.log_chat)
return false, result
elseif not result then
return api.answer_inline_query(
inline_query.id,
api.inline_result()
:id()
:type('article')
:title(configuration.errors.results)
:description(plugin.help)
:input_message_content(api.input_text_message_content(plugin.help))
)
end
end
end
end
if not inline_query.query or inline_query.query:gsub('%s', '') == '' then
local offset = inline_query.offset and tonumber(inline_query.offset) or 0
local list = mattata.get_inline_list(self.info.username, offset)
if #list == 0 then
local title = 'No more results found!'
local description = 'There were no more inline features found. Use @' .. self.info.username .. ' <query> to search for more information about commands matching the given search query.'
return mattata.send_inline_article(inline_query.id, title, description)
end
return mattata.answer_inline_query(inline_query.id, json.encode(list), 0, false, tostring(offset + 50))
end
local help = require('plugins.help')
return help.on_inline_query(self, inline_query, configuration, language)
end
function mattata:on_callback_query(message, callback_query)
if not callback_query.from then return false end
if not callback_query.message or not callback_query.message.chat then
message = {
['chat'] = {},
['message_id'] = callback_query.inline_message_id,
['from'] = callback_query.from
}
else
message = callback_query.message
message.exists = true
message = mattata.process_nicknames(message)
callback_query = mattata.process_nicknames(callback_query)
end
if not self.chats[tostring(message.chat.id)] then
self.chats[tostring(message.chat.id)] = message.chat
self.chats[tostring(message.chat.id)].disabled_plugins = redis:smembers('disabled_plugins:' .. message.chat.id) or {}
end
local language = require('languages.' .. mattata.get_user_language(callback_query.from.id))
if message.chat.id and mattata.is_group(message) and mattata.get_setting(message.chat.id, 'force group language') then
language = require('languages.' .. (mattata.get_value(message.chat.id, 'group language') or 'en_gb'))
end
self.language = language
if redis:get('global_blocklist:' .. callback_query.from.id) and not callback_query.data:match('^join_captcha') and not mattata.is_global_admin(callback_query.from.id) then
return false, 'This user is globally blocklisted!'
elseif message and message.exists then
if message.reply and message.chat.type ~= 'channel' and callback_query.from.id ~= message.reply.from.id and not callback_query.data:match('^game:') and not callback_query.data:match('^report:') and not mattata.is_global_admin(callback_query.from.id) then
local output = 'Only ' .. message.reply.from.first_name .. ' can use this!'
return mattata.answer_callback_query(callback_query.id, output)
end
end
for _, plugin in ipairs(self.plugins) do
if not callback_query.data or not callback_query.from then
return false
elseif plugin.name == callback_query.data:match('^(.-):.-$') and plugin.on_callback_query then
callback_query.data = callback_query.data:match('^[%a_]+:(.-)$')
if not callback_query.data then
plugin = callback_query.data
callback_query = ''
end
local success, result = pcall(
function()
return plugin.on_callback_query(self, callback_query, message or false, configuration, language)
end
)
if not success then
mattata.send_message(configuration.admins[1], json.encode(callback_query, {indent=true}))
-- mattata.answer_callback_query(callback_query.id, language['errors']['generic'])
local exception = string.format('%s: %s', callback_query.from.id, callback_query.data)
mattata.exception(self, result, exception, configuration.log_chat)
return false, result
end
end
end
return true
end
mattata.send_message = api.send_message
-- A variant of mattata.send_message(), optimised for sending a message as a reply that forces a
-- reply back from the user.
function mattata.send_force_reply(message, text, parse_mode, disable_web_page_preview, token)
local success = api.send_message(
message,
text,
parse_mode,
disable_web_page_preview,
false,
message.message_id,
'{"force_reply":true,"selective":true}',
token
)
return success
end
function mattata.get_chat(chat_id, only_api, token)
local user = mattata.get_user(chat_id)
if user then
return user
end
local success = api.get_chat(chat_id, token)
if only_api then -- stops antispam using usernames stored in the database
return success
elseif success and success.result.type == 'private' then
mattata.process_user(success.result)
elseif success then
mattata.process_chat(success.result)
end
chat_id = success and success.result.id or chat_id
local result = redis:hgetall('chat:' .. tostring(chat_id) .. ':info')
if not result or type(result) == 'table' and not next(result) then
return false
end
success.result = result
if not success.result.id then
success.result.id = chat_id
redis:hset('chat:' .. chat_id .. ':info', 'id', chat_id)
end
return success
end
function mattata:is_plugin_disabled(plugin, message)
if not plugin or not message then
return false
end
plugin = plugin:lower():gsub('^administration/', '')
if mattata.table_contains(configuration.permanent_plugins, plugin) then
return false
elseif type(message) ~= 'table' then
message = {
['chat'] = {
['id'] = message
}
}
if tostring(message.chat.id):match('^%-100') then
message.chat.type = 'supergroup'
else
message.chat.type = 'private'
end
end
if not self.chats[tostring(message.chat.id)] then
self.chats[tostring(message.chat.id)] = message.chat
end
if not self.chats[tostring(message.chat.id)].disabled_plugins then
self.chats[tostring(message.chat.id)].disabled_plugins = redis:smembers('disabled_plugins:' .. message.chat.id)
end
if not mattata.table_contains(self.chats[tostring(message.chat.id)].disabled_plugins, plugin) then
return false
end
local exists = redis:sismember('disabled_plugins:' .. message.chat.id, plugin)
return exists and true or false
end
function mattata:exception(err, message, log_chat)
local output = string.format(
'[%s]\n%s: %s\n%s\n',
os.date('%X'),
self.info.username,
mattata.escape_html(err) or '',
mattata.escape_html(message)
)
if log_chat then
return mattata.send_message(
log_chat,
string.format('<pre>%s</pre>', output),
'html'
)
end
return output
end
function mattata.is_group_admin(chat_id, user_id, is_real_admin)
if not chat_id or not user_id then
return false
elseif mattata.is_global_admin(chat_id) or mattata.is_global_admin(user_id) then
return true
elseif not is_real_admin and mattata.is_group_mod(chat_id, user_id) then
return true
end
local user, res = mattata.get_chat_member(chat_id, user_id)
if not user or not user.result then
return false, res
elseif user.result.status == 'creator' or user.result.status == 'administrator' then
return true, res
end
return false, user.result.status
end
function mattata.is_group_mod(chat_id, user_id)
if not chat_id or not user_id then
return false
elseif redis:sismember('administration:' .. chat_id .. ':mods', user_id) then
return true
end
return false
end
function mattata.process_chat(chat)
chat.id_str = tostring(chat.id)
if chat.type == 'private' then
return mattata.process_user(chat)
end
if not redis:hexists('chat:' .. chat.id .. ':info', 'id') then
print(
string.format(
'%s[34m[+] Added the chat %s to the database!%s[0m',
string.char(27),
chat.username and '@' .. chat.username or chat.id,
string.char(27)
)
)
end
redis:hset('chat:' .. chat.id .. ':info', 'title', chat.title)
redis:hset('chat:' .. chat.id .. ':info', 'type', chat.type)
if chat.username then
chat.username = chat.username:lower()
redis:hset('chat:' .. chat.id .. ':info', 'username', chat.username)
redis:set('username:' .. chat.username, chat.id)
if not redis:sismember('chat:' .. chat.id .. ':usernames', chat.username) then
redis:sadd('chat:' .. chat.id .. ':usernames', chat.username)
end
end
redis:hset('chat:' .. chat.id .. ':info', 'id', chat.id)
return chat
end
function mattata.process_user(user)
if not user then return user end
if not user.id or not user.first_name then return false end
redis:hset('user:' .. user.id .. ':info', 'id', user.id)
local new = false
user.name = user.first_name
if user.last_name then
user.name = user.name .. ' ' .. user.last_name
end
if not redis:hget('user:' .. user.id .. ':info', 'id') and configuration.debug then
print(
string.format(
'%s[34m[+] Added the user %s to the database!%s%s[0m',
string.char(27),
user.username and '@' .. user.username or user.id,
user.language_code and ' Language: ' .. user.language_code or '',
string.char(27)
)
)
new = true
elseif configuration.debug then
print(
string.format(
'%s[34m[+] Updated information about the user %s in the database!%s%s[0m',
string.char(27),
user.username and '@' .. user.username or user.id,
user.language_code and ' Language: ' .. user.language_code or '',
string.char(27)
)
)
end
redis:hset('user:' .. user.id .. ':info', 'type', 'private')
redis:hset('user:' .. user.id .. ':info', 'name', user.name)
redis:hset('user:' .. user.id .. ':info', 'first_name', user.first_name)
if user.last_name then
redis:hset('user:' .. user.id .. ':info', 'last_name', user.last_name)
else
redis:hdel('user:' .. user.id .. ':info', 'last_name')
end
if user.username then
user.username = user.username:lower()
redis:hset('user:' .. user.id .. ':info', 'username', user.username)
redis:set('username:' .. user.username, user.id)
if not redis:sismember('user:' .. user.id .. ':usernames', user.username) then
redis:sadd('user:' .. user.id .. ':usernames', user.username)
end
else
redis:hdel('user:' .. user.id .. ':info', 'username')
end
if user.language_code then
if mattata.does_language_exist(user.language_code) and not redis:hget('chat:' .. user.id .. ':settings', 'language') then
-- If a translation exists for the user's language code, and they haven't selected
-- a language already, then set it as their primary language!
redis:hset('chat:' .. user.id .. ':settings', 'language', user.language_code)
end
redis:hset('user:' .. user.id .. ':info', 'language_code', user.language_code)
else
redis:hdel('user:' .. user.id .. ':info', 'language_code')
end
redis:hset('user:' .. user.id .. ':info', 'is_bot', tostring(user.is_bot))
if new then
redis:hset('user:' .. user.id .. ':info', 'id', user.id)
end
if redis:get('nick:' .. user.id) then
user.first_name = redis:get('nick:' .. user.id)
user.name = user.first_name
user.last_name = nil
end
return user, new
end
function mattata.sort_message(message)
message.is_natural_language = false
message.text = message.text or message.caption or '' -- Ensure there is always a value assigned to message.text.
message.text = message.text:gsub('^/(%a+)%_', '/%1 ')
if message.text:match('^[/!#]start .-$') then -- Allow deep-linking through the /start command.
message.text = '/' .. message.text:match('^[/!#]start (.-)$')
end
message.is_media = mattata.is_media(message)
message.media_type = mattata.media_type(message)
message.file_id = mattata.file_id(message)
message.is_alias = false -- We sort this later.
message.is_service_message, message.service_message = mattata.service_message(message)
if message.caption_entities then
message.entities = message.caption_entities
message.caption_entities = nil
end
if message.from.language_code then
message.from.language_code = message.from.language_code:lower():gsub('%-', '_') -- make it fit with the names of our language files
if message.from.language_code:len() == 2 and message.from.language_code ~= 'en' then
message.from.language_code = message.from.language_code .. '_' .. message.from.language_code
elseif message.from.language_code:len() == 2 or message.from.language_code == 'root' then -- not sure why but some english users were having `root` return as their language
message.from.language_code = 'en_us'
end
end
message.reply = message.reply and mattata.sort_message(message.reply) or nil
if message.from then
message.from = mattata.process_user(message.from)
end
if message.reply then
message.reply.from = mattata.process_user(message.reply.from)
end
if message.forward_from then
message.forward_from = mattata.process_user(message.forward_from)
end
if message.chat and message.chat.type ~= 'private' then
-- Add the user to the set of users in the current chat.
if configuration.administration.store_chat_members and message.from then
if not redis:sismember('chat:' .. message.chat.id .. ':users', message.from.id) then
redis:sadd('chat:' .. message.chat.id .. ':users', message.from.id)
end
end
if message.new_chat_members then
message.chat = mattata.process_chat(message.chat)
for i = 1, #message.new_chat_members do
if configuration.administration.store_chat_users then
redis:sadd('chat:' .. message.chat.id .. ':users', message.new_chat_members[i].id) -- add users to the chat's set in the database
end
message.new_chat_members[i] = mattata.process_user(message.new_chat_members[i])
end
elseif message.left_chat_member then -- if they've left the chat then there's no need for them to be in the set anymore
message.chat = mattata.process_chat(message.chat)
message.left_chat_member = mattata.process_user(message.left_chat_member)
if configuration.administration.store_chat_users then
redis:srem('chat:' .. message.chat.id .. ':users', message.left_chat_member.id)
end
end
end
if message.text and message.chat and message.reply and message.reply.from and message.reply.from.id == api.info.id then
local action = redis:get('action:' .. message.chat.id .. ':' .. message.reply.message_id)
-- If an action was saved for the replied-to message (as part of a multiple step command), then
-- we'll get information about the action.
if action then
message.text = action .. ' ' .. message.text -- Concatenate the saved action's command
-- with the new `message.text`.
message.reply = nil -- This caused some issues with administrative commands which would
-- prioritise replied-to users over users given by arguments.
redis:del(action) -- Delete the action for this message, since we've done what we needed to do
-- with it now.
end
end
if message.entities then
for n, entities in pairs(message.entities) do
if entities.type == 'text_mention' then
message.text = message.text:gsub(message.entities[n].user.first_name, message.entities[n].user.id)
end
end
end
return message
end
function mattata.is_global_admin(id)
for _, v in pairs(configuration.admins) do
if id == v then
return true
end
end
return false
end
function mattata.get_user(input, force_api, is_id_plugin, cache_only)
if tonumber(input) == nil and input then -- check it's not an ID
input = input:match('^%@?(.-)$')
input = redis:get('username:' .. input:lower())
end
if not input or tonumber(input) == nil then -- if it's still not an ID then we'll give up
return false
end
local user = redis:hgetall('user:' .. tostring(input) .. ':info')
if is_id_plugin and user.id then
local success = mattata.get_chat(user.id) -- Try and get latest info about the user for the ID plugin
if success then
return success
end
end
if user.username and not cache_only then
local scrape, scrape_res = https.request('https://t.me/' .. user.username)
if scrape_res == 200 then
local bio = scrape:match('%<div class="tgme_page_description "%>(.-)%</div%>')
if bio then
bio = bio:gsub('%b<>', '')
bio = html.decode(bio)
user.bio = bio
end
end
end
if user.id then
return {
['result'] = {
['id'] = tonumber(user.id),
['type'] = user.type,
['name'] = user.name,
['first_name'] = user.first_name,
['last_name'] = user.last_name,
['username'] = user.username,
['is_bot'] = user.is_bot,
['bio'] = user.bio
}
}
end
if force_api then
return mattata.get_chat(input)
end
return false
end
function mattata.get_inline_list(username, offset)
offset = offset and tonumber(offset) or 0
local inline_list = {}
table.sort(inline_plugin_list)
for k, v in pairs(inline_plugin_list) do
if k > offset and k < offset + 50 then -- The bot API only accepts a maximum of 50 results, hence we need the offset.
v = v:gsub('\n', ' ')
table.insert(
inline_list,
mattata.inline_result()
:type('article')
:id(tostring(k))
:title(v:match('^(/.-) %- .-$'))
:description(v:match('^/.- %- (.-)$'))
:input_message_content(
mattata.input_text_message_content(
string.format(
'• %s - %s\n\nTo use this command inline, you must use the syntax:\n@%s %s',
v:match('^(/.-) %- .-$'),
v:match('^/.- %- (.-)$'),
username,
v:match('^(/.-) %- .-$')
)
)
)
:reply_markup(
mattata.inline_keyboard():row(
mattata.row():switch_inline_query_button('Show me how!', v:match('^(/.-) '))
)
)
)
end
end
return inline_list
end
function mattata:get_help(is_administrative, chat_id)
local list_to_use = is_administrative == true and administrative_plugin_list or plugin_list
local help = {}
local count = 1
table.sort(list_to_use)
for _, v in pairs(list_to_use) do
if v:match('^/.- %- .-$') then
-- Do some replacement for plugins that have different primary commands to their plugin name.
local to_match = v:gsub('/np', '/lastfm'):gsub('/r/', '/reddit '):gsub('/s/', '/sed '):gsub('(/cat)', '%1s')
local plugin = to_match:match('^/([%w_]+) .-$')
if not chat_id or not mattata.is_plugin_disabled(self, plugin, chat_id) then
local command, description = v:match('^(.-) %- (.-)$')
local parameters = ' '
if not command then mattata.send_message(configuration.admins[1], v) end
if command:match(' [%[<]') then
command, parameters = command:match('^(.-)( .-)$')
parameters = '<code>' .. mattata.escape_html(parameters) .. '</code> '
end
local output = command .. parameters .. '- <em>' .. mattata.escape_html(description) .. '</em>'
table.insert(help, utf8.char(8226) .. ' ' .. output)
count = count + 1
end
end
end
return help
end
function mattata.format_time(seconds)
if not seconds or tonumber(seconds) == nil then
return false
end
seconds = tonumber(seconds) -- Make sure we're handling a numerical value
local minutes = math.floor(seconds / 60)
if minutes == 0 then
return seconds ~= 1 and seconds .. ' seconds' or seconds .. ' second'
elseif minutes < 60 then
return minutes ~= 1 and minutes .. ' minutes' or minutes .. ' minute'
end
local hours = math.floor(seconds / 3600)
if hours == 0 then
return minutes ~= 1 and minutes .. ' minutes' or minutes .. ' minute'
elseif hours < 24 then
return hours ~= 1 and hours .. ' hours' or hours .. ' hour'
end
local days = math.floor(seconds / 86400)
if days == 0 then
return hours ~= 1 and hours .. ' hours' or hours .. ' hour'
elseif days < 7 then
return days ~= 1 and days .. ' days' or days .. ' day'
end
local weeks = math.floor(seconds / 604800)
if weeks == 0 then
return days ~= 1 and days .. ' days' or days .. ' day'
else
return weeks ~= 1 and weeks .. ' weeks' or weeks .. ' week'
end
end
function mattata.does_language_exist(language)
return pcall( -- nice and simple, perform a pcall to require the language, and if it errors then it doesn't exist
function()
return require('languages.' .. language)
end
)
end