-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyval_commands.py
1493 lines (1247 loc) · 50.7 KB
/
pyval_commands.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 -*-
"""pyval_commands.py
Handles commands for pyvalbot.py, separate from the rest of the other
irc bot functionality to prevent mess.
-Christopher Welborn
"""
from datetime import datetime
import json
import os
import re
from sys import version as sysversion
import urllib2
from easysettings import EasySettings
from twisted.python import log
from pyval_exec import ExecBox, TimedOut
from pyval_util import (
NAME,
VERSION,
get_args,
humantime,
timefromsecs)
ADMINFILE = '{}_admins.lst'.format(NAME.lower().replace(' ', '-'))
BANFILE = '{}_banned.lst'.format(NAME.lower().replace(' ', '-'))
HELPFILE = '{}_help.json'.format(NAME.lower().replace(' ', '-'))
# Parses common string for True/False values.
true_values = ('true', 'on', 'yes', '1')
false_values = ('false', 'off', 'no', '0')
bool_values = list(true_values)
bool_values.extend(false_values)
boolpat = re.compile('\[({})\]'.format('|'.join(bool_values)), re.IGNORECASE)
intpat = re.compile('\[(\d+)\]')
def block_dict_val(data, blockedlst, value=None):
""" Block certain dict/config values from being seen.
Replaces a keys value if any strings in blockedlst are found.
Strings are found if they start or end with any string in the
blocked list.
Values are replaces with the 'value' argument.
This is meant to be used with string representations of dicts.
The original data is unchanged, the changed version is returned.
Arguments:
data : dict or EasySetting instance.
blockedlst : Tuple of strings, if found in a key it is blocked.
value : New value for blocked items. Defaults to: '********'
"""
if isinstance(data, dict):
d = data
elif isinstance(data, EasySettings):
d = data.settings
else:
# Not the correct type to be blocked.
return data
if value is None:
# Default value for blocked vlaues.
value = '********'
# Block all 'password/pw' values from dict/settings...
newdata = {}
for k, v in d.items():
keystr = str(k)
if keystr.startswith(blockedlst) or keystr.endswith(blockedlst):
newdata[k] = value
else:
newdata[k] = v
return newdata
def load_json_object(filename):
""" Loads an object from a json file,
returns {} on failure.
"""
try:
with open(filename, 'r') as fjson:
rawjson = fjson.read()
except (OSError, IOError) as exio:
log.msg('\nError loading json from: {}\n{}'.format(filename, exio))
return {}
try:
jsonobj = json.loads(rawjson)
except Exception as ex:
log.msg('\nError parsing json from: {}\n{}'.format(filename, ex))
return {}
return jsonobj
def parse_bool(s):
return parse_true(s[1:-1]) if boolpat.match(s) else None
def parse_false(s):
return s.lower() in false_values
def parse_true(s):
return s.lower() in true_values
def pasteit(data):
""" Submit a paste to welbornprod.com/paste ...
data should be a dict with at least:
{'content': <paste content>}
with optional settings:
{'author': 'name',
'title': 'paste title',
'content': 'this is content',
'private': True,
'onhold': True,
}
"""
pasteurl = 'https://welbornprod.com/paste/api/submit'
try:
newdata = json.dumps(data)
except Exception as exenc:
log.msg('Unable to encode paste data: {}\n{}'.format(data, exenc))
return None
req = urllib2.Request(
pasteurl,
data=newdata.encode('utf-8'),
headers={
'User-Agent': '{} v. {}'.format(NAME, VERSION),
'Content-Type': 'application/json; charset=utf-8',
'Content-Encoding': 'utf-8'
})
try:
con = urllib2.urlopen(req)
except Exception as exopen:
log.msg('Unable to open paste url: {}\n{}'.format(pasteurl, exopen))
return None
try:
resp = con.read()
except Exception as exread:
log.msg(
'Unable to read paste response from {}\n{}'.format(
pasteurl,
exread))
return None
try:
respdata = json.loads(resp)
except Exception as exjson:
log.error('Unable to decode JSON from {}\n{}'.format(
pasteurl,
exjson))
return None
status = respdata.get('status', 'error')
if status == 'error':
# Server responded with json error response.
errmsg = respdata.get('message', '<no msg>')
log.msg('Paste site responded with error: {}'.format(errmsg))
# Little something for the unit tests..
# The error is most likely 'too many pastes in a row',
# just return the error msg so the test will pass and be printed.
if data.get('author', '').startswith('<pyvaltest>'):
return 'TESTERROR: {}'.format(errmsg)
# Paste site errored, no url given to the chat user.
return None
# Good response.
suburl = respdata.get('url', None)
if suburl:
finalurl = 'https://welbornprod.com{}'.format(suburl)
return finalurl
# No url found to respond with.
return None
class AdminHandler(object):
""" Handles admin functions like bans/admins/settings. """
def __init__(self, help_info=None):
# These are overwritten by the PyValIRCProtocol()
self.quit = None
self.sendLine = None
self.ctcpMakeQuery = None
self.do_action = None
self.handlinglock = None
# Set startup time.
self.starttime = datetime.now()
# Current channels the bot is in.
self.channels = []
# These are all set by PyValIRCProtocol after config is loaded.
self.argd = {}
self.cmdchar = '*'
self.config = {}
self.nickname = None
self.topicfmt = ''
self.topicmsg = ''
self.noheartbeatlog = False
# Whether or not to use PyVal.ExecBoxs blacklist.
self.blacklist = False
# Monitoring options. (privmsgs, all recvline, include ips)
self.monitor = False
self.monitordata = False
self.monitorips = False
# If this is true, privmsgs are forwarded to the admins.
self.forwardmsgs = True
# List of admins/banned
self.admins = self.admins_load()
self.banned = self.ban_load()
self.banned_warned = {}
# Time of last response sent (rate-limiting/bans)
self.last_handle = None
# The msg that was last sent.
self.last_msg = None
# Last nick responded to (rate-limiting/bans)
self.last_nick = None
# Last command handled (dupe-blocking/rate-limiting)
self.last_command = None
# Whether or not response rate-limiting is enabled.
self.limit_rate = True
# Time in between commands required for a user.
# If the user sends multiple commands before this limit is reached,
# their 'ban-warned' count increases.
self.msg_timelimit = 3
# Number of 'ban-warns' before perma-banning a nick.
self.banwarn_limit = 3
# Current load, and lock required to change its value.
self.handlingcount = 0
self.handlinglock = None
# Number of handled requests
self.handled = 0
# Help dict {'user': {'cmd': {'args': null, {'desc': 'mycommand'}}},
# 'admin': <same as 'user' key> }
# Tests can pass a preloaded help_info in.
self.help_info = help_info if help_info else self.load_help()
if self.help_info:
if (not help_info):
# Print a message if help was loaded from file
log.msg('Help info file loaded: {}'.format(HELPFILE))
else:
log.msg('No help commands will be available.')
def admins_add(self, nick):
""" Add an admin to the list and save it. """
if nick in self.admins:
return 'already an admin: {}'.format(nick)
self.admins.add(nick)
if self.admins_save():
return 'added admin: {}'.format(nick)
else:
return 'unable to save admins, {} is not permanent.'.format(nick)
def admins_list(self):
""" List admins. """
return 'admins: {}'.format(', '.join(self.admins))
def admins_load(self):
""" Load admins from list. """
# admin is cj until the admins file says otherwise.
admins = {'cjwelborn'}
if not os.path.exists(ADMINFILE):
log.msg('No admins list, defaults will be used.')
return admins
try:
with open(ADMINFILE) as fread:
admins = set(l.strip() for l in fread.readlines())
except EnvironmentError as ex:
log.msg('Unable to load admins list:\n{}'.format(ex))
pass
return admins
def admins_remove(self, nick):
""" Remove an admin from the list and save it. """
if nick in self.admins:
self.admins.remove(nick)
if self.admins_save():
msg = 'removed admin: {nick}'
else:
msg = 'unable to save admins, {nick} will persist on restart'
return msg.format(nick=nick)
return 'not an admin: {}'.format(nick)
def admins_save(self):
""" Save current admins list. """
try:
with open(ADMINFILE, 'w') as f:
f.write('\n'.join(sorted(self.admins)))
f.write('\n')
return True
except (IOError, OSError) as ex:
log.msg('Error saving admin list:\n{}'.format(ex))
return False
def ban_add(self, nick, permaban=False):
""" Add a warning to a nick, after 3 warnings ban them for good. """
if nick in self.admins:
# Admins wont be banned or counted.
return ''
if permaban:
# Straight to permaban. (better to use ban_addperma now)
self.ban_addperma(nick)
return 'no more.'
# Auto banner.
if nick in self.banned_warned.keys():
# Increment the warning count.
self.banned_warned[nick]['last'] = datetime.now()
self.banned_warned[nick]['count'] += 1
newcount = self.banned_warned[nick]['count']
if newcount == self.banwarn_limit:
# No more warnigns, permaban.
self.banned.append(nick)
self.ban_save()
return 'no more.'
elif newcount == (self.banwarn_limit - 1):
# last warning.
return 'really, slow down with your commands.'
else:
# First warning.
self.banned_warned[nick] = {'last': datetime.now(), 'count': 1}
# Warning count increased, not last warning or permaban yet.
return 'slow down with your commands.'
def ban_addperma(self, nick):
""" Add a permanently banned nick. """
banned = []
if isinstance(nick, (list, tuple)):
for n in nick:
if (n not in self.admins) and (n not in self.banned):
self.banned.append(n)
banned.append(n)
else:
if (nick not in self.admins) and (nick not in self.banned):
self.banned.append(nick)
banned.append(n)
saved = self.ban_save() if banned else False
if saved:
return banned
else:
return []
def ban_load(self):
""" Load banned nicks if any are available. """
banned = []
if not os.path.isfile(BANFILE):
return banned
try:
with open(BANFILE) as fread:
banned = [l.strip('\n') for l in fread.readlines()]
except (IOError, OSError) as exos:
log.msg('Unable to load banned file: {}\n{}'.format(
BANFILE,
exos))
return banned
def ban_remove(self, nicklst):
""" Remove nicks from the banned list. """
if not nicklst:
return []
removed = []
for nick in nicklst:
if nick in self.banned:
while nick in self.banned:
self.banned.remove(nick)
# Reset ban warnings.
if nick in self.banned_warned.keys():
self.banned_warned[nick] = {'last': datetime.now(),
'count': 0}
removed.append(nick)
saved = self.ban_save()
if saved:
return removed
else:
return []
def ban_save(self):
""" Load perma-banned list. """
try:
with open(BANFILE, 'w') as f:
f.write('\n'.join(self.banned))
return True
except (IOError, OSError) as exos:
log.msg('Unable to save banned file: {}\n{}'.format(
BANFILE,
exos))
return False
def get_uptime(self):
""" Return the current uptime in seconds for this instance.
Further processing can be done with pyval_util.timefromsecs().
"""
return int((datetime.now() - self.starttime).total_seconds())
def handling_decrease(self):
if self.handlingcount > 0:
self.handlinglock.acquire()
self.handlingcount -= 1
self.handlinglock.release()
def handling_increase(self):
self.handlinglock.acquire()
self.handlingcount += 1
self.handlinglock.release()
def identify(self, pw):
""" Send an IDENTIFY msg to NickServ. """
log.msg('Identifying with nickserv...')
if not pw:
return 'No password supplied for IDENTIFY.'
self.sendLine('PRIVMSG NickServ :IDENTIFY '
'{} {}'.format(self.nickname, pw))
return None
def load_help(self):
""" Load help from json file. """
return load_json_object(HELPFILE)
def op_request(self, channel=None, nick=None, reverse=False):
""" op or deop a user through ChanServ.
Arguments:
channel : Default channel is '##<self.nickname>'.
nick : Default user is the bot itself.
reverse : Use DEOP instead of OP.
"""
chanservcmd = (
'deop' if reverse else 'op',
channel or '##{}'.format(self.nickname),
nick or self.nickname
)
self.sendmsg('ChanServ', ' '.join(chanservcmd))
def save_config(self):
""" Save config settings to disk.
Returns the number of items changed/saved.
Returns None on failure.
"""
if not hasattr(self, 'argd'):
log.msg('Unable to save config, admin.argd not found!')
return None
if not hasattr(self, 'config'):
log.msg('Unable to save config, admin.config not found!')
return None
changecnt = 0
for argopt, argval in self.argd.items():
configopt = argopt.strip('--')
configval = self.config.get(configopt, default=None)
if argval and (argval != configval):
# New config option.
self.config.set(configopt, argval)
changecnt += 1
if changecnt > 0:
if self.config.save():
# Save was a success.
return changecnt
# Bad save.
return None
else:
# No items to save.
return 0
def sendmsg_tochans(self, msgtext):
""" Send the same message to all channels pyvalbot is in. """
for chan in self.channels:
self.sendmsg(chan, msgtext)
def sendmsg_toadmins(self, msgtext, fromnick=None):
""" Sends a private message to all admins as pyvalbot.
Can be disabled by settings self.forwardsmsgs = False
If fromnick is set, it will be included in the message.
"""
if fromnick:
msg = '{}: {}'.format(fromnick, msgtext)
else:
msg = '{}'.format(msgtext)
if self.forwardmsgs:
for adminnick in self.admins:
# Don't send the admin's own message to them.
if fromnick != adminnick:
self.sendmsg(adminnick, msg)
def sendmsg(self, target, msgtext):
""" Send a private message as pyvalbot.
This is a shortcut to: self.sendLine('PRIVMSG target: msgtext')
"""
if (self.last_nick, self.last_msg) != (target, msgtext):
self.sendLine('PRIVMSG {} :{}'.format(target, msgtext))
self.last_nick = target
self.last_msg = msgtext
def set_topic(self, topic=None, channel=None):
""" Try to set the bot's channel topic.
If no topic is given, self.topicmsg is used.
"""
self.sendLine('TOPIC {chan} :{msg}'.format(
chan=channel or '##{}'.format(self.nickname),
msg=topic or self.topicmsg))
class CommandHandler(object):
""" Handles commands/messages sent from pyvalbot.py """
def __init__(self, **kwargs):
""" Keyword Arguments:
** These are required. **
adminhandler : Shared AdminHandler() for these functions.
defer_ : Shared defer module.
reactor_ : Shared reactor module.
task_ : Shared task module.
"""
self.admin = kwargs.get('adminhandler', None)
self.defer = kwargs.get('defer_', None)
self.reactor = kwargs.get('reactor_', None)
self.task = kwargs.get('task_', None)
self.commands = CommandFuncs(defer_=self.defer,
reactor_=self.reactor,
task_=self.task,
adminhandler=self.admin)
def parse_command(self, msg, username=None):
""" Parse a message, return corresponding command function if found,
otherwise, return None.
"""
command, sep, rest = msg.lstrip(self.admin.cmdchar).partition(' ')
# Retrieve function related to this command.
func = getattr(self.commands, 'cmd_' + command, None)
# Check admin command.
if username and (username in self.admin.admins):
adminfunc = getattr(self.commands, 'admin_' + command, None)
if adminfunc:
# return callable admin command.
return adminfunc
# Return callable function for command.
return func
def parse_data(self, user, channel, msg):
""" Parse raw data from privmsg().
Logs messages if 'monitor' or 'monitorips' is set.
Returns parse_command(msg) if it is a command,
otherwise it returns None.
Arguments:
user : (str) - user string (full nick!host format).
channel : (str) - channel where the msg came from.
msg : (str) - content of the message.
"""
# Parse irc name, ip address from user.
username, ipstr = self.parse_username(user)
# Monitor incoming messages?
if self.admin.monitor:
# Include ip address in print info?
if self.admin.monitorips:
userstr = '{} ({})'.format(username, ipstr)
else:
userstr = username
log.msg('[{}]\t{}:\t{}'.format(channel, userstr, msg))
elif (channel == self.admin.nickname):
if not msg.startswith(self.admin.cmdchar):
# normal private msg sent directly to pyval.
log.msg('Message from {}: {}'.format(username, msg))
self.admin.sendmsg_toadmins(msg, fromnick=username)
# Handle message
if msg.startswith(self.admin.cmdchar):
return self.parse_command(msg, username=username)
# Not a command.
return None
def parse_username(self, rawuser):
""" Parse a raw username into (ircname, ipaddress),
returns (rawuser, '') on failure.
"""
if '!' in rawuser:
splituser = rawuser.split('!')
username = splituser[0].strip()
rawip = splituser[1]
if '@' in rawip:
ipaddress = rawip.split('@')[1]
else:
ipaddress = rawip
else:
username = rawuser
ipaddress = ''
return (username, ipaddress)
class CommandFuncs(object):
""" Holds only the command-handling functions themselves. """
def __init__(self, **kwargs):
""" Keyword Arguments:
** These are required. **
adminhandler : Shared AdminHandler() for these functions.
defer_ : Shared defer module.
reactor_ : Shared reactor module.
task_ : Shared task module.
"""
self.admin = kwargs.get('adminhandler', None)
self.defer = kwargs.get('defer_', None)
self.reactor = kwargs.get('reactor_', None)
self.task = kwargs.get('task_', None)
# Commands (must begin with cmd)
def admin_adminadd(self, rest, nick=None):
""" Add an admin to the list. """
return self.admin.admins_add(rest)
def admin_adminhelp(self, rest, nick=None):
""" Build list of admin commands. """
self.admin.sendmsg(
nick,
self.get_help(role='admin', cmdname=rest, usernick=None))
def admin_adminlist(self, rest, nick=None):
""" List current admins. """
return self.admin.admins_list()
def admin_adminmsg(self, rest, nick=None):
""" Send a message to all pyvalbot admins. """
if not rest:
return 'Must give a message to send!'
self.admin.sendmsg_toadmins(rest)
return None
def admin_adminreload(self, rest, nick=None):
""" Reloads admin list for IRCClient. """
# Really need to reorganize things, this is getting ridiculous.
self.admin.admins_load()
return 'admins loaded.'
def admin_adminrem(self, rest, nick=None):
""" Alias for admin_adminremove """
return self.admin_adminremove(rest)
def admin_adminremove(self, rest, nick=None):
""" Remove an admin from the handlers list. """
return self.admin.admins_remove(rest)
def admin_ban(self, rest, nick=None):
""" Ban a nick. """
if not rest:
return 'usage: {}ban <nick>'.format(self.admin.cmdchar)
nicks = rest.split(' ')
alreadybanned = [n for n in nicks if n in self.admin.banned]
banned = self.admin.ban_addperma(nicks)
notbanned = [n for n in nicks
if (n not in banned) and (n not in alreadybanned)]
msg = []
if banned:
msg.append('banned: {}'.format(', '.join(banned)))
if alreadybanned:
msg.append('already banned: '
'{}'.format(', '.join(alreadybanned)))
if notbanned:
msg.append('unable to ban: {}'.format(', '.join(notbanned)))
return ', '.join(msg)
def admin_banned(self, rest, nick=None):
""" list banned. """
banned = ', '.join(sorted(self.admin.banned))
if banned:
return 'currently banned: {}'.format(banned)
else:
return 'nobody is banned.'
def admin_banwarns(self, rest, nick=None):
""" list ban warnings. """
banwarns = []
for warnednick in sorted(self.admin.banned_warned.keys()):
count = self.admin.banned_warned[warnednick]['count']
banwarns.append('{}: {}'.format(warnednick, count))
if banwarns:
return '[{}]'.format(']['.join(banwarns))
else:
return 'no ban warnings issued.'
def admin_blacklist(self, rest, nick=None):
""" Toggle the blacklist option """
if rest == '?' or (not rest):
# current status will be printed at the bottom of this func.
pass
elif rest == '-':
# Toggle current value.
self.admin.blacklist = False if self.admin.blacklist else True
else:
if parse_true(rest):
self.admin.blacklist = True
elif parse_false(rest):
self.admin.blacklist = False
else:
return 'invalid value for blacklist option (true/false).'
return 'blacklist enabled: {}'.format(self.admin.blacklist)
def admin_channels(self, rest, nick=None):
""" Return a list of current channels for the bot. """
return 'current channels: {}'.format(', '.join(self.admin.channels))
def admin_chanmsg(self, rest, nick=None):
""" Send a msg to all channels pyvalbot is in. """
if not rest:
return 'Must give a message to send!'
self.admin.sendmsg_tochans(rest)
return None
def admin_configget(self, rest, nick=None):
""" Retrieve value for a config setting. """
if not rest:
return 'usage: {}configget <option>'.format(self.admin.cmdchar)
val = self.admin.config.get(rest, '__NOTSET__')
if val == '__NOTSET__':
return '{}: <not set>'.format(rest)
# Filter some config settings (dont want passwords sent to chat)
blocked = ('pw', 'password')
if rest.startswith(blocked) or rest.endswith(blocked):
return '{}: ********'.format(rest)
# Value is ok to send to chat.
return '{}: {}'.format(rest, val)
def admin_configlist(self, rest, nick=None):
""" List current config. Filters certain items from chat. """
return self.admin_getattr('admin.config')
def admin_configsave(self, rest, nick=None):
""" Save the current config (cmdline options) to disk. """
saved = self.admin.save_config()
if saved is None:
return 'unable to save config.'
return 'saved {} new config settings.'.format(saved)
def admin_configset(self, rest, nick=None):
""" Set value for a config setting. """
usagestr = 'usage: {}configset <option> <value>'.format(
self.admin.cmdchar
)
if not rest:
return usagestr
args = rest.split(' ')
if len(args) < 2:
# Not enough args.
return usagestr
opt, val = args[0], ' '.join(args[1:])
if val == '-':
# Have to pass - to blank-out config settings.
val = None
elif boolpat.match(val):
# Have a valid bool config value, use it.
val = parse_true(val[1:-1])
elif intpat.match(val):
try:
val = int(val[1:-1])
except (TypeError, ValueError):
return 'bad int value: {}'.format(val[1:-1])
if self.admin.config.setsave(opt, val):
return 'saved {}: {}'.format(opt, val)
# Failure.
return 'unable to save: {}: {}'.format(opt, val)
def admin_deop(self, rest, nick=None):
""" Request deop from ChanServ on behalf of the bot. """
if not rest:
self.admin.op_request(reverse=True)
return None
chan, _, nick = rest.partition(' ')
if not chan.startswith('#'):
# No channel given, request ops for nick in ##<botnick>
nick = chan
chan = None
self.admin.op_request(channel=chan, nick=nick, reverse=True)
def admin_deopme(self, rest, nick=None):
""" Request deop from the bot (if the bot is an op itself) """
chan = rest if rest.startswith('#') else None
self.admin.op_request(channel=chan, nick=nick, reverse=True)
def admin_getattr(self, rest, nick=None):
""" Return value for attribute. """
if not rest:
return 'usage: {}getattr <attribute>'.format(self.admin.cmdchar)
parent, attrname, attrval = self.parse_attrstr(rest)
if attrname is None:
return 'no attribute named: {}'.format(rest)
# Block certain config attributes from being printed.
if ('password' in attrname) or attrname.endswith('pw'):
attrval = '********'
elif 'config' in rest:
# Block password config from chat.
attrval = block_dict_val(attrval, ('password', 'pw'))
attrval = str(attrval)
if len(attrval) > 250:
attrval = '{} ...truncated'.format(attrval[:250])
return '{} = {}'.format(rest, attrval)
def admin_id(self, rest, nick=None):
""" Shortcut for admin_identify """
return self.admin.identify(rest)
def admin_identify(self, rest, nick=None):
""" Identify with nickserv, expects !identify password """
return self.admin.identify(rest)
def admin_join(self, rest, nick=None):
""" Join a channel as pyval. """
if ',' in rest:
# multiple channel names.
chans = [s.strip() for s in rest.split(',')]
else:
# single channel.
chans = [rest]
alreadyin = []
for chan in chans:
if not chan.startswith('#'):
chan = '#{}'.format(chan)
if chan in self.admin.channels:
# already in that channel, send a msg in a moment.
alreadyin.append(chan)
else:
log.msg('Joining: {}'.format(chan))
self.admin.sendLine('JOIN {}'.format(chan))
if alreadyin:
chanstr = 'channel' if len(alreadyin) == 1 else 'channels'
return 'Already in {}: {}'.format(chanstr,
', '.join(alreadyin))
# Joined channels, no response is sent
# (you can look at the log/stdout)
return None
def admin_limitrate(self, rest, nick=None):
""" Toggle limit_rate """
if rest == '?' or (not rest):
# current status will be printed at the bottom of this func.
pass
elif rest == '-':
# Toggle current value.
self.admin.limit_rate = False if self.admin.limit_rate else True
else:
if parse_true(rest):
self.admin.limit_rate = True
elif parse_false(rest):
self.admin.limit_rate = False
else:
return 'invalid value for limitrate option (true/false).'
return 'limitrate enabled: {}'.format(self.admin.limit_rate)
def admin_me(self, rest, nick=None):
""" Perform an irc action, /ME <channel> <text> """
cmdargs = rest.split()
if len(cmdargs) < 2:
return 'usage: {}me <channel> <text>'.format(self.admin.cmdchar)
channel, text = cmdargs[0], ' '.join(cmdargs[1:])
if not channel.startswith('#'):
channel = '#{}'.format(channel)
if channel not in self.admin.channels:
return 'not in that channel: {}'.format(channel)
self.admin.do_action(channel, text)
return None
def admin_msg(self, rest, nick=None):
""" Send a private msg, expects !msg nick/channel message """
msgparts = rest.split()
if len(msgparts) < 2:
return 'need target and message.'
target = msgparts[0]
msgtext = ' '.join(msgparts[1:])
self.admin.sendmsg(target, msgtext)
return None
def admin_op(self, rest, nick=None):
""" Request ops from ChanServ on behalf of the bot. """
if not rest:
self.admin.op_request()
return None
chan, _, nick = rest.partition(' ')
if not chan.startswith('#'):
# No channel given, request ops for nick in ##<botnick>
nick = chan
chan = None
self.admin.op_request(channel=chan, nick=nick)
def admin_opme(self, rest, nick=None):
""" Request ops from the bot (if the bot is an op itself) """
chan = rest if rest.startswith('#') else None
self.admin.op_request(channel=chan, nick=nick)
def admin_part(self, rest, nick=None):
""" Leave a channel as pyval. """
if ',' in rest:
# multichannel
chans = [s.strip() for s in rest.split(',')]
else:
# single channel.
chans = [rest]
notinchans = []
for chan in chans:
if not chan.startswith('#'):
chan = '#{}'.format(chan)
if chan in self.admin.channels:
log.msg('Parting from: {}'.format(chan))
self.admin.sendLine('PART {}'.format(chan))
else:
# not in that channel, send a msg in a moment.
notinchans.append(chan)
if notinchans:
chanstr = 'channel' if len(notinchans) == 1 else 'channel'
return 'Not in {}: {}'.format(chanstr, ', '.join(notinchans))
# parted channel(s) no response is sent.
# (you can check the log/stdout)
return None
def admin_partall(self, rest, nick=None):
""" Part all current channels.
The only way to re-join is to send a private msg to pyval,
or shutdown and restart.
"""
return self.admin_part(','.join(self.admin.channels))
def admin_say(self, rest, nick=None):
""" Send chat message back to person. """
if not rest:
return None
log.msg('Saying: {}'.format(rest))
return rest