irclib -- Internet Relay Chat (IRC) protocol client library

irclib.py 52KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. # -*- coding: utf-8 -*-
  2. # Copyright (C) 1999-2002 Joel Rosdahl
  3. # Portions Copyright © 2011 Jason R. Coombs
  4. #
  5. # This library is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU Lesser General Public
  7. # License as published by the Free Software Foundation; either
  8. # version 2.1 of the License, or (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. # Lesser General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public
  16. # License along with this library; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. #
  19. # keltus <keltus@users.sourceforge.net>
  20. """
  21. irclib -- Internet Relay Chat (IRC) protocol client library.
  22. This library is intended to encapsulate the IRC protocol at a quite
  23. low level. It provides an event-driven IRC client framework. It has
  24. a fairly thorough support for the basic IRC protocol, CTCP, DCC chat,
  25. but DCC file transfers is not yet supported.
  26. In order to understand how to make an IRC client, I'm afraid you more
  27. or less must understand the IRC specifications. They are available
  28. here: [IRC specifications].
  29. The main features of the IRC client framework are:
  30. * Abstraction of the IRC protocol.
  31. * Handles multiple simultaneous IRC server connections.
  32. * Handles server PONGing transparently.
  33. * Messages to the IRC server are done by calling methods on an IRC
  34. connection object.
  35. * Messages from an IRC server triggers events, which can be caught
  36. by event handlers.
  37. * Reading from and writing to IRC server sockets are normally done
  38. by an internal select() loop, but the select()ing may be done by
  39. an external main loop.
  40. * Functions can be registered to execute at specified times by the
  41. event-loop.
  42. * Decodes CTCP tagging correctly (hopefully); I haven't seen any
  43. other IRC client implementation that handles the CTCP
  44. specification subtilties.
  45. * A kind of simple, single-server, object-oriented IRC client class
  46. that dispatches events to instance methods is included.
  47. Current limitations:
  48. * The IRC protocol shines through the abstraction a bit too much.
  49. * Data is not written asynchronously to the server, i.e. the write()
  50. may block if the TCP buffers are stuffed.
  51. * There are no support for DCC file transfers.
  52. * The author haven't even read RFC 2810, 2811, 2812 and 2813.
  53. * Like most projects, documentation is lacking...
  54. .. [IRC specifications] http://www.irchelp.org/irchelp/rfc/
  55. """
  56. import bisect
  57. import re
  58. import select
  59. import socket
  60. import string
  61. import time
  62. import types
  63. import ssl as ssl_mod
  64. import datetime
  65. try:
  66. import pkg_resources
  67. _pkg = pkg_resources.require('python-irclib')[0]
  68. VERSION = tuple(int(res) for res in re.findall('\d+', _pkg.version))
  69. except Exception:
  70. VERSION = ()
  71. DEBUG = False
  72. # TODO
  73. # ----
  74. # (maybe) thread safety
  75. # (maybe) color parser convenience functions
  76. # documentation (including all event types)
  77. # (maybe) add awareness of different types of ircds
  78. # send data asynchronously to the server (and DCC connections)
  79. # (maybe) automatically close unused, passive DCC connections after a while
  80. # NOTES
  81. # -----
  82. # connection.quit() only sends QUIT to the server.
  83. # ERROR from the server triggers the error event and the disconnect event.
  84. # dropping of the connection triggers the disconnect event.
  85. class IRCError(Exception):
  86. """Represents an IRC exception."""
  87. pass
  88. class IRC(object):
  89. """Class that handles one or several IRC server connections.
  90. When an IRC object has been instantiated, it can be used to create
  91. Connection objects that represent the IRC connections. The
  92. responsibility of the IRC object is to provide an event-driven
  93. framework for the connections and to keep the connections alive.
  94. It runs a select loop to poll each connection's TCP socket and
  95. hands over the sockets with incoming data for processing by the
  96. corresponding connection.
  97. The methods of most interest for an IRC client writer are server,
  98. add_global_handler, remove_global_handler, execute_at,
  99. execute_delayed, process_once and process_forever.
  100. Here is an example:
  101. irc = irclib.IRC()
  102. server = irc.server()
  103. server.connect("irc.some.where", 6667, "my_nickname")
  104. server.privmsg("a_nickname", "Hi there!")
  105. irc.process_forever()
  106. This will connect to the IRC server irc.some.where on port 6667
  107. using the nickname my_nickname and send the message "Hi there!"
  108. to the nickname a_nickname.
  109. """
  110. def __init__(self, fn_to_add_socket=None,
  111. fn_to_remove_socket=None,
  112. fn_to_add_timeout=None):
  113. """Constructor for IRC objects.
  114. Optional arguments are fn_to_add_socket, fn_to_remove_socket
  115. and fn_to_add_timeout. The first two specify functions that
  116. will be called with a socket object as argument when the IRC
  117. object wants to be notified (or stop being notified) of data
  118. coming on a new socket. When new data arrives, the method
  119. process_data should be called. Similarly, fn_to_add_timeout
  120. is called with a number of seconds (a floating point number)
  121. as first argument when the IRC object wants to receive a
  122. notification (by calling the process_timeout method). So, if
  123. e.g. the argument is 42.17, the object wants the
  124. process_timeout method to be called after 42 seconds and 170
  125. milliseconds.
  126. The three arguments mainly exist to be able to use an external
  127. main loop (for example Tkinter's or PyGTK's main app loop)
  128. instead of calling the process_forever method.
  129. An alternative is to just call ServerConnection.process_once()
  130. once in a while.
  131. """
  132. if fn_to_add_socket and fn_to_remove_socket:
  133. self.fn_to_add_socket = fn_to_add_socket
  134. self.fn_to_remove_socket = fn_to_remove_socket
  135. else:
  136. self.fn_to_add_socket = None
  137. self.fn_to_remove_socket = None
  138. self.fn_to_add_timeout = fn_to_add_timeout
  139. self.connections = []
  140. self.handlers = {}
  141. self.delayed_commands = [] # list of DelayedCommands
  142. self.add_global_handler("ping", _ping_ponger, -42)
  143. def server(self):
  144. """Creates and returns a ServerConnection object."""
  145. c = ServerConnection(self)
  146. self.connections.append(c)
  147. return c
  148. def process_data(self, sockets):
  149. """Called when there is more data to read on connection sockets.
  150. Arguments:
  151. sockets -- A list of socket objects.
  152. See documentation for IRC.__init__.
  153. """
  154. for s in sockets:
  155. for c in self.connections:
  156. if s == c._get_socket():
  157. c.process_data()
  158. def process_timeout(self):
  159. """Called when a timeout notification is due.
  160. See documentation for IRC.__init__.
  161. """
  162. while self.delayed_commands:
  163. command = self.delayed_commands[0]
  164. if not command.due():
  165. break
  166. command.function(*command.arguments)
  167. if isinstance(command, PeriodicCommand):
  168. self._schedule_command(command.next())
  169. del self.delayed_commands[0]
  170. def process_once(self, timeout=0):
  171. """Process data from connections once.
  172. Arguments:
  173. timeout -- How long the select() call should wait if no
  174. data is available.
  175. This method should be called periodically to check and process
  176. incoming data, if there are any. If that seems boring, look
  177. at the process_forever method.
  178. """
  179. sockets = map(lambda x: x._get_socket(), self.connections)
  180. sockets = filter(lambda x: x != None, sockets)
  181. if sockets:
  182. (i, o, e) = select.select(sockets, [], [], timeout)
  183. self.process_data(i)
  184. else:
  185. time.sleep(timeout)
  186. self.process_timeout()
  187. def process_forever(self, timeout=0.2):
  188. """Run an infinite loop, processing data from connections.
  189. This method repeatedly calls process_once.
  190. Arguments:
  191. timeout -- Parameter to pass to process_once.
  192. """
  193. while 1:
  194. self.process_once(timeout)
  195. def disconnect_all(self, message=""):
  196. """Disconnects all connections."""
  197. for c in self.connections:
  198. c.disconnect(message)
  199. def add_global_handler(self, event, handler, priority=0):
  200. """Adds a global handler function for a specific event type.
  201. Arguments:
  202. event -- Event type (a string). Check the values of the
  203. numeric_events dictionary in irclib.py for possible event
  204. types.
  205. handler -- Callback function.
  206. priority -- A number (the lower number, the higher priority).
  207. The handler function is called whenever the specified event is
  208. triggered in any of the connections. See documentation for
  209. the Event class.
  210. The handler functions are called in priority order (lowest
  211. number is highest priority). If a handler function returns
  212. "NO MORE", no more handlers will be called.
  213. """
  214. if not event in self.handlers:
  215. self.handlers[event] = []
  216. bisect.insort(self.handlers[event], ((priority, handler)))
  217. def remove_global_handler(self, event, handler):
  218. """Removes a global handler function.
  219. Arguments:
  220. event -- Event type (a string).
  221. handler -- Callback function.
  222. Returns 1 on success, otherwise 0.
  223. """
  224. if not event in self.handlers:
  225. return 0
  226. for h in self.handlers[event]:
  227. if handler == h[1]:
  228. self.handlers[event].remove(h)
  229. return 1
  230. def execute_at(self, at, function, arguments=()):
  231. """Execute a function at a specified time.
  232. Arguments:
  233. at -- Execute at this time (standard "time_t" time).
  234. function -- Function to call.
  235. arguments -- Arguments to give the function.
  236. """
  237. command = DelayedCommand.at_time(at, function, arguments)
  238. self._schedule_command(command)
  239. def execute_delayed(self, delay, function, arguments=()):
  240. """
  241. Execute a function after a specified time.
  242. delay -- How many seconds to wait.
  243. function -- Function to call.
  244. arguments -- Arguments to give the function.
  245. """
  246. command = DelayedCommand(delay, function, arguments)
  247. self._schedule_command(command)
  248. def execute_every(self, period, function, arguments=()):
  249. """
  250. Execute a function every 'period' seconds.
  251. period -- How often to run (always waits this long for first).
  252. function -- Function to call.
  253. arguments -- Arguments to give the function.
  254. """
  255. command = PeriodicCommand(period, function, arguments)
  256. self._schedule_command(command)
  257. def _schedule_command(self, command):
  258. bisect.insort(self.delayed_commands, command)
  259. if self.fn_to_add_timeout:
  260. self.fn_to_add_timeout(total_seconds(command.delay))
  261. def dcc(self, dcctype="chat"):
  262. """Creates and returns a DCCConnection object.
  263. Arguments:
  264. dcctype -- "chat" for DCC CHAT connections or "raw" for
  265. DCC SEND (or other DCC types). If "chat",
  266. incoming data will be split in newline-separated
  267. chunks. If "raw", incoming data is not touched.
  268. """
  269. c = DCCConnection(self, dcctype)
  270. self.connections.append(c)
  271. return c
  272. def _handle_event(self, connection, event):
  273. """[Internal]"""
  274. h = self.handlers
  275. th = sorted(h.get("all_events", []) + h.get(event.eventtype(), []))
  276. for handler in th:
  277. if handler[1](connection, event) == "NO MORE":
  278. return
  279. def _remove_connection(self, connection):
  280. """[Internal]"""
  281. self.connections.remove(connection)
  282. if self.fn_to_remove_socket:
  283. self.fn_to_remove_socket(connection._get_socket())
  284. class DelayedCommand(datetime.datetime):
  285. """
  286. A command to be executed after some delay (seconds or timedelta).
  287. """
  288. def __new__(cls, delay, function, arguments):
  289. if not isinstance(delay, datetime.timedelta):
  290. delay = datetime.timedelta(seconds=delay)
  291. at = datetime.datetime.utcnow() + delay
  292. cmd = datetime.datetime.__new__(DelayedCommand, at.year,
  293. at.month, at.day, at.hour, at.minute, at.second,
  294. at.microsecond, at.tzinfo)
  295. cmd.delay = delay
  296. cmd.function = function
  297. cmd.arguments = arguments
  298. return cmd
  299. def at_time(cls, at, function, arguments):
  300. """
  301. Construct a DelayedCommand to come due at `at`, where `at` may be
  302. a datetime or timestamp.
  303. """
  304. if isinstance(at, int):
  305. at = datetime.datetime.utcfromtimestamp(at)
  306. delay = at - datetime.datetime.utcnow()
  307. return cls(delay, function, arguments)
  308. at_time = classmethod(at_time)
  309. def due(self):
  310. return datetime.datetime.utcnow() >= self
  311. class PeriodicCommand(DelayedCommand):
  312. """
  313. Like a deferred command, but expect this command to run every delay
  314. seconds.
  315. """
  316. def next(self):
  317. return PeriodicCommand(self.delay, self.function,
  318. self.arguments)
  319. _rfc_1459_command_regexp = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
  320. class Connection(object):
  321. """Base class for IRC connections.
  322. Must be overridden.
  323. """
  324. def __init__(self, irclibobj):
  325. self.irclibobj = irclibobj
  326. def _get_socket():
  327. raise IRCError("Not overridden")
  328. ##############################
  329. ### Convenience wrappers.
  330. def execute_at(self, at, function, arguments=()):
  331. self.irclibobj.execute_at(at, function, arguments)
  332. def execute_delayed(self, delay, function, arguments=()):
  333. self.irclibobj.execute_delayed(delay, function, arguments)
  334. def execute_every(self, period, function, arguments=()):
  335. self.irclibobj.execute_every(period, function, arguments)
  336. class ServerConnectionError(IRCError):
  337. pass
  338. class ServerNotConnectedError(ServerConnectionError):
  339. pass
  340. # Huh!? Crrrrazy EFNet doesn't follow the RFC: their ircd seems to
  341. # use \n as message separator! :P
  342. _linesep_regexp = re.compile("\r?\n")
  343. class ServerConnection(Connection):
  344. """This class represents an IRC server connection.
  345. ServerConnection objects are instantiated by calling the server
  346. method on an IRC object.
  347. """
  348. def __init__(self, irclibobj):
  349. super(ServerConnection, self).__init__(irclibobj)
  350. self.connected = 0 # Not connected yet.
  351. self.socket = None
  352. self.ssl = None
  353. def connect(self, server, port, nickname, password=None, username=None,
  354. ircname=None, localaddress="", localport=0, ssl=False, ipv6=False):
  355. """Connect/reconnect to a server.
  356. Arguments:
  357. server -- Server name.
  358. port -- Port number.
  359. nickname -- The nickname.
  360. password -- Password (if any).
  361. username -- The username.
  362. ircname -- The IRC name ("realname").
  363. localaddress -- Bind the connection to a specific local IP address.
  364. localport -- Bind the connection to a specific local port.
  365. ssl -- Enable support for ssl.
  366. ipv6 -- Enable support for ipv6.
  367. This function can be called to reconnect a closed connection.
  368. Returns the ServerConnection object.
  369. """
  370. if self.connected:
  371. self.disconnect("Changing servers")
  372. self.previous_buffer = ""
  373. self.handlers = {}
  374. self.real_server_name = ""
  375. self.real_nickname = nickname
  376. self.server = server
  377. self.port = port
  378. self.nickname = nickname
  379. self.username = username or nickname
  380. self.ircname = ircname or nickname
  381. self.password = password
  382. self.localaddress = localaddress
  383. self.localport = localport
  384. self.localhost = socket.gethostname()
  385. if ipv6:
  386. self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  387. else:
  388. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  389. try:
  390. self.socket.bind((self.localaddress, self.localport))
  391. self.socket.connect((self.server, self.port))
  392. if ssl:
  393. self.ssl = ssl_mod.wrap_socket(self.socket)
  394. except socket.error as x:
  395. self.socket.close()
  396. self.socket = None
  397. raise ServerConnectionError("Couldn't connect to socket: %s" % x)
  398. self.connected = 1
  399. if self.irclibobj.fn_to_add_socket:
  400. self.irclibobj.fn_to_add_socket(self.socket)
  401. # Log on...
  402. if self.password:
  403. self.pass_(self.password)
  404. self.nick(self.nickname)
  405. self.user(self.username, self.ircname)
  406. return self
  407. def close(self):
  408. """Close the connection.
  409. This method closes the connection permanently; after it has
  410. been called, the object is unusable.
  411. """
  412. self.disconnect("Closing object")
  413. self.irclibobj._remove_connection(self)
  414. def _get_socket(self):
  415. """[Internal]"""
  416. return self.socket
  417. def get_server_name(self):
  418. """Get the (real) server name.
  419. This method returns the (real) server name, or, more
  420. specifically, what the server calls itself.
  421. """
  422. if self.real_server_name:
  423. return self.real_server_name
  424. else:
  425. return ""
  426. def get_nickname(self):
  427. """Get the (real) nick name.
  428. This method returns the (real) nickname. The library keeps
  429. track of nick changes, so it might not be the nick name that
  430. was passed to the connect() method. """
  431. return self.real_nickname
  432. def process_data(self):
  433. """[Internal]"""
  434. try:
  435. if self.ssl:
  436. new_data = self.ssl.read(2 ** 14)
  437. else:
  438. new_data = self.socket.recv(2 ** 14)
  439. except socket.error:
  440. # The server hung up.
  441. self.disconnect("Connection reset by peer")
  442. return
  443. if not new_data:
  444. # Read nothing: connection must be down.
  445. self.disconnect("Connection reset by peer")
  446. return
  447. lines = _linesep_regexp.split(self.previous_buffer + str(new_data))
  448. # Save the last, unfinished line.
  449. self.previous_buffer = lines.pop()
  450. for line in lines:
  451. if DEBUG:
  452. print("FROM SERVER:", line)
  453. if not line:
  454. continue
  455. prefix = None
  456. command = None
  457. arguments = None
  458. self._handle_event(Event("all_raw_messages",
  459. self.get_server_name(),
  460. None,
  461. [line]))
  462. m = _rfc_1459_command_regexp.match(line)
  463. if m.group("prefix"):
  464. prefix = m.group("prefix")
  465. if not self.real_server_name:
  466. self.real_server_name = prefix
  467. if m.group("command"):
  468. command = m.group("command").lower()
  469. if m.group("argument"):
  470. a = m.group("argument").split(" :", 1)
  471. arguments = a[0].split()
  472. if len(a) == 2:
  473. arguments.append(a[1])
  474. # Translate numerics into more readable strings.
  475. if command in numeric_events:
  476. command = numeric_events[command]
  477. if command == "nick":
  478. if nm_to_n(prefix) == self.real_nickname:
  479. self.real_nickname = arguments[0]
  480. elif command == "welcome":
  481. # Record the nickname in case the client changed nick
  482. # in a nicknameinuse callback.
  483. self.real_nickname = arguments[0]
  484. if command in ["privmsg", "notice"]:
  485. target, message = arguments[0], arguments[1]
  486. messages = _ctcp_dequote(message)
  487. if command == "privmsg":
  488. if is_channel(target):
  489. command = "pubmsg"
  490. else:
  491. if is_channel(target):
  492. command = "pubnotice"
  493. else:
  494. command = "privnotice"
  495. for m in messages:
  496. if type(m) is types.TupleType:
  497. if command in ["privmsg", "pubmsg"]:
  498. command = "ctcp"
  499. else:
  500. command = "ctcpreply"
  501. m = list(m)
  502. if DEBUG:
  503. print("command: %s, source: %s, target: %s, arguments: %s" % (
  504. command, prefix, target, m))
  505. self._handle_event(Event(command, prefix, target, m))
  506. if command == "ctcp" and m[0] == "ACTION":
  507. self._handle_event(Event("action", prefix, target, m[1:]))
  508. else:
  509. if DEBUG:
  510. print("command: %s, source: %s, target: %s, arguments: %s" % (
  511. command, prefix, target, [m]))
  512. self._handle_event(Event(command, prefix, target, [m]))
  513. else:
  514. target = None
  515. if command == "quit":
  516. arguments = [arguments[0]]
  517. elif command == "ping":
  518. target = arguments[0]
  519. else:
  520. target = arguments[0]
  521. arguments = arguments[1:]
  522. if command == "mode":
  523. if not is_channel(target):
  524. command = "umode"
  525. if DEBUG:
  526. print("command: %s, source: %s, target: %s, arguments: %s" % (
  527. command, prefix, target, arguments))
  528. self._handle_event(Event(command, prefix, target, arguments))
  529. def _handle_event(self, event):
  530. """[Internal]"""
  531. self.irclibobj._handle_event(self, event)
  532. if event.eventtype() in self.handlers:
  533. for fn in self.handlers[event.eventtype()]:
  534. fn(self, event)
  535. def is_connected(self):
  536. """Return connection status.
  537. Returns true if connected, otherwise false.
  538. """
  539. return self.connected
  540. def add_global_handler(self, *args):
  541. """Add global handler.
  542. See documentation for IRC.add_global_handler.
  543. """
  544. self.irclibobj.add_global_handler(*args)
  545. def remove_global_handler(self, *args):
  546. """Remove global handler.
  547. See documentation for IRC.remove_global_handler.
  548. """
  549. self.irclibobj.remove_global_handler(*args)
  550. def action(self, target, action):
  551. """Send a CTCP ACTION command."""
  552. self.ctcp("ACTION", target, action)
  553. def admin(self, server=""):
  554. """Send an ADMIN command."""
  555. self.send_raw(" ".join(["ADMIN", server]).strip())
  556. def ctcp(self, ctcptype, target, parameter=""):
  557. """Send a CTCP command."""
  558. ctcptype = ctcptype.upper()
  559. self.privmsg(target, "\001%s%s\001" % (ctcptype, parameter and (" " + parameter) or ""))
  560. def ctcp_reply(self, target, parameter):
  561. """Send a CTCP REPLY command."""
  562. self.notice(target, "\001%s\001" % parameter)
  563. def disconnect(self, message=""):
  564. """Hang up the connection.
  565. Arguments:
  566. message -- Quit message.
  567. """
  568. if not self.connected:
  569. return
  570. self.connected = 0
  571. self.quit(message)
  572. try:
  573. self.socket.close()
  574. except socket.error:
  575. pass
  576. self.socket = None
  577. self._handle_event(Event("disconnect", self.server, "", [message]))
  578. def globops(self, text):
  579. """Send a GLOBOPS command."""
  580. self.send_raw("GLOBOPS :" + text)
  581. def info(self, server=""):
  582. """Send an INFO command."""
  583. self.send_raw(" ".join(["INFO", server]).strip())
  584. def invite(self, nick, channel):
  585. """Send an INVITE command."""
  586. self.send_raw(" ".join(["INVITE", nick, channel]).strip())
  587. def ison(self, nicks):
  588. """Send an ISON command.
  589. Arguments:
  590. nicks -- List of nicks.
  591. """
  592. self.send_raw("ISON " + " ".join(nicks))
  593. def join(self, channel, key=""):
  594. """Send a JOIN command."""
  595. self.send_raw("JOIN %s%s" % (channel, (key and (" " + key))))
  596. def kick(self, channel, nick, comment=""):
  597. """Send a KICK command."""
  598. self.send_raw("KICK %s %s%s" % (channel, nick, (comment and (" :" + comment))))
  599. def links(self, remote_server="", server_mask=""):
  600. """Send a LINKS command."""
  601. command = "LINKS"
  602. if remote_server:
  603. command = command + " " + remote_server
  604. if server_mask:
  605. command = command + " " + server_mask
  606. self.send_raw(command)
  607. def list(self, channels=None, server=""):
  608. """Send a LIST command."""
  609. command = "LIST"
  610. if channels:
  611. command = command + " " + ",".join(channels)
  612. if server:
  613. command = command + " " + server
  614. self.send_raw(command)
  615. def lusers(self, server=""):
  616. """Send a LUSERS command."""
  617. self.send_raw("LUSERS" + (server and (" " + server)))
  618. def mode(self, target, command):
  619. """Send a MODE command."""
  620. self.send_raw("MODE %s %s" % (target, command))
  621. def motd(self, server=""):
  622. """Send an MOTD command."""
  623. self.send_raw("MOTD" + (server and (" " + server)))
  624. def names(self, channels=None):
  625. """Send a NAMES command."""
  626. self.send_raw("NAMES" + (channels and (" " + ",".join(channels)) or ""))
  627. def nick(self, newnick):
  628. """Send a NICK command."""
  629. self.send_raw("NICK " + newnick)
  630. def notice(self, target, text):
  631. """Send a NOTICE command."""
  632. # Should limit len(text) here!
  633. self.send_raw("NOTICE %s :%s" % (target, text))
  634. def oper(self, nick, password):
  635. """Send an OPER command."""
  636. self.send_raw("OPER %s %s" % (nick, password))
  637. def part(self, channels, message=""):
  638. """Send a PART command."""
  639. channels = always_iterable(channels)
  640. cmd_parts = [
  641. 'PART',
  642. ','.join(channels),
  643. ]
  644. if message: cmd_parts.append(message)
  645. self.send_raw(' '.join(cmd_parts))
  646. def pass_(self, password):
  647. """Send a PASS command."""
  648. self.send_raw("PASS " + password)
  649. def ping(self, target, target2=""):
  650. """Send a PING command."""
  651. self.send_raw("PING %s%s" % (target, target2 and (" " + target2)))
  652. def pong(self, target, target2=""):
  653. """Send a PONG command."""
  654. self.send_raw("PONG %s%s" % (target, target2 and (" " + target2)))
  655. def privmsg(self, target, text):
  656. """Send a PRIVMSG command."""
  657. # Should limit len(text) here!
  658. self.send_raw("PRIVMSG %s :%s" % (target, text))
  659. def privmsg_many(self, targets, text):
  660. """Send a PRIVMSG command to multiple targets."""
  661. # Should limit len(text) here!
  662. self.send_raw("PRIVMSG %s :%s" % (",".join(targets), text))
  663. def quit(self, message=""):
  664. """Send a QUIT command."""
  665. # Note that many IRC servers don't use your QUIT message
  666. # unless you've been connected for at least 5 minutes!
  667. self.send_raw("QUIT" + (message and (" :" + message)))
  668. def send_raw(self, string):
  669. """Send raw string to the server.
  670. The string will be padded with appropriate CR LF.
  671. """
  672. if self.socket is None:
  673. raise ServerNotConnectedError("Not connected.")
  674. try:
  675. if self.ssl:
  676. self.ssl.write(string + "\r\n")
  677. else:
  678. #print(type(string + "\r\n"))
  679. obj = string + "\r\n"
  680. self.socket.send(obj.encode())
  681. if DEBUG:
  682. print("TO SERVER:", string)
  683. except socket.error:
  684. # Ouch!
  685. self.disconnect("Connection reset by peer.")
  686. def squit(self, server, comment=""):
  687. """Send an SQUIT command."""
  688. self.send_raw("SQUIT %s%s" % (server, comment and (" :" + comment)))
  689. def stats(self, statstype, server=""):
  690. """Send a STATS command."""
  691. self.send_raw("STATS %s%s" % (statstype, server and (" " + server)))
  692. def time(self, server=""):
  693. """Send a TIME command."""
  694. self.send_raw("TIME" + (server and (" " + server)))
  695. def topic(self, channel, new_topic=None):
  696. """Send a TOPIC command."""
  697. if new_topic is None:
  698. self.send_raw("TOPIC " + channel)
  699. else:
  700. self.send_raw("TOPIC %s :%s" % (channel, new_topic))
  701. def trace(self, target=""):
  702. """Send a TRACE command."""
  703. self.send_raw("TRACE" + (target and (" " + target)))
  704. def user(self, username, realname):
  705. """Send a USER command."""
  706. self.send_raw("USER %s 0 * :%s" % (username, realname))
  707. def userhost(self, nicks):
  708. """Send a USERHOST command."""
  709. self.send_raw("USERHOST " + ",".join(nicks))
  710. def users(self, server=""):
  711. """Send a USERS command."""
  712. self.send_raw("USERS" + (server and (" " + server)))
  713. def version(self, server=""):
  714. """Send a VERSION command."""
  715. self.send_raw("VERSION" + (server and (" " + server)))
  716. def wallops(self, text):
  717. """Send a WALLOPS command."""
  718. self.send_raw("WALLOPS :" + text)
  719. def who(self, target="", op=""):
  720. """Send a WHO command."""
  721. self.send_raw("WHO%s%s" % (target and (" " + target), op and (" o")))
  722. def whois(self, targets):
  723. """Send a WHOIS command."""
  724. self.send_raw("WHOIS " + ",".join(targets))
  725. def whowas(self, nick, max="", server=""):
  726. """Send a WHOWAS command."""
  727. self.send_raw("WHOWAS %s%s%s" % (nick,
  728. max and (" " + max),
  729. server and (" " + server)))
  730. class DCCConnectionError(IRCError):
  731. pass
  732. class DCCConnection(Connection):
  733. """This class represents a DCC connection.
  734. DCCConnection objects are instantiated by calling the dcc
  735. method on an IRC object.
  736. """
  737. def __init__(self, irclibobj, dcctype):
  738. super(DCCConnection, self).__init__(irclibobj)
  739. self.connected = 0
  740. self.passive = 0
  741. self.dcctype = dcctype
  742. self.peeraddress = None
  743. self.peerport = None
  744. def connect(self, address, port):
  745. """Connect/reconnect to a DCC peer.
  746. Arguments:
  747. address -- Host/IP address of the peer.
  748. port -- The port number to connect to.
  749. Returns the DCCConnection object.
  750. """
  751. self.peeraddress = socket.gethostbyname(address)
  752. self.peerport = port
  753. self.socket = None
  754. self.previous_buffer = ""
  755. self.handlers = {}
  756. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  757. self.passive = 0
  758. try:
  759. self.socket.connect((self.peeraddress, self.peerport))
  760. except socket.error as x:
  761. raise DCCConnectionError("Couldn't connect to socket: %s" % x)
  762. self.connected = 1
  763. if self.irclibobj.fn_to_add_socket:
  764. self.irclibobj.fn_to_add_socket(self.socket)
  765. return self
  766. def listen(self):
  767. """Wait for a connection/reconnection from a DCC peer.
  768. Returns the DCCConnection object.
  769. The local IP address and port are available as
  770. self.localaddress and self.localport. After connection from a
  771. peer, the peer address and port are available as
  772. self.peeraddress and self.peerport.
  773. """
  774. self.previous_buffer = ""
  775. self.handlers = {}
  776. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  777. self.passive = 1
  778. try:
  779. self.socket.bind((socket.gethostbyname(socket.gethostname()), 0))
  780. self.localaddress, self.localport = self.socket.getsockname()
  781. self.socket.listen(10)
  782. except socket.error as x:
  783. raise DCCConnectionError("Couldn't bind socket: %s" % x)
  784. return self
  785. def disconnect(self, message=""):
  786. """Hang up the connection and close the object.
  787. Arguments:
  788. message -- Quit message.
  789. """
  790. if not self.connected:
  791. return
  792. self.connected = 0
  793. try:
  794. self.socket.close()
  795. except socket.error:
  796. pass
  797. self.socket = None
  798. self.irclibobj._handle_event(
  799. self,
  800. Event("dcc_disconnect", self.peeraddress, "", [message]))
  801. self.irclibobj._remove_connection(self)
  802. def process_data(self):
  803. """[Internal]"""
  804. if self.passive and not self.connected:
  805. conn, (self.peeraddress, self.peerport) = self.socket.accept()
  806. self.socket.close()
  807. self.socket = conn
  808. self.connected = 1
  809. if DEBUG:
  810. print("DCC connection from %s:%d" % (
  811. self.peeraddress, self.peerport))
  812. self.irclibobj._handle_event(
  813. self,
  814. Event("dcc_connect", self.peeraddress, None, None))
  815. return
  816. try:
  817. new_data = self.socket.recv(2 ** 14)
  818. except socket.error:
  819. # The server hung up.
  820. self.disconnect("Connection reset by peer")
  821. return
  822. if not new_data:
  823. # Read nothing: connection must be down.
  824. self.disconnect("Connection reset by peer")
  825. return
  826. if self.dcctype == "chat":
  827. # The specification says lines are terminated with LF, but
  828. # it seems safer to handle CR LF terminations too.
  829. chunks = _linesep_regexp.split(self.previous_buffer + new_data)
  830. # Save the last, unfinished line.
  831. self.previous_buffer = chunks[-1]
  832. if len(self.previous_buffer) > 2 ** 14:
  833. # Bad peer! Naughty peer!
  834. self.disconnect()
  835. return
  836. chunks = chunks[:-1]
  837. else:
  838. chunks = [new_data]
  839. command = "dccmsg"
  840. prefix = self.peeraddress
  841. target = None
  842. for chunk in chunks:
  843. if DEBUG:
  844. print("FROM PEER:", chunk)
  845. arguments = [chunk]
  846. if DEBUG:
  847. print("command: %s, source: %s, target: %s, arguments: %s" % (
  848. command, prefix, target, arguments))
  849. self.irclibobj._handle_event(
  850. self,
  851. Event(command, prefix, target, arguments))
  852. def _get_socket(self):
  853. """[Internal]"""
  854. return self.socket
  855. def privmsg(self, string):
  856. """Send data to DCC peer.
  857. The string will be padded with appropriate LF if it's a DCC
  858. CHAT session.
  859. """
  860. try:
  861. self.socket.send(string)
  862. if self.dcctype == "chat":
  863. self.socket.send("\n")
  864. if DEBUG:
  865. print("TO PEER: %s\n" % string)
  866. except socket.error:
  867. # Ouch!
  868. self.disconnect("Connection reset by peer.")
  869. class SimpleIRCClient(object):
  870. """A simple single-server IRC client class.
  871. This is an example of an object-oriented wrapper of the IRC
  872. framework. A real IRC client can be made by subclassing this
  873. class and adding appropriate methods.
  874. The method on_join will be called when a "join" event is created
  875. (which is done when the server sends a JOIN messsage/command),
  876. on_privmsg will be called for "privmsg" events, and so on. The
  877. handler methods get two arguments: the connection object (same as
  878. self.connection) and the event object.
  879. Instance attributes that can be used by sub classes:
  880. ircobj -- The IRC instance.
  881. connection -- The ServerConnection instance.
  882. dcc_connections -- A list of DCCConnection instances.
  883. """
  884. def __init__(self):
  885. self.ircobj = IRC()
  886. self.connection = self.ircobj.server()
  887. self.dcc_connections = []
  888. self.ircobj.add_global_handler("all_events", self._dispatcher, -10)
  889. self.ircobj.add_global_handler("dcc_disconnect", self._dcc_disconnect, -10)
  890. def _dispatcher(self, c, e):
  891. """[Internal]"""
  892. if DEBUG:
  893. print("irclib.py:_dispatcher:%s" % e.eventtype())
  894. m = "on_" + e.eventtype()
  895. if hasattr(self, m):
  896. getattr(self, m)(c, e)
  897. def _dcc_disconnect(self, c, e):
  898. self.dcc_connections.remove(c)
  899. def connect(self, server, port, nickname, password=None, username=None,
  900. ircname=None, localaddress="", localport=0, ssl=False, ipv6=False):
  901. """Connect/reconnect to a server.
  902. Arguments:
  903. server -- Server name.
  904. port -- Port number.
  905. nickname -- The nickname.
  906. password -- Password (if any).
  907. username -- The username.
  908. ircname -- The IRC name.
  909. localaddress -- Bind the connection to a specific local IP address.
  910. localport -- Bind the connection to a specific local port.
  911. ssl -- Enable support for ssl.
  912. ipv6 -- Enable support for ipv6.
  913. This function can be called to reconnect a closed connection.
  914. """
  915. self.connection.connect(server, port, nickname,
  916. password, username, ircname,
  917. localaddress, localport, ssl, ipv6)
  918. def dcc_connect(self, address, port, dcctype="chat"):
  919. """Connect to a DCC peer.
  920. Arguments:
  921. address -- IP address of the peer.
  922. port -- Port to connect to.
  923. Returns a DCCConnection instance.
  924. """
  925. dcc = self.ircobj.dcc(dcctype)
  926. self.dcc_connections.append(dcc)
  927. dcc.connect(address, port)
  928. return dcc
  929. def dcc_listen(self, dcctype="chat"):
  930. """Listen for connections from a DCC peer.
  931. Returns a DCCConnection instance.
  932. """
  933. dcc = self.ircobj.dcc(dcctype)
  934. self.dcc_connections.append(dcc)
  935. dcc.listen()
  936. return dcc
  937. def start(self):
  938. """Start the IRC client."""
  939. self.ircobj.process_forever()
  940. class Event(object):
  941. """Class representing an IRC event."""
  942. def __init__(self, eventtype, source, target, arguments=None):
  943. """Constructor of Event objects.
  944. Arguments:
  945. eventtype -- A string describing the event.
  946. source -- The originator of the event (a nick mask or a server).
  947. target -- The target of the event (a nick or a channel).
  948. arguments -- Any event specific arguments.
  949. """
  950. self._eventtype = eventtype
  951. self._source = source
  952. self._target = target
  953. if arguments:
  954. self._arguments = arguments
  955. else:
  956. self._arguments = []
  957. def eventtype(self):
  958. """Get the event type."""
  959. return self._eventtype
  960. def source(self):
  961. """Get the event source."""
  962. return self._source
  963. def target(self):
  964. """Get the event target."""
  965. return self._target
  966. def arguments(self):
  967. """Get the event arguments."""
  968. return self._arguments
  969. _LOW_LEVEL_QUOTE = "\020"
  970. _CTCP_LEVEL_QUOTE = "\134"
  971. _CTCP_DELIMITER = "\001"
  972. _low_level_mapping = {
  973. "0": "\000",
  974. "n": "\n",
  975. "r": "\r",
  976. _LOW_LEVEL_QUOTE: _LOW_LEVEL_QUOTE
  977. }
  978. _low_level_regexp = re.compile(_LOW_LEVEL_QUOTE + "(.)")
  979. def mask_matches(nick, mask):
  980. """Check if a nick matches a mask.
  981. Returns true if the nick matches, otherwise false.
  982. """
  983. nick = irc_lower(nick)
  984. mask = irc_lower(mask)
  985. mask = mask.replace("\\", "\\\\")
  986. for ch in ".$|[](){}+":
  987. mask = mask.replace(ch, "\\" + ch)
  988. mask = mask.replace("?", ".")
  989. mask = mask.replace("*", ".*")
  990. r = re.compile(mask, re.IGNORECASE)
  991. return r.match(nick)
  992. _special = "-[]\\`^{}"
  993. nick_characters = string.ascii_letters + string.digits + _special
  994. def _ctcp_dequote(message):
  995. """[Internal] Dequote a message according to CTCP specifications.
  996. The function returns a list where each element can be either a
  997. string (normal message) or a tuple of one or two strings (tagged
  998. messages). If a tuple has only one element (ie is a singleton),
  999. that element is the tag; otherwise the tuple has two elements: the
  1000. tag and the data.
  1001. Arguments:
  1002. message -- The message to be decoded.
  1003. """
  1004. def _low_level_replace(match_obj):
  1005. ch = match_obj.group(1)
  1006. # If low_level_mapping doesn't have the character as key, we
  1007. # should just return the character.
  1008. return _low_level_mapping.get(ch, ch)
  1009. if _LOW_LEVEL_QUOTE in message:
  1010. # Yup, there was a quote. Release the dequoter, man!
  1011. message = _low_level_regexp.sub(_low_level_replace, message)
  1012. if _CTCP_DELIMITER not in message:
  1013. return [message]
  1014. else:
  1015. # Split it into parts. (Does any IRC client actually *use*
  1016. # CTCP stacking like this?)
  1017. chunks = message.split(_CTCP_DELIMITER)
  1018. messages = []
  1019. i = 0
  1020. while i < len(chunks) - 1:
  1021. # Add message if it's non-empty.
  1022. if len(chunks[i]) > 0:
  1023. messages.append(chunks[i])
  1024. if i < len(chunks) - 2:
  1025. # Aye! CTCP tagged data ahead!
  1026. messages.append(tuple(chunks[i + 1].split(" ", 1)))
  1027. i = i + 2
  1028. if len(chunks) % 2 == 0:
  1029. # Hey, a lonely _CTCP_DELIMITER at the end! This means
  1030. # that the last chunk, including the delimiter, is a
  1031. # normal message! (This is according to the CTCP
  1032. # specification.)
  1033. messages.append(_CTCP_DELIMITER + chunks[-1])
  1034. return messages
  1035. def is_channel(string):
  1036. """Check if a string is a channel name.
  1037. Returns true if the argument is a channel name, otherwise false.
  1038. """
  1039. return string and string[0] in "#&+!"
  1040. def ip_numstr_to_quad(num):
  1041. """Convert an IP number as an integer given in ASCII
  1042. representation (e.g. '3232235521') to an IP address string
  1043. (e.g. '192.168.0.1')."""
  1044. n = long(num)
  1045. p = map(str, map(int, [n >> 24 & 0xFF, n >> 16 & 0xFF,
  1046. n >> 8 & 0xFF, n & 0xFF]))
  1047. return ".".join(p)
  1048. def ip_quad_to_numstr(quad):
  1049. """Convert an IP address string (e.g. '192.168.0.1') to an IP
  1050. number as an integer given in ASCII representation
  1051. (e.g. '3232235521')."""
  1052. p = map(long, quad.split("."))
  1053. s = str((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])
  1054. if s[-1] == "L":
  1055. s = s[:-1]
  1056. return s
  1057. def nm_to_n(s):
  1058. """Get the nick part of a nickmask.
  1059. (The source of an Event is a nickmask.)
  1060. """
  1061. return s.split("!")[0]
  1062. def nm_to_uh(s):
  1063. """Get the userhost part of a nickmask.
  1064. (The source of an Event is a nickmask.)
  1065. """
  1066. return s.split("!")[1]
  1067. def nm_to_h(s):
  1068. """Get the host part of a nickmask.
  1069. (The source of an Event is a nickmask.)
  1070. """
  1071. return s.split("@")[1]
  1072. def nm_to_u(s):
  1073. """Get the user part of a nickmask.
  1074. (The source of an Event is a nickmask.)
  1075. """
  1076. s = s.split("!")[1]
  1077. return s.split("@")[0]
  1078. def parse_nick_modes(mode_string):
  1079. """Parse a nick mode string.
  1080. The function returns a list of lists with three members: sign,
  1081. mode and argument. The sign is "+" or "-". The argument is
  1082. always None.
  1083. Example:
  1084. >>> parse_nick_modes("+ab-c")
  1085. [['+', 'a', None], ['+', 'b', None], ['-', 'c', None]]
  1086. """
  1087. return _parse_modes(mode_string, "")
  1088. def parse_channel_modes(mode_string):
  1089. """Parse a channel mode string.
  1090. The function returns a list of lists with three members: sign,
  1091. mode and argument. The sign is "+" or "-". The argument is
  1092. None if mode isn't one of "b", "k", "l", "v" or "o".
  1093. Example:
  1094. >>> parse_channel_modes("+ab-c foo")
  1095. [['+', 'a', None], ['+', 'b', 'foo'], ['-', 'c', None]]
  1096. """
  1097. return _parse_modes(mode_string, "bklvo")
  1098. def _parse_modes(mode_string, unary_modes=""):
  1099. """[Internal]"""
  1100. modes = []
  1101. arg_count = 0
  1102. # State variable.
  1103. sign = ""
  1104. a = mode_string.split()
  1105. if len(a) == 0:
  1106. return []
  1107. else:
  1108. mode_part, args = a[0], a[1:]
  1109. if mode_part[0] not in "+-":
  1110. return []
  1111. for ch in mode_part:
  1112. if ch in "+-":
  1113. sign = ch
  1114. elif ch == " ":
  1115. pass
  1116. elif ch in unary_modes:
  1117. if len(args) >= arg_count + 1:
  1118. modes.append([sign, ch, args[arg_count]])
  1119. arg_count = arg_count + 1
  1120. else:
  1121. modes.append([sign, ch, None])
  1122. else:
  1123. modes.append([sign, ch, None])
  1124. return modes
  1125. def _ping_ponger(connection, event):
  1126. """[Internal]"""
  1127. connection.pong(event.target())
  1128. # Numeric table mostly stolen from the Perl IRC module (Net::IRC).
  1129. numeric_events = {
  1130. "001": "welcome",
  1131. "002": "yourhost",
  1132. "003": "created",
  1133. "004": "myinfo",
  1134. "005": "featurelist", # XXX
  1135. "200": "tracelink",
  1136. "201": "traceconnecting",
  1137. "202": "tracehandshake",
  1138. "203": "traceunknown",
  1139. "204": "traceoperator",
  1140. "205": "traceuser",
  1141. "206": "traceserver",
  1142. "207": "traceservice",
  1143. "208": "tracenewtype",
  1144. "209": "traceclass",
  1145. "210": "tracereconnect",
  1146. "211": "statslinkinfo",
  1147. "212": "statscommands",
  1148. "213": "statscline",
  1149. "214": "statsnline",
  1150. "215": "statsiline",
  1151. "216": "statskline",
  1152. "217": "statsqline",
  1153. "218": "statsyline",
  1154. "219": "endofstats",
  1155. "221": "umodeis",
  1156. "231": "serviceinfo",
  1157. "232": "endofservices",
  1158. "233": "service",
  1159. "234": "servlist",
  1160. "235": "servlistend",
  1161. "241": "statslline",
  1162. "242": "statsuptime",
  1163. "243": "statsoline",
  1164. "244": "statshline",
  1165. "250": "luserconns",
  1166. "251": "luserclient",
  1167. "252": "luserop",
  1168. "253": "luserunknown",
  1169. "254": "luserchannels",
  1170. "255": "luserme",
  1171. "256": "adminme",
  1172. "257": "adminloc1",
  1173. "258": "adminloc2",
  1174. "259": "adminemail",
  1175. "261": "tracelog",
  1176. "262": "endoftrace",
  1177. "263": "tryagain",
  1178. "265": "n_local",
  1179. "266": "n_global",
  1180. "300": "none",
  1181. "301": "away",
  1182. "302": "userhost",
  1183. "303": "ison",
  1184. "305": "unaway",
  1185. "306": "nowaway",
  1186. "311": "whoisuser",
  1187. "312": "whoisserver",
  1188. "313": "whoisoperator",
  1189. "314": "whowasuser",
  1190. "315": "endofwho",
  1191. "316": "whoischanop",
  1192. "317": "whoisidle",
  1193. "318": "endofwhois",
  1194. "319": "whoischannels",
  1195. "321": "liststart",
  1196. "322": "list",
  1197. "323": "listend",
  1198. "324": "channelmodeis",
  1199. "329": "channelcreate",
  1200. "331": "notopic",
  1201. "332": "currenttopic",
  1202. "333": "topicinfo",
  1203. "341": "inviting",
  1204. "342": "summoning",
  1205. "346": "invitelist",
  1206. "347": "endofinvitelist",
  1207. "348": "exceptlist",
  1208. "349": "endofexceptlist",
  1209. "351": "version",
  1210. "352": "whoreply",
  1211. "353": "namreply",
  1212. "361": "killdone",
  1213. "362": "closing",
  1214. "363": "closeend",
  1215. "364": "links",
  1216. "365": "endoflinks",
  1217. "366": "endofnames",
  1218. "367": "banlist",
  1219. "368": "endofbanlist",
  1220. "369": "endofwhowas",
  1221. "371": "info",
  1222. "372": "motd",
  1223. "373": "infostart",
  1224. "374": "endofinfo",
  1225. "375": "motdstart",
  1226. "376": "endofmotd",
  1227. "377": "motd2", # 1997-10-16 -- tkil
  1228. "381": "youreoper",
  1229. "382": "rehashing",
  1230. "384": "myportis",
  1231. "391": "time",
  1232. "392": "usersstart",
  1233. "393": "users",
  1234. "394": "endofusers",
  1235. "395": "nousers",
  1236. "401": "nosuchnick",
  1237. "402": "nosuchserver",
  1238. "403": "nosuchchannel",
  1239. "404": "cannotsendtochan",
  1240. "405": "toomanychannels",
  1241. "406": "wasnosuchnick",
  1242. "407": "toomanytargets",
  1243. "409": "noorigin",
  1244. "411": "norecipient",
  1245. "412": "notexttosend",
  1246. "413": "notoplevel",
  1247. "414": "wildtoplevel",
  1248. "421": "unknowncommand",
  1249. "422": "nomotd",
  1250. "423": "noadmininfo",
  1251. "424": "fileerror",
  1252. "431": "nonicknamegiven",
  1253. "432": "erroneusnickname", # Thiss iz how its speld in thee RFC.
  1254. "433": "nicknameinuse",
  1255. "436": "nickcollision",
  1256. "437": "unavailresource", # "Nick temporally unavailable"
  1257. "441": "usernotinchannel",
  1258. "442": "notonchannel",
  1259. "443": "useronchannel",
  1260. "444": "nologin",
  1261. "445": "summondisabled",
  1262. "446": "usersdisabled",
  1263. "451": "notregistered",
  1264. "461": "needmoreparams",
  1265. "462": "alreadyregistered",
  1266. "463": "nopermforhost",
  1267. "464": "passwdmismatch",
  1268. "465": "yourebannedcreep", # I love this one...
  1269. "466": "youwillbebanned",
  1270. "467": "keyset",
  1271. "471": "channelisfull",
  1272. "472": "unknownmode",
  1273. "473": "inviteonlychan",
  1274. "474": "bannedfromchan",
  1275. "475": "badchannelkey",
  1276. "476": "badchanmask",
  1277. "477": "nochanmodes", # "Channel doesn't support modes"
  1278. "478": "banlistfull",
  1279. "481": "noprivileges",
  1280. "482": "chanoprivsneeded",
  1281. "483": "cantkillserver",
  1282. "484": "restricted", # Connection is restricted
  1283. "485": "uniqopprivsneeded",
  1284. "491": "nooperhost",
  1285. "492": "noservicehost",
  1286. "501": "umodeunknownflag",
  1287. "502": "usersdontmatch",
  1288. }
  1289. generated_events = [
  1290. # Generated events
  1291. "dcc_connect",
  1292. "dcc_disconnect",
  1293. "dccmsg",
  1294. "disconnect",
  1295. "ctcp",
  1296. "ctcpreply",
  1297. ]
  1298. protocol_events = [
  1299. # IRC protocol events
  1300. "error",
  1301. "join",
  1302. "kick",
  1303. "mode",
  1304. "part",
  1305. "ping",
  1306. "privmsg",
  1307. "privnotice",
  1308. "pubmsg",
  1309. "pubnotice",
  1310. "quit",
  1311. "invite",
  1312. "pong",
  1313. ]
  1314. all_events = generated_events + protocol_events + list(numeric_events.values())
  1315. # from jaraco.util.itertools
  1316. def always_iterable(item):
  1317. """
  1318. Given an object, always return an iterable. If the item is not
  1319. already iterable, return a tuple containing only the item.
  1320. >>> always_iterable([1,2,3])
  1321. [1, 2, 3]
  1322. >>> always_iterable('foo')
  1323. ('foo',)
  1324. >>> always_iterable(None)
  1325. (None,)
  1326. >>> always_iterable(xrange(10))
  1327. xrange(10)
  1328. """
  1329. if isinstance(item, basestring) or not hasattr(item, '__iter__'):
  1330. item = item,
  1331. return item
  1332. # from jaraco.util.string
  1333. class FoldedCase(str):
  1334. """
  1335. A case insensitive string class; behaves just like str
  1336. except compares equal when the only variation is case.
  1337. >>> s = FoldedCase('hello world')
  1338. >>> s == 'Hello World'
  1339. True
  1340. >>> 'Hello World' == s
  1341. True
  1342. >>> s.index('O')
  1343. 4
  1344. >>> s.split('O')
  1345. ['hell', ' w', 'rld']
  1346. >>> names = map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])
  1347. >>> names.sort()
  1348. >>> names
  1349. ['alpha', 'Beta', 'GAMMA']
  1350. """
  1351. def __lt__(self, other):
  1352. return self.lower() < other.lower()
  1353. def __gt__(self, other):
  1354. return self.lower() > other.lower()
  1355. def __eq__(self, other):
  1356. return self.lower() == other.lower()
  1357. def __hash__(self):
  1358. return hash(self.lower())
  1359. # cache lower since it's likely to be called frequently.
  1360. def lower(self):
  1361. self._lower = super(FoldedCase, self).lower()
  1362. self.lower = lambda: self._lower
  1363. return self._lower
  1364. def index(self, sub):
  1365. return self.lower().index(sub.lower())
  1366. def split(self, splitter=' ', maxsplit=0):
  1367. pattern = re.compile(re.escape(splitter), re.I)
  1368. return pattern.split(self, maxsplit)
  1369. class IRCFoldedCase(FoldedCase):
  1370. """
  1371. A version of FoldedCase that honors the IRC specification for lowercased
  1372. strings (RFC 1459).
  1373. >>> IRCFoldedCase('Foo^').lower()
  1374. 'foo~'
  1375. >>> IRCFoldedCase('[this]') == IRCFoldedCase('{THIS}')
  1376. True
  1377. """
  1378. translation = str.maketrans(
  1379. string.ascii_uppercase + r"[]\^",
  1380. string.ascii_lowercase + r"{}|~",
  1381. )
  1382. def lower(self):
  1383. return self.translate(self.translation)
  1384. # for compatibility
  1385. def irc_lower(str):
  1386. return IRCFoldedCase(str).lower()
  1387. def total_seconds(td):
  1388. """
  1389. Python 2.7 adds a total_seconds method to timedelta objects.
  1390. See http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds
  1391. """
  1392. try:
  1393. result = td.total_seconds()
  1394. except AttributeError:
  1395. result = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
  1396. return result