-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathghbot.py
executable file
·1342 lines (876 loc) · 44.9 KB
/
ghbot.py
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
#! /usr/bin/python3
import configparser
from dbi import dbi
import difflib
from enum import Enum
from http_server import http_server
from ircbot import ircbot, irc_keepalive
import math
from mqtt_handler import mqtt_handler
import nltk
from plugin_handler import plugins_class
import random
import select
import socket
import sys
import threading
import time
import traceback
class ghbot(ircbot):
class internal_command_rc(Enum):
HANDLED = 0x00
ERROR = 0x10
NOT_INTERNAL = 0xff
def __init__(self, host, port, nick, password, channels, m, db, cmd_prefix, local_plugin_subdir):
super().__init__(host, port, nick, password, channels)
self.cmd_prefix = cmd_prefix
self.db = db
self.mqtt = m
self.plugins = dict()
self.plugins_lock = threading.Lock()
self.plugins_gone = dict()
self.local_plugins = plugins_class(self, local_plugin_subdir, 'ghb_')
now = time.time()
# v make these into dictionaries v TODO
self.plugins['addacl'] = ['Add an ACL, format: addacl user|group <user|group> group|cmd <group-name|cmd-name>', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['delacl'] = ['Remove an ACL, format: delacl <user> group|cmd <group-name|cmd-name>', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['listacls'] = ['List all ACLs for a user or group', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['deluser'] = ['Forget a person; removes all ACLs for that nick', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['clone'] = ['Clone ACLs from one user to another', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['meet'] = ['Use this when a user (nick) has a new hostname: meet <nick>', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['merge'] = ['Use this to add a host-alias for an existing user (nick): merge <new-nick> <old-nick>', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['commands'] = ['Show list of known commands', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['help'] = ['Help for commands, parameter is the command to get help for', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['more'] = ['Continue outputting a too long line of text', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['define'] = ['Define a command that will be replied to with a definable text, format: !define <command> <text... with %m (/me), %q (parameters) and %u (nick of invoker) escapes, %n for notice>', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['deldefine']= ['Delete a define (by number)', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['alias'] = ['Add a different name for a command, format: !alias <newname> <oldname>', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['searchdefine'] = ['Search for defines that match a partial text', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['searchalias'] = ['Search for aliases that match a partial text', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['viewalias'] = ['Show what an alias is doing', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['listgroups']= ['Shows a list of available groups', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['showgroup']= ['Shows a list of commands or members in a group (showgroup commands|members <groupname>)', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['apro'] = ['Show commands that match a partial text', None, now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['reloadlp'] = ['Reload a "local" plugin', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['listlp'] = ['List "local" plugins', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['showlp'] = ['Show commands of a "local" plugin', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.plugins['loadlp'] = ['Load "local" plugins that are not loaded yet', 'sysops', now, 'Flok', 'harkbot.vm.nurd.space']
self.hardcoded_plugins = set()
for p in self.plugins:
self.hardcoded_plugins.add(p)
for local_plugin in self.local_plugins.list_plugins(): # iterate over each plugin .py-file
all_commands = self.local_plugins.get_commandos(local_plugin)
for command, parameters in all_commands: # iterate over each command that a plugin can have
# they're hardcoded; don't allow to override
self.hardcoded_plugins.add(command)
# register in the plugin-list
self.plugins[command] = parameters
self.topic_privmsg = []
self.topic_notice = []
self.topic_topic = []
self.topic_to_nick = f'to/irc-person/'
for channel in self.channels:
self.topic_privmsg.append(f'to/irc/{channel[1:]}/privmsg') # Send reply in channel via PRIVMSG
self.topic_notice.append(f'to/irc/{channel[1:]}/notice') # Send reply in channel via NOTICE
self.topic_topic.append(f'to/irc/{channel[1:]}/topic') # Sets TOPIC for channel
self.topic_register = f'to/bot/register' # topic where plugins announce themselves
self.topic_request = f'to/bot/request' # topic where plugins request bot-actions
self.mqtt.subscribe(self.topic_request, self._recv_msg_cb)
for topic in self.topic_privmsg:
self.mqtt.subscribe(topic, self._recv_msg_cb)
for topic in self.topic_notice:
self.mqtt.subscribe(topic, self._recv_msg_cb)
for topic in self.topic_topic:
self.mqtt.subscribe(topic, self._recv_msg_cb)
self.mqtt.subscribe('to/irc/#', self._recv_msg_cb) # required for pm-commands :-/
self.pm_topic = 'to/irc/\\' # to match on
self.mqtt.subscribe(self.topic_to_nick + '#', self._recv_msg_cb)
self.mqtt.subscribe(self.topic_register, self._recv_msg_cb)
self.host = host
self.port = port
self.nick = nick
self.channel = channel
self.fd = None
self.state = self.session_state.DISCONNECTED
self.state_since = time.time()
self.users = dict()
self.name = 'GHBot IRC'
self.start()
self.plugin_cleaner = threading.Thread(target=self._plugin_cleaner)
self.plugin_cleaner.start()
# ask plugins to register themselves so that we know which
# commands are available (and what they're for etc.)
self._plugin_command('register')
self._plugin_parameter('prefix', self.cmd_prefix, True)
# checks how old the the latest registration of a plugin is.
# too old? (10 seconds) then forget the plugin-command.
def _plugin_cleaner(self):
while True:
try:
time.sleep(4.9)
to_delete = []
now = time.time()
self.plugins_lock.acquire()
for plugin in self.plugins:
if now - self.plugins[plugin][2] >= 10. and plugin not in self.hardcoded_plugins: # 5 seconds timeout
to_delete.append(plugin)
for plugin in to_delete:
del self.plugins[plugin]
self.plugins_gone[plugin] = now
self.plugins_lock.release()
except Exception as e:
print(f'_plugin_cleaner: failed to clean: {e}')
def _plugin_command(self, cmd):
self.mqtt.publish('from/bot/command', cmd, persistent=False)
def _plugin_parameter(self, key, value, persistent):
self.mqtt.publish(f'from/bot/parameter/{key}', value, persistent=persistent)
def _register_plugin(self, msg):
self.plugins_lock.acquire()
try:
elements = msg.split('|')
cmd = None
descr = ''
acl_group = None
athr = ''
location = ''
for element in elements:
k, v = element.split('=')
if k == 'cmd':
cmd = v
elif k == 'descr':
descr = v
elif k == 'agrp':
acl_group = v
elif k == 'athr':
athr = v
elif k == 'loc':
location = v
if cmd != None:
if not cmd in self.hardcoded_plugins:
if not cmd in self.plugins:
print(f'_register_plugin: first announcement of {cmd}')
self.plugins[cmd] = [descr, acl_group, time.time(), athr, location]
if cmd in self.plugins_gone:
del self.plugins_gone[cmd]
else:
print(f'_register_plugin: cannot override "hardcoded" plugin ({cmd})')
else:
print(f'_register_plugin: cmd missing in plugin registration')
except Exception as e:
print(f'_register_plugin: problem while processing plugin registration "{msg}": {e}')
self.plugins_lock.release()
def _send_topics_to_plugins(self):
for channel in self.topics:
self.mqtt.publish(f'from/irc/{channel}/topic', self.topics[channel])
def _recv_msg_cb(self, topic, msg):
try:
# print(f'irc::_recv_msg_cb: received "{msg}" for topic {topic}')
topic = topic[len(self.mqtt.get_topix_prefix()):]
parts = topic.split('/')
if msg.find('\n') != -1 or msg.find('\r') != -1:
print(f'irc::_recv_msg_cb: invalid content to send for {topic}')
return
if topic in self.topic_privmsg:
self.send_ok('#' + parts[2], self.escapes(msg))
elif topic in self.topic_notice:
self.send_notice('#' + parts[2], msg)
elif topic in self.topic_topic:
self.send(f'TOPIC #{parts[2]} :{msg}')
elif topic in self.topic_request:
print(f'plugin requested {msg}')
if msg == 'topics':
self._send_topics_to_plugins()
elif topic in self.topic_register:
self._register_plugin(msg)
elif parts[0] + '/' + parts[1] in self.topic_to_nick:
if parts[-1].lower() == 'mode':
self.send(f'MODE #{parts[2]} {msg}')
else:
nick = parts[2]
if nick[0] == '\\':
nick = nick[1:]
self.send_ok(nick, msg)
elif self.pm_topic in topic:
nick = parts[2][1:] # remove '\'
self.send_ok(nick, msg)
else:
print(f'irc::_recv_msg_cb: invalid topic {topic}')
return
except Exception as e:
print(f'irc::_recv_msg_cb: exception {e} while processing {topic}|{msg} (at line number: {e.__traceback__.tb_lineno})')
def check_acl_alias(self, who):
with self.db.db.cursor() as cursor:
# see if this is an alias, then if so: pick main address
cursor.execute('SELECT main_account FROM account_aliasses WHERE account=%s', (who.lower(),))
row = cursor.fetchone()
if row != None:
who = row[0].lower()
print(f'Using ACL {who}')
return who
def check_acls(self, who, command):
self.plugins_lock.acquire()
# "no group" is for everyone
if command in self.plugins and self.plugins[command][1] == None:
self.plugins_lock.release()
return (True, None)
plugin_group = self.plugins[command][1]
self.plugins_lock.release()
self.db.probe() # to prevent those pesky "sever has gone away" problems
with self.db.db.cursor() as cursor:
who = self.check_acl_alias(who)
# check per user ACLs (can override group as defined in plugin)
cursor.execute('SELECT COUNT(*) FROM acls WHERE command=%s AND who=%s', (command.lower(), who.lower()))
row = cursor.fetchone()
if row[0] >= 1:
return (True, plugin_group)
# check per group ACLs (can override group as defined in plugin)
cursor.execute('SELECT COUNT(*) FROM acls, acl_groups WHERE acl_groups.who=%s AND acl_groups.group_name=acls.who AND command=%s', (who.lower(), command.lower()))
row = cursor.fetchone()
if row[0] >= 1:
return (True, plugin_group)
# check if user is in group as specified by plugin
cursor.execute('SELECT COUNT(*) FROM acl_groups WHERE group_name=%s AND who=%s', (plugin_group, who.lower()))
row = cursor.fetchone()
if row[0] >= 1:
return (True, plugin_group)
return (False, plugin_group)
def list_acls(self, who):
self.db.probe()
with self.db.db.cursor() as cursor:
who = self.check_acl_alias(who)
cursor.execute('SELECT DISTINCT item FROM (SELECT command AS item FROM acls WHERE who=%s UNION SELECT group_name AS item FROM acl_groups WHERE who=%s) AS in_ ORDER BY item', (who.lower(), who.lower()))
out = []
for row in cursor:
out.append(row[0])
return out
def add_acl(self, who, command):
self.db.probe()
with self.db.db.cursor() as cursor:
who = self.check_acl_alias(who)
try:
cursor.execute('INSERT INTO acls(command, who) VALUES(%s, %s)', (command.lower(), who.lower()))
self.db.db.commit()
return (True, 'Ok')
except Exception as e:
return (False, f'irc::add_acl: failed to insert acl ({e})')
def del_acl(self, who, command):
self.db.probe()
with self.db.db.cursor() as cursor:
who = self.check_acl_alias(who)
try:
cursor.execute('DELETE FROM acls WHERE command=%s AND who=%s LIMIT 1', (command.lower(), who.lower()))
self.db.db.commit()
if cursor.rowcount == 1:
return (True, 'Ok')
return (False, 'That command/nick combination was not known')
except Exception as e:
return (False, f'irc::del_acl: failed to delete acl ({e})')
def forget_acls(self, who):
match_ = who + '!%'
with self.db.db.cursor() as cursor:
who = self.check_acl_alias(who)
try:
cursor.execute('DELETE FROM acls WHERE who LIKE %s', (match_,))
any_del = cursor.rowcount == 1
cursor.execute('DELETE FROM acl_groups WHERE who LIKE %s', (match_,))
any_del |= cursor.rowcount == 1
self.db.db.commit()
if any_del:
return (True, 'Ok')
return (False, 'No acls found for that nick')
except Exception as e:
return (False, f'irc::forget_acls: failed to forget acls for {match_}: {e}')
def clone_acls(self, from_, to_):
with self.db.db.cursor() as cursor:
who = self.check_acl_alias(who)
try:
cursor.execute('SELECT group_name FROM acl_groups WHERE who=%s', (from_,))
for row in cursor.fetchall():
cursor.execute('INSERT INTO acl_groups(group_name, who) VALUES(%s, %s)', (row, to_))
self.db.db.commit()
return (True, 'Ok')
except Exception as e:
return (False, f'failed to clone acls: {e}')
def merge_nick(self, new_nick, old_nick):
with self.db.db.cursor() as cursor:
if '%' in old_nick or '%' in new_nick:
return (False, 'haxxxor')
match_ = old_nick if '!' in old_nick else (old_nick + '!%')
try:
cursor.execute('SELECT who FROM acl_groups WHERE who LIKE %s GROUP BY who', (match_,))
rows = cursor.fetchall()
if len(rows) == 0:
return (False, f'Old user ({old_nick}) is not known')
if len(rows) > 1:
full_names = [row[0] for row in rows]
return (False, f'Old user ({old_nick}) is ambiguous: {", ".join(full_names)}')
print(rows, new_nick)
cursor.execute('INSERT INTO account_aliasses(main_account, account) VALUES(%s, %s)', (rows[0][0], new_nick.lower()))
self.db.db.commit()
return (True, 'Ok')
except Exception as e:
return (False, f'failed to add alias: {e}, {e.__traceback__.tb_lineno}')
# new_fullname is the new 'nick!user@host'
def update_acls(self, who, new_fullname):
self.db.probe()
match_ = who + '!%'
with self.db.db.cursor() as cursor:
try:
cursor.execute('UPDATE acls SET who=%s WHERE who LIKE %s', (new_fullname, match_))
any_upd = cursor.rowcount == 1
cursor.execute('UPDATE acl_groups SET who=%s WHERE who LIKE %s', (new_fullname, match_))
any_upd |= cursor.rowcount == 1
self.db.db.commit()
if any_upd:
return (True, 'Ok')
return (False, 'No such user')
except Exception as e:
return (False, f'irc::update_acls: failed to update acls ({e})')
def group_add(self, who, group):
self.db.probe()
who = self.check_acl_alias(who)
with self.db.db.cursor() as cursor:
try:
cursor.execute('INSERT INTO acl_groups(who, group_name) VALUES(%s, %s)', (who.lower(), group.lower()))
self.db.db.commit()
return (True, 'Ok')
except Exception as e:
return (False, f'irc::group_add: failed to insert group-member ({e})')
def group_del(self, who, group):
self.db.probe()
who = self.check_acl_alias(who)
with self.db.db.cursor() as cursor:
try:
cursor.execute('DELETE FROM acl_groups WHERE who=%s AND group_name=%s LIMIT 1', (who.lower(), group.lower()))
self.db.db.commit()
if cursor.rowcount == 1:
return (True, 'Ok')
return (False, 'That user/group combination was not known')
except Exception as e:
return (False, f'irc::group-del: failed to delete group-member ({e}, {e.__traceback__.tb_lineno})')
def check_user_known(self, user):
if '!' in user:
for cur_user in self.users:
if self.users[cur_user] == user:
return True
return False
if not user in self.users:
return False
if self.users[user] == None or self.users[user] == '?':
return False
return True
def is_group(self, group):
self.db.probe()
with self.db.db.cursor() as cursor:
try:
cursor.execute('SELECT COUNT(*) FROM acl_groups WHERE group_name=%s LIMIT 1', (group.lower(), ))
row = cursor.fetchone()
if row[0] >= 1:
return True
except Exception as e:
send_notice(self.owner, f'irc::is_group: failed to query database for group {group} ({e})')
return False
# e.g. 'group', 'bla' where 'group' is the key and 'bla' the value
def find_key_in_list(self, list_, item, search_start):
try:
idx = list_.index(item, search_start)
# check if an argument is following it
if idx == len(list_) - 1:
idx = None
except ValueError as ve:
idx = None
return idx
def invoke_who_and_wait(self, user):
self.send(f'WHO {user}')
start = time.time()
while self.check_user_known(user) == False:
t_diff = time.time() - start
if t_diff >= 5.0:
break
with self.cond_352:
self.cond_352.wait(5.0 - t_diff)
def list_plugins(self):
self.plugins_lock.acquire()
plugins = ', '.join(sorted(self.plugins))
self.plugins_lock.release()
return plugins
def add_define(self, command, is_alias, arguments):
self.db.probe()
with self.db.db.cursor() as cursor:
try:
cursor.execute('INSERT INTO aliasses(command, is_command, replacement_text) VALUES(%s, %s, %s)', (command.lower(), 1 if is_alias else 0, arguments))
self.db.db.commit()
return (True, cursor.lastrowid, 'Ok')
except Exception as e:
return (False, -1, f'irc::add_define: failed to insert alias ({e})')
def del_define(self, nr):
self.db.probe()
with self.db.db.cursor() as cursor:
try:
cursor.execute('DELETE FROM aliasses WHERE nr=%s', (nr,))
self.db.db.commit()
if cursor.rowcount == 1:
return (True, 'Ok')
return (False, f'irc::del_define: unexpected affected rows count {cursor.rowcount}')
except Exception as e:
return (False, f'irc::del_define: failed to delete alias {nr} ({e})')
def similar_to(self, wrong):
best_score = 1000
best_alternative = '(no suggestion)'
best_score2 = -1000
best_alternative2 = '(no suggestion)'
for command in self.plugins:
current_score = nltk.edit_distance(command, wrong)
current_score2 = difflib.SequenceMatcher(None, command, wrong).ratio()
if current_score < best_score:
best_score = current_score
best_alternative = command
if current_score2 > best_score2:
best_score2 = current_score2
best_alternative2 = command
results = [best_alternative, best_alternative2]
self.db.probe()
with self.db.db.cursor() as cursor:
try:
cursor.execute('select command from aliasses where command sounds like %s', (wrong,))
row = cursor.fetchone()
results.append(row[0])
except Exception as e:
pass
return results
def search_define(self, what):
self.db.probe()
with self.db.db.cursor() as cursor:
try:
cursor.execute('SELECT command, nr, replacement_text FROM aliasses WHERE nr=%s OR command like %s ORDER BY nr DESC', (what, f'%%{what.lower()}%%',))
results = []
for row in cursor:
results.append(row)
if len(results) > 0:
return (results, True, 'Ok')
except Exception as e:
return (None, False, f'irc::del_define: failed to delete alias {nr} ({e})')
return (None, True, 'None')
def escapes(self, text):
if '%R' in text:
text = text.replace('%R', f'{random.randint(0, 100)}')
if '%m' in text:
text = text.strip('%m')
text = '\001ACTION ' + text.strip() + '\001'
return text
def check_aliasses(self, text, username):
parts = text.split(' ')
command = parts[0]
with self.db.db.cursor() as cursor:
cursor.execute('SELECT is_command, replacement_text FROM aliasses WHERE command=%s ORDER BY RAND() LIMIT 1', (command.lower(), ))
row = cursor.fetchone()
if row == None:
return (False, None, False)
is_command = row[0]
repl_text = row[1]
space = text.find(' ')
if space == -1:
query_text = username
if '!' in query_text:
query_text = query_text[0:query_text.find('!')]
else:
query_text = text[space + 1:]
if is_command: # initially only replaces command
text = repl_text + ' ' + query_text
else:
text = repl_text
text = self.escapes(text)
if username != None:
exclamation_mark = username.find('!')
if exclamation_mark != -1:
username = username[0:exclamation_mark]
text = text.replace('%u', username)
text = text.replace('%q', query_text)
notice = False
if '%n' in text:
text = text.replace('%n', '')
notice = True
return (is_command, text, notice)
def invoke_internal_commands(self, prefix, command, splitted_args, channel):
identifier = None
target_type = None
check_user = '(not given)'
if channel == self.nick:
channel = prefix
if '!' in channel:
channel = channel[0:channel.find('!')]
if splitted_args != None and len(splitted_args) >= 2:
if len(splitted_args) >= 3: # addacl
target_type = splitted_args[1]
check_user = splitted_args[2].lower()
else:
target_type = None
check_user = splitted_args[1].lower()
if check_user in self.users:
identifier = self.users[check_user]
elif '!' in check_user:
identifier = check_user
elif self.is_group(check_user):
identifier = check_user
# print(f'identifier {identifier}, user known: {self.check_user_known(identifier)}, is group: {self.is_group(identifier)}')
identifier_is_known = (self.check_user_known(identifier) or self.is_group(identifier)) if identifier != None else False
if command == 'addacl':
group_idx = self.find_key_in_list(splitted_args, 'group', 2)
cmd_idx = self.find_key_in_list(splitted_args, 'cmd', 2)
if not identifier_is_known and target_type == 'user':
self.invoke_who_and_wait(check_user)
if check_user in self.users:
identifier = self.users[check_user]
# print(identifier, check_user, splitted_args)
if group_idx != None:
group_name = splitted_args[group_idx + 1]
rc = self.group_add(identifier, group_name) # who, group
if rc[0]:
self.send_ok(channel, f'User {identifier} added to group {group_name}')
return self.internal_command_rc.HANDLED
else:
self.send_error(channel, rc[1])
return self.internal_command_rc.ERROR
elif cmd_idx != None:
cmd_name = splitted_args[cmd_idx + 1]
self.plugins_lock.acquire()
plugin_known = cmd_name in self.plugins
self.plugins_lock.release()
if plugin_known:
rc = self.add_acl(identifier, cmd_name) # who, command
if rc[0]: # who, command
self.send_ok(channel, f'ACL added for user or group {identifier} for command {cmd_name}')
return self.internal_command_rc.HANDLED
else:
self.send_error(channel, f'Failed to add ACL - did it exist already? ({rc[1]})')
return self.internal_command_rc.ERROR
else:
self.send_error(channel, f'ACL added for user {identifier} for command {cmd_name} NOT added: command/plugin not known')
return self.internal_command_rc.HANDLED
else:
self.send_error(channel, f'Usage: addacl user|group <user|group> group|cmd <group-name|cmd-name>')
return self.internal_command_rc.ERROR
elif command == 'delacl':
group_idx = self.find_key_in_list(splitted_args, 'group', 2)
cmd_idx = self.find_key_in_list(splitted_args, 'cmd', 2)
if not identifier_is_known and target_type == 'user':
self.invoke_who_and_wait(check_user)
if check_user in self.users:
identifier = self.users[check_user]
if group_idx != None:
group_name = splitted_args[group_idx + 1]
rc = self.group_del(identifier, group_name) # who, group
if rc[0]: # who, group
self.send_ok(channel, f'User {identifier} removed from group {group_name}')
return self.internal_command_rc.HANDLED
else:
self.send_error(channel, rc[1])
return self.internal_command_rc.ERROR
elif cmd_idx != None:
cmd_name = splitted_args[cmd_idx + 1]
rc = self.del_acl(identifier, cmd_name) # who, command
if rc[0]: # who, command
self.send_ok(channel, f'ACL removed for user {identifier} for command {cmd_name}')
return self.internal_command_rc.HANDLED
else:
self.send_error(channel, f'Failed to delete ACL ({rc[1]})')
return self.internal_command_rc.ERROR
else:
self.send_error(channel, f'Usage: delacl user <user> group|cmd <group-name|cmd-name>')
return self.internal_command_rc.ERROR
elif command == 'listacls':
if not identifier_is_known:
self.invoke_who_and_wait(check_user)
if check_user in self.users:
identifier = self.users[check_user]
if identifier != None:
acls = self.list_acls(identifier)
str_acls = ', '.join(acls)
self.send_ok(channel, f'ACLs for user {identifier}: "{str_acls}"')
else:
self.send_error(channel, 'Please provide a nick')
return self.internal_command_rc.HANDLED
elif command == 'meet':
if splitted_args != None and len(splitted_args) == 2:
user_to_update = splitted_args[1]
self.invoke_who_and_wait(user_to_update)
if user_to_update in self.users:
ok, error_text = self.update_acls(user_to_update, self.users[user_to_update])
if ok:
self.send_ok(channel, f'User {user_to_update} updated to {self.users[user_to_update]}')
else:
self.send_error(channel, error_text)
else:
self.send_error(channel, f'User {user_to_update} is not known')
else:
self.send_error(channel, f'Meet parameter missing ({splitted_args} given)')
elif command == 'merge':
if splitted_args != None and len(splitted_args) == 3:
new_nick = splitted_args[1].lower()
old_nick = splitted_args[2].lower()
self.invoke_who_and_wait(new_nick)
if new_nick in self.users:
ok, error_text = self.merge_nick(self.users[new_nick], old_nick)
if ok:
self.send_ok(channel, f'Added alias for {old_nick}: {self.users[new_nick]}')
else:
self.send_error(channel, error_text)
else:
self.send_error(channel, f'Merge: user {new_nick} is not known (to be merged with {old_nick})')
else:
self.send_error(channel, f'Meet parameter(s) missing ({splitted_args} given)')
elif command == 'commands':
plugins = self.list_plugins()
self.send_ok(channel, f'Known commands: {plugins}')
return self.internal_command_rc.HANDLED
elif command == 'define' or command == 'alias':
if len(splitted_args) >= 3:
self.plugins_lock.acquire()
plugin_known = splitted_args[1] in self.plugins
self.plugins_lock.release()
if plugin_known:
self.send_error(channel, f'Cannot override internal/plugin commands')
else:
is_alias = command == 'alias'
also_known_as = ' '.join(splitted_args[2:])
if is_alias and also_known_as[0] == '!':
also_known_as = also_known_as[1:]
rc, nr, err = self.add_define(splitted_args[1], is_alias, also_known_as)
if rc == True:
self.send_ok(channel, f'{command} added (number: {nr})')
else:
self.send_error(channel, f'Failed to add {command}: {err}')
else:
self.send_error(channel, f'{command} missing arguments')
elif command == 'searchdefine' or command == 'searchalias':
if len(splitted_args) >= 2:
found, ok, err = self.search_define(splitted_args[1])
if found != None:
defines = None
for entry in found:
if defines == None:
defines = ''
else:
defines += ', '
defines += f'{entry[0]}: {entry[1]}'
self.send_ok(channel, defines)