-
Notifications
You must be signed in to change notification settings - Fork 0
/
irc_b.py
3078 lines (2488 loc) · 97.6 KB
/
irc_b.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
# -*- test-case-name: twisted.words.test.test_irc -*-
# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Internet Relay Chat Protocol for client and server.
Future Plans
============
The way the IRCClient class works here encourages people to implement
IRC clients by subclassing the ephemeral protocol class, and it tends
to end up with way more state than it should for an object which will
be destroyed as soon as the TCP transport drops. Someone oughta do
something about that, ya know?
The DCC support needs to have more hooks for the client for it to be
able to ask the user things like \"Do you want to accept this session?\"
and \"Transfer #2 is 67% done.\" and otherwise manage the DCC sessions.
Test coverage needs to be better.
@author: Kevin Turner
@see: RFC 1459: Internet Relay Chat Protocol
@see: RFC 2812: Internet Relay Chat: Client Protocol
@see: U{The Client-To-Client-Protocol
<http://www.irchelp.org/irchelp/rfc/ctcpspec.html>}
"""
"""
modifications by me ([email protected])
isupport:
added the new stuff from the ISUPPORT branch owned by exarkun
changed all passings of int in ISUPPORT to _intOrDefault
added a second dictionary, features2, to store value strings where parsing the value failed
changed IRC_RPL_ISUPPORT to call IRC_RPL_BOUNCE if it detects a bounce message, since
apparently the code for that command can also mean bounce
added irclower(), which uses CASEMAPPING but with a default
ctcp:
unless I read the code wrong, all ctcp messages go to the same functions whether they were
sent to a channel or to the user. so if the client didn't think to check, i guess a person
could send a DCC request to a channel and everybody using twisted IRC would respond to it?
so i changed all ctcp messages to go to a priv or a chan version. or does the server
prevent that? either way, due to the following addition, i wanted /me actions to be sent
to the two separate places
i also added a chanmsg function to complement the privmsg function.
added usersplit()
changed joined, parted, etc. to return the full nick!ident@host instead of just the nick portion.
changed a couple of ctcp replies
added names() and endofnames()
any other changes I forgot about
"""
import errno, os, random, re, stat, struct, sys, time, types, traceback
import string, socket
from os import path
from twisted.internet import reactor, protocol
from twisted.persisted import styles
from twisted.protocols import basic
from twisted.python import log, reflect, text
NUL = chr(0)
CR = chr(015)
NL = chr(012)
LF = NL
SPC = chr(040)
CHANNEL_PREFIXES = '&#!+'
irclowertranslations = {
"ascii": string.maketrans(string.uppercase,
string.lowercase),
"rfc1549": string.maketrans(string.uppercase + "\x7B\x7C\x7D\x7E",
string.lowercase + "\x5B\x5C\x5E\x5F"),
"strict-rfc1549": string.maketrans(string.uppercase + "\x7B\x7C\x7D",
string.lowercase + "\x5B\x5C\x5E")
}
usersplit = re.compile("(?P<nick>.*?)!(?P<ident>.*?)@(?P<host>.*)").match
class IRCBadMessage(Exception):
pass
class IRCPasswordMismatch(Exception):
pass
def irclower(text):
trans = irclowertranslations["rfc1549"]
return text.translate(trans)
def parsemsg(s):
"""Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
return prefix, command, args
def split(str, length = 80):
"""I break a message into multiple lines.
I prefer to break at whitespace near str[length]. I also break at \\n.
@returns: list of strings
"""
if length <= 0:
raise ValueError("Length must be a number greater than zero")
r = []
while len(str) > length:
w, n = str[:length].rfind(' '), str[:length].find('\n')
if w == -1 and n == -1:
line, str = str[:length], str[length:]
else:
if n == -1:
i = w
else:
i = n
if i == 0: # just skip the space or newline. don't append any output.
str = str[1:]
continue
line, str = str[:i], str[i+1:]
r.append(line)
if len(str):
r.extend(str.split('\n'))
return r
def _intOrDefault(value, default=None):
"""
Convert a value to an integer if possible.
@rtype: C{int} or type of L{default}
@return: An integer when C{value} can be converted to an integer,
otherwise return C{default}
"""
if value:
try:
return int(value)
except (TypeError, ValueError):
pass
return default
class UnhandledCommand(RuntimeError):
"""
A command dispatcher could not locate an appropriate command handler.
"""
class _CommandDispatcherMixin(object):
"""
Dispatch commands to handlers based on their name.
Command handler names should be of the form C{prefix_commandName},
where C{prefix} is the value specified by L{prefix}, and must
accept the parameters as given to L{dispatch}.
Attempting to mix this in more than once for a single class will cause
strange behaviour, due to L{prefix} being overwritten.
@type prefix: C{str}
@ivar prefix: Command handler prefix, used to locate handler attributes
"""
prefix = None
def dispatch(self, commandName, *args):
"""
Perform actual command dispatch.
"""
def _getMethodName(command):
return '%s_%s' % (self.prefix, command)
def _getMethod(name):
return getattr(self, _getMethodName(name), None)
method = _getMethod(commandName)
if method is not None:
return method(*args)
method = _getMethod('unknown')
if method is None:
raise UnhandledCommand("No handler for %r could be found" % (_getMethodName(commandName),))
return method(commandName, *args)
class IRC(protocol.Protocol):
"""Internet Relay Chat server protocol.
"""
buffer = ""
hostname = None
encoding = None
def connectionMade(self):
self.channels = []
if self.hostname is None:
self.hostname = socket.getfqdn()
def sendLine(self, line):
if self.encoding is not None:
if isinstance(line, unicode):
line = line.encode(self.encoding)
self.transport.write("%s%s%s" % (line, CR, LF))
def sendMessage(self, command, *parameter_list, **prefix):
"""Send a line formatted as an IRC message.
First argument is the command, all subsequent arguments
are parameters to that command. If a prefix is desired,
it may be specified with the keyword argument 'prefix'.
"""
if not command:
raise ValueError, "IRC message requires a command."
if ' ' in command or command[0] == ':':
# Not the ONLY way to screw up, but provides a little
# sanity checking to catch likely dumb mistakes.
raise ValueError, "Somebody screwed up, 'cuz this doesn't" \
" look like a command to me: %s" % command
line = string.join([command] + list(parameter_list))
if prefix.has_key('prefix'):
line = ":%s %s" % (prefix['prefix'], line)
self.sendLine(line)
if len(parameter_list) > 15:
log.msg("Message has %d parameters (RFC allows 15):\n%s" %
(len(parameter_list), line))
def dataReceived(self, data):
"""This hack is to support mIRC, which sends LF only,
even though the RFC says CRLF. (Also, the flexibility
of LineReceiver to turn "line mode" on and off was not
required.)
"""
lines = (self.buffer + data).split(LF)
# Put the (possibly empty) element after the last LF back in the
# buffer
self.buffer = lines.pop()
for line in lines:
if len(line) <= 2:
# This is a blank line, at best.
continue
if line[-1] == CR:
line = line[:-1]
prefix, command, params = parsemsg(line)
# mIRC is a big pile of doo-doo
command = command.upper()
# DEBUG: log.msg( "%s %s %s" % (prefix, command, params))
self.handleCommand(command, prefix, params)
def handleCommand(self, command, prefix, params):
"""Determine the function to call for the given command and call
it with the given arguments.
"""
method = getattr(self, "irc_%s" % command, None)
try:
if method is not None:
method(prefix, params)
else:
self.irc_unknown(prefix, command, params)
except:
log.deferr()
def irc_unknown(self, prefix, command, params):
"""Implement me!"""
raise NotImplementedError(command, prefix, params)
# Helper methods
def privmsg(self, sender, recip, message):
"""Send a message to a channel or user
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it
must start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The message being sent.
"""
self.sendLine(":%s PRIVMSG %s :%s" % (sender, recip, lowQuote(message)))
def notice(self, sender, recip, message):
"""Send a \"notice\" to a channel or user.
Notices differ from privmsgs in that the RFC claims they are different.
Robots are supposed to send notices and not respond to them. Clients
typically display notices differently from privmsgs.
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it
must start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The message being sent.
"""
self.sendLine(":%s NOTICE %s :%s" % (sender, recip, message))
def action(self, sender, recip, message):
"""Send an action to a channel or user.
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it
must start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The action being sent.
"""
self.sendLine(":%s ACTION %s :%s" % (sender, recip, message))
def topic(self, user, channel, topic, author=None):
"""Send the topic to a user.
@type user: C{str} or C{unicode}
@param user: The user receiving the topic. Only their nick name, not
the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the topic.
@type topic: C{str} or C{unicode} or C{None}
@param topic: The topic string, unquoted, or None if there is
no topic.
@type author: C{str} or C{unicode}
@param author: If the topic is being changed, the full username and hostmask
of the person changing it.
"""
if author is None:
if topic is None:
self.sendLine(':%s %s %s %s :%s' % (
self.hostname, RPL_NOTOPIC, user, channel, 'No topic is set.'))
else:
self.sendLine(":%s %s %s %s :%s" % (
self.hostname, RPL_TOPIC, user, channel, lowQuote(topic)))
else:
self.sendLine(":%s TOPIC %s :%s" % (author, channel, lowQuote(topic)))
def topicAuthor(self, user, channel, author, date):
"""
Send the author of and time at which a topic was set for the given
channel.
This sends a 333 reply message, which is not part of the IRC RFC.
@type user: C{str} or C{unicode}
@param user: The user receiving the topic. Only their nick name, not
the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this information is relevant.
@type author: C{str} or C{unicode}
@param author: The nickname (without hostmask) of the user who last
set the topic.
@type date: C{int}
@param date: A POSIX timestamp (number of seconds since the epoch)
at which the topic was last set.
"""
self.sendLine(':%s %d %s %s %s %d' % (
self.hostname, 333, user, channel, author, date))
def names(self, user, channel, names):
"""Send the names of a channel's participants to a user.
@type user: C{str} or C{unicode}
@param user: The user receiving the name list. Only their nick
name, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the namelist.
@type names: C{list} of C{str} or C{unicode}
@param names: The names to send.
"""
# XXX If unicode is given, these limits are not quite correct
prefixLength = len(channel) + len(user) + 10
namesLength = 512 - prefixLength
L = []
count = 0
for n in names:
if count + len(n) + 1 > namesLength:
self.sendLine(":%s %s %s = %s :%s" % (
self.hostname, RPL_NAMREPLY, user, channel, ' '.join(L)))
L = [n]
count = len(n)
else:
L.append(n)
count += len(n) + 1
if L:
self.sendLine(":%s %s %s = %s :%s" % (
self.hostname, RPL_NAMREPLY, user, channel, ' '.join(L)))
self.sendLine(":%s %s %s %s :End of /NAMES list" % (
self.hostname, RPL_ENDOFNAMES, user, channel))
def who(self, user, channel, memberInfo):
"""
Send a list of users participating in a channel.
@type user: C{str} or C{unicode}
@param user: The user receiving this member information. Only their
nick name, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the member
information.
@type memberInfo: C{list} of C{tuples}
@param memberInfo: For each member of the given channel, a 7-tuple
containing their username, their hostmask, the server to which they
are connected, their nickname, the letter "H" or "G" (wtf do these
mean?), the hopcount from C{user} to this member, and this member's
real name.
"""
for info in memberInfo:
(username, hostmask, server, nickname, flag, hops, realName) = info
assert flag in ("H", "G")
self.sendLine(":%s %s %s %s %s %s %s %s %s :%d %s" % (
self.hostname, RPL_WHOREPLY, user, channel,
username, hostmask, server, nickname, flag, hops, realName))
self.sendLine(":%s %s %s %s :End of /WHO list." % (
self.hostname, RPL_ENDOFWHO, user, channel))
def whois(self, user, nick, username, hostname, realName, server, serverInfo, oper, idle, signOn, channels):
"""
Send information about the state of a particular user.
@type user: C{str} or C{unicode}
@param user: The user receiving this information. Only their nick
name, not the full hostmask.
@type nick: C{str} or C{unicode}
@param nick: The nickname of the user this information describes.
@type username: C{str} or C{unicode}
@param username: The user's username (eg, ident response)
@type hostname: C{str}
@param hostname: The user's hostmask
@type realName: C{str} or C{unicode}
@param realName: The user's real name
@type server: C{str} or C{unicode}
@param server: The name of the server to which the user is connected
@type serverInfo: C{str} or C{unicode}
@param serverInfo: A descriptive string about that server
@type oper: C{bool}
@param oper: Indicates whether the user is an IRC operator
@type idle: C{int}
@param idle: The number of seconds since the user last sent a message
@type signOn: C{int}
@param signOn: A POSIX timestamp (number of seconds since the epoch)
indicating the time the user signed on
@type channels: C{list} of C{str} or C{unicode}
@param channels: A list of the channels which the user is participating in
"""
self.sendLine(":%s %s %s %s %s %s * :%s" % (
self.hostname, RPL_WHOISUSER, user, nick, username, hostname, realName))
self.sendLine(":%s %s %s %s %s :%s" % (
self.hostname, RPL_WHOISSERVER, user, nick, server, serverInfo))
if oper:
self.sendLine(":%s %s %s %s :is an IRC operator" % (
self.hostname, RPL_WHOISOPERATOR, user, nick))
self.sendLine(":%s %s %s %s %d %d :seconds idle, signon time" % (
self.hostname, RPL_WHOISIDLE, user, nick, idle, signOn))
self.sendLine(":%s %s %s %s :%s" % (
self.hostname, RPL_WHOISCHANNELS, user, nick, ' '.join(channels)))
self.sendLine(":%s %s %s %s :End of WHOIS list." % (
self.hostname, RPL_ENDOFWHOIS, user, nick))
def join(self, who, where):
"""Send a join message.
@type who: C{str} or C{unicode}
@param who: The name of the user joining. Should be of the form
username!ident@hostmask (unless you know better!).
@type where: C{str} or C{unicode}
@param where: The channel the user is joining.
"""
self.sendLine(":%s JOIN %s" % (who, where))
def part(self, who, where, reason=None):
"""Send a part message.
@type who: C{str} or C{unicode}
@param who: The name of the user joining. Should be of the form
username!ident@hostmask (unless you know better!).
@type where: C{str} or C{unicode}
@param where: The channel the user is joining.
@type reason: C{str} or C{unicode}
@param reason: A string describing the misery which caused
this poor soul to depart.
"""
if reason:
self.sendLine(":%s PART %s :%s" % (who, where, reason))
else:
self.sendLine(":%s PART %s" % (who, where))
def channelMode(self, user, channel, mode, *args):
"""
Send information about the mode of a channel.
@type user: C{str} or C{unicode}
@param user: The user receiving the name list. Only their nick
name, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the namelist.
@type mode: C{str}
@param mode: A string describing this channel's modes.
@param args: Any additional arguments required by the modes.
"""
self.sendLine(":%s %s %s %s %s %s" % (
self.hostname, RPL_CHANNELMODEIS, user, channel, mode, ' '.join(args)))
class ServerSupportedFeatures(_CommandDispatcherMixin):
"""
Handle ISUPPORT messages.
Information regarding the specifics of ISUPPORT was gleaned from
<http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt>.
"""
prefix = 'isupport'
def __init__(self):
self._features = {
'CHANNELLEN': 200,
'CHANTYPES': '#&',
'MODES': 3,
'NICKLEN': 9,
'PREFIX': self._parsePrefixParam('(ov)@+')}
self._features2 = {}
def _splitParamArgs(cls, params, valueProcessor=None):
"""
Split ISUPPORT parameter arguments.
Values can optionally be processed by C{valueProcessor}.
For example::
>>> ServerSupportedFeatures._splitParamArgs(['A:1', 'B:2'])
(('A', '1'), ('B', '2'))
@type params: C{iterable} of C{str}
@type valueProcessor: C{callable} taking {str}
@param valueProcessor: Callable to process argument values, or C{None}
to perform no processing
@rtype: C{tuple} of C{(str, object)}
@return: Sequence of C{(name, processedValue)}
"""
if valueProcessor is None:
valueProcessor = lambda x: x
def _parse():
for param in params:
if ':' not in param:
param += ':'
a, b = param.split(':', 1)
yield a, valueProcessor(b)
return tuple(_parse())
_splitParamArgs = classmethod(_splitParamArgs)
def _unescapeParamValue(cls, value):
"""
Unescape an ISUPPORT parameter.
The only form of supported escape is C{\\xHH}, where HH must be a valid
2-digit hexadecimal number.
@rtype: C{str}
"""
def _unescape():
parts = value.split('\\x')
# The first part can never be preceeded by the escape.
yield parts.pop(0)
for s in parts:
octet, rest = s[:2], s[2:]
try:
octet = int(octet, 16)
except ValueError:
raise ValueError('Invalid hex octet: %r' % (octet,))
yield chr(octet) + rest
if '\\x' not in value:
return value
return ''.join(_unescape())
_unescapeParamValue = classmethod(_unescapeParamValue)
def _splitParam(cls, param):
"""
Split an ISUPPORT parameter.
@type param: C{str}
@rtype: C{(str, list)}
@return C{(key, arguments)}
"""
if '=' not in param:
param += '='
key, value = param.split('=', 1)
return key, map(cls._unescapeParamValue, value.split(','))
_splitParam = classmethod(_splitParam)
def _parsePrefixParam(cls, prefix):
"""
Parse the ISUPPORT "PREFIX" parameter.
"""
if not prefix:
return None
if prefix[0] != '(' and ')' not in prefix:
return None
modes, symbols = prefix.split(')', 1)
modes = modes[1:]
return dict(zip(modes, symbols))
_parsePrefixParam = classmethod(_parsePrefixParam)
def getFeature(self, feature, default=None):
"""
Get a server supported feature's value.
A feature with the value C{None} is equivalent to the feature being
unsupported.
@type feature: C{str}
@param feature: Feature name
@type default: C{object}
@param default: The value to default to, assuming that C{feature}
is not supported
@return: Feature value
"""
return self._features.get(feature, default)
def hasFeature(self, feature):
"""
Determine whether a feature is supported or not.
@rtype: C{bool}
"""
return self.getFeature(feature) is not None
def parse(self, params):
"""
Parse ISUPPORT parameters.
If an unknown parameter is encountered, it is simply added to the
dictionary, keyed by its name, as a tuple of the parameters provided.
@type params: C{iterable} of C{str}
@param params: Iterable of ISUPPORT parameters to parse
"""
for param in params:
key, value = self._splitParam(param)
if key.startswith('-'):
self._features.pop(key[1:], None)
else:
self._features[key] = self.dispatch(key, value)
if self._features[key] is None:
self._features2[key] = value
print "isupport: ", (key, value) #debug
#todo: check to see if the value is in the right form
def isupport_unknown(self, command, params):
"""
Unknown ISUPPORT parameter.
"""
return tuple(params)
def isupport_CHANLIMIT(self, params):
"""
The maximum number of each channel type a user may join.
"""
return self._splitParamArgs(params, _intOrDefault)
def isupport_CHANMODES(self, params):
"""
Available channel modes.
There are 4 categories of channel mode::
addressModes - Modes that add or remove an address to or from a
list, these modes always take a parameter.
param - Modes that change a setting on a channel, these modes
always take a parameter.
setParam - Modes that change a setting on a channel, these modes
only take a parameter when being set.
noParam - Modes that change a setting on a channel, these modes
never take a parameter.
"""
names = ('addressModes', 'param', 'setParam', 'noParam')
items = map(lambda key, value: (key, value or ''), names, params)
return dict(items)
def isupport_CHANNELLEN(self, params):
"""
Maximum length of a channel name a client may create.
"""
return _intOrDefault(params[0], self.getFeature('CHANNELLEN'))
def isupport_CHANTYPES(self, params):
"""
Valid channel prefixes.
"""
return tuple(params[0])
def isupport_EXCEPTS(self, params):
"""
Mode character for "ban exceptions".
The presence of this parameter indicates that the server supports
this functionality.
"""
return params[0] or 'e'
def isupport_IDCHAN(self, params):
"""
Safe channel identifiers.
The presence of this parameter indicates that the server supports
this functionality.
"""
return self._splitParamArgs(params)
def isupport_INVEX(self, params):
"""
Mode character for "invite exceptions".
The presence of this parameter indicates that the server supports
this functionality.
"""
return params[0] or 'I'
def isupport_KICKLEN(self, params):
"""
Maximum length of a kick message a client may provide.
"""
return _intOrDefault(params[0])
def isupport_MAXLIST(self, params):
"""
Maximum number of "list modes" a client may set on a channel at once.
List modes are identified by the "addressModes" key in CHANMODES.
"""
return self._splitParamArgs(params, _intOrDefault)
def isupport_MODES(self, params):
"""
Maximum number of modes accepting parameters that may be sent, by a
client, in a single MODE command.
"""
return _intOrDefault(params[0])
def isupport_NETWORK(self, params):
"""
IRC network name.
"""
return params[0]
def isupport_NICKLEN(self, params):
"""
Maximum length of a nickname the client may use.
"""
return _intOrDefault(params[0], self.getFeature('NICKLEN'))
def isupport_PREFIX(self, params):
"""
Mapping of channel modes that clients may have to status flags.
"""
return self._parsePrefixParam(params[0])
def isupport_SAFELIST(self, params):
"""
Flag indicating that a client may request a LIST without being
disconnected due to the large amount of data generated.
"""
return True
def isupport_STATUSMSG(self, params):
"""
The server supports sending messages to only to clients on a channel
with a specific status.
"""
return params[0]
def isupport_TARGMAX(self, params):
"""
Maximum number of targets allowable for commands that accept multiple
targets.
"""
return dict(self._splitParamArgs(params, _intOrDefault))
def isupport_TOPICLEN(self, params):
"""
Maximum length of a topic that may be set.
"""
return _intOrDefault(params[0])
class IRCClient(basic.LineReceiver):
"""Internet Relay Chat client protocol, with sprinkles.
In addition to providing an interface for an IRC client protocol,
this class also contains reasonable implementations of many common
CTCP methods.
TODO
====
- Limit the length of messages sent (because the IRC server probably
does).
- Add flood protection/rate limiting for my CTCP replies.
- NickServ cooperation. (a mix-in?)
- Heartbeat. The transport may die in such a way that it does not realize
it is dead until it is written to. Sending something (like \"PING
this.irc-host.net\") during idle peroids would alleviate that. If
you're concerned with the stability of the host as well as that of the
transport, you might care to watch for the corresponding PONG.
@ivar nickname: Nickname the client will use.
@ivar password: Password used to log on to the server. May be C{None}.
@ivar realname: Supplied to the server during login as the \"Real name\"
or \"ircname\". May be C{None}.
@ivar username: Supplied to the server during login as the \"User name\".
May be C{None}
@ivar userinfo: Sent in reply to a C{USERINFO} CTCP query. If C{None}, no
USERINFO reply will be sent.
\"This is used to transmit a string which is settable by
the user (and never should be set by the client).\"
@ivar fingerReply: Sent in reply to a C{FINGER} CTCP query. If C{None}, no
FINGER reply will be sent.
@type fingerReply: Callable or String
@ivar versionName: CTCP VERSION reply, client name. If C{None}, no VERSION
reply will be sent.
@ivar versionNum: CTCP VERSION reply, client version,
@ivar versionEnv: CTCP VERSION reply, environment the client is running in.
@ivar sourceURL: CTCP SOURCE reply, a URL where the source code of this
client may be found. If C{None}, no SOURCE reply will be sent.
@ivar lineRate: Minimum delay between lines sent to the server. If
C{None}, no delay will be imposed.
@type lineRate: Number of Seconds.
@type supported: L{ServerSupportedFeatures}
@ivar supported: Available ISUPPORT features on the server
"""
motd = ""
nickname = 'irc'
password = None
realname = None
username = None
### Responses to various CTCP queries.
userinfo = None
# fingerReply is a callable returning a string, or a str()able object.
fingerReply = None
versionName = None
versionNum = None
versionEnv = None
sourceURL = "This client uses a custom-modified version of Twisted Words IRC http://twistedmatrix.com/downloads/"
dcc_destdir = '.'
dcc_sessions = None
# 'mode': (added, removed) i.e.:
# 'l': (True, False) accepts an arg when added and no arg when removed
# from http://www.faqs.org/rfcs/rfc1459.html - 4.2.3.1 Channel modes
# if you want other modes to accept args, add them here, by default unknown
# modes won't accept any arg
_modeAcceptsArg = {
'o': (True, True), # op/deop a user
'h': (True, True), # hop/dehop (halfop) a user (not defined in RFC)
'v': (True, True), # voice/devoice a user
'b': (True, True), # ban/unban a user/mask
'l': (True, False), # set the user limit to channel
'k': (True, False), # set a channel key (password)
't': (False, False), # only ops set topic
's': (False, False), # secret channel
'p': (False, False), # private channel
'i': (False, False), # invite-only channel
'm': (False, False), # moderated channel
'n': (False, False), # no external messages
}
# If this is false, no attempt will be made to identify
# ourself to the server.
performLogin = 1
lineRate = None
_queue = None
_queueEmptying = None
delimiter = '\n' # '\r\n' will also work (see dataReceived)
__pychecker__ = 'unusednames=params,prefix,channel'
def __init__(self):
self.supported = ServerSupportedFeatures()
def _reallySendLine(self, line):