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

irclib.py 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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(u'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(u'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. From here everything need to be encoded in str from utf-8
  610. """
  611. string=string.encode('utf-8')
  612. if self.socket is None:
  613. raise ServerNotConnectedError, "Not connected."
  614. try:
  615. if self.ssl:
  616. self.ssl.write(string + "\r\n")
  617. else:
  618. self.socket.send(string + "\r\n")
  619. if DEBUG:
  620. print "TO SERVER:", string
  621. except socket.error, x:
  622. # Ouch!
  623. self.disconnect("Connection reset by peer.")
  624. def squit(self, server, comment=""):
  625. """Send an SQUIT command."""
  626. self.send_raw("SQUIT %s%s" % (server, comment and (" :" + comment)))
  627. def stats(self, statstype, server=""):
  628. """Send a STATS command."""
  629. self.send_raw("STATS %s%s" % (statstype, server and (" " + server)))
  630. def time(self, server=""):
  631. """Send a TIME command."""
  632. self.send_raw("TIME" + (server and (" " + server)))
  633. def topic(self, channel, new_topic=None):
  634. """Send a TOPIC command."""
  635. if new_topic is None:
  636. self.send_raw("TOPIC " + channel)
  637. else:
  638. self.send_raw("TOPIC %s :%s" % (channel, new_topic))
  639. def trace(self, target=""):
  640. """Send a TRACE command."""
  641. self.send_raw("TRACE" + (target and (" " + target)))
  642. def user(self, username, realname):
  643. """Send a USER command."""
  644. self.send_raw("USER %s 0 * :%s" % (username, realname))
  645. def userhost(self, nicks):
  646. """Send a USERHOST command."""
  647. self.send_raw("USERHOST " + ",".join(nicks))
  648. def users(self, server=""):
  649. """Send a USERS command."""
  650. self.send_raw("USERS" + (server and (" " + server)))
  651. def version(self, server=""):
  652. """Send a VERSION command."""
  653. self.send_raw("VERSION" + (server and (" " + server)))
  654. def wallops(self, text):
  655. """Send a WALLOPS command."""
  656. self.send_raw("WALLOPS :" + text)
  657. def who(self, target="", op=""):
  658. """Send a WHO command."""
  659. self.send_raw("WHO%s%s" % (target and (" " + target), op and (" o")))
  660. def whois(self, targets):
  661. """Send a WHOIS command."""
  662. self.send_raw("WHOIS " + ",".join(targets))
  663. def whowas(self, nick, max="", server=""):
  664. """Send a WHOWAS command."""
  665. self.send_raw("WHOWAS %s%s%s" % (nick,
  666. max and (" " + max),
  667. server and (" " + server)))
  668. class DCCConnectionError(IRCError):
  669. pass
  670. class DCCConnection(Connection):
  671. """This class represents a DCC connection.
  672. DCCConnection objects are instantiated by calling the dcc
  673. method on an IRC object.
  674. """
  675. def __init__(self, irclibobj, dcctype):
  676. Connection.__init__(self, irclibobj)
  677. self.connected = 0
  678. self.passive = 0
  679. self.dcctype = dcctype
  680. self.peeraddress = None
  681. self.peerport = None
  682. def connect(self, address, port):
  683. """Connect/reconnect to a DCC peer.
  684. Arguments:
  685. address -- Host/IP address of the peer.
  686. port -- The port number to connect to.
  687. Returns the DCCConnection object.
  688. """
  689. self.peeraddress = socket.gethostbyname(address)
  690. self.peerport = port
  691. self.socket = None
  692. self.previous_buffer = ""
  693. self.handlers = {}
  694. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  695. self.passive = 0
  696. try:
  697. self.socket.connect((self.peeraddress, self.peerport))
  698. except socket.error, x:
  699. raise DCCConnectionError, "Couldn't connect to socket: %s" % x
  700. self.connected = 1
  701. if self.irclibobj.fn_to_add_socket:
  702. self.irclibobj.fn_to_add_socket(self.socket)
  703. return self
  704. def listen(self):
  705. """Wait for a connection/reconnection from a DCC peer.
  706. Returns the DCCConnection object.
  707. The local IP address and port are available as
  708. self.localaddress and self.localport. After connection from a
  709. peer, the peer address and port are available as
  710. self.peeraddress and self.peerport.
  711. """
  712. self.previous_buffer = ""
  713. self.handlers = {}
  714. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  715. self.passive = 1
  716. try:
  717. self.socket.bind((socket.gethostbyname(socket.gethostname()), 0))
  718. self.localaddress, self.localport = self.socket.getsockname()
  719. self.socket.listen(10)
  720. except socket.error, x:
  721. raise DCCConnectionError, "Couldn't bind socket: %s" % x
  722. return self
  723. def disconnect(self, message=""):
  724. """Hang up the connection and close the object.
  725. Arguments:
  726. message -- Quit message.
  727. """
  728. if not self.connected:
  729. return
  730. self.connected = 0
  731. try:
  732. self.socket.close()
  733. except socket.error, x:
  734. pass
  735. self.socket = None
  736. self.irclibobj._handle_event(
  737. self,
  738. Event("dcc_disconnect", self.peeraddress, "", [message]))
  739. self.irclibobj._remove_connection(self)
  740. def process_data(self):
  741. """[Internal]"""
  742. if self.passive and not self.connected:
  743. conn, (self.peeraddress, self.peerport) = self.socket.accept()
  744. self.socket.close()
  745. self.socket = conn
  746. self.connected = 1
  747. if DEBUG:
  748. print "DCC connection from %s:%d" % (
  749. self.peeraddress, self.peerport)
  750. self.irclibobj._handle_event(
  751. self,
  752. Event("dcc_connect", self.peeraddress, None, None))
  753. return
  754. try:
  755. new_data = self.socket.recv(2**14)
  756. except socket.error, x:
  757. # The server hung up.
  758. self.disconnect("Connection reset by peer")
  759. return
  760. if not new_data:
  761. # Read nothing: connection must be down.
  762. self.disconnect("Connection reset by peer")
  763. return
  764. if self.dcctype == "chat":
  765. # The specification says lines are terminated with LF, but
  766. # it seems safer to handle CR LF terminations too.
  767. chunks = _linesep_regexp.split(self.previous_buffer + new_data)
  768. # Save the last, unfinished line.
  769. self.previous_buffer = chunks[-1]
  770. if len(self.previous_buffer) > 2**14:
  771. # Bad peer! Naughty peer!
  772. self.disconnect()
  773. return
  774. chunks = chunks[:-1]
  775. else:
  776. chunks = [new_data]
  777. command = "dccmsg"
  778. prefix = self.peeraddress
  779. target = None
  780. for chunk in chunks:
  781. if DEBUG:
  782. print "FROM PEER:", chunk
  783. arguments = [chunk]
  784. if DEBUG:
  785. print "command: %s, source: %s, target: %s, arguments: %s" % (
  786. command, prefix, target, arguments)
  787. self.irclibobj._handle_event(
  788. self,
  789. Event(command, prefix, target, arguments))
  790. def _get_socket(self):
  791. """[Internal]"""
  792. return self.socket
  793. def privmsg(self, string):
  794. """Send data to DCC peer.
  795. The string will be padded with appropriate LF if it's a DCC
  796. CHAT session.
  797. """
  798. try:
  799. self.socket.send(string)
  800. if self.dcctype == "chat":
  801. self.socket.send("\n")
  802. if DEBUG:
  803. print "TO PEER: %s\n" % string
  804. except socket.error, x:
  805. # Ouch!
  806. self.disconnect("Connection reset by peer.")
  807. class SimpleIRCClient:
  808. """A simple single-server IRC client class.
  809. This is an example of an object-oriented wrapper of the IRC
  810. framework. A real IRC client can be made by subclassing this
  811. class and adding appropriate methods.
  812. The method on_join will be called when a "join" event is created
  813. (which is done when the server sends a JOIN messsage/command),
  814. on_privmsg will be called for "privmsg" events, and so on. The
  815. handler methods get two arguments: the connection object (same as
  816. self.connection) and the event object.
  817. Instance attributes that can be used by sub classes:
  818. ircobj -- The IRC instance.
  819. connection -- The ServerConnection instance.
  820. dcc_connections -- A list of DCCConnection instances.
  821. """
  822. def __init__(self):
  823. self.ircobj = IRC()
  824. self.connection = self.ircobj.server()
  825. self.dcc_connections = []
  826. self.ircobj.add_global_handler("all_events", self._dispatcher, -10)
  827. self.ircobj.add_global_handler("dcc_disconnect", self._dcc_disconnect, -10)
  828. def _dispatcher(self, c, e):
  829. """[Internal]"""
  830. m = "on_" + e.eventtype()
  831. if hasattr(self, m):
  832. getattr(self, m)(c, e)
  833. def _dcc_disconnect(self, c, e):
  834. self.dcc_connections.remove(c)
  835. def connect(self, server, port, nickname, password=None, username=None,
  836. ircname=None, localaddress="", localport=0, ssl=False, ipv6=False):
  837. """Connect/reconnect to a server.
  838. Arguments:
  839. server -- Server name.
  840. port -- Port number.
  841. nickname -- The nickname.
  842. password -- Password (if any).
  843. username -- The username.
  844. ircname -- The IRC name.
  845. localaddress -- Bind the connection to a specific local IP address.
  846. localport -- Bind the connection to a specific local port.
  847. ssl -- Enable support for ssl.
  848. ipv6 -- Enable support for ipv6.
  849. This function can be called to reconnect a closed connection.
  850. """
  851. self.connection.connect(server, port, nickname,
  852. password, username, ircname,
  853. localaddress, localport, ssl, ipv6)
  854. def dcc_connect(self, address, port, dcctype="chat"):
  855. """Connect to a DCC peer.
  856. Arguments:
  857. address -- IP address of the peer.
  858. port -- Port to connect to.
  859. Returns a DCCConnection instance.
  860. """
  861. dcc = self.ircobj.dcc(dcctype)
  862. self.dcc_connections.append(dcc)
  863. dcc.connect(address, port)
  864. return dcc
  865. def dcc_listen(self, dcctype="chat"):
  866. """Listen for connections from a DCC peer.
  867. Returns a DCCConnection instance.
  868. """
  869. dcc = self.ircobj.dcc(dcctype)
  870. self.dcc_connections.append(dcc)
  871. dcc.listen()
  872. return dcc
  873. def start(self):
  874. """Start the IRC client."""
  875. self.ircobj.process_forever()
  876. class Event:
  877. """Class representing an IRC event."""
  878. def __init__(self, eventtype, source, target, arguments=None):
  879. """Constructor of Event objects.
  880. Arguments:
  881. eventtype -- A string describing the event.
  882. source -- The originator of the event (a nick mask or a server).
  883. target -- The target of the event (a nick or a channel).
  884. arguments -- Any event specific arguments.
  885. """
  886. self._eventtype = eventtype
  887. self._source = source
  888. self._target = target
  889. if arguments:
  890. self._arguments = arguments
  891. else:
  892. self._arguments = []
  893. def eventtype(self):
  894. """Get the event type."""
  895. return self._eventtype
  896. def source(self):
  897. """Get the event source."""
  898. return self._source
  899. def target(self):
  900. """Get the event target."""
  901. return self._target
  902. def arguments(self):
  903. """Get the event arguments."""
  904. return self._arguments
  905. _LOW_LEVEL_QUOTE = "\020"
  906. _CTCP_LEVEL_QUOTE = "\134"
  907. _CTCP_DELIMITER = "\001"
  908. _low_level_mapping = {
  909. "0": "\000",
  910. "n": "\n",
  911. "r": "\r",
  912. _LOW_LEVEL_QUOTE: _LOW_LEVEL_QUOTE
  913. }
  914. _low_level_regexp = re.compile(_LOW_LEVEL_QUOTE + "(.)")
  915. def mask_matches(nick, mask):
  916. """Check if a nick matches a mask.
  917. Returns true if the nick matches, otherwise false.
  918. """
  919. nick = irc_lower(nick)
  920. mask = irc_lower(mask)
  921. mask = mask.replace("\\", "\\\\")
  922. for ch in ".$|[](){}+":
  923. mask = mask.replace(ch, "\\" + ch)
  924. mask = mask.replace("?", ".")
  925. mask = mask.replace("*", ".*")
  926. r = re.compile(mask, re.IGNORECASE)
  927. return r.match(nick)
  928. _special = "-[]\\`^{}"
  929. nick_characters = string.ascii_letters + string.digits + _special
  930. _ircstring_translation = string.maketrans(string.ascii_uppercase + "[]\\^",
  931. string.ascii_lowercase + "{}|~")
  932. def irc_lower(s):
  933. """Returns a lowercased string.
  934. The definition of lowercased comes from the IRC specification (RFC
  935. 1459).
  936. """
  937. return s.translate(_ircstring_translation)
  938. def _ctcp_dequote(message):
  939. """[Internal] Dequote a message according to CTCP specifications.
  940. The function returns a list where each element can be either a
  941. string (normal message) or a tuple of one or two strings (tagged
  942. messages). If a tuple has only one element (ie is a singleton),
  943. that element is the tag; otherwise the tuple has two elements: the
  944. tag and the data.
  945. Arguments:
  946. message -- The message to be decoded.
  947. """
  948. def _low_level_replace(match_obj):
  949. ch = match_obj.group(1)
  950. # If low_level_mapping doesn't have the character as key, we
  951. # should just return the character.
  952. return _low_level_mapping.get(ch, ch)
  953. if _LOW_LEVEL_QUOTE in message:
  954. # Yup, there was a quote. Release the dequoter, man!
  955. message = _low_level_regexp.sub(_low_level_replace, message)
  956. if _CTCP_DELIMITER not in message:
  957. return [message]
  958. else:
  959. # Split it into parts. (Does any IRC client actually *use*
  960. # CTCP stacking like this?)
  961. chunks = message.split(_CTCP_DELIMITER)
  962. messages = []
  963. i = 0
  964. while i < len(chunks)-1:
  965. # Add message if it's non-empty.
  966. if len(chunks[i]) > 0:
  967. messages.append(chunks[i])
  968. if i < len(chunks)-2:
  969. # Aye! CTCP tagged data ahead!
  970. messages.append(tuple(chunks[i+1].split(" ", 1)))
  971. i = i + 2
  972. if len(chunks) % 2 == 0:
  973. # Hey, a lonely _CTCP_DELIMITER at the end! This means
  974. # that the last chunk, including the delimiter, is a
  975. # normal message! (This is according to the CTCP
  976. # specification.)
  977. messages.append(_CTCP_DELIMITER + chunks[-1])
  978. return messages
  979. def is_channel(string):
  980. """Check if a string is a channel name.
  981. Returns true if the argument is a channel name, otherwise false.
  982. """
  983. return string and string[0] in "#&+!"
  984. def ip_numstr_to_quad(num):
  985. """Convert an IP number as an integer given in ASCII
  986. representation (e.g. '3232235521') to an IP address string
  987. (e.g. '192.168.0.1')."""
  988. n = long(num)
  989. p = map(str, map(int, [n >> 24 & 0xFF, n >> 16 & 0xFF,
  990. n >> 8 & 0xFF, n & 0xFF]))
  991. return ".".join(p)
  992. def ip_quad_to_numstr(quad):
  993. """Convert an IP address string (e.g. '192.168.0.1') to an IP
  994. number as an integer given in ASCII representation
  995. (e.g. '3232235521')."""
  996. p = map(long, quad.split("."))
  997. s = str((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])
  998. if s[-1] == "L":
  999. s = s[:-1]
  1000. return s
  1001. def nm_to_n(s):
  1002. """Get the nick part of a nickmask.
  1003. (The source of an Event is a nickmask.)
  1004. """
  1005. return s.split("!")[0]
  1006. def nm_to_uh(s):
  1007. """Get the userhost part of a nickmask.
  1008. (The source of an Event is a nickmask.)
  1009. """
  1010. return s.split("!")[1]
  1011. def nm_to_h(s):
  1012. """Get the host part of a nickmask.
  1013. (The source of an Event is a nickmask.)
  1014. """
  1015. return s.split("@")[1]
  1016. def nm_to_u(s):
  1017. """Get the user part of a nickmask.
  1018. (The source of an Event is a nickmask.)
  1019. """
  1020. s = s.split("!")[1]
  1021. return s.split("@")[0]
  1022. def parse_nick_modes(mode_string):
  1023. """Parse a nick mode string.
  1024. The function returns a list of lists with three members: sign,
  1025. mode and argument. The sign is \"+\" or \"-\". The argument is
  1026. always None.
  1027. Example:
  1028. >>> irclib.parse_nick_modes(\"+ab-c\")
  1029. [['+', 'a', None], ['+', 'b', None], ['-', 'c', None]]
  1030. """
  1031. return _parse_modes(mode_string, "")
  1032. def parse_channel_modes(mode_string):
  1033. """Parse a channel mode string.
  1034. The function returns a list of lists with three members: sign,
  1035. mode and argument. The sign is \"+\" or \"-\". The argument is
  1036. None if mode isn't one of \"b\", \"k\", \"l\", \"v\" or \"o\".
  1037. Example:
  1038. >>> irclib.parse_channel_modes(\"+ab-c foo\")
  1039. [['+', 'a', None], ['+', 'b', 'foo'], ['-', 'c', None]]
  1040. """
  1041. return _parse_modes(mode_string, "bklvo")
  1042. def _parse_modes(mode_string, unary_modes=""):
  1043. """[Internal]"""
  1044. modes = []
  1045. arg_count = 0
  1046. # State variable.
  1047. sign = ""
  1048. a = mode_string.split()
  1049. if len(a) == 0:
  1050. return []
  1051. else:
  1052. mode_part, args = a[0], a[1:]
  1053. if mode_part[0] not in "+-":
  1054. return []
  1055. for ch in mode_part:
  1056. if ch in "+-":
  1057. sign = ch
  1058. elif ch == " ":
  1059. collecting_arguments = 1
  1060. elif ch in unary_modes:
  1061. if len(args) >= arg_count + 1:
  1062. modes.append([sign, ch, args[arg_count]])
  1063. arg_count = arg_count + 1
  1064. else:
  1065. modes.append([sign, ch, None])
  1066. else:
  1067. modes.append([sign, ch, None])
  1068. return modes
  1069. def _ping_ponger(connection, event):
  1070. """[Internal]"""
  1071. connection.pong(event.target())
  1072. # Numeric table mostly stolen from the Perl IRC module (Net::IRC).
  1073. numeric_events = {
  1074. "001": "welcome",
  1075. "002": "yourhost",
  1076. "003": "created",
  1077. "004": "myinfo",
  1078. "005": "featurelist", # XXX
  1079. "200": "tracelink",
  1080. "201": "traceconnecting",
  1081. "202": "tracehandshake",
  1082. "203": "traceunknown",
  1083. "204": "traceoperator",
  1084. "205": "traceuser",
  1085. "206": "traceserver",
  1086. "207": "traceservice",
  1087. "208": "tracenewtype",
  1088. "209": "traceclass",
  1089. "210": "tracereconnect",
  1090. "211": "statslinkinfo",
  1091. "212": "statscommands",
  1092. "213": "statscline",
  1093. "214": "statsnline",
  1094. "215": "statsiline",
  1095. "216": "statskline",
  1096. "217": "statsqline",
  1097. "218": "statsyline",
  1098. "219": "endofstats",
  1099. "221": "umodeis",
  1100. "231": "serviceinfo",
  1101. "232": "endofservices",
  1102. "233": "service",
  1103. "234": "servlist",
  1104. "235": "servlistend",
  1105. "241": "statslline",
  1106. "242": "statsuptime",
  1107. "243": "statsoline",
  1108. "244": "statshline",
  1109. "250": "luserconns",
  1110. "251": "luserclient",
  1111. "252": "luserop",
  1112. "253": "luserunknown",
  1113. "254": "luserchannels",
  1114. "255": "luserme",
  1115. "256": "adminme",
  1116. "257": "adminloc1",
  1117. "258": "adminloc2",
  1118. "259": "adminemail",
  1119. "261": "tracelog",
  1120. "262": "endoftrace",
  1121. "263": "tryagain",
  1122. "265": "n_local",
  1123. "266": "n_global",
  1124. "300": "none",
  1125. "301": "away",
  1126. "302": "userhost",
  1127. "303": "ison",
  1128. "305": "unaway",
  1129. "306": "nowaway",
  1130. "311": "whoisuser",
  1131. "312": "whoisserver",
  1132. "313": "whoisoperator",
  1133. "314": "whowasuser",
  1134. "315": "endofwho",
  1135. "316": "whoischanop",
  1136. "317": "whoisidle",
  1137. "318": "endofwhois",
  1138. "319": "whoischannels",
  1139. "321": "liststart",
  1140. "322": "list",
  1141. "323": "listend",
  1142. "324": "channelmodeis",
  1143. "329": "channelcreate",
  1144. "331": "notopic",
  1145. "332": "currenttopic",
  1146. "333": "topicinfo",
  1147. "341": "inviting",
  1148. "342": "summoning",
  1149. "346": "invitelist",
  1150. "347": "endofinvitelist",
  1151. "348": "exceptlist",
  1152. "349": "endofexceptlist",
  1153. "351": "version",
  1154. "352": "whoreply",
  1155. "353": "namreply",
  1156. "361": "killdone",
  1157. "362": "closing",
  1158. "363": "closeend",
  1159. "364": "links",
  1160. "365": "endoflinks",
  1161. "366": "endofnames",
  1162. "367": "banlist",
  1163. "368": "endofbanlist",
  1164. "369": "endofwhowas",
  1165. "371": "info",
  1166. "372": "motd",
  1167. "373": "infostart",
  1168. "374": "endofinfo",
  1169. "375": "motdstart",
  1170. "376": "endofmotd",
  1171. "377": "motd2", # 1997-10-16 -- tkil
  1172. "381": "youreoper",
  1173. "382": "rehashing",
  1174. "384": "myportis",
  1175. "391": "time",
  1176. "392": "usersstart",
  1177. "393": "users",
  1178. "394": "endofusers",
  1179. "395": "nousers",
  1180. "401": "nosuchnick",
  1181. "402": "nosuchserver",
  1182. "403": "nosuchchannel",
  1183. "404": "cannotsendtochan",
  1184. "405": "toomanychannels",
  1185. "406": "wasnosuchnick",
  1186. "407": "toomanytargets",
  1187. "409": "noorigin",
  1188. "411": "norecipient",
  1189. "412": "notexttosend",
  1190. "413": "notoplevel",
  1191. "414": "wildtoplevel",
  1192. "421": "unknowncommand",
  1193. "422": "nomotd",
  1194. "423": "noadmininfo",
  1195. "424": "fileerror",
  1196. "431": "nonicknamegiven",
  1197. "432": "erroneusnickname", # Thiss iz how its speld in thee RFC.
  1198. "433": "nicknameinuse",
  1199. "436": "nickcollision",
  1200. "437": "unavailresource", # "Nick temporally unavailable"
  1201. "441": "usernotinchannel",
  1202. "442": "notonchannel",
  1203. "443": "useronchannel",
  1204. "444": "nologin",
  1205. "445": "summondisabled",
  1206. "446": "usersdisabled",
  1207. "451": "notregistered",
  1208. "461": "needmoreparams",
  1209. "462": "alreadyregistered",
  1210. "463": "nopermforhost",
  1211. "464": "passwdmismatch",
  1212. "465": "yourebannedcreep", # I love this one...
  1213. "466": "youwillbebanned",
  1214. "467": "keyset",
  1215. "471": "channelisfull",
  1216. "472": "unknownmode",
  1217. "473": "inviteonlychan",
  1218. "474": "bannedfromchan",
  1219. "475": "badchannelkey",
  1220. "476": "badchanmask",
  1221. "477": "nochanmodes", # "Channel doesn't support modes"
  1222. "478": "banlistfull",
  1223. "481": "noprivileges",
  1224. "482": "chanoprivsneeded",
  1225. "483": "cantkillserver",
  1226. "484": "restricted", # Connection is restricted
  1227. "485": "uniqopprivsneeded",
  1228. "491": "nooperhost",
  1229. "492": "noservicehost",
  1230. "501": "umodeunknownflag",
  1231. "502": "usersdontmatch",
  1232. }
  1233. generated_events = [
  1234. # Generated events
  1235. "dcc_connect",
  1236. "dcc_disconnect",
  1237. "dccmsg",
  1238. "disconnect",
  1239. "ctcp",
  1240. "ctcpreply",
  1241. ]
  1242. protocol_events = [
  1243. # IRC protocol events
  1244. "error",
  1245. "join",
  1246. "kick",
  1247. "mode",
  1248. "part",
  1249. "ping",
  1250. "privmsg",
  1251. "privnotice",
  1252. "pubmsg",
  1253. "pubnotice",
  1254. "quit",
  1255. "invite",
  1256. "pong",
  1257. ]
  1258. all_events = generated_events + protocol_events + numeric_events.values()