-
Notifications
You must be signed in to change notification settings - Fork 0
/
BlackSmith.py
1421 lines (1261 loc) · 43 KB
/
BlackSmith.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 python
# -*- coding: utf-8 -*-
# BlackSmith Bot Core
# BlackSmith.py
# Als [Als@exploit.in]
# Evgen [meb81@mail.ru]
# dimichxp [dimichxp@gmail.com]
# mrDoctorWhо [mrdoctorwho@gmail.com]
# Boris Kotov [admin@avoozl.ru]
# Mike Mintz [mikemintz@gmail.com]
# WitcherGeralt [WitcherGeralt@rocketmail.com]
# By WitcherGeralt, based on Talisman by Als (Neutron by Gh0st)
################ import modules ################################################################
from __future__ import with_statement
from traceback import format_exc as error_, print_exc as Print_Error
import sys, os, gc, time, types, threading, os.path
from glob import glob
os.chdir(os.path.dirname(__file__))
sys.path.append("modules")
from enconf import *; from hammer import *
import xmpp, macros, simplejson, re, string, random, urllib, urllib2, smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders
################ Statistics cache ##############################################################
INFO = {'start': 0, 'msg': 0, 'prs': 0, 'iq': 0, 'cmd': 0, 'thr': 0, 'errs': 0}
INFA = {'outmsg': 0, 'outiq': 0, 'fr': 0, 'fw': 0, 'fcr': 0, 'cfw': 0}
RSTR = {'AUTH': [], 'BAN': [], 'VN': 'off'}
STOP = {'mto': 0, 'jids': {}}
DCNT = {'col': 0, 'Yes!': True}
LAST = {'time': 0, 'null': 0, 'cmd': 'start'}
################ friendly handlers #############################################################
if os.environ.has_key("TERM"):
COLORS_ENABLED = True
else:
COLORS_ENABLED = False
color0 = chr(27)+"[0m"
color1 = chr(27)+"[33m"
color2 = chr(27)+"[31;1m"
color3 = chr(27)+"[32m"
color4 = chr(27)+"[34;1m"
def retry_body(x, y):
try:
body, color = unicode(x), y
except:
body, color = x, False
return (body, color)
def text_color(text, color):
if COLORS_ENABLED:
text = color+text+color0
return text
def Print(text, color = False):
try:
if color:
text = text_color(text, color)
print text
except:
LAST['null'] += 1
def try_sleep(slp):
try:
time.sleep(slp)
except KeyboardInterrupt:
os._exit(0)
except:
LAST['null'] += 1
def Exit(text, exit, slp):
Print(text, color2); try_sleep(slp)
if exit:
os._exit(0)
else:
os.execl(sys.executable, sys.executable, os.path.abspath(sys.argv[0]))
################ Configuration Items ###########################################################
GENERAL_CONFIG_FILE = 'static/source.py'
GLOBACCESS_FILE = 'dynamic/access.txt'
GROUPCHATS_FILE = 'dynamic/chats.txt'
QUESTIONS_FILE = 'static/veron.txt'
ROSTER_FILE = 'dynamic/roster.txt'
PLUGIN_DIR = 'plugins'
PID_FILE = 'PID.txt'
BOT_OS, BOT_PID = os.name, os.getpid()
if BOT_OS == 'nt':
os.system('COLOR 0C')
def PASS_GENERATOR(codename, col):
symbols = '0123456789%s._(!}{#)' % (string.letters)
for x in range(0, col):
codename += random.choice(symbols)
return codename
try:
GENERAL_CONFIG = file(GENERAL_CONFIG_FILE)
exec GENERAL_CONFIG in globals()
GENERAL_CONFIG.close()
except:
Exit('\n\nError: unable to read general config file!', 1, 30)
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except:
Print('\n\nError: can`t set default encoding!', color2)
try:
execfile('static/versions.py')
except:
Exit('\n\nError: verfile (versions.py) isn`t exists!', 1, 30)
if BOT_OS == 'nt':
os.system('Title BlackSmith - %s' % (Caps))
DEFAULT_NICK = DEFAULT_NICK_(DEFAULT_NICK)
MEMORY_LIMIT = MEMORY_LIMIT_(MEMORY_LIMIT)
################ lists handlers ################################################################
MESSAGE_HANDLERS = []
OUTGOING_MESSAGE_HANDLERS = []
JOIN_HANDLERS = []
LEAVE_HANDLERS = []
IQ_HANDLERS = []
PRESENCE_HANDLERS = []
COMMAND_HANDLERS = {}
STAGE0_INIT = []
STAGE1_INIT = []
STAGE2_INIT = []
STAGE3_INIT = []
################ lists & client & others #######################################################
MACROS = macros.Macros()
ONLINE = False
online = lambda cl: cl.isConnected()
ADLIST = []
ANSWER = {}
PREFIX = {}
STATUS = {}
ERRORS = {}
COMMOFF = {}
COMMSTAT = {}
COMMANDS = {}
RUNTIMES = {}
BOT_NICKS = {}
QUESTIONS = {}
ACCBYCONF = {}
CONFACCESS = {}
GLOBACCESS = {}
GROUPCHATS = {}
UNAVALABLE = []
(JCON, ROSTER) = (None, False)
smph = threading.BoundedSemaphore(value = 100)
mtx = threading.Lock()
wsmph = threading.BoundedSemaphore(value = 1)
################ file work handlers ############################################################
def check_file(conf = None, file = "", data = ""):
if conf:
filename = 'dynamic/%s/%s' % (conf, file)
if not check_nosimbols(filename):
filename = encode_filename(filename)
else:
filename = 'dynamic/%s' % (file)
return initialize_file(filename, data)
def initialize_file(filename, data = ""):
if len(filename.split('/')) >= 4:
return False
if os.path.exists(filename):
return True
try:
folder = os.path.dirname(filename)
if folder and not os.path.exists(folder):
os.mkdir(folder, 0755)
if os.access(filename, os.F_OK):
fl = file(filename, 'w')
else:
fl = open(filename, 'w')
INFA['fcr'] += 1
if not data:
data = '{}'
fl.write(data)
fl.close()
except:
return False
return True
def read_file(filename):
if filename.count('/') > 1:
if not check_nosimbols(filename):
filename = encode_filename(filename)
fl = file(filename, 'r')
INFA['fr'] += 1
data = fl.read()
fl.close()
return data
def file_add(filename, data):
if filename.count('/') > 1:
if not check_nosimbols(filename):
filename = encode_filename(filename)
try:
fl = file(filename, 'a')
INFA['fw'] += 1
fl.write(data)
fl.close()
except:
LAST['null'] += 1
def write_file(filename, data):
if filename.count('/') > 1:
if not check_nosimbols(filename):
filename = encode_filename(filename)
with wsmph:
mtx.acquire()
try:
fl = file(filename, 'w')
INFA['fw'] += 1
fl.write(data)
fl.close()
finally:
mtx.release()
################ lytic crashlog ################################################################
def Dispatch_fail():
crashfile = file('__main__.crash', 'a')
Print_Error(limit = None, file = crashfile)
crashfile.close()
def lytic_crashlog(handler, command = None):
DIR, handler, Number, error_body = "feillog", handler.func_name, (len(ERRORS.keys()) + 1), error_()
ERRORS[Number] = error_body
if ONLINE:
if command:
error = u'команды "%s" (%s)' % (command, handler)
else:
error = u'процесса "%s"' % (handler)
delivery(u'При выполнении %s --> произошла ошибка!' % (error))
else:
Print('\n\nError: can`t execut "%s"!' % (handler), color2)
filename = (DIR+'/error[%s]%s.crash') % (str(INFA['cfw'] + 1), time.strftime('[%H.%M.%S][%d.%m.%Y]', time.localtime()))
try:
if not os.path.exists(DIR):
os.mkdir(DIR, 0755)
crashfile = file(filename, 'w')
INFA['cfw'] += 1
Print_Error(limit = None, file = crashfile)
crashfile.close()
if ONLINE:
if BOT_OS == 'nt':
delivery(u'Ошибку смотри по команде --> "ошибка %s" (Крэшфайл --> %s)' % (str(Number), filename))
else:
delivery(u'Ошибку смотри по командам --> "ошибка %s", "sh cat %s"' % (str(Number), filename))
else:
Print('\n\nCrash file --> %s\nError number --> %s' % (filename, str(Number)), color2)
except:
Print_Error()
if ONLINE:
delivery(error_body)
else:
(body, color) = retry_body(error_body, color2)
Print(body, color)
################ list handlers #################################################################
def register_message_handler(instance):
name = instance.func_name
for handler in MESSAGE_HANDLERS:
if name == handler.func_name:
MESSAGE_HANDLERS.remove(handler)
MESSAGE_HANDLERS.append(instance)
def register_outgoing_message_handler(instance):
name = instance.func_name
for handler in OUTGOING_MESSAGE_HANDLERS:
if name == handler.func_name:
OUTGOING_MESSAGE_HANDLERS.remove(handler)
OUTGOING_MESSAGE_HANDLERS.append(instance)
def register_join_handler(instance):
name = instance.func_name
for handler in JOIN_HANDLERS:
if name == handler.func_name:
JOIN_HANDLERS.remove(handler)
JOIN_HANDLERS.append(instance)
def register_leave_handler(instance):
name = instance.func_name
for handler in LEAVE_HANDLERS:
if name == handler.func_name:
LEAVE_HANDLERS.remove(handler)
LEAVE_HANDLERS.append(instance)
def register_iq_handler(instance):
name = instance.func_name
for handler in IQ_HANDLERS:
if name == handler.func_name:
IQ_HANDLERS.remove(handler)
IQ_HANDLERS.append(instance)
def register_presence_handler(instance):
name = instance.func_name
for handler in PRESENCE_HANDLERS:
if name == handler.func_name:
PRESENCE_HANDLERS.remove(handler)
PRESENCE_HANDLERS.append(instance)
def register_stage0_init(instance):
name = instance.func_name
for handler in STAGE0_INIT:
if name == handler.func_name:
STAGE0_INIT.remove(handler)
STAGE0_INIT.append(instance)
def register_stage1_init(instance):
name = instance.func_name
for handler in STAGE1_INIT:
if name == handler.func_name:
STAGE1_INIT.remove(handler)
STAGE1_INIT.append(instance)
def register_stage2_init(instance):
name = instance.func_name
for handler in STAGE2_INIT:
if name == handler.func_name:
STAGE2_INIT.remove(handler)
STAGE2_INIT.append(instance)
def register_stage3_init(instance):
name = instance.func_name
for handler in STAGE3_INIT:
if name == handler.func_name:
STAGE3_INIT.remove(handler)
STAGE3_INIT.append(instance)
def register_command_handler(instance, command, category = [], access = 0, desc = None, syntax = None, examples = []):
command = command.decode('utf-8')
if not COMMSTAT.has_key(command):
COMMSTAT[command] = {'col': 0, 'users': []}
COMMAND_HANDLERS[command] = instance
COMMANDS[command] = {'category': category, 'access': access, 'desc': desc, 'syntax': syntax, 'examples': examples}
################ call & execut handlers ########################################################
def ThreadError():
return (str(sys.exc_info()[1]) == "can't start new thread")
def Try_Thr(Thread, number = 0):
if number >= 4:
raise RuntimeError, 'Thread try limit!'
try:
Thread.start()
except:
Try_Thr(Thread, (number + 1))
def Thread_Run(Thread, handler, command = None):
try:
Thread.start()
except:
if ThreadError():
try:
Try_Thr(Thread)
except RuntimeError:
try:
Thread.run()
except:
lytic_crashlog(handler, command)
else:
lytic_crashlog(Thread_Run, command)
def execute_message_handler(message_handler, raw, type, source, body):
try:
message_handler(raw, type, source, body)
except:
lytic_crashlog(message_handler)
def call_message_handlers(raw, type, source, body):
for handler in MESSAGE_HANDLERS:
with smph:
INFO['thr'] += 1
Thread = threading.Thread(None, execute_message_handler, 'inmsg-%d' % (INFO['thr']),(handler, raw, type, source, body,))
Thread_Run(Thread, handler)
def execute_outmsg_handler(outgoing_message_handler, target, body, obody):
try:
outgoing_message_handler(target, body, obody)
except:
lytic_crashlog(outgoing_message_handler)
def call_outgoing_message_handlers(target, body, obody):
for handler in OUTGOING_MESSAGE_HANDLERS:
with smph:
INFO['thr'] += 1
Thread = threading.Thread(None, execute_outmsg_handler, 'outmsg-%d' % (INFO['thr']),(handler, target, body, obody,))
Thread_Run(Thread, handler)
def execute_join_handler(join_handler, conf, nick, afl, role):
try:
join_handler(conf, nick, afl, role)
except:
lytic_crashlog(join_handler)
def call_join_handlers(conf, nick, afl, role):
for handler in JOIN_HANDLERS:
with smph:
INFO['thr'] += 1
Thread = threading.Thread(None, execute_join_handler, 'join-%d' % (INFO['thr']),(handler, conf, nick, afl, role,))
Thread_Run(Thread, handler)
def execute_leave_handler(leave_handler, conf, nick, reason, code):
try:
leave_handler(conf, nick, reason, code)
except:
lytic_crashlog(leave_handler)
def call_leave_handlers(conf, nick, reason, code):
for handler in LEAVE_HANDLERS:
with smph:
INFO['thr'] += 1
Thread = threading.Thread(None, execute_leave_handler, 'leave-%d' % (INFO['thr']),(handler, conf, nick, reason, code,))
Thread_Run(Thread, handler)
def execute_iq_handler(iq_handler, iq):
try:
iq_handler(iq)
except:
lytic_crashlog(iq_handler)
def call_iq_handlers(iq):
for handler in IQ_HANDLERS:
with smph:
INFO['thr'] += 1
Thread = threading.Thread(None, execute_iq_handler, 'iq-%d' % (INFO['thr']),(handler, iq,))
Thread_Run(Thread, handler)
def execute_presence_handler(presence_handler, prs):
try:
presence_handler(prs)
except:
lytic_crashlog(presence_handler)
def call_presence_handlers(prs):
for handler in PRESENCE_HANDLERS:
with smph:
INFO['thr'] += 1
Thread = threading.Thread(None, execute_presence_handler, 'prs-%d' % (INFO['thr']),(handler, prs,))
Thread_Run(Thread, handler)
def execut_stage_init(stage_handler, conf = None):
try:
if conf:
stage_handler(conf)
else:
stage_handler()
except:
lytic_crashlog(stage_handler)
def call_stage0_init():
for handler in STAGE0_INIT:
execut_stage_init(handler)
def call_stage1_init(conf):
for handler in STAGE1_INIT:
execut_stage_init(handler, conf)
def call_stage2_init():
for handler in STAGE2_INIT:
execut_stage_init(handler)
def call_stage3_init():
for handler in STAGE3_INIT:
execut_stage_init(handler)
def execute_command_handler(commnad_handler, command, type, source, body):
try:
commnad_handler(type, source, body)
except:
lytic_crashlog(commnad_handler, command)
def call_command_handlers(command, type, source, body, callee):
real_access = MACROS.get_access(callee, source[1])
if real_access <= 0:
real_access = COMMANDS[command]['access']
if COMMAND_HANDLERS.has_key(command):
if has_access(source[0], real_access, source[1]):
with smph:
handler = COMMAND_HANDLERS[command]
INFO['thr'] += 1
Thread = threading.Thread(None, execute_command_handler, 'command-%d' % (INFO['thr']),(handler, command, type, source, body,))
Thread_Run(Thread, handler, command)
COMMSTAT[command]['col'] += 1
jid = handler_jid(source[0])
if jid not in COMMSTAT[command]['users']:
COMMSTAT[command]['users'].append(jid)
else:
reply(type, source, u'недостаточный доступ')
################ load pugins ###################################################################
def load_plugins():
Print('\n\nLOADING PLUGINS:', color4)
ltc, tal, Npl = [], [], []
for Plugin in os.listdir(PLUGIN_DIR):
Ext = Plugin[-3:].lower()
if Ext == '.py':
filename = '%s/%s' % (PLUGIN_DIR, Plugin)
try:
data = file(filename).read(20)
except:
data = '# |-| levaya shnyaga |-|'
Plug = Plugin.split('_pl')
if data.count('lytic'):
try:
execfile(filename, globals()); ltc.append(Plug[0])
except:
Npl.append(Plug[0])
elif data.count('talis'):
try:
execfile(filename, globals()); tal.append(Plug[0])
except:
Npl.append(Plug[0])
else:
Npl.append(Plug[0])
if ltc:
lts = ', '.join(sorted(ltc))
Print(('\n\nLoaded %d BlackSmith plugins:\n' % len(ltc))+lts, color3)
if tal:
ts = ', '.join(sorted(tal))
Print(('\n\nLoaded %d Talisman plugins:\n' % len(tal))+ts, color1)
if Npl:
Ns = ', '.join(sorted(Npl))
Print(('\n\nThere are %d unloadable plugins:\n' % len(Npl))+Ns, color2)
else:
Print('\n\nThere are not unloadable plugins!', color3)
################ other handlers ################################################################
def load_roster_config():
if initialize_file(ROSTER_FILE, str(RSTR)):
globals()['RSTR'] = eval(read_file(ROSTER_FILE))
else:
Print('\n\nError: roster config file is not exist!', color2)
def load_quests():
if os.path.exists(QUESTIONS_FILE):
globals()['QUESTIONS'] = eval(read_file(QUESTIONS_FILE))
else:
Print('\n\nError: questions file is not exist!', color2)
def read_pipe(command):
try:
pipe = os.popen(command)
data = pipe.read()
pipe.close()
if BOT_OS == 'nt':
data = data.decode('cp866')
except:
data = '(error)'
return data
read_link = lambda link: urllib.urlopen(link).read()
def read_url(link, Browser = False):
req = urllib2.Request(link)
if Browser:
req.add_header('User-agent', Browser)
site = urllib2.urlopen(req)
data = site.read()
return data
def re_search(lt, key, key2):
lt = lt[re.search(key, lt).end():]
data = lt[:re.search(key2, lt).start()]
return data.strip()
def handler_botnick(conf):
if conf in BOT_NICKS:
return BOT_NICKS[conf]
return DEFAULT_NICK
def handler_jid(instance):
if isinstance(instance, types.InstanceType):
instance = unicode(instance)
list = instance.split('/', 1)
chat = list[0].lower()
if (len(list) == 2) and GROUPCHATS.has_key(chat):
if GROUPCHATS[chat].has_key(list[1]):
return GROUPCHATS[chat][list[1]]['jid']
return chat
def save_conflist(conf, nick = None, code = None):
if initialize_file(GROUPCHATS_FILE):
list = eval(read_file(GROUPCHATS_FILE))
if conf not in list:
list[conf] = {'nick': nick, 'code': code}
elif nick and conf and code:
list[conf] = {'nick': nick, 'code': code}
elif nick and conf:
list[conf]['nick'] = nick
elif code and conf:
list[conf]['code'] = code
elif conf:
del list[conf]
write_file(GROUPCHATS_FILE, str(list))
else:
Print('\n\nError: can`t append conference to chatrooms list file!', color2)
def memory_usage():
PID, memory = str(BOT_PID), '0'
if BOT_OS == 'posix':
lines = read_pipe('ps -o rss -p %s' % (PID)).splitlines()
if len(lines) >= 2:
memory = lines[1].strip()
elif BOT_OS == 'nt':
lines = read_pipe('TASKLIST /FI "IMAGENAME eq python.exe').splitlines()
for line in lines:
slist = line.split()
if len(slist) >= 6 and PID == slist[1].strip():
memory = '%s%s' % (slist[4].strip(), slist[5].strip())
break
return (0 if not check_number(memory) else int(memory))
def command_Prefix(conf, command):
if command in [u'хелп', u'комлист', u'команды', u'префикс', u'тест']:
return command
if PREFIX[conf] == command[:1]:
return command[1:]
return 'none_command'
def Prefix_state(combody, bot_nick):
cmd_nick = combody.split()[0]
for symbol in [':', ',', '>']:
cmd_nick = cmd_nick.replace(symbol, '')
if cmd_nick != bot_nick:
return False
return True
def check_number(number):
try:
int(number)
except:
return False
return True
def replace_all(retxt, list, data = False):
for x in list:
retxt = retxt.replace(x, data if data != False else list[x])
return retxt
def that_day():
return int(time.strftime('%Y%m%d', time.gmtime()))
Elist = [' %s' % (x) for x in [u'0 мес', u'0 дн', u'0 час', u'0 мин', u'0 сек']]
def timeElapsed(or_seconds):
minutes, seconds = divmod(or_seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
months, days = divmod(days, 30)
years, months = divmod(months, 12)
text = u'%d сек' % (seconds)
if or_seconds >= 60:
text = u'%d мин %s' % (minutes, text)
if or_seconds >= 3600:
text = u'%d час %s' % (hours, text)
if or_seconds >= 86400:
text = u'%d дн %s' % (days, text)
if or_seconds >= 2592000:
text = u'%d мес %s' % (months, text)
if or_seconds >= 31104000:
text = u'%d лет %s' % (years, text)
return replace_all(text, Elist, '')
def upkeep():
try:
threading.Timer(360, upkeep).start()
except:
delivery(u'Внимание! Командуй --> "exec threading.Timer(360, upkeep).start()"')
sys.exc_clear()
if BOT_OS == 'nt':
import msvcrt; msvcrt.heapmin()
gc.collect()
if MEMORY_LIMIT and memory_usage() >= MEMORY_LIMIT:
sys_exit('memory leak')
################ access handlers ###############################################################
def load_access_levels():
if initialize_file(GLOBACCESS_FILE):
globals()['GLOBACCESS'] = eval(read_file(GLOBACCESS_FILE))
else:
Print('\n\nError: access file is not exist!', color2)
def form_admins_list():
if BOSS not in GLOBACCESS:
GLOBACCESS[BOSS] = 100
for jid in GLOBACCESS:
if GLOBACCESS[jid] >= 80:
ADLIST.append(jid)
def change_local_access(conf, jid, level = 0):
if conf not in ACCBYCONF:
ACCBYCONF[conf] = {}
if level:
ACCBYCONF[conf][jid] = level
else:
ACCBYCONF[conf][jid] = 0
def change_global_access(jid, level = 0):
if level:
GLOBACCESS[jid] = level
else:
del GLOBACCESS[jid]
write_file(GLOBACCESS_FILE, str(GLOBACCESS))
def user_level(source, conf):
jid, level = handler_jid(source), 10
if GLOBACCESS.has_key(jid):
level = GLOBACCESS[jid]
elif CONFACCESS.has_key(conf) and CONFACCESS[conf].has_key(jid):
level = CONFACCESS[conf][jid]
elif ACCBYCONF.has_key(conf) and ACCBYCONF[conf].has_key(jid):
level = ACCBYCONF[conf][jid]
return level
def has_access(source, level, conf):
if user_level(source, conf) >= int(level):
return True
return False
################ join/leave & message send handlers ############################################
def send_join_presece(conf, nick, code = None):
Presence = xmpp.protocol.Presence('%s/%s' % (conf, nick))
Presence.setStatus(STATUS[conf]['message'])
Presence.setShow(STATUS[conf]['status'])
Presence.setTag('c', namespace = xmpp.NS_CAPS, attrs = {'node': Caps, 'ver': CapsVer})
Pres = Presence.setTag('x', namespace = xmpp.NS_MUC)
Pres.addChild('history', {'maxchars': '0'})
if code:
Pres.setTagData('password', code)
JCON.send(Presence)
def join_groupchat(conf, nick, code = None):
call_stage1_init(conf)
if conf not in GROUPCHATS:
GROUPCHATS[conf] = {}
if conf not in STATUS:
STATUS[conf] = {'message': 'BlackSmith by WitcherGeralt', 'status': 'chat'}
save_conflist(conf, nick, code)
send_join_presece(conf, nick, code)
def leave_groupchat(conf, status = None):
Presence = xmpp.Presence(conf, 'unavailable')
if status:
Presence.setStatus(status)
JCON.send(Presence)
if conf in GROUPCHATS:
del GROUPCHATS[conf]
save_conflist(conf)
def handler_rebody(target, body, ltype):
col, all = 0, str(len(body) / PRIV_MSG_LIMIT + 1)
while len(body) > PRIV_MSG_LIMIT:
col = col + 1
text = '[%d/%s] %s[...]' % (col, all, body[:PRIV_MSG_LIMIT])
JCON.send(xmpp.Message(target, text.strip(), ltype))
body = body[PRIV_MSG_LIMIT:]
time.sleep(2)
return '[%d/%s] %s' % ((col + 1), all, body)
def delivery(body):
if not isinstance(body, unicode):
body = body.decode('utf-8', 'replace')
INFA['outmsg'] += 1
try:
JCON.send(xmpp.Message(BOSS, body, 'chat'))
except:
file_add('delivery.txt', body)
def msg(target, body):
if not isinstance(body, unicode):
body = body.decode('utf-8', 'replace')
obody = body
if GROUPCHATS.has_key(target):
ltype = 'groupchat'
if len(body) > CHAT_MSG_LIMIT:
body = body[:CHAT_MSG_LIMIT]+(u'[...]\n\n>>> Лимит %d знаков! Продолжение по команде "далее".' % (CHAT_MSG_LIMIT))
else:
ltype = 'chat'
if len(body) > PRIV_MSG_LIMIT:
body = handler_rebody(target, body, ltype)
JCON.send(xmpp.Message(target, body.strip(), ltype))
INFA['outmsg'] += 1
call_outgoing_message_handlers(target, body, obody)
def reply(ltype, source, body):
if not isinstance(body, unicode):
body = body.decode('utf-8', 'replace')
if ltype == 'public':
body = '%s: %s' % (source[2], body)
msg(source[1], body)
elif ltype == 'private':
msg(source[0], body)
def send_unavailable(status):
Presence = xmpp.Presence(typ = 'unavailable')
Presence.setStatus(status)
JCON.send(Presence)
def change_bot_status(conf, text, status):
Presence = xmpp.protocol.Presence('%s/%s' % (conf, handler_botnick(conf)))
Presence.setStatus(text)
Presence.setShow(status)
Presence.setTag('c', namespace = xmpp.NS_CAPS, attrs = {'node': Caps, 'ver': CapsVer})
JCON.send(Presence)
################ role/afl iq handlers ##########################################################
def handler_iq_send(conf, item_name, item, afrls, afrl, rsn = None):
stanza = xmpp.Iq(to = conf, typ = 'set')
INFA['outiq'] += 1
stanza.setID('lytic_%d' % (INFA['outiq']))
query = xmpp.Node('query')
query.setNamespace(xmpp.NS_MUC_ADMIN)
afl_role = query.addChild('item', {item_name: item, afrls: afrl})
if rsn:
afl_role.setTagData('reason', rsn)
stanza.addChild(node = query)
JCON.send(stanza)
def handler_unban(conf, jid):
handler_iq_send(conf, 'jid', jid, 'affiliation', 'none')
def handler_banjid(conf, jid, reason):
handler_iq_send(conf, 'jid', jid, 'affiliation', 'outcast', reason)
def handler_ban(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'affiliation', 'outcast', reason)
def handler_none(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'affiliation', 'none', reason)
def handler_member(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'affiliation', 'member', reason)
def handler_admin(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'affiliation', 'admin', reason)
def handler_owner(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'affiliation', 'owner', reason)
def handler_kick(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'role', 'none', reason)
def handler_visitor(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'role', 'visitor', reason)
def handler_participant(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'role', 'participant', reason)
def handler_moder(conf, nick, reason):
handler_iq_send(conf, 'nick', nick, 'role', 'moderator', reason)
################ message handler & others ######################################################
def roster_check(instance, body):
if instance not in ANSWER:
QA = random.choice(QUESTIONS.keys())
ANSWER[instance] = {'key': QUESTIONS[QA]['answer'], 'tryes': 0}
msg(instance, u'Привет! Мне нужно убедиться что ты не бот, %s, У тебя три попытки и 1 минута!' % (QUESTIONS[QA]['question']))
INFO['thr'] += 1
try:
threading.Timer(60, roster_timer,(instance,)).start()
except:
LAST['null'] += 1
elif ANSWER[instance]['tryes'] >= 3:
roster_ban(instance)
elif ANSWER[instance]['key'] == body.lower():
RSTR['AUTH'].append(instance)
write_file(ROSTER_FILE, str(RSTR))
msg(instance, u'Праильно! Вэлкам!')
ROSTER.Authorize(instance)
ROSTER.Subscribe(instance)
ROSTER.setItem(instance, instance, ['USERS'])
del ANSWER[instance]
delivery(u'Контакт %s прошел IQ проверку и был добавлен в группу "USERS"!' % (instance))
else:
ANSWER[instance]['tryes'] += 1
msg(instance, u'Включи мозг! Неправильно!')
def roster_ban(instance):
if not instance.count('@conf'):
RSTR['BAN'].append(instance)
write_file(ROSTER_FILE, str(RSTR))
msg(instance, u'Поздравляю ты в бане!')
ROSTER.Unsubscribe(instance)
if instance in ROSTER.getItems():
ROSTER.delItem(instance)
del ANSWER[instance]
delivery(u'Контакт %s не прошел IQ проверку и был добавлен в ростер бан!' % (instance))
def roster_timer(roster_user):
if roster_user not in (RSTR['AUTH'] + RSTR['BAN']):
roster_ban(roster_user)
def feil_message(fromjid, instance, bot_nick, body, error):
if error == '500':
time.sleep(0.6)
msg(fromjid, body)
elif error == '406':
send_join_presece(instance, bot_nick)
time.sleep(0.6)
msg(fromjid, body)
def kill_flooder(flooder, roster, nick, instance):
change_global_access(flooder, -100)
if roster:
delivery(u'Внимание! %s флудит мне в ростер!' % (flooder))
else:
botnick = handler_botnick(instance)
handler_kick(instance, nick, '%s: flooder!' % (botnick))
try:
threading.Timer(360, change_global_access,(flooder, -5)).start()
except:
LAST['null'] += 1
def flood_timer(fromjid, instance, nick):
STOP['mto'] += 1
if STOP['mto'] >= 4:
if instance in GROUPCHATS or instance.count('@conf'):
flooder, roster = handler_jid(fromjid), False
else:
flooder, roster = instance, True
if flooder not in STOP['jids']:
STOP['jids'][flooder] = 1
time.sleep(6)
STOP['jids'][flooder] -= 1
else:
STOP['jids'][flooder] += 1
if flooder not in ADLIST and STOP['jids'][flooder] >= 4:
if flooder.count('@') and flooder.count('.'):
kill_flooder(flooder, roster, nick, instance)
time.sleep(6)
del STOP['jids'][flooder]
else:
botnick = handler_botnick(instance)
handler_kick(fromjid, nick, '%s: flooder!' % (botnick))
time.sleep(6)
del STOP['jids'][flooder]
else:
time.sleep(6)
STOP['jids'][flooder] -= 1
STOP['mto'] -= 1
else:
time.sleep(4)
STOP['mto'] -= 1
def MESSAGE_PROCESSING(client, stanza):
fromjid = stanza.getFrom()
INFO['msg'] += 1
instance = fromjid.getStripped().lower()
if user_level(fromjid, instance) <= -100:
return
if instance in UNAVALABLE and not MSERVE:
return
if stanza.timestamp:
return