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

irclib.py 48KB

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