/
arsenic.py
1565 lines (1184 loc) · 53.4 KB
/
arsenic.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/env pypy
# -*- coding: utf-8 -*-
# pylint: disable=C0103
# pylint: disable=W0702
# pylint: disable=R0912
# pylint: disable=R0915
# pylint: disable=R0914
"""Arsenic development
This is WIP code under active development.
"""
import ConfigParser
import anydbm
import hashlib
import imp
import os
import platform
import sqlite3
import sys
import time
import types
import urllib2
import uuid
import dill as pickle
from twisted.internet import protocol, reactor, ssl
from twisted.python import log
from twisted.words.protocols import irc
import encoder # Local module, can be overridden with mod_load
##################
# Please do not use this code anywhere else unless you know EXACTLY what you're doing
reload(sys)
sys.setdefaultencoding("utf-8")
##################
VER = '1.5.0dev'
class conf(Exception):
"""Automatically generated"""
if len(sys.argv) == 2:
if sys.argv[1].startswith('--config='):
config_dir_tmp = sys.argv[1].split('=', 1)[1]
if config_dir_tmp == '':
raise conf('No path specified')
else:
if not os.path.isdir(config_dir_tmp):
raise conf('config path not found')
else:
if __name__ == '__main__': # testing check
raise SystemExit(1)
raise conf(
'arsenic takes a single argument, --config=/path/to/config/dir')
else:
config_dir_tmp = '.'
config_dir = config_dir_tmp # Unit testing workaround
class configManager(ConfigParser.ConfigParser):
def __init__(self, fd):
ConfigParser.ConfigParser.__init__(self)
self.readfp(fd)
self.fd = fd
def save(self):
self.fd.seek(0) # This mess is required
self.fd.truncate() # otherwise we get in to this weird
self.fd.flush() # situation where we have 2
self.write(self.fd) # configs in one file
self.fd.flush()
def get(self, module, item, default=False):
if self.has_option(module, item):
return ConfigParser.ConfigParser.get(self, module, item)
else:
return default
def set(self, module, item, value):
if not self.has_section(module):
self.add_section(module)
ConfigParser.ConfigParser.set(self, module, item, value)
self.save()
return True
def remove(self, module, item):
if self.has_section(module) and self.has_option(module, item):
self.remove_option(module, item)
self.save()
return True
else:
return False
if __name__ == '__main__': # unit testing support
config = configManager(open(os.path.join(config_dir, 'kgb.conf'), 'r+b'))
else:
config = configManager(open(os.path.join('.', 'kgb.conf'), 'r+b'))
class Profile:
def __init__(self, connector):
self.connector = connector
def __SafeSQL__(self, string): # Practice safe SQL, wear a sanitizer
return ''.join(e for e in string if
e.isalnum() or e == '@' or e == '!' or e == '.' or e == '_' or e == '-' or e == '[' or e == ']' \
or e == '\\' or e == ' ^ ' or e == '`' or e == '{' or e == '}')
def register(self, usermask):
nick = usermask.split('!', 1)[0]
ident = usermask.split('!', 1)[1].split('@', 1)[0]
hostmask = usermask.split('@', 1)[1]
c = self.connector.execute('SELECT * FROM users WHERE nickname = ?', (nick,)) # Check if username exists
if c.fetchone() != None:
return
try:
self.connector.execute('INSERT INTO profile(username) VALUES (?)',
(nick,))
self.connector.execute('INSERT INTO users(username, nickname, ident, hostmask) VALUES (?, ?, ?, ?)',
(nick, nick, ident, hostmask,))
self.connector.commit()
log.msg("Created user %s" % nick)
return usermask
except:
return False
def getuser(self, usermask):
if not usermask:
return False
nick = usermask.split('!', 1)[0]
ident = usermask.split('!', 1)[1].split('@', 1)[0]
hostmask = usermask.split('@', 1)[1]
trusted = True
c = self.connector.execute(
'SELECT * FROM profile WHERE profile.username = (SELECT username FROM users WHERE hostmask = ?)',
(hostmask,))
tmp_u = c.fetchone()
if tmp_u is None:
c = self.connector.execute(
'SELECT * FROM profile WHERE profile.username = (SELECT username FROM users WHERE nickname = ? AND ident = ?)',
(nick, ident,))
tmp_u = c.fetchone()
if tmp_u is None:
c = self.connector.execute(
'SELECT * FROM profile WHERE profile.username = (SELECT username FROM users WHERE nickname = ? OR ident = ?)',
(nick, ident,))
tmp_u = c.fetchone()
if tmp_u is None:
return self.getuser(self.register(usermask))
else:
if debug:
log.msg("Notice: %s not trustable" % (usermask))
trusted = False
u = tmp_u
else:
log.msg("Updating hostmask for " + nick)
self.connector.execute('UPDATE users SET hostmask = ? WHERE nickname = ?', (hostmask, nick,))
self.connector.commit()
return self.getuser(usermask)
else:
u = tmp_u # Turn temp in to actual user info
username = u[0]
old_nick_conn = self.connector.execute('SELECT * FROM users WHERE username = ?', (username,))
old_nick = old_nick_conn.fetchone()[1]
if nick != old_nick:
self.connector.execute('UPDATE users SET nickname = ? WHERE username = ?', (nick, username,))
self.connector.commit()
loc_lat = u[1]
loc_lng = u[2]
if u[3] is not None:
if u[3] == 0:
unit = 'us'
elif u[3] == 1:
unit = 'si'
elif u[3] == 2:
unit = 'ca'
elif u[3] == 3:
unit = 'uk2'
else:
unit = 'us'
else:
unit = 'us'
if u[4] == 0:
gender = False
elif u[4] == 1:
gender = True
else:
gender = None
height = u[5] # cm
weight = u[6] # kg
if u[7] == 1:
privacy = True
else:
privacy = False
if u[8] == 1:
isverified = True
else:
isverified = False
if u[9] == 1 and trusted:
isop = True
else:
isop = False
class user:
def __init__(self):
pass
setattr(user, 'username', username)
setattr(user, 'nickname', nick)
setattr(user, 'ident', ident)
setattr(user, 'hostname', hostmask)
setattr(user, 'userhost', usermask)
setattr(user, 'lat', loc_lat)
setattr(user, 'lon', loc_lng)
setattr(user, 'unit', unit)
setattr(user, 'gender', gender)
setattr(user, 'height', height)
setattr(user, 'weight', weight)
setattr(user, 'privacy', privacy)
setattr(user, 'isverified', isverified)
setattr(user, 'isop', isop)
setattr(user, 'trusted', trusted)
return user
def getuser_byname(self, username): # Caution, user not authenticated
c = self.connector.execute('SELECT * FROM users WHERE username = ?', (username,))
u = c.fetchone()
if u:
return self.getuser('%s!%s@%s' % (u[1], u[2], u[3]))
else:
return False
def getuser_bynick(self, nickname): # Caution, user not authenticated
c = self.connector.execute('SELECT * FROM users WHERE nickname = ?', (nickname,))
u = c.fetchone()
if u:
return self.getuser('%s!%s@%s' % (u[1], u[2], u[3]))
else:
return False
def update(self, username, nickname=None, ident=None, hostname=None, lat=None, lon=None, unit=None, gender=None,
height=None, weight=None, privacy=None, isverified=None, isop=None):
if not self.getuser_byname(username):
return False
sql_str = 'update profile set'
sql_user_str = 'update user set'
if nickname is not None:
sql_user_str += ' nickname = "%s", ' % (self.__SafeSQL__(nickname))
if ident is not None:
sql_user_str += ' ident = "%s", ' % (self.__SafeSQL__(ident))
if hostname is not None:
sql_user_str += ' hostname = "%s", ' % (self.__SafeSQL__(hostname))
if lat is not None:
try:
lat = float(lat) # Check if valid number
sql_str += ' loc_lat = "%s", ' % lat
except:
log.msg("Error, could not turn lat in to float")
return False
if lon is not None:
try:
lon = float(lon) # Check if valid number
sql_str += ' loc_lng = "%s", ' % lon
except:
log.msg("Error, could not turn lon in to float")
return False
if unit is not None:
if unit is 'auto':
value = None
elif unit == 'us':
value = 0
elif unit == 'si':
value = 1
elif unit == 'ca':
value = 2
elif unit == 'uk2':
value = 3
else:
return False
log.msg("Incorrect unit supplied")
sql_str += ' unit = "%s", ' % value # 5 choices means no sql issues
if gender is not None:
if gender:
gender = 1 # M
else:
gender = 0 # F
sql_str += ' gender = "%s", ' % (gender)
if height is not None:
try:
height = float(height) # Check if valid number
sql_str += ' height = "%s", ' % height
except:
log.msg("Error, could not turn height in to float")
return False
if weight is not None:
try:
weight = float(weight) # Check if valid number
sql_str += ' weight = "%s", ' % weight
except:
log.msg("Error, could not turn weight in to float")
return False
if privacy is not None:
if privacy:
privacy = 1
else:
privacy = 0
sql_str += ' privacy = "%s", ' % (privacy)
if isverified is not None:
if isverified:
isverified = 1
else:
isverified = 0
sql_str += ' isverified = "%s", ' % (isverified)
if isop is not None:
if isop:
isop = 1
else:
isop = 0
sql_str += ' isop = "%s", ' % (isop)
if '=' in sql_str:
sql_str = '%s where username = "%s";' % (sql_str[0:len(sql_str) - 2], self.__SafeSQL__(username))
self.connector.execute(sql_str)
if '=' in sql_user_str:
sql_user_str = '%s where username = "%s";' % (
sql_user_str[0:len(sql_user_str) - 2], self.__SafeSQL__(username))
self.connector.execute(sql_user_str)
try:
self.connector.commit()
return True
except:
log.msg("Unable to commit profile changes, does the user exist?")
return False
def set_password(self, username, password):
pw = hashlib.sha512(username + password + salt).hexdigest()
self.connector.execute('UPDATE profile SET password = ? WHERE username = ?', (pw, username,))
self.connector.commit()
def check_if_password(self, username):
c = self.connector.execute('SELECT password FROM profile WHERE username = ?', (username,))
pw = c.fetchone()[0]
if pw:
return True
else:
return False
def validate_password(self, username, password):
new_pw = hashlib.sha512(username + password + salt).hexdigest()
c = self.connector.execute('SELECT password FROM profile WHERE username = ?', (username,))
old_pw = c.fetchone()[0]
if new_pw == old_pw:
return True
else:
return False
def link(self, username, password, nickname):
if self.validate_password(username, password):
self.connector.execute('UPDATE users SET username = ? WHERE nickname = ?', (username, nickname,))
self.connector.commit()
return True
else:
return False
def save():
clist = ''
slist = ''
for i in channel_list:
clist = '%s, %s' % (clist, i)
if clist[0] != '#':
clist = clist[2:]
try: # silent catched error if not syncing
for i in sync_channels:
slist = '%s,%s>%s' % (slist, i, sync_channels[i])
if slist[0] != '#':
slist = slist[1:]
config.set('main', 'sync_channel', slist)
except:
pass
config.set('main', 'channel', clist)
config.save()
def checkauth(user):
"""Checks if hostmask is bot op"""
user_host = user.split('!', 1)[1]
try: # needed for non message op commands
c = conn.execute(
'SELECT * FROM op WHERE username = ?', (user_host,))
except:
c = None
if c is not None:
# for user in oplist: #disabled as this is a major DoS
# if user.startswith('!'):
# oplist.remove(user)
# oplist.add(encoder.decode(user))
if user_host in oplist:
return True
elif c.fetchone() is not None:
return True
else:
return False
else:
if user_host in oplist:
return True
else:
return False
def checkowner(user):
"""Checks if hostmask is bot owner"""
user_host = user.split('!', 1)[1]
if user_host in ownerlist:
return True
else:
return False
class Arsenic(irc.IRCClient):
"""Twisted callbacks registered here"""
def __init__(self, profileManager, cache_fd, extra=False, unittest=False):
self.profileManager = profileManager
self.__extra__ = extra
self.unittest = unittest
self.cache_fd = cache_fd
if extra:
self.msg = extra.msg
if unittest:
log.msg("################## [RUNNING IN TEST MODE] ####################")
global key # unit testing hacks
global ownerlist
global mod_declare_privmsg
global mod_declare_userjoin
global mod_declare_syncmsg
global modlook
global irc_relay
global channel_list
global updateconfig
global config_dir
key = unittest.key
ownerlist = unittest.ownerlist
mod_declare_privmsg = unittest.mod_declare_privmsg
mod_declare_userjoin = unittest.mod_declare_userjoin
mod_declare_syncmsg = unittest.mod_declare_syncmsg
modlook = unittest.modlook
irc_relay = ""
channel_list = unittest.channel_list
updateconfig = unittest.updateconfig
config_dir = '.'
irc.IRCClient = unittest
return
class persist:
def __init__(self):
pass
save = persist()
lockerbox = {}
floodprotect = False
versionName = 'KittyHawk'
versionNum = VER
versionEnv = platform.platform()
sourceURL = "https://github.com/KittyHawkIRC"
def ctcp(self, data):
data = data.strip('\x01')
if data.startswith('CLIENTINFO'):
return [('CLIENTINFO', 'ACTION CLIENTINFO PING SOURCE TIME VERSION')]
elif data.startswith('VERSION'):
return [('VERSION', '%s %s (%s)' % (self.versionName, self.versionNum, self.versionEnv))]
elif data.startswith('PING'):
return [('PING', data.split(' ', 1)[1])]
elif data.startswith('SOURCE'):
return [('SOURCE', self.sourceURL)]
elif data.startswith('TIME'):
return [('TIME', time.ctime())]
elif data.startswith('ACTION'):
return None
else:
return [('ERRMSG', '%s :unknown query' % (data))]
nickname = config.get('main', 'name')
# Joins channels on invite
autoinvite = config.getboolean('main', 'autoinvite')
def join(self, channel): # hijack superclass join
if not channel in channel_list:
channel_list.append(channel)
if updateconfig: # Save file every join call
save()
irc.IRCClient.join(self, channel)
def sendLine(self, line):
irc.IRCClient.sendLine(self, line)
def leave(self, channel): # hijacks superclass leave
if channel in channel_list:
channel_list.remove(channel)
if updateconfig: # Save file every leave call
save()
irc.IRCClient.leave(self, channel)
def msg(self, user, message, length=None): # hijacks superclass msg for unicode support
irc.IRCClient.msg(self, user, message.encode('UTF-8'), length=None)
def cache_reopen(self):
self.cache_fd.close()
self.cache_fd = anydbm.open(cache_name, 'c')
def cache_save_all(self):
for item in self.lockerbox:
self.cache_fd[item] = pickle.dumps(self.lockerbox[item])
self.cache_reopen()
def __cache_save__(self, item): # save 1 item to reduce overhead
if not self.unittest:
self.cache_fd[item] = pickle.dumps(self.lockerbox[item])
self.cache_reopen()
return True
def cache_load(self):
# In theory, this should work
for item in cache_fd.keys():
try:
self.lockerbox[item] = pickle.loads(self.cache_fd[item])
except:
log.msg("Error loading cache: " + item)
def cache_status(self):
if cache_state == 1:
self.msg(self.channel, 'Cache loaded correctly (%s)' % cache_name)
elif cache_state == 2:
self.msg(self.channel, 'Cache loaded read only (%s)' % cache_name)
elif cache_state == 3:
self.msg(self.channel, 'A new cache was created (%s)' % cache_name)
elif cache_state == 0:
self.msg(self.channel, 'Unable to load cache entirely (%s)' % cache_name)
def connectionMade(self):
irc.IRCClient.connectionMade(self)
self.msg('NickServ', 'identify ' + self.factory.nspassword)
def connectionLost(self, reason):
irc.IRCClient.connectionLost(self, reason)
# callbacks for events
def signedOn(self):
nickname = config.get('main', 'nickname')
if nickname:
self.nickname = nickname
self.setNick(nickname)
for i in channel_list:
self.join(i)
self.cache_load() # load cached lockerbox
def kickedFrom(self, channel, user, message):
time.sleep(3)
self.join(channel)
del user
def syncmsg(self, cbuser, inchannel, outchannel, msg):
setattr(self, 'type', 'syncmsg')
setattr(self, 'message', msg)
setattr(self, 'user', self.profileManager.getuser(cbuser))
setattr(self, 'incoming_channel', inchannel)
setattr(self, 'outgoing_channel', outchannel)
setattr(self, 'ver', VER)
setattr(self, 'store', save)
##### Hijack config object functions to reduce scope
def __config_get__(item, default=False): # stubs, basically
return config.get(mod_declare_privmsg[command], item, default)
def __config_set__(item, value):
return config.set(mod_declare_privmsg[command], item, value)
def __config_remove__(item):
return config_remove(mod_declare_privmsg[command], item)
setattr(self, 'config_get', __config_get__)
setattr(self, 'config_set', __config_set__)
setattr(self, 'config_remove', __config_remove__)
for command in mod_declare_syncmsg:
try:
self.lockerbox[command]
except:
self.lockerbox[command] = self.persist()
setattr(self, 'locker', self.lockerbox[command])
modlook[
mod_declare_syncmsg[command]].callback(
self)
def userJoined(self, cbuser, cbchannel):
setattr(self, 'type', 'userjoin')
if cbuser != self.nickname:
setattr(self, 'profile', self.profileManager.getuser_bynick(cbuser))
setattr(self, 'channel', cbchannel)
setattr(self, 'ver', VER)
##### Hijack config object functions to reduce scope
for command in mod_declare_userjoin:
modlook[
mod_declare_userjoin[command]].callback(
self)
def search(self, query):
q = ''.join(('%', query, '%')).replace(' ', '%').decode('utf-8')
c = conn.execute(
"SELECT name, response, (CASE WHEN name LIKE ? THEN 0 ELSE 1 END) keyfirst \
FROM command \
WHERE name LIKE ? OR response LIKE ? \
ORDER BY keyfirst, CASE WHEN name LIKE ? AND response LIKE ? THEN 0 ELSE 1 END, name", (q, q, q, q, q,))
queryList = c.fetchmany(20) # list of tuples
prettyList = {} # A dict, as nature intended
cut = 750 / (len(queryList) + 1) # Try to sanely adjust output size based on query
if queryList == []:
return 'Error, 0 results found'
for tup in queryList:
prettyList[tup[0]] = tup[1][:cut] + (tup[1][cut:] and '..')
output = ''
for i in prettyList:
output = key + '%s: %s | %s' % (i, prettyList[i], output)
output = output[:len(output) - 5]
return output
def privmsg(self, user, channel, msg):
if not channel.startswith('#'):
channel = self.nickname
if msg.startswith('\x01') and msg.endswith('\x01'):
reply = self.ctcp(msg)
if reply:
self.ctcpMakeReply(user.split('!', 1)[0], reply)
return
profile = self.profileManager.getuser(user)
auth = profile.isop
owner = checkowner(user) # Config file set value
# Start module execution
command = msg.split(' ', 1)[0].lower()
if type(channel) == 'str':
lower_channel = channel.lower()
if lower_channel in sync_channels: # syncing
u = profile.nickname
self.msg(sync_channels[lower_channel], '<%s> %s' % (u, msg))
self.syncmsg(user, lower_channel,
sync_channels[lower_channel], msg)
iskey = False
if command.startswith(key):
command = command.split(key, 1)[1]
iskey = True
else:
command = command
if iskey or (channel == self.nickname and (
auth or command == 'set_password' or command == 'change_password' or command == 'link')):
setattr(self, 'isop', auth)
setattr(self, 'isowner', owner)
setattr(self, 'type', 'privmsg')
setattr(self, 'command', command)
setattr(self, 'message', msg)
setattr(self, 'user', user) # This will change to a profile object soon!
setattr(self, 'channel', channel)
setattr(self, 'ver', VER)
setattr(self, 'profile', profile) # Provide profile support to modules (temporary!)
if command in mod_declare_privmsg:
try:
self.lockerbox[mod_declare_privmsg[command]]
except:
self.lockerbox[mod_declare_privmsg[
command]] = self.persist()
# attributes
setattr(self, 'store', save)
setattr(self, 'locker', self.lockerbox[
mod_declare_privmsg[command]])
##### Hijack config object functions to reduce scope
def __config_get__(item, default=False): # stubs, basically
return config.get(mod_declare_privmsg[command], item, default)
def __config_set__(item, value):
return config.set(mod_declare_privmsg[command], item, value)
def __config_remove__(item):
return config_remove(mod_declare_privmsg[command], item)
setattr(self, 'config_get', __config_get__)
setattr(self, 'config_set', __config_set__)
setattr(self, 'config_remove', __config_remove__)
def __nest_cache_save__(self): # Nested cache save, yolo?
return self.__cache_save__(mod_declare_privmsg[command])
setattr(self, 'cache_save', __nest_cache_save__)
log_data = "Command: %s, user: %s, channel: %s, data: %s" % (
command, user, channel, msg)
log.msg(log_data)
u = user.split('!', 1)[0]
if channel == self.nickname:
# private commands
if irc_relay != "":
self.msg(irc_relay, user + " said " + msg)
if owner:
if command == 'op':
op = self.profileManager.getuser_byname(msg.split()[1])
if op: # Check if profile exists
if not op.isop: # Make sure the user isn't already an op
self.profileManager.update(op, isop=True)
self.msg(self.profile.nickname, 'Successfully made %s a bot operator!' % (op.nickname))
self.msg(op.nickname, "You're now a bot operator! Message me help for commands.")
else:
self.msg(self.profile.nickname, '%s is already an operator.' % (op.nickname))
else:
self.msg(self.profile.nickname, 'Error, no user was found.')
elif command == 'deop':
op = self.profileManager.getuser_byname(msg.split()[1])
if op: # Check if profile exists
if op.isop: # Make sure the user is an op
self.profileManager.update(op, isop=False)
self.msg(self.profile.nickname, 'Bot operator status removed from %s.' % (op.nickname))
else:
self.msg(self.profile.nickname, '%s is not an operator.' % (op.nickname))
else:
self.msg(self.profile.nickname, 'Error, no user was found.')
elif command == 'mod_inject':
mod = msg.split(' ')[1]
url = msg.split(' ')[2]
req = urllib2.Request(
url, headers={'User-Agent': 'UNIX:KittyHawk http://github.com/KittyHawkIRC'})
fd = urllib2.urlopen(req)
mod_src = open(
config_dir + '/modules/' + mod + '.py', 'w')
data = fd.read()
mod_src.write(data)
os.fsync(mod_src)
fd.close()
mod_src.close()
elif command == 'mod_load':
mod = msg.split(' ')[1]
mod_src = open(config_dir + '/modules/' + mod + '.py')
mod_bytecode = compile(
mod_src.read().replace(u"\u2018", "").replace(u"\u2019", "").replace(u"\u201c",
"").replace(
u"\u201d", ""), '<string>', 'exec')
mod_src.close()
modlook[mod] = imp.new_module(mod)
sys.modules[mod] = modlook[mod]
exec mod_bytecode in modlook[mod].__dict__
declare_table = modlook[mod].declare()
for i in declare_table:
cmd_check = declare_table[i]
if cmd_check == 'privmsg':
mod_declare_privmsg[i] = mod
elif cmd_check == 'userjoin':
mod_declare_userjoin[i] = mod
elif cmd_check == 'syncmsg':
mod_declare_syncmsg[i] = mod
elif command == 'update_inject':
try:
url = msg.split(' ')[1]
except:
url = 'https://raw.githubusercontent.com/KittyHawkIRC/core/master/arsenic.py'
req = urllib2.Request(
url, headers={'User-Agent': 'UNIX:KittyHawk http://github.com/KittyHawkIRC'})
fd = urllib2.urlopen(req)
mod_src = open(sys.argv[0], 'w')
data = fd.read()
mod_src.write(data)
os.fsync(mod_src)
fd.close()
mod_src.close()
elif command == 'update_restart':
try:
self.cache_reopen()
mod_src = open(sys.argv[0])
compile(mod_src.read(), '<string>',
'exec') # syntax testing
args = sys.argv[:]
args.insert(0, sys.executable)
# os.chdir(_startup_cwd)
os.execv(sys.executable, args)
except:
self.msg(u, 'Syntax error!')
elif command == 'update_patch':
self.msg(u, 'Starting patch')
log.msg('Starting runtime patching!')
mod_src = open(sys.argv[0])
mod_bytecode = compile(
mod_src.read(), '<string>', 'exec')
mod_src.close()
self.msg(u, 'Bytecode compiled, starting runtime patch')
log.msg('Arsenic bytecode compiled, attempting patching')
runtime_patch(mod_bytecode)
self.msg(u, 'KittyHawk updated to VER %s' % VER)
elif command == 'inject':
self.lineReceived(msg.split(' ', 1)[1])
elif command == 'raw':
self.sendLine(msg.split(' ', 1)[1])
elif command == 'config_get':
opts = msg.split()
module = opts[1]
item = opts[2]
self.msg(u, str(config.get(module, item, False)))
elif command == 'config_set':
opts = msg.split()
module = opts[1]
item = opts[2]
value_list = opts[3:]
value = ''
for i in value_list:
value += i + ' '
self.msg(u, str(config.set(module, item, value[:len(value) - 1])))
elif command == 'config_remove':
opts = msg.split()
module = opts[1]
item = opts[2]
self.msg(u, str(config_remove(module, item)))
elif command == 'config_list':
opts = msg.split()
module = opts[1]
if config.has_section(module):
self.msg(u, str(config.options(module)))