forked from progval/Limnoria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallbacks.py
1847 lines (1688 loc) · 73.5 KB
/
callbacks.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
# -*- coding: utf8 -*-
###
# Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2014, James McCoy
# Copyright (c) 2010-2021, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
"""
This module contains the basic callbacks for handling PRIVMSGs.
"""
import re
import copy
import time
from . import shlex
import codecs
import getopt
import inspect
import warnings
from . import (conf, ircdb, irclib, ircmsgs, ircutils, log, registry,
utils, world)
from .utils import minisix
from .utils.iter import any, all
from .i18n import PluginInternationalization
_ = PluginInternationalization()
def _addressed(irc, msg, prefixChars=None, nicks=None,
prefixStrings=None, whenAddressedByNick=None,
whenAddressedByNickAtEnd=None, payload=None):
"""Determines whether this message is a command to the bot (because of a
prefix char/string, or because the bot's nick is used as prefix, or because
it's a private message, etc.).
Returns the actual content of the command (ie. the content of the message,
stripped of the prefix that was used to determine if it's addressed).
If 'payload' is not None, its value is used instead of msg.args[1] as the
content of the message."""
if isinstance(irc, str):
warnings.warn(
"callbacks.addressed's first argument should now be be the Irc "
"object instead of the bot's nick.",
DeprecationWarning)
network = None
nick = irc
else:
network = irc.network
nick = irc.nick
def get(group):
v = group.getSpecific(network=network, channel=msg.channel)
return v()
def stripPrefixStrings(payload):
for prefixString in prefixStrings:
if payload.startswith(prefixString):
payload = payload[len(prefixString):].lstrip()
return payload
if msg.command == 'NOTICE':
return ''
assert msg.command in ('PRIVMSG', 'TAGMSG'), msg.command
target = msg.channel or msg.args[0]
if not payload:
payload = msg.args[1]
if not payload:
return ''
if prefixChars is None:
prefixChars = get(conf.supybot.reply.whenAddressedBy.chars)
if whenAddressedByNick is None:
whenAddressedByNick = get(conf.supybot.reply.whenAddressedBy.nick)
if whenAddressedByNickAtEnd is None:
r = conf.supybot.reply.whenAddressedBy.nick.atEnd
whenAddressedByNickAtEnd = get(r)
if prefixStrings is None:
prefixStrings = get(conf.supybot.reply.whenAddressedBy.strings)
# We have to check this before nicks -- try "@google supybot" with supybot
# and whenAddressedBy.nick.atEnd on to see why.
if any(payload.startswith, prefixStrings):
return stripPrefixStrings(payload)
elif payload[0] in prefixChars:
return payload[1:].strip()
if nicks is None:
nicks = get(conf.supybot.reply.whenAddressedBy.nicks)
nicks = list(map(ircutils.toLower, nicks))
else:
nicks = list(nicks) # Just in case.
nicks.insert(0, ircutils.toLower(nick))
# Ok, let's see if it's a private message.
if ircutils.nickEqual(target, nick):
payload = stripPrefixStrings(payload)
while payload and payload[0] in prefixChars:
payload = payload[1:].lstrip()
return payload
# Ok, not private. Does it start with our nick?
elif whenAddressedByNick:
for nick in nicks:
lowered = ircutils.toLower(payload)
if lowered.startswith(nick):
try:
(maybeNick, rest) = payload.split(None, 1)
toContinue = False
while not ircutils.isNick(maybeNick, strictRfc=True):
if maybeNick[-1].isalnum():
toContinue = True
break
maybeNick = maybeNick[:-1]
if toContinue:
continue
if ircutils.nickEqual(maybeNick, nick):
return rest
else:
continue
except ValueError: # split didn't work.
continue
elif whenAddressedByNickAtEnd and lowered.rstrip().endswith(nick):
rest = payload.rstrip()[:-len(nick)]
possiblePayload = rest.rstrip(' \t,;')
if possiblePayload != rest:
# There should be some separator between the nick and the
# previous alphanumeric character.
return possiblePayload
if get(conf.supybot.reply.whenNotAddressed):
return payload
else:
return ''
def addressed(irc, msg, **kwargs):
"""If msg is addressed to 'name', returns the portion after the address.
Otherwise returns the empty string.
"""
payload = msg.addressed
if payload is not None:
return payload
else:
payload = _addressed(irc, msg, **kwargs)
msg.tag('addressed', payload)
return payload
def canonicalName(command, preserve_spaces=False):
"""Turn a command into its canonical form.
Currently, this makes everything lowercase and removes all dashes and
underscores.
"""
if minisix.PY2 and isinstance(command, unicode):
command = command.encode('utf-8')
elif minisix.PY3 and isinstance(command, bytes):
command = command.decode()
special = '\t-_'
if not preserve_spaces:
special += ' '
reAppend = ''
while command and command[-1] in special:
reAppend = command[-1] + reAppend
command = command[:-1]
return ''.join([x for x in command if x not in special]).lower() + reAppend
def reply(*args, **kwargs):
warnings.warn('callbacks.reply is deprecated. Use irc.reply instead.',
DeprecationWarning)
return _makeReply(dynamic.irc, *args, **kwargs)
def _makeReply(irc, msg, s,
prefixNick=None, private=None,
notice=None, to=None, action=None, error=False,
stripCtcp=True):
msg.tag('repliedTo')
# Ok, let's make the target:
# XXX This isn't entirely right. Consider to=#foo, private=True.
target = ircutils.replyTo(msg)
def isPublic(s):
return irc.isChannel(irc.stripChannelPrefix(s))
if to is not None and isPublic(to):
target = to
if isPublic(target):
channel = irc.stripChannelPrefix(target)
else:
channel = None
if notice is None:
notice = conf.get(conf.supybot.reply.withNotice,
channel=channel, network=irc.network)
if private is None:
private = conf.get(conf.supybot.reply.inPrivate,
channel=channel, network=irc.network)
if prefixNick is None:
prefixNick = conf.get(conf.supybot.reply.withNickPrefix,
channel=channel, network=irc.network)
if error:
notice =conf.get(conf.supybot.reply.error.withNotice,
channel=channel, network=irc.network) or notice
private=conf.get(conf.supybot.reply.error.inPrivate,
channel=channel, network=irc.network) or private
s = _('Error: ') + s
if private:
prefixNick = False
if to is None:
target = msg.nick
else:
target = to
if action:
prefixNick = False
if to is None:
to = msg.nick
if stripCtcp:
s = s.strip('\x01')
# Ok, now let's make the payload:
s = ircutils.safeArgument(s)
if not s and not action:
s = _('Error: I tried to send you an empty message.')
if prefixNick and isPublic(target):
# Let's may sure we don't do, "#channel: foo.".
if not isPublic(to):
s = '%s: %s' % (to, s)
if not isPublic(target):
if conf.supybot.reply.withNoticeWhenPrivate():
notice = True
# And now, let's decide whether it's a PRIVMSG or a NOTICE.
msgmaker = ircmsgs.privmsg
if notice:
msgmaker = ircmsgs.notice
# We don't use elif here because actions can't be sent as NOTICEs.
if action:
msgmaker = ircmsgs.action
# Finally, we'll return the actual message.
ret = msgmaker(target, s)
ret.tag('inReplyTo', msg)
if 'msgid' in msg.server_tags \
and conf.supybot.protocols.irc.experimentalExtensions() \
and 'message-tags' in irc.state.capabilities_ack:
# In theory, msgid being in server_tags implies message-tags was
# negotiated, but the +reply spec requires it explicitly. Plus, there's
# no harm in doing this extra check, in case a plugin is replying
# across network (as it may happen with '@network command').
ret.server_tags['+draft/reply'] = msg.server_tags['msgid']
if msg.channel and not irc.isChannel(ret.args[0]):
# If replying in non-channel to a channel message, use the tag
# defined in https://github.com/ircv3/ircv3-specifications/pull/498
ret.server_tags["+draft/channel-context"] = msg.channel
return ret
def error(*args, **kwargs):
warnings.warn('callbacks.error is deprecated. Use irc.error instead.',
DeprecationWarning)
return _makeErrorReply(dynamic.irc, *args, **kwargs)
def _makeErrorReply(irc, msg, s, **kwargs):
"""Makes an error reply to msg with the appropriate error payload."""
kwargs['error'] = True
msg.tag('isError')
return _makeReply(irc, msg, s, **kwargs)
def getHelp(method, name=None, doc=None):
if name is None:
name = method.__name__
if doc is None:
if method.__doc__ is None:
doclines = ['This command has no help. Complain to the author.']
else:
doclines = method.__doc__.splitlines()
else:
doclines = doc.splitlines()
s = '%s %s' % (name, doclines.pop(0))
if doclines:
help = ' '.join(doclines)
s = '(%s) -- %s' % (ircutils.bold(s), help)
return utils.str.normalizeWhitespace(s)
def getSyntax(method, name=None, doc=None):
if name is None:
name = method.__name__
if doc is None:
doclines = method.__doc__.splitlines()
else:
doclines = doc.splitlines()
return '%s %s' % (name, doclines[0])
class Error(Exception):
"""Generic class for errors in Privmsg callbacks."""
pass
class ArgumentError(Error):
"""The bot replies with a help message when this is raised."""
pass
class SilentError(Error):
"""An error that we should not notify the user."""
pass
class Tokenizer(object):
# This will be used as a global environment to evaluate strings in.
# Evaluation is, of course, necessary in order to allow escaped
# characters to be properly handled.
#
# These are the characters valid in a token. Everything printable except
# double-quote, left-bracket, and right-bracket.
separators = '\x00\r\n \t'
def __init__(self, brackets='', pipe=False, quotes='"'):
if brackets:
self.separators += brackets
self.left = brackets[0]
self.right = brackets[1]
else:
self.left = ''
self.right = ''
self.pipe = pipe
if self.pipe:
self.separators += '|'
self.quotes = quotes
self.separators += quotes
def _handleToken(self, token):
if token[0] == token[-1] and token[0] in self.quotes:
token = token[1:-1]
# FIXME: No need to tell you this is a hack.
# It has to handle both IRC commands and serialized configuration.
#
# Whoever you are, if you make a single modification to this
# code, TEST the code with Python 2 & 3, both with the unit
# tests and on IRC with this: @echo "好"
if minisix.PY2:
try:
token = token.encode('utf8').decode('string_escape')
token = token.decode('utf8')
except:
token = token.decode('string_escape')
else:
token = codecs.getencoder('utf8')(token)[0]
token = codecs.getdecoder('unicode_escape')(token)[0]
try:
token = token.encode('iso-8859-1').decode()
except: # Prevent issue with tokens like '"\\x80"'.
pass
return token
def _insideBrackets(self, lexer):
ret = []
while True:
token = lexer.get_token()
if not token:
raise SyntaxError(_('Missing "%s". You may want to '
'quote your arguments with double '
'quotes in order to prevent extra '
'brackets from being evaluated '
'as nested commands.') % self.right)
elif token == self.right:
return ret
elif token == self.left:
ret.append(self._insideBrackets(lexer))
else:
ret.append(self._handleToken(token))
return ret
def tokenize(self, s):
lexer = shlex.shlex(minisix.io.StringIO(s))
lexer.commenters = ''
lexer.quotes = self.quotes
lexer.separators = self.separators
args = []
ends = []
while True:
token = lexer.get_token()
if not token:
break
elif token == '|' and self.pipe:
# The "and self.pipe" might seem redundant here, but it's there
# for strings like 'foo | bar', where a pipe stands alone as a
# token, but shouldn't be treated specially.
if not args:
raise SyntaxError(_('"|" with nothing preceding. I '
'obviously can\'t do a pipe with '
'nothing before the |.'))
ends.append(args)
args = []
elif token == self.left:
args.append(self._insideBrackets(lexer))
elif token == self.right:
raise SyntaxError(_('Spurious "%s". You may want to '
'quote your arguments with double '
'quotes in order to prevent extra '
'brackets from being evaluated '
'as nested commands.') % self.right)
else:
args.append(self._handleToken(token))
if ends:
if not args:
raise SyntaxError(_('"|" with nothing following. I '
'obviously can\'t do a pipe with '
'nothing after the |.'))
args.append(ends.pop())
while ends:
args[-1].append(ends.pop())
return args
def tokenize(s, channel=None, network=None):
"""A utility function to create a Tokenizer and tokenize a string."""
pipe = False
brackets = ''
nested = conf.supybot.commands.nested
if nested():
brackets = nested.brackets.getSpecific(network, channel)()
if conf.get(nested.pipeSyntax,
channel=channel, network=network): # No nesting, no pipe.
pipe = True
quotes = conf.supybot.commands.quotes.getSpecific(network, channel)()
try:
ret = Tokenizer(brackets=brackets,pipe=pipe,quotes=quotes).tokenize(s)
return ret
except ValueError as e:
raise SyntaxError(str(e))
def formatCommand(command):
return ' '.join(command)
def checkCommandCapability(msg, cb, commandName):
plugin = cb.name().lower()
if not isinstance(commandName, minisix.string_types):
assert commandName[0] == plugin, ('checkCommandCapability no longer '
'accepts command names that do not start with the callback\'s '
'name (%s): %s') % (plugin, commandName)
commandName = '.'.join(commandName)
def checkCapability(capability):
assert ircdb.isAntiCapability(capability)
if ircdb.checkCapability(msg.prefix, capability):
log.info('Preventing %s from calling %s because of %s.',
msg.prefix, commandName, capability)
raise RuntimeError(capability)
try:
antiCommand = ircdb.makeAntiCapability(commandName)
checkCapability(antiCommand)
checkAtEnd = [commandName]
default = conf.supybot.capabilities.default()
if msg.channel:
channel = msg.channel
checkCapability(ircdb.makeChannelCapability(channel, antiCommand))
chanCommand = ircdb.makeChannelCapability(channel, commandName)
checkAtEnd += [chanCommand]
default &= ircdb.channels.getChannel(channel).defaultAllow
return not (default or \
any(lambda x: ircdb.checkCapability(msg.prefix, x),
checkAtEnd))
except RuntimeError as e:
s = ircdb.unAntiCapability(str(e))
return s
class RichReplyMethods(object):
"""This is a mixin so these replies need only be defined once. It operates
under several assumptions, including the fact that 'self' is an Irc object
of some sort and there is a self.msg that is an IrcMsg."""
def __makeReply(self, prefix, s):
if s:
s = '%s %s' % (prefix, s)
else:
s = prefix
return ircutils.standardSubstitute(self, self.msg, s)
def _getConfig(self, wrapper):
return conf.get(wrapper,
channel=self.msg.channel, network=self.irc.network)
def replySuccess(self, s='', **kwargs):
r"""Replies with a success message, configurable with
``supybot.replies.success`` or the Success plugin.
:arg str s:
Text to append to the standard success message
:arg \**kwargs:
See :meth:`NestedCommandsIrcProxy.reply`'s keyword arguments
"""
v = self._getConfig(conf.supybot.replies.success)
if v:
s = self.__makeReply(v, s)
return self.reply(s, **kwargs)
else:
self.noReply()
def replyError(self, s='', **kwargs):
v = self._getConfig(conf.supybot.replies.error)
if 'msg' in kwargs:
msg = kwargs['msg']
if ircdb.checkCapability(msg.prefix, 'owner'):
v = self._getConfig(conf.supybot.replies.errorOwner)
if v:
s = self.__makeReply(v, s)
return self.reply(s, **kwargs)
else:
self.noReply()
def _getTarget(self, to=None):
"""Compute the target according to self.to, the provided to,
and self.private, and return it. Mainly used by reply methods."""
# FIXME: Don't set self.to.
# I still set it to be sure I don't introduce a regression,
# but it does not make sense for .reply() and .replies() to
# change the state of this Irc object.
if to is not None:
self.to = self.to or to
if self.private:
target = to or self.msg.nick
elif self.msg.channel is None:
target = self.msg.nick
else:
target = self.to or self.msg.args[0]
return target
def replies(self, L, prefixer=None, joiner=None,
onlyPrefixFirst=False,
oneToOne=None, **kwargs):
if prefixer is None:
prefixer = ''
if joiner is None:
joiner = utils.str.commaAndify
if isinstance(prefixer, minisix.string_types):
prefixer = prefixer.__add__
if isinstance(joiner, minisix.string_types):
joiner = joiner.join
to = self._getTarget(kwargs.get('to'))
if oneToOne is None: # Can be True, False, or None
if self.irc.isChannel(to):
oneToOne = conf.get(conf.supybot.reply.oneToOne,
channel=to, network=self.irc.network)
else:
oneToOne = conf.supybot.reply.oneToOne()
if oneToOne:
return self.reply(prefixer(joiner(L)), **kwargs)
else:
msg = None
first = True
for s in L:
if onlyPrefixFirst:
if first:
first = False
msg = self.reply(prefixer(s), **kwargs)
else:
msg = self.reply(s, **kwargs)
else:
msg = self.reply(prefixer(s), **kwargs)
return msg
def noReply(self, msg=None):
self.repliedTo = True
def _error(self, s, Raise=False, **kwargs):
if Raise:
raise Error(s)
else:
return self.error(s, **kwargs)
def errorNoCapability(self, capability, s='', **kwargs):
if 'Raise' not in kwargs:
kwargs['Raise'] = True
log.warning('Denying %s for lacking %q capability.',
self.msg.prefix, capability)
# noCapability means "don't send a specific capability error
# message" not "don't send a capability error message at all", like
# one would think
if self._getConfig(conf.supybot.reply.error.noCapability) or \
capability in conf.supybot.capabilities.private():
v = self._getConfig(conf.supybot.replies.genericNoCapability)
else:
v = self._getConfig(conf.supybot.replies.noCapability)
try:
v %= capability
except TypeError: # No %s in string
pass
s = self.__makeReply(v, s)
if s:
return self._error(s, **kwargs)
elif kwargs['Raise']:
raise Error()
def errorPossibleBug(self, s='', **kwargs):
v = self._getConfig(conf.supybot.replies.possibleBug)
if s:
s += ' (%s)' % v
else:
s = v
return self._error(s, **kwargs)
def errorNotRegistered(self, s='', **kwargs):
v = self._getConfig(conf.supybot.replies.notRegistered)
return self._error(self.__makeReply(v, s), **kwargs)
def errorNoUser(self, s='', name='that user', **kwargs):
if 'Raise' not in kwargs:
kwargs['Raise'] = True
v = self._getConfig(conf.supybot.replies.noUser)
try:
v = v % name
except TypeError:
log.warning('supybot.replies.noUser should have one "%s" in it.')
return self._error(self.__makeReply(v, s), **kwargs)
def errorRequiresPrivacy(self, s='', **kwargs):
v = self._getConfig(conf.supybot.replies.requiresPrivacy)
return self._error(self.__makeReply(v, s), **kwargs)
def errorInvalid(self, what, given=None, s='', repr=True, **kwargs):
if given is not None:
if repr:
given = _repr(given)
else:
given = '"%s"' % given
v = _('%s is not a valid %s.') % (given, what)
else:
v = _('That\'s not a valid %s.') % what
if 'Raise' not in kwargs:
kwargs['Raise'] = True
if s:
v += ' ' + s
return self._error(v, **kwargs)
_repr = repr
class ReplyIrcProxy(RichReplyMethods):
"""This class is a thin wrapper around an irclib.Irc object that gives it
the reply() and error() methods (as well as everything in RichReplyMethods,
based on those two).
If ``replyIrc`` is given in addition to ``irc``, commands will be run on ``irc``
but replies will be delivered to ``replyIrc``. This is used by the Network
plugin to run commands on other networks."""
_mores = ircutils.IrcDict()
def __init__(self, irc, msg, replyIrc=None):
self.irc = irc
self.replyIrc = replyIrc or irc
self.msg = msg
self.getRealIrc()._setMsgChannel(self.msg)
def getRealIrc(self):
"""Returns the real irclib.Irc object underlying this proxy chain."""
if isinstance(self.irc, irclib.Irc):
return self.irc
else:
return self.irc.getRealIrc()
# This should make us be considered equal to our irclib.Irc object for
# hashing; an important thing (no more "too many open files" exceptions :))
def __hash__(self):
return hash(self.getRealIrc())
def __eq__(self, other):
return self.getRealIrc() == other
__req__ = __eq__
def __ne__(self, other):
return not (self == other)
__rne__ = __ne__
def error(self, s, msg=None, **kwargs):
if 'Raise' in kwargs and kwargs['Raise']:
raise Error()
if msg is None:
msg = self.msg
if s:
m = _makeErrorReply(self.replyIrc, msg, s, **kwargs)
self.replyIrc.queueMsg(m)
return m
def _defaultPrefixNick(self, msg):
if msg.channel:
return conf.get(conf.supybot.reply.withNickPrefix,
channel=msg.channel, network=self.irc.network)
else:
return conf.supybot.reply.withNickPrefix()
def reply(self, s, msg=None, **kwargs):
"""
Keyword arguments:
:arg bool noLengthCheck:
True if the length shouldn't be checked (used for 'more' handling)
:arg bool prefixNick:
False if the nick shouldn't be prefixed to the reply.
:arg bool action:
True if the reply should be an action.
:arg bool private:
True if the reply should be in private.
:arg bool notice:
True if the reply should be noticed when the bot is configured
to do so.
:arg str to:
The nick or channel the reply should go to.
Defaults to msg.args[0] (or msg.nick if private)
:arg bool sendImmediately:
True if the reply should use sendMsg() which
bypasses conf.supybot.protocols.irc.throttleTime
and gets sent before any queued messages
"""
if msg is None:
msg = self.msg
assert not isinstance(s, ircmsgs.IrcMsg), \
'Old code alert: there is no longer a "msg" argument to reply.'
kwargs.pop('noLengthCheck', None)
if 'target' not in kwargs:
# TODO: deduplicate this with _getTarget
# TODO: it looks like 'target' is never in kwargs.
# (an old version of this code crashed when 'target' was
# not given, but no one complained). Remove the conditional?
if kwargs.get('private', False) or msg.channel is None:
kwargs['target'] = msg.nick
else:
kwargs['target'] = kwargs.get('to', None) or msg.args[0]
if 'prefixNick' not in kwargs:
kwargs['prefixNick'] = self._defaultPrefixNick(msg)
if kwargs.get("action"):
kwargs["prefixNick"] = False
kwargs["noLengthCheck"] = True
self._sendReply(s, msg=msg, **kwargs)
def __getattr__(self, attr):
return getattr(self.irc, attr)
def _replyOverhead(self, msg, **kwargs):
"""Returns the number of bytes added to a PRIVMSG payload, either by
Limnoria itself or by the server.
Ignores tag bytes, as they are accounted for separately."""
# FIXME: big hack.
# _makeReply does a lot of internal state computation, especially
# related to the final target to use.
# I tried to get them out of _makeReply but it's a clusterfuck, so I
# gave up. Instead, we call _makeReply with a dummy payload to guess
# what overhead it will add.
payload = 'foo'
channel = msg.channel
msg = copy.deepcopy(msg) # because _makeReply calls .tag('repliedTo')
msg.channel = channel # ugh... copy.deepcopy uses msg.__reduce__
reply_msg = _makeReply(self, msg, payload, **kwargs)
# strip tags, add prefix
reply_msg = ircmsgs.IrcMsg(
msg=reply_msg, server_tags={}, prefix=self.prefix)
return len(str(reply_msg)) - len(payload)
def _sendReply(self, s, target, msg, sendImmediately=False,
noLengthCheck=False, **kwargs):
if sendImmediately:
sendMsg = self.replyIrc.sendMsg
else:
sendMsg = self.replyIrc.queueMsg
if isinstance(self.replyIrc, self.__class__):
s = s[:conf.supybot.reply.maximumLength()]
return self.replyIrc.reply(s,
noLengthCheck=noLengthCheck,
**kwargs)
elif noLengthCheck:
# noLengthCheck only matters to NestedCommandsIrcProxy, so
# it's not used here. Just in case you were wondering.
m = _makeReply(self.replyIrc, msg, s, **kwargs)
sendMsg(m)
return m
else:
s = ircutils.safeArgument(s)
allowedLength = conf.get(conf.supybot.reply.mores.length,
channel=target, network=self.replyIrc.network)
if not allowedLength: # 0 indicates this.
allowedLength = 512 - self._replyOverhead(msg, **kwargs)
maximumMores = conf.get(conf.supybot.reply.mores.maximum,
channel=target, network=self.replyIrc.network)
maximumLength = allowedLength * maximumMores
if len(s) > maximumLength:
log.warning('Truncating to %s bytes from %s bytes.',
maximumLength, len(s))
s = s[:maximumLength]
s_size = len(s.encode()) if minisix.PY3 else len(s)
if s_size <= allowedLength or \
not conf.get(conf.supybot.reply.mores,
channel=target, network=self.replyIrc.network):
# There's no need for action=self.action here because
# action implies noLengthCheck, which has already been
# handled. Let's stick an assert in here just in case.
assert not kwargs.get('action')
m = _makeReply(self.replyIrc, msg, s, **kwargs)
sendMsg(m)
return m
# The '(XX more messages)' may have not the same
# length in the current locale
allowedLength -= len(_('(XX more messages)')) + 1 # bold
chunks = ircutils.wrap(s, allowedLength)
# Last messages to display at the beginning of the list
# (which is used like a stack)
chunks.reverse()
instant = conf.get(conf.supybot.reply.mores.instant,
channel=target, network=self.replyIrc.network)
# Big complex loop ahead, with lots of cases and opportunities for
# off-by-one errors. Here is the meaning of each of the variables
#
# * 'i' is the number of chunks after the current one
#
# * 'is_first' is True when the message is the very first message
# (so last iteration of the loop)
#
# * 'is_last' is True when the message is the very last (so first
# iteration of the loop)
#
# * 'is_instant' is True when the message is in one of the messages
# sent immediately when the command is called, ie. without
# calling @misc more. (when supybot.reply.mores.instant is 1,
# which is the default, this is equivalent to 'is_first')
#
# * 'is_last_instant' is True when the message is the last of the
# instant message (so the first iteration of the loop with an
# instant message).
#
# We need all this complexity because pagination is hard, and we
# want:
#
# * the '(XX more messages)' suffix on the last instant message,
# and every other message (mandatory, it's a great feature),
# but not on the other instant messages (mandatory when
# multiline is enabled, but very nice to have in general)
# * the nick prefix on the first message and every other message
# that isn't instant (mandatory), but not on the other instant
# messages (also mandatory only when multiline is enabled)
msgs = []
for (i, chunk) in enumerate(chunks):
is_first = i == len(chunks) - 1
is_last = i == 0
is_instant = len(chunks) - i <= instant
is_last_instant = len(chunks) - i == instant
if is_last:
# last message, no suffix to add
pass
elif is_instant and not is_last_instant:
# one of the first messages, and the next one will
# also be sent immediately, so no suffix
pass
else:
if i == 1:
more = _('more message')
else:
more = _('more messages')
n = ircutils.bold('(%i %s)' % (len(msgs), more))
chunk = '%s %s' % (chunk, n)
if is_instant and not is_first:
d = kwargs.copy()
d['prefixNick'] = False
msgs.append(_makeReply(self.replyIrc, msg, chunk, **d))
else:
msgs.append(_makeReply(self.replyIrc, msg, chunk, **kwargs))
instant_messages = []
while instant > 0 and msgs:
instant -= 1
response = msgs.pop()
instant_messages.append(response)
# XXX We should somehow allow these to be returned, but
# until someone complains, we'll be fine :) We
# can't return from here, though, for obvious
# reasons.
# return m
if conf.supybot.protocols.irc.experimentalExtensions() \
and 'draft/multiline' in \
self.replyIrc.state.capabilities_ack \
and len(instant_messages) > 1:
# More than one message to send now, and we are allowed to use
# multiline batches, so let's do it
self.replyIrc.queueMultilineBatches(
instant_messages, target, msg.nick, concat=True,
allowedLength=allowedLength,
sendImmediately=sendImmediately)
else:
for instant_msg in instant_messages:
sendMsg(instant_msg)
if not msgs:
return
prefix = msg.prefix
if target and ircutils.isNick(target):
try:
state = self.replyIrc.state
prefix = state.nickToHostmask(target)
except KeyError:
pass # We'll leave it as it is.
if '!' in prefix and '@' in prefix:
mask = prefix.split('!', 1)[1]
self._mores[mask] = msgs
public = bool(self.msg.channel)
private = kwargs.get('private', False) or not public
self._mores[msg.nick] = (private, msgs)
return response
def queueMultilineBatches(self, msgs, target, targetNick, concat,
allowedLength=0, sendImmediately=False):
"""Queues the msgs passed as argument in batches using draft/multiline
batches.
This errors if experimentalExtensions is disabled or draft/multiline
was not negotiated."""
assert conf.supybot.protocols.irc.experimentalExtensions()
assert 'draft/multiline' in self.state.capabilities_ack
if allowedLength: # 0 indicates this.
largest_msg_size = allowedLength
else:
# Used as upper bound of each message's size to decide how many
# messages to put in each batch.
largest_msg_size = max(len(msg.args[1]) for msg in msgs)
multiline_cap_values = ircutils.parseCapabilityKeyValue(
self.state.capabilities_ls['draft/multiline'])
# All the messages in instant_messages are to be sent
# immediately, in multiline batches.
max_bytes_per_batch = int(multiline_cap_values['max-bytes'])
# We have to honor max_bytes_per_batch, but I don't want to
# encode messages again here just to have their length, so
# let's assume they all have the maximum length.
# It's not optimal, but close enough and simplifies the code.
messages_per_batch = max_bytes_per_batch // largest_msg_size
# "Clients MUST NOT send tags other than draft/multiline-concat and
# batch on messages within the batch. In particular, all client-only
# tags associated with the message must be sent attached to the initial
# BATCH command."
# -- <https://ircv3.net/specs/extensions/multiline>
# So we copy the tags of the first message, discard the tags of all
# other messages, and apply the tags to the opening BATCH
server_tags = msgs[0].server_tags
for batch_msgs in utils.iter.grouper(msgs, messages_per_batch):
# TODO: should use sendBatch instead of queueBatch if
# sendImmediately is True
batch_name = ircutils.makeLabel()
batch = []
batch.append(ircmsgs.IrcMsg(command='BATCH',
args=('+' + batch_name, 'draft/multiline', target),
server_tags=server_tags))
for (i, batch_msg) in enumerate(batch_msgs):
if batch_msg is None:
continue # 'grouper' generates None at the end
assert 'batch' not in batch_msg.server_tags
# Discard the existing tags, and add the batch ones.
batch_msg.server_tags = {'batch': batch_name}
if concat and i > 0:
# Tell clients not to add a newline after this
batch_msg.server_tags['draft/multiline-concat'] = None
batch.append(batch_msg)
batch.append(ircmsgs.IrcMsg(
command='BATCH', args=('-' + batch_name,)))
self.queueBatch(batch)
SimpleProxy = ReplyIrcProxy # Backwards-compatibility
class NestedCommandsIrcProxy(ReplyIrcProxy):
"A proxy object to allow proper nesting of commands (even threaded ones)."
def __init__(self, irc, msg, args, nested=0, replyIrc=None):
assert isinstance(args, list), 'Args should be a list, not a string.'
super(NestedCommandsIrcProxy, self).__init__(
irc, msg, replyIrc=replyIrc)
self.nested = nested
self.repliedTo = False
if not self.nested and isinstance(irc, self.__class__):
# This means we were given an NestedCommandsIrcProxy instead of an
# irclib.Irc, and so we're obviously nested. But nested wasn't
# set! So we take our given Irc's nested value.
self.nested += irc.nested
maxNesting = conf.supybot.commands.nested.maximum()