pax_global_header00006660000000000000000000000064130254702000014503gustar00rootroot0000000000000052 comment=6e8d18e00463a3cb196d2d75f191b015a1dbfde4 python-irc-8.5.3+dfsg/000077500000000000000000000000001302547020000145335ustar00rootroot00000000000000python-irc-8.5.3+dfsg/CHANGES.rst000066400000000000000000000266641302547020000163530ustar00rootroot00000000000000Changes ------- 8.5.3 ===== * Issue #28: Fix TypeError in version calculation in irc.bot CTCP version. 8.5.2 ===== * Updated DCC send and receive scripts (Issue #27). 8.5.1 ===== * Fix timestamp support in ``schedule.DelayedCommand`` construction. 8.5 === * ``irc.client.NickMask`` is now a Unicode object on Python 2. Fixes issue reported in pull request #19. * Issue #24: Added `DCCConnection.send_bytes` for transmitting binary data. `privmsg` remains to support transmitting text. 8.4 === * Code base now runs natively on Python 2 and Python 3, but requires `six `_ to be installed. * Issue #25: Rate-limiting has been updated to be finer grained (preventing bursts exceeding the limit following idle periods). 8.3.2 ===== * Issue #22: Catch error in bot.py on NAMREPLY when nick is not in any visible channel. 8.3.1 ===== * Fixed encoding errors in server on Python 3. 8.3 === * Added a ``set_keepalive`` method to the ServerConnection. Sends a periodic PING message every indicated interval. 8.2 === * Added support for throttling send_raw messages via the ServerConnection object. For example, on any connection object: connection.set_rate_limit(30) That would set the rate limit to 30 Hz (30 per second). Thanks to Jason Kendall for the suggestion and bug fixes. 8.1.2 ===== * Fix typo in `client.NickMask`. 8.1.1 ===== * Fix typo in bot.py. 8.1 === * Issue #15: Added client support for ISUPPORT directives on server connections. Now, each ServerConnection has a `features` attribute which reflects the features supported by the server. See the docs for `irc.features` for details about the implementation. 8.0.1 ===== * Issue #14: Fix errors when handlers of the same priority are added under Python 3. This also fixes the unintended behavior of allowing handlers of the same priority to compare as unequal. 8.0 === This release brings several backward-incompatible changes to the scheduled commands. * Refactored implementation of schedule classes. No longer do they override the datetime constructor, but now only provide suitable classmethods for construction in various forms. * Removed backward-compatible references from irc.client. * Remove 'arguments' parameter from scheduled commands. Clients that reference the schedule classes from irc.client or that construct them from the basic constructor will need to update to use the new class methods:: - DelayedCommand -> DelayedCommand.after - PeriodicCommand -> PeriodicCommand.after Arguments may no longer be passed to the 'function' callback, but one is encouraged instead to use functools.partial to attach parameters to the callback. For example:: DelayedCommand.after(3, func, ('a', 10)) becomes:: func = functools.partial(func, 'a', 10) DelayedCommand.after(3, func) This mode puts less constraints on the both the handler and the caller. For example, a caller can now pass keyword arguments instead:: func = functools.partial(func, name='a', quantity=10) DelayedCommand.after(3, func) Readability, maintainability, and usability go up. 7.1.2 ===== * Issue #13: TypeError on Python 3 when constructing PeriodicCommand (and thus execute_every). 7.1.1 ===== * Fixed regression created in 7.0 where PeriodicCommandFixedDelay would only cause the first command to be scheduled, but not subsequent ones. 7.1 === * Moved scheduled command classes to irc.schedule module. Kept references for backwards-compatibility. 7.0 === * PeriodicCommand now raises a ValueError if it's created with a negative or zero delay (meaning all subsequent commands are immediately due). This fixes #12. * Renamed the parameters to the IRC object. If you use a custom event loop and your code constructs the IRC object with keyword parameters, you will need to update your code to use the new names, so:: IRC(fn_to_add_socket=adder, fn_to_remove_socket=remover, fn_to_add_timeout=timeout) becomes:: IRC(on_connect=adder, on_disconnect=remover, on_schedule=timeout) If you don't use a custom event loop or you pass the parameters positionally, no change is necessary. 6.0.1 ===== * Fixed some unhandled exceptions in server client connections when the client would disconnect in response to messages sent after select was called. 6.0 === * Moved `LineBuffer` and `DecodingLineBuffer` from client to buffer module. Backward-compatible references have been kept for now. * Removed daemon mode and log-to-file options for server. * Miscellaneous bugfixes in server. 5.1.1 ===== * Fix error in 2to3 conversion on irc/server.py (issue #11). 5.1 === The IRC library is now licensed under the MIT license. * Added irc/server.py, based on hircd by Ferry Boender. * Added support for CAP command (pull request #10), thanks to Danneh Oaks. 5.0 === Another backward-incompatible change. In irc 5.0, many of the unnecessary getter functions have been removed and replaced with simple attributes. This change addresses issue #2. In particular: - Connection._get_socket() -> Connection.socket (including subclasses) - Event.eventtype() -> Event.type - Event.source() -> Event.source - Event.target() -> Event.target - Event.arguments() -> Event.arguments The `nm_to_*` functions were removed. Instead, use the NickMask class attributes. These deprecated function aliases were removed from irc.client:: - parse_nick_modes -> modes.parse_nick_modes - parse_channel_modes -> modes.parse_channel_modes - generated_events -> events.generated - protocol_events -> events.protocol - numeric_events -> events.numeric - all_events -> events.all - irc_lower -> strings.lower Also, the parameter name when constructing an event was renamed from `eventtype` to simply `type`. 4.0 === * Removed deprecated arguments to ServerConnection.connect. See notes on the 3.3 release on how to use the connect_factory parameter if your application requires ssl, ipv6, or other connection customization. 3.6.1 ===== * Filter out disconnected sockets when processing input. 3.6 === * Created two new exceptions in `irc.client`: `MessageTooLong` and `InvalidCharacters`. * Use explicit exceptions instead of ValueError when sending data. 3.5 === * SingleServerIRCBot now accepts keyword arguments which are passed through to the `ServerConnection.connect` method. One can use this to use SSL for connections:: factory = irc.connection.Factory(wrapper=ssl.wrap_socket) bot = irc.bot.SingleServerIRCBot(..., connect_factory = factory) 3.4.2 ===== * Issue #6: Fix AttributeError when legacy parameters are passed to `ServerConnection.connect`. * Issue #7: Fix TypeError on `iter(LineBuffer)`. 3.4.1 ===== 3.4 never worked - the decoding customization feature was improperly implemented and never tested. * The ServerConnection now allows custom classes to be supplied to customize the decoding of incoming lines. For example, to disable the decoding of incoming lines, replace the `buffer_class` on the ServerConnection with a version that passes through the lines directly:: irc.client.ServerConnection.buffer_class = irc.client.LineBuffer This fixes #5. 3.4 === *Broken Release* 3.3 === * Added `connection` module with a Factory for creating socket connections. * Added `connect_factory` parameter to the ServerConnection. It's now possible to create connections with custom SSL parameters or other socket wrappers. For example, to create a connection with a custom SSL cert:: import ssl import irc.client import irc.connection import functools irc = irc.client.IRC() server = irc.server() wrapper = functools.partial(ssl.wrap_socket, ssl_cert=my_cert()) server.connect(connect_factory = irc.connection.Factory(wrapper=wrapper)) With this release, many of the parameters to `ServerConnection.connect` are now deprecated: - localaddress - localport - ssl - ipv6 Instead, one should pass the appropriate values to a `connection.Factory` instance and pass that factory to the .connect method. Backwards-compatibility will be maintained for these parameters until the release of irc 4.0. 3.2.3 ===== * Restore Python 2.6 compatibility. 3.2.2 ===== * Protect from UnicodeDecodeError when decoding data on the wire when data is not properly encoded in ASCII or UTF-8. 3.2.1 ===== * Additional branch protected by mutex. 3.2 === * Implemented thread safety via a reentrant lock guarding shared state in IRC objects. 3.1.1 ===== * Fix some issues with bytes/unicode on Python 3 3.1 === * Distribute using setuptools rather than paver. * Minor tweaks for Python 3 support. Now installs on Python 3. 3.0.1 ===== * Added error checking when sending a message - for both message length and embedded carriage returns. Fixes #4. * Updated README. 3.0 === * Improved Unicode support. Fixes failing tests and errors lowering Unicode channel names. * Issue #3541414 - The ServerConnection and DCCConnection now encode any strings as UTF-8 before transmitting. * Issue #3527371 - Updated strings.FoldedCase to support comparison against objects of other types. * Shutdown the sockets before closing. Applications that are currently encoding unicode as UTF-8 before passing the strings to `ServerConnection.send_raw` need to be updated to send Unicode or ASCII. 2.0.4 ===== This release officially deprecates 2.0.1-2.0.3 in favor of 3.0. * Re-release of irc 2.0 (without the changes from 2.0.1-2.0.3) for correct compatibility indication. 2.0 === * DelayedCommands now use the local time for calculating 'at' and 'due' times. This will be more friendly for simple servers. Servers that expect UTC times should either run in UTC or override DelayedCommand.now to return an appropriate time object for 'now'. For example:: def startup_bot(): irc.client.DelayedCommand.now = irc.client.DelayedCommand.utcnow ... 1.1 === * Added irc.client.PeriodicCommandFixedDelay. Schedule this command to have a function executed at a specific time and then at periodic intervals thereafter. 1.0 === * Removed `irclib` and `ircbot` legacy modules. 0.9 === * Fix file saving using dccreceive.py on Windows. Fixes #2863199. * Created NickMask class from nm_to_* functions. Now if a source is a NickMask, one can access the .nick, .host, and .user attributes. * Use correct attribute for saved connect args. Fixes #3523057. 0.8 === * Added ServerConnection.reconnect method. Fixes #3515580. 0.7.1 ===== * Added missing events. Fixes #3515578. 0.7 === * Moved functionality from irclib module to irc.client module. * Moved functionality from ircbot module to irc.bot module. * Retained irclib and ircbot modules for backward-compatibility. These will be removed in 1.0. * Renamed project to simply 'irc'. To support the new module structure, simply replace references to the irclib module with irc.client and ircbot module with irc.bot. This project will support that interface through all versions of irc 1.x, so if you've made these changes, you can safely depend on `irc >= 0.7, <2.0dev`. 0.6.3 ===== * Fixed failing test where DelayedCommands weren't being sorted properly. DelayedCommand a now subclass of the DateTime object, where the command's due time is the datetime. Fixed issue #3518508. 0.6.2 ===== * Fixed incorrect usage of Connection.execute_delayed (again). 0.6.0 ===== * Minimum Python requirement is now Python 2.6. Python 2.3 and earlier should use 0.5.0 or earlier. * Removed incorrect usage of Connection.execute_delayed. Added Connection.execute_every. Fixed issue 3516241. * Use new-style classes. python-irc-8.5.3+dfsg/COPYING000066400000000000000000000636501302547020000156000ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. ^L Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. ^L GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. ^L Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. ^L 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. ^L 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. ^L 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. ^L 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ^L How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! python-irc-8.5.3+dfsg/LICENSE000066400000000000000000000017771302547020000155540ustar00rootroot00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-irc-8.5.3+dfsg/MANIFEST.in000066400000000000000000000000531302547020000162670ustar00rootroot00000000000000include setup.py include paver-minilib.zip python-irc-8.5.3+dfsg/PKG-INFO000066400000000000000000000561641302547020000156440ustar00rootroot00000000000000Metadata-Version: 1.1 Name: irc Version: 8.5.3 Summary: IRC (Internet Relay Chat) protocol client library for Python Home-page: http://python-irclib.sourceforge.net Author: Jason R. Coombs Author-email: jaraco@jaraco.com License: MIT Description: Internet Relay Chat (IRC) protocol client library ------------------------------------------------- The home of irclib is: https://bitbucket.org/jaraco/irc You can `download project releases from PyPI `_. Some legacy content is still available at the `foundational SourceForge site `_. Tests are `continuously run `_ using Travis-CI. |BuildStatus|_ .. |BuildStatus| image:: https://secure.travis-ci.org/jaraco/irc.png .. _BuildStatus: https://travis-ci.org/jaraco/irc This library is intended to encapsulate the IRC protocol at a quite low level. It provides an event-driven IRC client framework. It has a fairly thorough support for the basic IRC protocol, CTCP and DCC connections. In order to understand how to make an IRC client, I'm afraid you more or less must understand the IRC specifications. They are available here: http://www.irchelp.org/irchelp/rfc/ Installation ============ IRC requires Python 2.6 or newer (including Python 3). You have several options to install the IRC project. * Use "easy_install irc" or "pip install irc" to grab the latest version from the cheeseshop (recommended). * Run "python setup.py install" (from the source distribution) or * Run "paver install" (from repo checkout, requires paver) or * Copy irc directory to appropriate site-packages directory. Client Features =============== The main features of the IRC client framework are: * Abstraction of the IRC protocol. * Handles multiple simultaneous IRC server connections. * Handles server PONGing transparently. * Messages to the IRC server are done by calling methods on an IRC connection object. * Messages from an IRC server triggers events, which can be caught by event handlers. * Reading from and writing to IRC server sockets are normally done by an internal select() loop, but the select()ing may be done by an external main loop. * Functions can be registered to execute at specified times by the event-loop. * Decodes CTCP tagging correctly (hopefully); I haven't seen any other IRC client implementation that handles the CTCP specification subtilties. * A kind of simple, single-server, object-oriented IRC client class that dispatches events to instance methods is included. * DCC connection support. Current limitations: * The IRC protocol shines through the abstraction a bit too much. * Data is not written asynchronously to the server (and DCC peers), i.e. the write() may block if the TCP buffers are stuffed. * Like most projects, documentation is lacking... Unfortunately, this library isn't as well-documented as I would like it to be. I think the best way to get started is to read and understand the example program irccat, which is included in the distribution. The following files might be of interest: * irc/client.py The library itself. Read the code along with comments and docstrings to get a grip of what it does. Use it at your own risk and read the source, Luke! * irc/bot.py An IRC bot implementation. * irc/server.py A basic IRC server implementation. Suitable for testing, but not production quality. Examples ======== Example scripts in the scripts directory: * irccat A simple example of how to use the IRC client. irccat reads text from stdin and writes it to a specified user or channel on an IRC server. * irccat2 The same as above, but using the SimpleIRCClient class. * servermap Another simple example. servermap connects to an IRC server, finds out what other IRC servers there are in the net and prints a tree-like map of their interconnections. * testbot An example bot that uses the SingleServerIRCBot class from irc.bot. The bot enters a channel and listens for commands in private messages or channel traffic. It also accepts DCC invitations and echos back sent DCC chat messages. * dccreceive Receives a file over DCC. * dccsend Sends a file over DCC. NOTE: If you're running one of the examples on a unix command line, you need to escape the # symbol in the channel. For example, use \\#test or "#test" instead of #test. Decoding Input ============== By default, the IRC library does attempt to decode all incoming streams as UTF-8, but the author acknowledges that there are cases where decoding is undesirable or a custom decoding option is desirable. To support these cases, since irc 3.4.2, the ServerConnection class may be customized. The 'buffer_class' attribute on the ServerConnection determines what class is used for buffering lines from the input stream. By default it is DecodingLineBuffer, but may be re-assigned with another class, such as irc buffer.LineBuffer, which does not decode the lines and passes them through as byte strings. The 'buffer_class' attribute may be assigned for all instances of ServerConnection by overriding the class attribute:: irc.client.ServerConnection.buffer_class = irc.buffer.LineBuffer or it may be overridden on a per-instance basis (as long as it's overridden before the connection is established):: server = irc.client.IRC().server() server.buffer_class = irc.buffer.LineBuffer server.connect() Alternatively, some clients may still want to decode the input using a different encoding:: irc.client.ServerConnection.buffer_class.encoding = 'latin-1' or using a less strict decoder:: irc.client.ServerConnection.buffer_class.errors = 'replace' Notes and Contact Info ====================== Enjoy. Maintainer: Jason R. Coombs Original Author: Joel Rosdahl Changes ------- 8.5.3 ===== * Issue #28: Fix TypeError in version calculation in irc.bot CTCP version. 8.5.2 ===== * Updated DCC send and receive scripts (Issue #27). 8.5.1 ===== * Fix timestamp support in ``schedule.DelayedCommand`` construction. 8.5 === * ``irc.client.NickMask`` is now a Unicode object on Python 2. Fixes issue reported in pull request #19. * Issue #24: Added `DCCConnection.send_bytes` for transmitting binary data. `privmsg` remains to support transmitting text. 8.4 === * Code base now runs natively on Python 2 and Python 3, but requires `six `_ to be installed. * Issue #25: Rate-limiting has been updated to be finer grained (preventing bursts exceeding the limit following idle periods). 8.3.2 ===== * Issue #22: Catch error in bot.py on NAMREPLY when nick is not in any visible channel. 8.3.1 ===== * Fixed encoding errors in server on Python 3. 8.3 === * Added a ``set_keepalive`` method to the ServerConnection. Sends a periodic PING message every indicated interval. 8.2 === * Added support for throttling send_raw messages via the ServerConnection object. For example, on any connection object: connection.set_rate_limit(30) That would set the rate limit to 30 Hz (30 per second). Thanks to Jason Kendall for the suggestion and bug fixes. 8.1.2 ===== * Fix typo in `client.NickMask`. 8.1.1 ===== * Fix typo in bot.py. 8.1 === * Issue #15: Added client support for ISUPPORT directives on server connections. Now, each ServerConnection has a `features` attribute which reflects the features supported by the server. See the docs for `irc.features` for details about the implementation. 8.0.1 ===== * Issue #14: Fix errors when handlers of the same priority are added under Python 3. This also fixes the unintended behavior of allowing handlers of the same priority to compare as unequal. 8.0 === This release brings several backward-incompatible changes to the scheduled commands. * Refactored implementation of schedule classes. No longer do they override the datetime constructor, but now only provide suitable classmethods for construction in various forms. * Removed backward-compatible references from irc.client. * Remove 'arguments' parameter from scheduled commands. Clients that reference the schedule classes from irc.client or that construct them from the basic constructor will need to update to use the new class methods:: - DelayedCommand -> DelayedCommand.after - PeriodicCommand -> PeriodicCommand.after Arguments may no longer be passed to the 'function' callback, but one is encouraged instead to use functools.partial to attach parameters to the callback. For example:: DelayedCommand.after(3, func, ('a', 10)) becomes:: func = functools.partial(func, 'a', 10) DelayedCommand.after(3, func) This mode puts less constraints on the both the handler and the caller. For example, a caller can now pass keyword arguments instead:: func = functools.partial(func, name='a', quantity=10) DelayedCommand.after(3, func) Readability, maintainability, and usability go up. 7.1.2 ===== * Issue #13: TypeError on Python 3 when constructing PeriodicCommand (and thus execute_every). 7.1.1 ===== * Fixed regression created in 7.0 where PeriodicCommandFixedDelay would only cause the first command to be scheduled, but not subsequent ones. 7.1 === * Moved scheduled command classes to irc.schedule module. Kept references for backwards-compatibility. 7.0 === * PeriodicCommand now raises a ValueError if it's created with a negative or zero delay (meaning all subsequent commands are immediately due). This fixes #12. * Renamed the parameters to the IRC object. If you use a custom event loop and your code constructs the IRC object with keyword parameters, you will need to update your code to use the new names, so:: IRC(fn_to_add_socket=adder, fn_to_remove_socket=remover, fn_to_add_timeout=timeout) becomes:: IRC(on_connect=adder, on_disconnect=remover, on_schedule=timeout) If you don't use a custom event loop or you pass the parameters positionally, no change is necessary. 6.0.1 ===== * Fixed some unhandled exceptions in server client connections when the client would disconnect in response to messages sent after select was called. 6.0 === * Moved `LineBuffer` and `DecodingLineBuffer` from client to buffer module. Backward-compatible references have been kept for now. * Removed daemon mode and log-to-file options for server. * Miscellaneous bugfixes in server. 5.1.1 ===== * Fix error in 2to3 conversion on irc/server.py (issue #11). 5.1 === The IRC library is now licensed under the MIT license. * Added irc/server.py, based on hircd by Ferry Boender. * Added support for CAP command (pull request #10), thanks to Danneh Oaks. 5.0 === Another backward-incompatible change. In irc 5.0, many of the unnecessary getter functions have been removed and replaced with simple attributes. This change addresses issue #2. In particular: - Connection._get_socket() -> Connection.socket (including subclasses) - Event.eventtype() -> Event.type - Event.source() -> Event.source - Event.target() -> Event.target - Event.arguments() -> Event.arguments The `nm_to_*` functions were removed. Instead, use the NickMask class attributes. These deprecated function aliases were removed from irc.client:: - parse_nick_modes -> modes.parse_nick_modes - parse_channel_modes -> modes.parse_channel_modes - generated_events -> events.generated - protocol_events -> events.protocol - numeric_events -> events.numeric - all_events -> events.all - irc_lower -> strings.lower Also, the parameter name when constructing an event was renamed from `eventtype` to simply `type`. 4.0 === * Removed deprecated arguments to ServerConnection.connect. See notes on the 3.3 release on how to use the connect_factory parameter if your application requires ssl, ipv6, or other connection customization. 3.6.1 ===== * Filter out disconnected sockets when processing input. 3.6 === * Created two new exceptions in `irc.client`: `MessageTooLong` and `InvalidCharacters`. * Use explicit exceptions instead of ValueError when sending data. 3.5 === * SingleServerIRCBot now accepts keyword arguments which are passed through to the `ServerConnection.connect` method. One can use this to use SSL for connections:: factory = irc.connection.Factory(wrapper=ssl.wrap_socket) bot = irc.bot.SingleServerIRCBot(..., connect_factory = factory) 3.4.2 ===== * Issue #6: Fix AttributeError when legacy parameters are passed to `ServerConnection.connect`. * Issue #7: Fix TypeError on `iter(LineBuffer)`. 3.4.1 ===== 3.4 never worked - the decoding customization feature was improperly implemented and never tested. * The ServerConnection now allows custom classes to be supplied to customize the decoding of incoming lines. For example, to disable the decoding of incoming lines, replace the `buffer_class` on the ServerConnection with a version that passes through the lines directly:: irc.client.ServerConnection.buffer_class = irc.client.LineBuffer This fixes #5. 3.4 === *Broken Release* 3.3 === * Added `connection` module with a Factory for creating socket connections. * Added `connect_factory` parameter to the ServerConnection. It's now possible to create connections with custom SSL parameters or other socket wrappers. For example, to create a connection with a custom SSL cert:: import ssl import irc.client import irc.connection import functools irc = irc.client.IRC() server = irc.server() wrapper = functools.partial(ssl.wrap_socket, ssl_cert=my_cert()) server.connect(connect_factory = irc.connection.Factory(wrapper=wrapper)) With this release, many of the parameters to `ServerConnection.connect` are now deprecated: - localaddress - localport - ssl - ipv6 Instead, one should pass the appropriate values to a `connection.Factory` instance and pass that factory to the .connect method. Backwards-compatibility will be maintained for these parameters until the release of irc 4.0. 3.2.3 ===== * Restore Python 2.6 compatibility. 3.2.2 ===== * Protect from UnicodeDecodeError when decoding data on the wire when data is not properly encoded in ASCII or UTF-8. 3.2.1 ===== * Additional branch protected by mutex. 3.2 === * Implemented thread safety via a reentrant lock guarding shared state in IRC objects. 3.1.1 ===== * Fix some issues with bytes/unicode on Python 3 3.1 === * Distribute using setuptools rather than paver. * Minor tweaks for Python 3 support. Now installs on Python 3. 3.0.1 ===== * Added error checking when sending a message - for both message length and embedded carriage returns. Fixes #4. * Updated README. 3.0 === * Improved Unicode support. Fixes failing tests and errors lowering Unicode channel names. * Issue #3541414 - The ServerConnection and DCCConnection now encode any strings as UTF-8 before transmitting. * Issue #3527371 - Updated strings.FoldedCase to support comparison against objects of other types. * Shutdown the sockets before closing. Applications that are currently encoding unicode as UTF-8 before passing the strings to `ServerConnection.send_raw` need to be updated to send Unicode or ASCII. 2.0.4 ===== This release officially deprecates 2.0.1-2.0.3 in favor of 3.0. * Re-release of irc 2.0 (without the changes from 2.0.1-2.0.3) for correct compatibility indication. 2.0 === * DelayedCommands now use the local time for calculating 'at' and 'due' times. This will be more friendly for simple servers. Servers that expect UTC times should either run in UTC or override DelayedCommand.now to return an appropriate time object for 'now'. For example:: def startup_bot(): irc.client.DelayedCommand.now = irc.client.DelayedCommand.utcnow ... 1.1 === * Added irc.client.PeriodicCommandFixedDelay. Schedule this command to have a function executed at a specific time and then at periodic intervals thereafter. 1.0 === * Removed `irclib` and `ircbot` legacy modules. 0.9 === * Fix file saving using dccreceive.py on Windows. Fixes #2863199. * Created NickMask class from nm_to_* functions. Now if a source is a NickMask, one can access the .nick, .host, and .user attributes. * Use correct attribute for saved connect args. Fixes #3523057. 0.8 === * Added ServerConnection.reconnect method. Fixes #3515580. 0.7.1 ===== * Added missing events. Fixes #3515578. 0.7 === * Moved functionality from irclib module to irc.client module. * Moved functionality from ircbot module to irc.bot module. * Retained irclib and ircbot modules for backward-compatibility. These will be removed in 1.0. * Renamed project to simply 'irc'. To support the new module structure, simply replace references to the irclib module with irc.client and ircbot module with irc.bot. This project will support that interface through all versions of irc 1.x, so if you've made these changes, you can safely depend on `irc >= 0.7, <2.0dev`. 0.6.3 ===== * Fixed failing test where DelayedCommands weren't being sorted properly. DelayedCommand a now subclass of the DateTime object, where the command's due time is the datetime. Fixed issue #3518508. 0.6.2 ===== * Fixed incorrect usage of Connection.execute_delayed (again). 0.6.0 ===== * Minimum Python requirement is now Python 2.6. Python 2.3 and earlier should use 0.5.0 or earlier. * Removed incorrect usage of Connection.execute_delayed. Added Connection.execute_every. Fixed issue 3516241. * Use new-style classes. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 python-irc-8.5.3+dfsg/README.rst000066400000000000000000000132201302547020000162200ustar00rootroot00000000000000Internet Relay Chat (IRC) protocol client library ------------------------------------------------- The home of irclib is: https://bitbucket.org/jaraco/irc You can `download project releases from PyPI `_. Some legacy content is still available at the `foundational SourceForge site `_. Tests are `continuously run `_ using Travis-CI. |BuildStatus|_ .. |BuildStatus| image:: https://secure.travis-ci.org/jaraco/irc.png .. _BuildStatus: https://travis-ci.org/jaraco/irc This library is intended to encapsulate the IRC protocol at a quite low level. It provides an event-driven IRC client framework. It has a fairly thorough support for the basic IRC protocol, CTCP and DCC connections. In order to understand how to make an IRC client, I'm afraid you more or less must understand the IRC specifications. They are available here: http://www.irchelp.org/irchelp/rfc/ Installation ============ IRC requires Python 2.6 or newer (including Python 3). You have several options to install the IRC project. * Use "easy_install irc" or "pip install irc" to grab the latest version from the cheeseshop (recommended). * Run "python setup.py install" (from the source distribution) or * Run "paver install" (from repo checkout, requires paver) or * Copy irc directory to appropriate site-packages directory. Client Features =============== The main features of the IRC client framework are: * Abstraction of the IRC protocol. * Handles multiple simultaneous IRC server connections. * Handles server PONGing transparently. * Messages to the IRC server are done by calling methods on an IRC connection object. * Messages from an IRC server triggers events, which can be caught by event handlers. * Reading from and writing to IRC server sockets are normally done by an internal select() loop, but the select()ing may be done by an external main loop. * Functions can be registered to execute at specified times by the event-loop. * Decodes CTCP tagging correctly (hopefully); I haven't seen any other IRC client implementation that handles the CTCP specification subtilties. * A kind of simple, single-server, object-oriented IRC client class that dispatches events to instance methods is included. * DCC connection support. Current limitations: * The IRC protocol shines through the abstraction a bit too much. * Data is not written asynchronously to the server (and DCC peers), i.e. the write() may block if the TCP buffers are stuffed. * Like most projects, documentation is lacking... Unfortunately, this library isn't as well-documented as I would like it to be. I think the best way to get started is to read and understand the example program irccat, which is included in the distribution. The following files might be of interest: * irc/client.py The library itself. Read the code along with comments and docstrings to get a grip of what it does. Use it at your own risk and read the source, Luke! * irc/bot.py An IRC bot implementation. * irc/server.py A basic IRC server implementation. Suitable for testing, but not production quality. Examples ======== Example scripts in the scripts directory: * irccat A simple example of how to use the IRC client. irccat reads text from stdin and writes it to a specified user or channel on an IRC server. * irccat2 The same as above, but using the SimpleIRCClient class. * servermap Another simple example. servermap connects to an IRC server, finds out what other IRC servers there are in the net and prints a tree-like map of their interconnections. * testbot An example bot that uses the SingleServerIRCBot class from irc.bot. The bot enters a channel and listens for commands in private messages or channel traffic. It also accepts DCC invitations and echos back sent DCC chat messages. * dccreceive Receives a file over DCC. * dccsend Sends a file over DCC. NOTE: If you're running one of the examples on a unix command line, you need to escape the # symbol in the channel. For example, use \\#test or "#test" instead of #test. Decoding Input ============== By default, the IRC library does attempt to decode all incoming streams as UTF-8, but the author acknowledges that there are cases where decoding is undesirable or a custom decoding option is desirable. To support these cases, since irc 3.4.2, the ServerConnection class may be customized. The 'buffer_class' attribute on the ServerConnection determines what class is used for buffering lines from the input stream. By default it is DecodingLineBuffer, but may be re-assigned with another class, such as irc buffer.LineBuffer, which does not decode the lines and passes them through as byte strings. The 'buffer_class' attribute may be assigned for all instances of ServerConnection by overriding the class attribute:: irc.client.ServerConnection.buffer_class = irc.buffer.LineBuffer or it may be overridden on a per-instance basis (as long as it's overridden before the connection is established):: server = irc.client.IRC().server() server.buffer_class = irc.buffer.LineBuffer server.connect() Alternatively, some clients may still want to decode the input using a different encoding:: irc.client.ServerConnection.buffer_class.encoding = 'latin-1' or using a less strict decoder:: irc.client.ServerConnection.buffer_class.errors = 'replace' Notes and Contact Info ====================== Enjoy. Maintainer: Jason R. Coombs Original Author: Joel Rosdahl python-irc-8.5.3+dfsg/irc.egg-info/000077500000000000000000000000001302547020000170025ustar00rootroot00000000000000python-irc-8.5.3+dfsg/irc.egg-info/PKG-INFO000066400000000000000000000561641302547020000201130ustar00rootroot00000000000000Metadata-Version: 1.1 Name: irc Version: 8.5.3 Summary: IRC (Internet Relay Chat) protocol client library for Python Home-page: http://python-irclib.sourceforge.net Author: Jason R. Coombs Author-email: jaraco@jaraco.com License: MIT Description: Internet Relay Chat (IRC) protocol client library ------------------------------------------------- The home of irclib is: https://bitbucket.org/jaraco/irc You can `download project releases from PyPI `_. Some legacy content is still available at the `foundational SourceForge site `_. Tests are `continuously run `_ using Travis-CI. |BuildStatus|_ .. |BuildStatus| image:: https://secure.travis-ci.org/jaraco/irc.png .. _BuildStatus: https://travis-ci.org/jaraco/irc This library is intended to encapsulate the IRC protocol at a quite low level. It provides an event-driven IRC client framework. It has a fairly thorough support for the basic IRC protocol, CTCP and DCC connections. In order to understand how to make an IRC client, I'm afraid you more or less must understand the IRC specifications. They are available here: http://www.irchelp.org/irchelp/rfc/ Installation ============ IRC requires Python 2.6 or newer (including Python 3). You have several options to install the IRC project. * Use "easy_install irc" or "pip install irc" to grab the latest version from the cheeseshop (recommended). * Run "python setup.py install" (from the source distribution) or * Run "paver install" (from repo checkout, requires paver) or * Copy irc directory to appropriate site-packages directory. Client Features =============== The main features of the IRC client framework are: * Abstraction of the IRC protocol. * Handles multiple simultaneous IRC server connections. * Handles server PONGing transparently. * Messages to the IRC server are done by calling methods on an IRC connection object. * Messages from an IRC server triggers events, which can be caught by event handlers. * Reading from and writing to IRC server sockets are normally done by an internal select() loop, but the select()ing may be done by an external main loop. * Functions can be registered to execute at specified times by the event-loop. * Decodes CTCP tagging correctly (hopefully); I haven't seen any other IRC client implementation that handles the CTCP specification subtilties. * A kind of simple, single-server, object-oriented IRC client class that dispatches events to instance methods is included. * DCC connection support. Current limitations: * The IRC protocol shines through the abstraction a bit too much. * Data is not written asynchronously to the server (and DCC peers), i.e. the write() may block if the TCP buffers are stuffed. * Like most projects, documentation is lacking... Unfortunately, this library isn't as well-documented as I would like it to be. I think the best way to get started is to read and understand the example program irccat, which is included in the distribution. The following files might be of interest: * irc/client.py The library itself. Read the code along with comments and docstrings to get a grip of what it does. Use it at your own risk and read the source, Luke! * irc/bot.py An IRC bot implementation. * irc/server.py A basic IRC server implementation. Suitable for testing, but not production quality. Examples ======== Example scripts in the scripts directory: * irccat A simple example of how to use the IRC client. irccat reads text from stdin and writes it to a specified user or channel on an IRC server. * irccat2 The same as above, but using the SimpleIRCClient class. * servermap Another simple example. servermap connects to an IRC server, finds out what other IRC servers there are in the net and prints a tree-like map of their interconnections. * testbot An example bot that uses the SingleServerIRCBot class from irc.bot. The bot enters a channel and listens for commands in private messages or channel traffic. It also accepts DCC invitations and echos back sent DCC chat messages. * dccreceive Receives a file over DCC. * dccsend Sends a file over DCC. NOTE: If you're running one of the examples on a unix command line, you need to escape the # symbol in the channel. For example, use \\#test or "#test" instead of #test. Decoding Input ============== By default, the IRC library does attempt to decode all incoming streams as UTF-8, but the author acknowledges that there are cases where decoding is undesirable or a custom decoding option is desirable. To support these cases, since irc 3.4.2, the ServerConnection class may be customized. The 'buffer_class' attribute on the ServerConnection determines what class is used for buffering lines from the input stream. By default it is DecodingLineBuffer, but may be re-assigned with another class, such as irc buffer.LineBuffer, which does not decode the lines and passes them through as byte strings. The 'buffer_class' attribute may be assigned for all instances of ServerConnection by overriding the class attribute:: irc.client.ServerConnection.buffer_class = irc.buffer.LineBuffer or it may be overridden on a per-instance basis (as long as it's overridden before the connection is established):: server = irc.client.IRC().server() server.buffer_class = irc.buffer.LineBuffer server.connect() Alternatively, some clients may still want to decode the input using a different encoding:: irc.client.ServerConnection.buffer_class.encoding = 'latin-1' or using a less strict decoder:: irc.client.ServerConnection.buffer_class.errors = 'replace' Notes and Contact Info ====================== Enjoy. Maintainer: Jason R. Coombs Original Author: Joel Rosdahl Changes ------- 8.5.3 ===== * Issue #28: Fix TypeError in version calculation in irc.bot CTCP version. 8.5.2 ===== * Updated DCC send and receive scripts (Issue #27). 8.5.1 ===== * Fix timestamp support in ``schedule.DelayedCommand`` construction. 8.5 === * ``irc.client.NickMask`` is now a Unicode object on Python 2. Fixes issue reported in pull request #19. * Issue #24: Added `DCCConnection.send_bytes` for transmitting binary data. `privmsg` remains to support transmitting text. 8.4 === * Code base now runs natively on Python 2 and Python 3, but requires `six `_ to be installed. * Issue #25: Rate-limiting has been updated to be finer grained (preventing bursts exceeding the limit following idle periods). 8.3.2 ===== * Issue #22: Catch error in bot.py on NAMREPLY when nick is not in any visible channel. 8.3.1 ===== * Fixed encoding errors in server on Python 3. 8.3 === * Added a ``set_keepalive`` method to the ServerConnection. Sends a periodic PING message every indicated interval. 8.2 === * Added support for throttling send_raw messages via the ServerConnection object. For example, on any connection object: connection.set_rate_limit(30) That would set the rate limit to 30 Hz (30 per second). Thanks to Jason Kendall for the suggestion and bug fixes. 8.1.2 ===== * Fix typo in `client.NickMask`. 8.1.1 ===== * Fix typo in bot.py. 8.1 === * Issue #15: Added client support for ISUPPORT directives on server connections. Now, each ServerConnection has a `features` attribute which reflects the features supported by the server. See the docs for `irc.features` for details about the implementation. 8.0.1 ===== * Issue #14: Fix errors when handlers of the same priority are added under Python 3. This also fixes the unintended behavior of allowing handlers of the same priority to compare as unequal. 8.0 === This release brings several backward-incompatible changes to the scheduled commands. * Refactored implementation of schedule classes. No longer do they override the datetime constructor, but now only provide suitable classmethods for construction in various forms. * Removed backward-compatible references from irc.client. * Remove 'arguments' parameter from scheduled commands. Clients that reference the schedule classes from irc.client or that construct them from the basic constructor will need to update to use the new class methods:: - DelayedCommand -> DelayedCommand.after - PeriodicCommand -> PeriodicCommand.after Arguments may no longer be passed to the 'function' callback, but one is encouraged instead to use functools.partial to attach parameters to the callback. For example:: DelayedCommand.after(3, func, ('a', 10)) becomes:: func = functools.partial(func, 'a', 10) DelayedCommand.after(3, func) This mode puts less constraints on the both the handler and the caller. For example, a caller can now pass keyword arguments instead:: func = functools.partial(func, name='a', quantity=10) DelayedCommand.after(3, func) Readability, maintainability, and usability go up. 7.1.2 ===== * Issue #13: TypeError on Python 3 when constructing PeriodicCommand (and thus execute_every). 7.1.1 ===== * Fixed regression created in 7.0 where PeriodicCommandFixedDelay would only cause the first command to be scheduled, but not subsequent ones. 7.1 === * Moved scheduled command classes to irc.schedule module. Kept references for backwards-compatibility. 7.0 === * PeriodicCommand now raises a ValueError if it's created with a negative or zero delay (meaning all subsequent commands are immediately due). This fixes #12. * Renamed the parameters to the IRC object. If you use a custom event loop and your code constructs the IRC object with keyword parameters, you will need to update your code to use the new names, so:: IRC(fn_to_add_socket=adder, fn_to_remove_socket=remover, fn_to_add_timeout=timeout) becomes:: IRC(on_connect=adder, on_disconnect=remover, on_schedule=timeout) If you don't use a custom event loop or you pass the parameters positionally, no change is necessary. 6.0.1 ===== * Fixed some unhandled exceptions in server client connections when the client would disconnect in response to messages sent after select was called. 6.0 === * Moved `LineBuffer` and `DecodingLineBuffer` from client to buffer module. Backward-compatible references have been kept for now. * Removed daemon mode and log-to-file options for server. * Miscellaneous bugfixes in server. 5.1.1 ===== * Fix error in 2to3 conversion on irc/server.py (issue #11). 5.1 === The IRC library is now licensed under the MIT license. * Added irc/server.py, based on hircd by Ferry Boender. * Added support for CAP command (pull request #10), thanks to Danneh Oaks. 5.0 === Another backward-incompatible change. In irc 5.0, many of the unnecessary getter functions have been removed and replaced with simple attributes. This change addresses issue #2. In particular: - Connection._get_socket() -> Connection.socket (including subclasses) - Event.eventtype() -> Event.type - Event.source() -> Event.source - Event.target() -> Event.target - Event.arguments() -> Event.arguments The `nm_to_*` functions were removed. Instead, use the NickMask class attributes. These deprecated function aliases were removed from irc.client:: - parse_nick_modes -> modes.parse_nick_modes - parse_channel_modes -> modes.parse_channel_modes - generated_events -> events.generated - protocol_events -> events.protocol - numeric_events -> events.numeric - all_events -> events.all - irc_lower -> strings.lower Also, the parameter name when constructing an event was renamed from `eventtype` to simply `type`. 4.0 === * Removed deprecated arguments to ServerConnection.connect. See notes on the 3.3 release on how to use the connect_factory parameter if your application requires ssl, ipv6, or other connection customization. 3.6.1 ===== * Filter out disconnected sockets when processing input. 3.6 === * Created two new exceptions in `irc.client`: `MessageTooLong` and `InvalidCharacters`. * Use explicit exceptions instead of ValueError when sending data. 3.5 === * SingleServerIRCBot now accepts keyword arguments which are passed through to the `ServerConnection.connect` method. One can use this to use SSL for connections:: factory = irc.connection.Factory(wrapper=ssl.wrap_socket) bot = irc.bot.SingleServerIRCBot(..., connect_factory = factory) 3.4.2 ===== * Issue #6: Fix AttributeError when legacy parameters are passed to `ServerConnection.connect`. * Issue #7: Fix TypeError on `iter(LineBuffer)`. 3.4.1 ===== 3.4 never worked - the decoding customization feature was improperly implemented and never tested. * The ServerConnection now allows custom classes to be supplied to customize the decoding of incoming lines. For example, to disable the decoding of incoming lines, replace the `buffer_class` on the ServerConnection with a version that passes through the lines directly:: irc.client.ServerConnection.buffer_class = irc.client.LineBuffer This fixes #5. 3.4 === *Broken Release* 3.3 === * Added `connection` module with a Factory for creating socket connections. * Added `connect_factory` parameter to the ServerConnection. It's now possible to create connections with custom SSL parameters or other socket wrappers. For example, to create a connection with a custom SSL cert:: import ssl import irc.client import irc.connection import functools irc = irc.client.IRC() server = irc.server() wrapper = functools.partial(ssl.wrap_socket, ssl_cert=my_cert()) server.connect(connect_factory = irc.connection.Factory(wrapper=wrapper)) With this release, many of the parameters to `ServerConnection.connect` are now deprecated: - localaddress - localport - ssl - ipv6 Instead, one should pass the appropriate values to a `connection.Factory` instance and pass that factory to the .connect method. Backwards-compatibility will be maintained for these parameters until the release of irc 4.0. 3.2.3 ===== * Restore Python 2.6 compatibility. 3.2.2 ===== * Protect from UnicodeDecodeError when decoding data on the wire when data is not properly encoded in ASCII or UTF-8. 3.2.1 ===== * Additional branch protected by mutex. 3.2 === * Implemented thread safety via a reentrant lock guarding shared state in IRC objects. 3.1.1 ===== * Fix some issues with bytes/unicode on Python 3 3.1 === * Distribute using setuptools rather than paver. * Minor tweaks for Python 3 support. Now installs on Python 3. 3.0.1 ===== * Added error checking when sending a message - for both message length and embedded carriage returns. Fixes #4. * Updated README. 3.0 === * Improved Unicode support. Fixes failing tests and errors lowering Unicode channel names. * Issue #3541414 - The ServerConnection and DCCConnection now encode any strings as UTF-8 before transmitting. * Issue #3527371 - Updated strings.FoldedCase to support comparison against objects of other types. * Shutdown the sockets before closing. Applications that are currently encoding unicode as UTF-8 before passing the strings to `ServerConnection.send_raw` need to be updated to send Unicode or ASCII. 2.0.4 ===== This release officially deprecates 2.0.1-2.0.3 in favor of 3.0. * Re-release of irc 2.0 (without the changes from 2.0.1-2.0.3) for correct compatibility indication. 2.0 === * DelayedCommands now use the local time for calculating 'at' and 'due' times. This will be more friendly for simple servers. Servers that expect UTC times should either run in UTC or override DelayedCommand.now to return an appropriate time object for 'now'. For example:: def startup_bot(): irc.client.DelayedCommand.now = irc.client.DelayedCommand.utcnow ... 1.1 === * Added irc.client.PeriodicCommandFixedDelay. Schedule this command to have a function executed at a specific time and then at periodic intervals thereafter. 1.0 === * Removed `irclib` and `ircbot` legacy modules. 0.9 === * Fix file saving using dccreceive.py on Windows. Fixes #2863199. * Created NickMask class from nm_to_* functions. Now if a source is a NickMask, one can access the .nick, .host, and .user attributes. * Use correct attribute for saved connect args. Fixes #3523057. 0.8 === * Added ServerConnection.reconnect method. Fixes #3515580. 0.7.1 ===== * Added missing events. Fixes #3515578. 0.7 === * Moved functionality from irclib module to irc.client module. * Moved functionality from ircbot module to irc.bot module. * Retained irclib and ircbot modules for backward-compatibility. These will be removed in 1.0. * Renamed project to simply 'irc'. To support the new module structure, simply replace references to the irclib module with irc.client and ircbot module with irc.bot. This project will support that interface through all versions of irc 1.x, so if you've made these changes, you can safely depend on `irc >= 0.7, <2.0dev`. 0.6.3 ===== * Fixed failing test where DelayedCommands weren't being sorted properly. DelayedCommand a now subclass of the DateTime object, where the command's due time is the datetime. Fixed issue #3518508. 0.6.2 ===== * Fixed incorrect usage of Connection.execute_delayed (again). 0.6.0 ===== * Minimum Python requirement is now Python 2.6. Python 2.3 and earlier should use 0.5.0 or earlier. * Removed incorrect usage of Connection.execute_delayed. Added Connection.execute_every. Fixed issue 3516241. * Use new-style classes. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 python-irc-8.5.3+dfsg/irc.egg-info/SOURCES.txt000066400000000000000000000013351302547020000206700ustar00rootroot00000000000000.cvsignore .hgignore .hgtags .travis.yml CHANGES.rst COPYING LICENSE MANIFEST.in README.rst pavement.py setup.cfg setup.py irc/__init__.py irc/bot.py irc/buffer.py irc/client.py irc/connection.py irc/dict.py irc/events.py irc/features.py irc/functools.py irc/logging.py irc/modes.py irc/rfc.py irc/rfc2812.txt irc/schedule.py irc/server.py irc/strings.py irc/util.py irc.egg-info/PKG-INFO irc.egg-info/SOURCES.txt irc.egg-info/dependency_links.txt irc.egg-info/requires.txt irc.egg-info/top_level.txt irc/tests/__init__.py irc/tests/test_bot.py irc/tests/test_client.py irc/tests/test_schedule.py scripts/dccreceive.py scripts/dccsend.py scripts/irccat.py scripts/irccat2.py scripts/servermap.py scripts/ssl-cat.py scripts/testbot.pypython-irc-8.5.3+dfsg/irc.egg-info/dependency_links.txt000066400000000000000000000000011302547020000230500ustar00rootroot00000000000000 python-irc-8.5.3+dfsg/irc.egg-info/requires.txt000066400000000000000000000000031302547020000213730ustar00rootroot00000000000000sixpython-irc-8.5.3+dfsg/irc.egg-info/top_level.txt000066400000000000000000000000041302547020000215260ustar00rootroot00000000000000irc python-irc-8.5.3+dfsg/irc/000077500000000000000000000000001302547020000153105ustar00rootroot00000000000000python-irc-8.5.3+dfsg/irc/__init__.py000066400000000000000000000000001302547020000174070ustar00rootroot00000000000000python-irc-8.5.3+dfsg/irc/bot.py000066400000000000000000000277041302547020000164600ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 1999-2002 Joel Rosdahl # Portions Copyright © 2011-2012 Jason R. Coombs """ Simple IRC bot library. This module contains a single-server IRC bot class that can be used to write simpler bots. """ from __future__ import absolute_import import sys import irc.client import irc.modes from .dict import IRCDict class ServerSpec(object): """ An IRC server specification. >>> spec = ServerSpec('localhost') >>> spec.host 'localhost' >>> spec.port 6667 >>> spec.password >>> spec = ServerSpec('127.0.0.1', 6697, 'fooP455') >>> spec.password 'fooP455' """ def __init__(self, host, port=6667, password=None): self.host = host self.port = port self.password = password class SingleServerIRCBot(irc.client.SimpleIRCClient): """A single-server IRC bot class. The bot tries to reconnect if it is disconnected. The bot keeps track of the channels it has joined, the other clients that are present in the channels and which of those that have operator or voice modes. The "database" is kept in the self.channels attribute, which is an IRCDict of Channels. """ def __init__(self, server_list, nickname, realname, reconnection_interval=60, **connect_params): """Constructor for SingleServerIRCBot objects. Arguments: server_list -- A list of ServerSpec objects or tuples of parameters suitable for constructing ServerSpec objects. Defines the list of servers the bot will use (in order). nickname -- The bot's nickname. realname -- The bot's realname. reconnection_interval -- How long the bot should wait before trying to reconnect. dcc_connections -- A list of initiated/accepted DCC connections. **connect_params -- parameters to pass through to the connect method. """ super(SingleServerIRCBot, self).__init__() self.__connect_params = connect_params self.channels = IRCDict() self.server_list = [ ServerSpec(*server) if isinstance(server, (tuple, list)) else server for server in server_list ] assert all( isinstance(server, ServerSpec) for server in self.server_list ) if not reconnection_interval or reconnection_interval < 0: reconnection_interval = 2 ** 31 self.reconnection_interval = reconnection_interval self._nickname = nickname self._realname = realname for i in ["disconnect", "join", "kick", "mode", "namreply", "nick", "part", "quit"]: self.connection.add_global_handler(i, getattr(self, "_on_" + i), -20) def _connected_checker(self): """[Internal]""" if not self.connection.is_connected(): self.connection.execute_delayed(self.reconnection_interval, self._connected_checker) self.jump_server() def _connect(self): """ Establish a connection to the server at the front of the server_list. """ server = self.server_list[0] try: self.connect(server.host, server.port, self._nickname, server.password, ircname=self._realname, **self.__connect_params) except irc.client.ServerConnectionError: pass def _on_disconnect(self, c, e): self.channels = IRCDict() self.connection.execute_delayed(self.reconnection_interval, self._connected_checker) def _on_join(self, c, e): ch = e.target nick = e.source.nick if nick == c.get_nickname(): self.channels[ch] = Channel() self.channels[ch].add_user(nick) def _on_kick(self, c, e): nick = e.arguments[0] channel = e.target if nick == c.get_nickname(): del self.channels[channel] else: self.channels[channel].remove_user(nick) def _on_mode(self, c, e): modes = irc.modes.parse_channel_modes(" ".join(e.arguments)) t = e.target if irc.client.is_channel(t): ch = self.channels[t] for mode in modes: if mode[0] == "+": f = ch.set_mode else: f = ch.clear_mode f(mode[1], mode[2]) else: # Mode on self... XXX pass def _on_namreply(self, c, e): # e.arguments[0] == "@" for secret channels, # "*" for private channels, # "=" for others (public channels) # e.arguments[1] == channel # e.arguments[2] == nick list ch_type, channel, nick_list = e.arguments if channel == '*': # User is not in any visible channel # http://tools.ietf.org/html/rfc2812#section-3.2.5 return for nick in nick_list.split(): nick_modes = [] if nick[0] in self.connection.features.prefix: nick_modes.append(self.connection.features.prefix[nick[0]]) nick = nick[1:] for mode in nick_modes: self.channels[channel].set_mode(mode, nick) self.channels[channel].add_user(nick) def _on_nick(self, c, e): before = e.source.nick after = e.target for ch in self.channels.values(): if ch.has_user(before): ch.change_nick(before, after) def _on_part(self, c, e): nick = e.source.nick channel = e.target if nick == c.get_nickname(): del self.channels[channel] else: self.channels[channel].remove_user(nick) def _on_quit(self, c, e): nick = e.source.nick for ch in self.channels.values(): if ch.has_user(nick): ch.remove_user(nick) def die(self, msg="Bye, cruel world!"): """Let the bot die. Arguments: msg -- Quit message. """ self.connection.disconnect(msg) sys.exit(0) def disconnect(self, msg="I'll be back!"): """Disconnect the bot. The bot will try to reconnect after a while. Arguments: msg -- Quit message. """ self.connection.disconnect(msg) def get_version(self): """Returns the bot version. Used when answering a CTCP VERSION request. """ return "Python irc.bot ({version})".format( version=irc.client.VERSION_STRING) def jump_server(self, msg="Changing servers"): """Connect to a new server, possibly disconnecting from the current. The bot will skip to next server in the server_list each time jump_server is called. """ if self.connection.is_connected(): self.connection.disconnect(msg) self.server_list.append(self.server_list.pop(0)) self._connect() def on_ctcp(self, c, e): """Default handler for ctcp events. Replies to VERSION and PING requests and relays DCC requests to the on_dccchat method. """ nick = e.source.nick if e.arguments[0] == "VERSION": c.ctcp_reply(nick, "VERSION " + self.get_version()) elif e.arguments[0] == "PING": if len(e.arguments) > 1: c.ctcp_reply(nick, "PING " + e.arguments[1]) elif e.arguments[0] == "DCC" and e.arguments[1].split(" ", 1)[0] == "CHAT": self.on_dccchat(c, e) def on_dccchat(self, c, e): pass def start(self): """Start the bot.""" self._connect() super(SingleServerIRCBot, self).start() class Channel(object): """A class for keeping information about an IRC channel. This class can be improved a lot. """ def __init__(self): self.userdict = IRCDict() self.operdict = IRCDict() self.voiceddict = IRCDict() self.ownerdict = IRCDict() self.halfopdict = IRCDict() self.modes = {} def users(self): """Returns an unsorted list of the channel's users.""" return self.userdict.keys() def opers(self): """Returns an unsorted list of the channel's operators.""" return self.operdict.keys() def voiced(self): """Returns an unsorted list of the persons that have voice mode set in the channel.""" return self.voiceddict.keys() def owners(self): """Returns an unsorted list of the channel's owners.""" return self.ownerdict.keys() def halfops(self): """Returns an unsorted list of the channel's half-operators.""" return self.halfopdict.keys() def has_user(self, nick): """Check whether the channel has a user.""" return nick in self.userdict def is_oper(self, nick): """Check whether a user has operator status in the channel.""" return nick in self.operdict def is_voiced(self, nick): """Check whether a user has voice mode set in the channel.""" return nick in self.voiceddict def is_owner(self, nick): """Check whether a user has owner status in the channel.""" return nick in self.ownerdict def is_halfop(self, nick): """Check whether a user has half-operator status in the channel.""" return nick in self.halfopdict def add_user(self, nick): self.userdict[nick] = 1 def remove_user(self, nick): for d in self.userdict, self.operdict, self.voiceddict: if nick in d: del d[nick] def change_nick(self, before, after): self.userdict[after] = self.userdict.pop(before) if before in self.operdict: self.operdict[after] = self.operdict.pop(before) if before in self.voiceddict: self.voiceddict[after] = self.voiceddict.pop(before) def set_userdetails(self, nick, details): if nick in self.userdict: self.userdict[nick] = details def set_mode(self, mode, value=None): """Set mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ if mode == "o": self.operdict[value] = 1 elif mode == "v": self.voiceddict[value] = 1 elif mode == "q": self.ownerdict[value] = 1 elif mode == "h": self.halfopdict[value] = 1 else: self.modes[mode] = value def clear_mode(self, mode, value=None): """Clear mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ try: if mode == "o": del self.operdict[value] elif mode == "v": del self.voiceddict[value] elif mode == "q": del self.ownerdict[value] elif mode == "h": del self.halfopdict[value] else: del self.modes[mode] except KeyError: pass def has_mode(self, mode): return mode in self.modes def is_moderated(self): return self.has_mode("m") def is_secret(self): return self.has_mode("s") def is_protected(self): return self.has_mode("p") def has_topic_lock(self): return self.has_mode("t") def is_invite_only(self): return self.has_mode("i") def has_allow_external_messages(self): return self.has_mode("n") def has_limit(self): return self.has_mode("l") def limit(self): if self.has_limit(): return self.modes["l"] else: return None def has_key(self): return self.has_mode("k") python-irc-8.5.3+dfsg/irc/buffer.py000066400000000000000000000040041302547020000171310ustar00rootroot00000000000000from __future__ import unicode_literals import re class LineBuffer(object): r""" Buffer bytes read in from a connection and serve complete lines back. >>> b = LineBuffer() >>> len(b) 0 >>> b.feed(b'foo\nbar') >>> len(b) 7 >>> list(b.lines()) == [b'foo'] True >>> len(b) 3 >>> b.feed(b'bar\r\nbaz\n') >>> list(b.lines()) == [b'barbar', b'baz'] True >>> len(b) 0 The buffer will not perform any decoding. >>> b.feed(b'Ol\xe9\n') >>> list(b.lines()) == [b'Ol\xe9'] True The LineBuffer should also act as an iterable. >>> b.feed(b'iterate\nthis\n') >>> for line, expected in zip(b, [b'iterate', b'this']): ... assert line == expected """ line_sep_exp = re.compile(b'\r?\n') def __init__(self): self.buffer = b'' def feed(self, bytes): self.buffer += bytes def lines(self): lines = self.line_sep_exp.split(self.buffer) # save the last, unfinished, possibly empty line self.buffer = lines.pop() return iter(lines) def __iter__(self): return self.lines() def __len__(self): return len(self.buffer) class DecodingLineBuffer(LineBuffer): r""" Like LineBuffer, but decode the output (default assumes UTF-8). >>> utf8_word = b'Ol\xc3\xa9' >>> b = DecodingLineBuffer() >>> b.feed(b'bar\r\nbaz\n' + utf8_word + b'\n') >>> list(b.lines()) == ['bar', 'baz', utf8_word.decode('utf-8')] True >>> len(b) 0 Some clients will feed latin-1 or other encodings. If your client should support docoding from these clients (and not raise a UnicodeDecodeError), set errors='replace': >>> rb = DecodingLineBuffer() >>> b.errors = 'replace' >>> b.feed(b'Ol\xe9\n') >>> list(b.lines()) == ['Ol\ufffd'] True """ encoding = 'utf-8' errors = 'strict' def lines(self): return (line.decode(self.encoding, self.errors) for line in super(DecodingLineBuffer, self).lines()) python-irc-8.5.3+dfsg/irc/client.py000066400000000000000000001315031302547020000171430ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 1999-2002 Joel Rosdahl # Copyright © 2011-2013 Jason R. Coombs """ Internet Relay Chat (IRC) protocol client library. This library is intended to encapsulate the IRC protocol at a quite low level. It provides an event-driven IRC client framework. It has a fairly thorough support for the basic IRC protocol, CTCP, DCC chat, but DCC file transfers is not yet supported. In order to understand how to make an IRC client, I'm afraid you more or less must understand the IRC specifications. They are available here: [IRC specifications]. The main features of the IRC client framework are: * Abstraction of the IRC protocol. * Handles multiple simultaneous IRC server connections. * Handles server PONGing transparently. * Messages to the IRC server are done by calling methods on an IRC connection object. * Messages from an IRC server triggers events, which can be caught by event handlers. * Reading from and writing to IRC server sockets are normally done by an internal select() loop, but the select()ing may be done by an external main loop. * Functions can be registered to execute at specified times by the event-loop. * Decodes CTCP tagging correctly (hopefully); I haven't seen any other IRC client implementation that handles the CTCP specification subtilties. * A kind of simple, single-server, object-oriented IRC client class that dispatches events to instance methods is included. Current limitations: * The IRC protocol shines through the abstraction a bit too much. * Data is not written asynchronously to the server, i.e. the write() may block if the TCP buffers are stuffed. * There are no support for DCC file transfers. * The author haven't even read RFC 2810, 2811, 2812 and 2813. * Like most projects, documentation is lacking... .. [IRC specifications] http://www.irchelp.org/irchelp/rfc/ """ from __future__ import absolute_import, division import bisect import re import select import socket import string import time import struct import logging import threading import abc import collections import functools import itertools import six try: import pkg_resources except ImportError: pass from . import connection from . import events from . import functools as irc_functools from . import strings from . import util from . import buffer from . import schedule from . import features log = logging.getLogger(__name__) # set the version tuple try: VERSION_STRING = pkg_resources.require('irc')[0].version VERSION = tuple(int(res) for res in re.findall('\d+', VERSION_STRING)) except Exception: VERSION_STRING = 'unknown' VERSION = () # TODO # ---- # (maybe) color parser convenience functions # documentation (including all event types) # (maybe) add awareness of different types of ircds # send data asynchronously to the server (and DCC connections) # (maybe) automatically close unused, passive DCC connections after a while # NOTES # ----- # connection.quit() only sends QUIT to the server. # ERROR from the server triggers the error event and the disconnect event. # dropping of the connection triggers the disconnect event. class IRCError(Exception): "An IRC exception" class InvalidCharacters(ValueError): "Invalid characters were encountered in the message" class MessageTooLong(ValueError): "Message is too long" class PrioritizedHandler( collections.namedtuple('Base', ('priority', 'callback'))): def __lt__(self, other): "when sorting prioritized handlers, only use the priority" return self.priority < other.priority class IRC(object): """Class that handles one or several IRC server connections. When an IRC object has been instantiated, it can be used to create Connection objects that represent the IRC connections. The responsibility of the IRC object is to provide an event-driven framework for the connections and to keep the connections alive. It runs a select loop to poll each connection's TCP socket and hands over the sockets with incoming data for processing by the corresponding connection. The methods of most interest for an IRC client writer are server, add_global_handler, remove_global_handler, execute_at, execute_delayed, execute_every, process_once, and process_forever. Here is an example: client = irc.client.IRC() server = client.server() server.connect("irc.some.where", 6667, "my_nickname") server.privmsg("a_nickname", "Hi there!") client.process_forever() This will connect to the IRC server irc.some.where on port 6667 using the nickname my_nickname and send the message "Hi there!" to the nickname a_nickname. The methods of this class are thread-safe; accesses to and modifications of its internal lists of connections, handlers, and delayed commands are guarded by a mutex. """ def __do_nothing(*args, **kwargs): pass def __init__(self, on_connect=__do_nothing, on_disconnect=__do_nothing, on_schedule=__do_nothing): """Constructor for IRC objects. on_connect: optional callback invoked when a new connection is made. on_disconnect: optional callback invoked when a socket is disconnected. on_schedule: optional callback, usually supplied by an external event loop, to indicate in float seconds that the client needs to process events that many seconds in the future. An external event loop will implement this callback to schedule a call to process_timeout. The three arguments mainly exist to be able to use an external main loop (for example Tkinter's or PyGTK's main app loop) instead of calling the process_forever method. An alternative is to just call ServerConnection.process_once() once in a while. """ self._on_connect = on_connect self._on_disconnect = on_disconnect self._on_schedule = on_schedule self.connections = [] self.handlers = {} self.delayed_commands = [] # list of DelayedCommands # Modifications to these shared lists and dict need to be thread-safe self.mutex = threading.RLock() self.add_global_handler("ping", _ping_ponger, -42) def server(self): """Creates and returns a ServerConnection object.""" c = ServerConnection(self) with self.mutex: self.connections.append(c) return c def process_data(self, sockets): """Called when there is more data to read on connection sockets. Arguments: sockets -- A list of socket objects. See documentation for IRC.__init__. """ with self.mutex: log.log(logging.DEBUG-2, "process_data()") for s, c in itertools.product(sockets, self.connections): if s == c.socket: c.process_data() def process_timeout(self): """Called when a timeout notification is due. See documentation for IRC.__init__. """ with self.mutex: while self.delayed_commands: command = self.delayed_commands[0] if not command.due(): break command.function() if isinstance(command, schedule.PeriodicCommand): self._schedule_command(command.next()) del self.delayed_commands[0] def process_once(self, timeout=0): """Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are any. If that seems boring, look at the process_forever method. """ with self.mutex: log.log(logging.DEBUG-2, "process_once()") sockets = [x.socket for x in self.connections if x is not None] sockets = [x for x in sockets if x is not None] if sockets: (i, o, e) = select.select(sockets, [], [], timeout) self.process_data(i) else: time.sleep(timeout) self.process_timeout() def process_forever(self, timeout=0.2): """Run an infinite loop, processing data from connections. This method repeatedly calls process_once. Arguments: timeout -- Parameter to pass to process_once. """ # This loop should specifically *not* be mutex-locked. # Otherwise no other thread would ever be able to change # the shared state of an IRC object running this function. log.debug("process_forever(timeout=%s)", timeout) while 1: self.process_once(timeout) def disconnect_all(self, message=""): """Disconnects all connections.""" with self.mutex: for c in self.connections: c.disconnect(message) def add_global_handler(self, event, handler, priority=0): """Adds a global handler function for a specific event type. Arguments: event -- Event type (a string). Check the values of numeric_events for possible event types. handler -- Callback function taking 'connection' and 'event' parameters. priority -- A number (the lower number, the higher priority). The handler function is called whenever the specified event is triggered in any of the connections. See documentation for the Event class. The handler functions are called in priority order (lowest number is highest priority). If a handler function returns "NO MORE", no more handlers will be called. """ handler = PrioritizedHandler(priority, handler) with self.mutex: event_handlers = self.handlers.setdefault(event, []) bisect.insort(event_handlers, handler) def remove_global_handler(self, event, handler): """Removes a global handler function. Arguments: event -- Event type (a string). handler -- Callback function. Returns 1 on success, otherwise 0. """ with self.mutex: if not event in self.handlers: return 0 for h in self.handlers[event]: if handler == h.callback: self.handlers[event].remove(h) return 1 def execute_at(self, at, function, arguments=()): """Execute a function at a specified time. Arguments: at -- Execute at this time (standard "time_t" time). function -- Function to call. arguments -- Arguments to give the function. """ function = functools.partial(function, *arguments) command = schedule.DelayedCommand.at_time(at, function) self._schedule_command(command) def execute_delayed(self, delay, function, arguments=()): """ Execute a function after a specified time. delay -- How many seconds to wait. function -- Function to call. arguments -- Arguments to give the function. """ function = functools.partial(function, *arguments) command = schedule.DelayedCommand.after(delay, function) self._schedule_command(command) def execute_every(self, period, function, arguments=()): """ Execute a function every 'period' seconds. period -- How often to run (always waits this long for first). function -- Function to call. arguments -- Arguments to give the function. """ function = functools.partial(function, *arguments) command = schedule.PeriodicCommand.after(period, function) self._schedule_command(command) def _schedule_command(self, command): with self.mutex: bisect.insort(self.delayed_commands, command) self._on_schedule(util.total_seconds(command.delay)) def dcc(self, dcctype="chat"): """Creates and returns a DCCConnection object. Arguments: dcctype -- "chat" for DCC CHAT connections or "raw" for DCC SEND (or other DCC types). If "chat", incoming data will be split in newline-separated chunks. If "raw", incoming data is not touched. """ with self.mutex: c = DCCConnection(self, dcctype) self.connections.append(c) return c def _handle_event(self, connection, event): """ Handle an Event event incoming on ServerConnection connection. """ with self.mutex: h = self.handlers matching_handlers = sorted( h.get("all_events", []) + h.get(event.type, []) ) for handler in matching_handlers: result = handler.callback(connection, event) if result == "NO MORE": return def _remove_connection(self, connection): """[Internal]""" with self.mutex: self.connections.remove(connection) self._on_disconnect(connection.socket) _rfc_1459_command_regexp = re.compile("^(:(?P[^ ]+) +)?(?P[^ ]+)( *(?P .+))?") class Connection(object): """ Base class for IRC connections. """ __metaclass__ = abc.ABCMeta @abc.abstractproperty def socket(self): "The socket for this connection" def __init__(self, irclibobj): self.irclibobj = irclibobj ############################## ### Convenience wrappers. def execute_at(self, at, function, arguments=()): self.irclibobj.execute_at(at, function, arguments) def execute_delayed(self, delay, function, arguments=()): self.irclibobj.execute_delayed(delay, function, arguments) def execute_every(self, period, function, arguments=()): self.irclibobj.execute_every(period, function, arguments) class ServerConnectionError(IRCError): pass class ServerNotConnectedError(ServerConnectionError): pass class ServerConnection(Connection): """ An IRC server connection. ServerConnection objects are instantiated by calling the server method on an IRC object. """ buffer_class = buffer.DecodingLineBuffer socket = None def __init__(self, irclibobj): super(ServerConnection, self).__init__(irclibobj) self.connected = False self.features = features.FeatureSet() # save the method args to allow for easier reconnection. @irc_functools.save_method_args def connect(self, server, port, nickname, password=None, username=None, ircname=None, connect_factory=connection.Factory()): """Connect/reconnect to a server. Arguments: server -- Server name. port -- Port number. nickname -- The nickname. password -- Password (if any). username -- The username. ircname -- The IRC name ("realname"). server_address -- The remote host/port of the server. connect_factory -- A callable that takes the server address and returns a connection (with a socket interface). This function can be called to reconnect a closed connection. Returns the ServerConnection object. """ log.debug("connect(server=%r, port=%r, nickname=%r, ...)", server, port, nickname) if self.connected: self.disconnect("Changing servers") self.buffer = self.buffer_class() self.handlers = {} self.real_server_name = "" self.real_nickname = nickname self.server = server self.port = port self.server_address = (server, port) self.nickname = nickname self.username = username or nickname self.ircname = ircname or nickname self.password = password self.connect_factory = connect_factory try: self.socket = self.connect_factory(self.server_address) except socket.error as err: raise ServerConnectionError("Couldn't connect to socket: %s" % err) self.connected = True self.irclibobj._on_connect(self.socket) # Log on... if self.password: self.pass_(self.password) self.nick(self.nickname) self.user(self.username, self.ircname) return self def reconnect(self): """ Reconnect with the last arguments passed to self.connect() """ self.connect(*self._saved_connect.args, **self._saved_connect.kwargs) def close(self): """Close the connection. This method closes the connection permanently; after it has been called, the object is unusable. """ # Without this thread lock, there is a window during which # select() can find a closed socket, leading to an EBADF error. with self.irclibobj.mutex: self.disconnect("Closing object") self.irclibobj._remove_connection(self) def get_server_name(self): """Get the (real) server name. This method returns the (real) server name, or, more specifically, what the server calls itself. """ if self.real_server_name: return self.real_server_name else: return "" def get_nickname(self): """Get the (real) nick name. This method returns the (real) nickname. The library keeps track of nick changes, so it might not be the nick name that was passed to the connect() method. """ return self.real_nickname def process_data(self): "read and process input from self.socket" try: reader = getattr(self.socket, 'read', self.socket.recv) new_data = reader(2 ** 14) except socket.error: # The server hung up. self.disconnect("Connection reset by peer") return if not new_data: # Read nothing: connection must be down. self.disconnect("Connection reset by peer") return self.buffer.feed(new_data) for line in self.buffer: log.debug("FROM SERVER: %s", line) if not line: continue prefix = None command = None arguments = None self._handle_event(Event("all_raw_messages", self.get_server_name(), None, [line])) m = _rfc_1459_command_regexp.match(line) if m.group("prefix"): prefix = m.group("prefix") if not self.real_server_name: self.real_server_name = prefix if m.group("command"): command = m.group("command").lower() if m.group("argument"): a = m.group("argument").split(" :", 1) arguments = a[0].split() if len(a) == 2: arguments.append(a[1]) # Translate numerics into more readable strings. command = events.numeric.get(command, command) if command == "nick": if NickMask(prefix).nick == self.real_nickname: self.real_nickname = arguments[0] elif command == "welcome": # Record the nickname in case the client changed nick # in a nicknameinuse callback. self.real_nickname = arguments[0] elif command == "featurelist": self.features.load(arguments) if command in ["privmsg", "notice"]: target, message = arguments[0], arguments[1] messages = _ctcp_dequote(message) if command == "privmsg": if is_channel(target): command = "pubmsg" else: if is_channel(target): command = "pubnotice" else: command = "privnotice" for m in messages: if isinstance(m, tuple): if command in ["privmsg", "pubmsg"]: command = "ctcp" else: command = "ctcpreply" m = list(m) log.debug("command: %s, source: %s, target: %s, " "arguments: %s", command, prefix, target, m) self._handle_event(Event(command, NickMask(prefix), target, m)) if command == "ctcp" and m[0] == "ACTION": self._handle_event(Event("action", prefix, target, m[1:])) else: log.debug("command: %s, source: %s, target: %s, " "arguments: %s", command, prefix, target, [m]) self._handle_event(Event(command, NickMask(prefix), target, [m])) else: target = None if command == "quit": arguments = [arguments[0]] elif command == "ping": target = arguments[0] else: target = arguments[0] arguments = arguments[1:] if command == "mode": if not is_channel(target): command = "umode" log.debug("command: %s, source: %s, target: %s, " "arguments: %s", command, prefix, target, arguments) self._handle_event(Event(command, NickMask(prefix), target, arguments)) def _handle_event(self, event): """[Internal]""" self.irclibobj._handle_event(self, event) if event.type in self.handlers: for fn in self.handlers[event.type]: fn(self, event) def is_connected(self): """Return connection status. Returns true if connected, otherwise false. """ return self.connected def add_global_handler(self, *args): """Add global handler. See documentation for IRC.add_global_handler. """ self.irclibobj.add_global_handler(*args) def remove_global_handler(self, *args): """Remove global handler. See documentation for IRC.remove_global_handler. """ self.irclibobj.remove_global_handler(*args) def action(self, target, action): """Send a CTCP ACTION command.""" self.ctcp("ACTION", target, action) def admin(self, server=""): """Send an ADMIN command.""" self.send_raw(" ".join(["ADMIN", server]).strip()) def cap(self, subcommand, *args): """ Send a CAP command according to `the spec `_. Arguments: subcommand -- LS, LIST, REQ, ACK, CLEAR, END args -- capabilities, if required for given subcommand Example: .cap('LS') .cap('REQ', 'multi-prefix', 'sasl') .cap('END') """ cap_subcommands = set('LS LIST REQ ACK NAK CLEAR END'.split()) client_subcommands = set(cap_subcommands) - set('NAK') assert subcommand in client_subcommands, "invalid subcommand" def _multi_parameter(args): """ According to the spec:: If more than one capability is named, the RFC1459 designated sentinel (:) for a multi-parameter argument must be present. It's not obvious where the sentinel should be present or if it must be omitted for a single parameter, so follow convention and only include the sentinel prefixed to the first parameter if more than one parameter is present. """ if len(args) > 1: return (':' + args[0],) + args[1:] return args args = _multi_parameter(args) self.send_raw(' '.join(('CAP', subcommand) + args)) def ctcp(self, ctcptype, target, parameter=""): """Send a CTCP command.""" ctcptype = ctcptype.upper() self.privmsg(target, "\001%s%s\001" % (ctcptype, parameter and (" " + parameter) or "")) def ctcp_reply(self, target, parameter): """Send a CTCP REPLY command.""" self.notice(target, "\001%s\001" % parameter) def disconnect(self, message=""): """Hang up the connection. Arguments: message -- Quit message. """ if not self.connected: return self.connected = 0 self.quit(message) try: self.socket.shutdown(socket.SHUT_WR) self.socket.close() except socket.error: pass del self.socket self._handle_event(Event("disconnect", self.server, "", [message])) def globops(self, text): """Send a GLOBOPS command.""" self.send_raw("GLOBOPS :" + text) def info(self, server=""): """Send an INFO command.""" self.send_raw(" ".join(["INFO", server]).strip()) def invite(self, nick, channel): """Send an INVITE command.""" self.send_raw(" ".join(["INVITE", nick, channel]).strip()) def ison(self, nicks): """Send an ISON command. Arguments: nicks -- List of nicks. """ self.send_raw("ISON " + " ".join(nicks)) def join(self, channel, key=""): """Send a JOIN command.""" self.send_raw("JOIN %s%s" % (channel, (key and (" " + key)))) def kick(self, channel, nick, comment=""): """Send a KICK command.""" self.send_raw("KICK %s %s%s" % (channel, nick, (comment and (" :" + comment)))) def links(self, remote_server="", server_mask=""): """Send a LINKS command.""" command = "LINKS" if remote_server: command = command + " " + remote_server if server_mask: command = command + " " + server_mask self.send_raw(command) def list(self, channels=None, server=""): """Send a LIST command.""" command = "LIST" if channels: command = command + " " + ",".join(channels) if server: command = command + " " + server self.send_raw(command) def lusers(self, server=""): """Send a LUSERS command.""" self.send_raw("LUSERS" + (server and (" " + server))) def mode(self, target, command): """Send a MODE command.""" self.send_raw("MODE %s %s" % (target, command)) def motd(self, server=""): """Send an MOTD command.""" self.send_raw("MOTD" + (server and (" " + server))) def names(self, channels=None): """Send a NAMES command.""" self.send_raw("NAMES" + (channels and (" " + ",".join(channels)) or "")) def nick(self, newnick): """Send a NICK command.""" self.send_raw("NICK " + newnick) def notice(self, target, text): """Send a NOTICE command.""" # Should limit len(text) here! self.send_raw("NOTICE %s :%s" % (target, text)) def oper(self, nick, password): """Send an OPER command.""" self.send_raw("OPER %s %s" % (nick, password)) def part(self, channels, message=""): """Send a PART command.""" channels = util.always_iterable(channels) cmd_parts = [ 'PART', ','.join(channels), ] if message: cmd_parts.append(message) self.send_raw(' '.join(cmd_parts)) def pass_(self, password): """Send a PASS command.""" self.send_raw("PASS " + password) def ping(self, target, target2=""): """Send a PING command.""" self.send_raw("PING %s%s" % (target, target2 and (" " + target2))) def pong(self, target, target2=""): """Send a PONG command.""" self.send_raw("PONG %s%s" % (target, target2 and (" " + target2))) def privmsg(self, target, text): """Send a PRIVMSG command.""" self.send_raw("PRIVMSG %s :%s" % (target, text)) def privmsg_many(self, targets, text): """Send a PRIVMSG command to multiple targets.""" target = ','.join(targets) return self.privmsg(target, text) def quit(self, message=""): """Send a QUIT command.""" # Note that many IRC servers don't use your QUIT message # unless you've been connected for at least 5 minutes! self.send_raw("QUIT" + (message and (" :" + message))) def send_raw(self, string): """Send raw string to the server. The string will be padded with appropriate CR LF. """ # The string should not contain any carriage return other than the # one added here. if '\n' in string: raise InvalidCharacters( "Carriage returns not allowed in privmsg(text)") bytes = string.encode('utf-8') + b'\r\n' # According to the RFC http://tools.ietf.org/html/rfc2812#page-6, # clients should not transmit more than 512 bytes. if len(bytes) > 512: raise MessageTooLong( "Messages limited to 512 bytes including CR/LF") if self.socket is None: raise ServerNotConnectedError("Not connected.") sender = getattr(self.socket, 'write', self.socket.send) try: sender(bytes) log.debug("TO SERVER: %s", string) except socket.error: # Ouch! self.disconnect("Connection reset by peer.") def squit(self, server, comment=""): """Send an SQUIT command.""" self.send_raw("SQUIT %s%s" % (server, comment and (" :" + comment))) def stats(self, statstype, server=""): """Send a STATS command.""" self.send_raw("STATS %s%s" % (statstype, server and (" " + server))) def time(self, server=""): """Send a TIME command.""" self.send_raw("TIME" + (server and (" " + server))) def topic(self, channel, new_topic=None): """Send a TOPIC command.""" if new_topic is None: self.send_raw("TOPIC " + channel) else: self.send_raw("TOPIC %s :%s" % (channel, new_topic)) def trace(self, target=""): """Send a TRACE command.""" self.send_raw("TRACE" + (target and (" " + target))) def user(self, username, realname): """Send a USER command.""" self.send_raw("USER %s 0 * :%s" % (username, realname)) def userhost(self, nicks): """Send a USERHOST command.""" self.send_raw("USERHOST " + ",".join(nicks)) def users(self, server=""): """Send a USERS command.""" self.send_raw("USERS" + (server and (" " + server))) def version(self, server=""): """Send a VERSION command.""" self.send_raw("VERSION" + (server and (" " + server))) def wallops(self, text): """Send a WALLOPS command.""" self.send_raw("WALLOPS :" + text) def who(self, target="", op=""): """Send a WHO command.""" self.send_raw("WHO%s%s" % (target and (" " + target), op and (" o"))) def whois(self, targets): """Send a WHOIS command.""" self.send_raw("WHOIS " + ",".join(targets)) def whowas(self, nick, max="", server=""): """Send a WHOWAS command.""" self.send_raw("WHOWAS %s%s%s" % (nick, max and (" " + max), server and (" " + server))) def set_rate_limit(self, frequency): """ Set a `frequency` limit (messages per second) for this connection. Any attempts to send faster than this rate will block. """ self.send_raw = Throttler(self.send_raw, frequency) def set_keepalive(self, interval): """ Set a keepalive to occur every ``interval`` on this connection. """ pinger = functools.partial(self.ping, 'keep-alive') self.irclibobj.execute_every(period=interval, function=pinger) class Throttler(object): """ Rate-limit a function (or other callable) """ def __init__(self, func, max_rate=float('Inf')): if isinstance(func, Throttler): func = func.func self.func = func self.max_rate = max_rate self.reset() def reset(self): self.last_called = 0 def __call__(self, *args, **kwargs): # ensure at least 1/max_rate seconds from last call elapsed = time.time() - self.last_called must_wait = 1 / self.max_rate - elapsed time.sleep(max(0, must_wait)) self.last_called = time.time() return self.func(*args, **kwargs) class DCCConnectionError(IRCError): pass class DCCConnection(Connection): """This class represents a DCC connection. DCCConnection objects are instantiated by calling the dcc method on an IRC object. """ socket = None def __init__(self, irclibobj, dcctype): super(DCCConnection, self).__init__(irclibobj) self.connected = 0 self.passive = 0 self.dcctype = dcctype self.peeraddress = None self.peerport = None def connect(self, address, port): """Connect/reconnect to a DCC peer. Arguments: address -- Host/IP address of the peer. port -- The port number to connect to. Returns the DCCConnection object. """ self.peeraddress = socket.gethostbyname(address) self.peerport = port self.buffer = LineBuffer() self.handlers = {} self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.passive = 0 try: self.socket.connect((self.peeraddress, self.peerport)) except socket.error as x: raise DCCConnectionError("Couldn't connect to socket: %s" % x) self.connected = 1 self.irclibobj._on_connect(self.socket) return self def listen(self): """Wait for a connection/reconnection from a DCC peer. Returns the DCCConnection object. The local IP address and port are available as self.localaddress and self.localport. After connection from a peer, the peer address and port are available as self.peeraddress and self.peerport. """ self.buffer = LineBuffer() self.handlers = {} self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.passive = 1 try: self.socket.bind((socket.gethostbyname(socket.gethostname()), 0)) self.localaddress, self.localport = self.socket.getsockname() self.socket.listen(10) except socket.error as x: raise DCCConnectionError("Couldn't bind socket: %s" % x) return self def disconnect(self, message=""): """Hang up the connection and close the object. Arguments: message -- Quit message. """ if not self.connected: return self.connected = 0 try: self.socket.shutdown(socket.SHUT_WR) self.socket.close() except socket.error: pass del self.socket self.irclibobj._handle_event( self, Event("dcc_disconnect", self.peeraddress, "", [message])) self.irclibobj._remove_connection(self) def process_data(self): """[Internal]""" if self.passive and not self.connected: conn, (self.peeraddress, self.peerport) = self.socket.accept() self.socket.close() self.socket = conn self.connected = 1 log.debug("DCC connection from %s:%d", self.peeraddress, self.peerport) self.irclibobj._handle_event( self, Event("dcc_connect", self.peeraddress, None, None)) return try: new_data = self.socket.recv(2 ** 14) except socket.error: # The server hung up. self.disconnect("Connection reset by peer") return if not new_data: # Read nothing: connection must be down. self.disconnect("Connection reset by peer") return if self.dcctype == "chat": self.buffer.feed(new_data) chunks = list(self.buffer) if len(self.buffer) > 2 ** 14: # Bad peer! Naughty peer! self.disconnect() return else: chunks = [new_data] command = "dccmsg" prefix = self.peeraddress target = None for chunk in chunks: log.debug("FROM PEER: %s", chunk) arguments = [chunk] log.debug("command: %s, source: %s, target: %s, arguments: %s", command, prefix, target, arguments) self.irclibobj._handle_event( self, Event(command, prefix, target, arguments)) def privmsg(self, text): """ Send text to DCC peer. The text will be padded with a newline if it's a DCC CHAT session. """ if self.dcctype == 'chat': text += '\n' bytes = text.encode('utf-8') return self.send_bytes(bytes) def send_bytes(self, bytes): """ Send data to DCC peer. """ try: self.socket.send(bytes) log.debug("TO PEER: %r\n", bytes) except socket.error: self.disconnect("Connection reset by peer.") class SimpleIRCClient(object): """A simple single-server IRC client class. This is an example of an object-oriented wrapper of the IRC framework. A real IRC client can be made by subclassing this class and adding appropriate methods. The method on_join will be called when a "join" event is created (which is done when the server sends a JOIN messsage/command), on_privmsg will be called for "privmsg" events, and so on. The handler methods get two arguments: the connection object (same as self.connection) and the event object. Instance attributes that can be used by sub classes: ircobj -- The IRC instance. connection -- The ServerConnection instance. dcc_connections -- A list of DCCConnection instances. """ def __init__(self): self.ircobj = IRC() self.connection = self.ircobj.server() self.dcc_connections = [] self.ircobj.add_global_handler("all_events", self._dispatcher, -10) self.ircobj.add_global_handler("dcc_disconnect", self._dcc_disconnect, -10) def _dispatcher(self, connection, event): """ Dispatch events to on_ method, if present. """ log.debug("_dispatcher: %s", event.type) do_nothing = lambda c, e: None method = getattr(self, "on_" + event.type, do_nothing) method(connection, event) def _dcc_disconnect(self, c, e): self.dcc_connections.remove(c) def connect(self, *args, **kwargs): """Connect using the underlying connection""" self.connection.connect(*args, **kwargs) def dcc_connect(self, address, port, dcctype="chat"): """Connect to a DCC peer. Arguments: address -- IP address of the peer. port -- Port to connect to. Returns a DCCConnection instance. """ dcc = self.ircobj.dcc(dcctype) self.dcc_connections.append(dcc) dcc.connect(address, port) return dcc def dcc_listen(self, dcctype="chat"): """Listen for connections from a DCC peer. Returns a DCCConnection instance. """ dcc = self.ircobj.dcc(dcctype) self.dcc_connections.append(dcc) dcc.listen() return dcc def start(self): """Start the IRC client.""" self.ircobj.process_forever() class Event(object): "An IRC event." def __init__(self, type, source, target, arguments=None): """ Constructor of Event objects. Arguments: type -- A string describing the event. source -- The originator of the event (a nick mask or a server). target -- The target of the event (a nick or a channel). arguments -- Any event-specific arguments. """ self.type = type self.source = source self.target = target if arguments is None: arguments = [] self.arguments = arguments _LOW_LEVEL_QUOTE = "\020" _CTCP_LEVEL_QUOTE = "\134" _CTCP_DELIMITER = "\001" _low_level_mapping = { "0": "\000", "n": "\n", "r": "\r", _LOW_LEVEL_QUOTE: _LOW_LEVEL_QUOTE } _low_level_regexp = re.compile(_LOW_LEVEL_QUOTE + "(.)") def mask_matches(nick, mask): """Check if a nick matches a mask. Returns true if the nick matches, otherwise false. """ nick = strings.lower(nick) mask = strings.lower(mask) mask = mask.replace("\\", "\\\\") for ch in ".$|[](){}+": mask = mask.replace(ch, "\\" + ch) mask = mask.replace("?", ".") mask = mask.replace("*", ".*") r = re.compile(mask, re.IGNORECASE) return r.match(nick) _special = "-[]\\`^{}" nick_characters = string.ascii_letters + string.digits + _special def _ctcp_dequote(message): """[Internal] Dequote a message according to CTCP specifications. The function returns a list where each element can be either a string (normal message) or a tuple of one or two strings (tagged messages). If a tuple has only one element (ie is a singleton), that element is the tag; otherwise the tuple has two elements: the tag and the data. Arguments: message -- The message to be decoded. """ def _low_level_replace(match_obj): ch = match_obj.group(1) # If low_level_mapping doesn't have the character as key, we # should just return the character. return _low_level_mapping.get(ch, ch) if _LOW_LEVEL_QUOTE in message: # Yup, there was a quote. Release the dequoter, man! message = _low_level_regexp.sub(_low_level_replace, message) if _CTCP_DELIMITER not in message: return [message] else: # Split it into parts. (Does any IRC client actually *use* # CTCP stacking like this?) chunks = message.split(_CTCP_DELIMITER) messages = [] i = 0 while i < len(chunks) - 1: # Add message if it's non-empty. if len(chunks[i]) > 0: messages.append(chunks[i]) if i < len(chunks) - 2: # Aye! CTCP tagged data ahead! messages.append(tuple(chunks[i + 1].split(" ", 1))) i = i + 2 if len(chunks) % 2 == 0: # Hey, a lonely _CTCP_DELIMITER at the end! This means # that the last chunk, including the delimiter, is a # normal message! (This is according to the CTCP # specification.) messages.append(_CTCP_DELIMITER + chunks[-1]) return messages def is_channel(string): """Check if a string is a channel name. Returns true if the argument is a channel name, otherwise false. """ return string and string[0] in "#&+!" def ip_numstr_to_quad(num): """ Convert an IP number as an integer given in ASCII representation to an IP address string. >>> ip_numstr_to_quad('3232235521') '192.168.0.1' >>> ip_numstr_to_quad(3232235521) '192.168.0.1' """ n = int(num) packed = struct.pack('>L', n) bytes = struct.unpack('BBBB', packed) return ".".join(map(str, bytes)) def ip_quad_to_numstr(quad): """ Convert an IP address string (e.g. '192.168.0.1') to an IP number as a base-10 integer given in ASCII representation. >>> ip_quad_to_numstr('192.168.0.1') '3232235521' """ bytes = map(int, quad.split(".")) packed = struct.pack('BBBB', *bytes) return str(struct.unpack('>L', packed)[0]) class NickMask(six.text_type): """ A nickmask (the source of an Event) >>> nm = NickMask('pinky!username@example.com') >>> print(nm.nick) pinky >>> print(nm.host) example.com >>> print(nm.user) username >>> isinstance(nm, six.text_type) True >>> nm = 'красный!red@yahoo.ru' >>> if not six.PY3: nm = nm.decode('utf-8') >>> nm = NickMask(nm) >>> isinstance(nm.nick, six.text_type) True """ @classmethod def from_params(cls, nick, user, host): return cls('{nick}!{user}@{host}'.format(**vars())) @property def nick(self): return self.split("!")[0] @property def userhost(self): return self.split("!")[1] @property def host(self): return self.split("@")[1] @property def user(self): return self.userhost.split("@")[0] def _ping_ponger(connection, event): "A global handler for the 'ping' event" connection.pong(event.target) # for backward compatibility LineBuffer = buffer.LineBuffer DecodingLineBuffer = buffer.DecodingLineBuffer python-irc-8.5.3+dfsg/irc/connection.py000066400000000000000000000033671302547020000200320ustar00rootroot00000000000000 from __future__ import absolute_import import socket try: from importlib import import_module except ImportError: # for Python 2.6 compatibility import_module = __import__ identity = lambda x: x class Factory(object): """ A class for creating custom socket connections. To create a simple connection: server_address = ('localhost', 80) Factory()(server_address) To create an SSL connection: Factory(wrapper=ssl.wrap_socket)(server_address) To create an SSL connection with parameters to wrap_socket: wrapper = functools.partial(ssl.wrap_socket, ssl_cert=get_cert()) Factory(wrapper=wrapper)(server_address) To create an IPv6 connection: Factory(ipv6=True)(server_address) Note that Factory doesn't save the state of the socket itself. The caller must do that, as necessary. As a result, the Factory may be re-used to create new connections with the same settings. """ family = socket.AF_INET def __init__(self, bind_address=('', 0), wrapper=identity, ipv6=False): self.bind_address = bind_address self.wrapper = wrapper if ipv6: self.family = socket.AF_INET6 def from_legacy_params(self, localaddress='', localport=0, ssl=False, ipv6=False): if localaddress or localport: self.bind_address = (localaddress, localport) if ssl: self.wrapper = import_module('ssl').wrap_socket if ipv6: self.family = socket.AF_INET6 def connect(self, server_address): sock = self.wrapper(socket.socket(self.family, socket.SOCK_STREAM)) sock.bind(self.bind_address) sock.connect(server_address) return sock __call__ = connect python-irc-8.5.3+dfsg/irc/dict.py000066400000000000000000000044341302547020000166120ustar00rootroot00000000000000from __future__ import unicode_literals import six from . import strings # from jaraco.util.dictlib class KeyTransformingDict(dict): """ A dict subclass that transforms the keys before they're used. Subclasses may override the default key_transform to customize behavior. """ @staticmethod def key_transform(key): return key def __init__(self, *args, **kargs): super(KeyTransformingDict, self).__init__() # build a dictionary using the default constructs d = dict(*args, **kargs) # build this dictionary using transformed keys. for item in d.items(): self.__setitem__(*item) def __setitem__(self, key, val): key = self.key_transform(key) super(KeyTransformingDict, self).__setitem__(key, val) def __getitem__(self, key): key = self.key_transform(key) return super(KeyTransformingDict, self).__getitem__(key) def __contains__(self, key): key = self.key_transform(key) return super(KeyTransformingDict, self).__contains__(key) def __delitem__(self, key): key = self.key_transform(key) return super(KeyTransformingDict, self).__delitem__(key) def setdefault(self, key, *args, **kwargs): key = self.key_transform(key) return super(KeyTransformingDict, self).setdefault(key, *args, **kwargs) def pop(self, key, *args, **kwargs): key = self.key_transform(key) return super(KeyTransformingDict, self).pop(key, *args, **kwargs) class IRCDict(KeyTransformingDict): """ A dictionary of names whose keys are case-insensitive according to the IRC RFC rules. >>> d = IRCDict({'[This]': 'that'}, A='foo') The dict maintains the original case: >>> '[This]' in ''.join(d.keys()) True But the keys can be referenced with a different case >>> d['a'] == 'foo' True >>> d['{this}'] == 'that' True >>> d['{THIS}'] == 'that' True >>> '{thiS]' in d True This should work for operations like delete and pop as well. >>> d.pop('A') == 'foo' True >>> del d['{This}'] >>> len(d) 0 """ @staticmethod def key_transform(key): if isinstance(key, six.string_types): key = strings.IRCFoldedCase(key) return key python-irc-8.5.3+dfsg/irc/events.py000066400000000000000000000112101302547020000171610ustar00rootroot00000000000000# Numeric table based on the Perl's Net::IRC. numeric = { "001": "welcome", "002": "yourhost", "003": "created", "004": "myinfo", "005": "featurelist", # XXX "200": "tracelink", "201": "traceconnecting", "202": "tracehandshake", "203": "traceunknown", "204": "traceoperator", "205": "traceuser", "206": "traceserver", "207": "traceservice", "208": "tracenewtype", "209": "traceclass", "210": "tracereconnect", "211": "statslinkinfo", "212": "statscommands", "213": "statscline", "214": "statsnline", "215": "statsiline", "216": "statskline", "217": "statsqline", "218": "statsyline", "219": "endofstats", "221": "umodeis", "231": "serviceinfo", "232": "endofservices", "233": "service", "234": "servlist", "235": "servlistend", "241": "statslline", "242": "statsuptime", "243": "statsoline", "244": "statshline", "250": "luserconns", "251": "luserclient", "252": "luserop", "253": "luserunknown", "254": "luserchannels", "255": "luserme", "256": "adminme", "257": "adminloc1", "258": "adminloc2", "259": "adminemail", "261": "tracelog", "262": "endoftrace", "263": "tryagain", "265": "n_local", "266": "n_global", "300": "none", "301": "away", "302": "userhost", "303": "ison", "305": "unaway", "306": "nowaway", "311": "whoisuser", "312": "whoisserver", "313": "whoisoperator", "314": "whowasuser", "315": "endofwho", "316": "whoischanop", "317": "whoisidle", "318": "endofwhois", "319": "whoischannels", "321": "liststart", "322": "list", "323": "listend", "324": "channelmodeis", "329": "channelcreate", "331": "notopic", "332": "currenttopic", "333": "topicinfo", "341": "inviting", "342": "summoning", "346": "invitelist", "347": "endofinvitelist", "348": "exceptlist", "349": "endofexceptlist", "351": "version", "352": "whoreply", "353": "namreply", "361": "killdone", "362": "closing", "363": "closeend", "364": "links", "365": "endoflinks", "366": "endofnames", "367": "banlist", "368": "endofbanlist", "369": "endofwhowas", "371": "info", "372": "motd", "373": "infostart", "374": "endofinfo", "375": "motdstart", "376": "endofmotd", "377": "motd2", # 1997-10-16 -- tkil "381": "youreoper", "382": "rehashing", "384": "myportis", "391": "time", "392": "usersstart", "393": "users", "394": "endofusers", "395": "nousers", "401": "nosuchnick", "402": "nosuchserver", "403": "nosuchchannel", "404": "cannotsendtochan", "405": "toomanychannels", "406": "wasnosuchnick", "407": "toomanytargets", "409": "noorigin", "410": "invalidcapcmd", "411": "norecipient", "412": "notexttosend", "413": "notoplevel", "414": "wildtoplevel", "421": "unknowncommand", "422": "nomotd", "423": "noadmininfo", "424": "fileerror", "431": "nonicknamegiven", "432": "erroneusnickname", # Thiss iz how its speld in thee RFC. "433": "nicknameinuse", "436": "nickcollision", "437": "unavailresource", # "Nick temporally unavailable" "441": "usernotinchannel", "442": "notonchannel", "443": "useronchannel", "444": "nologin", "445": "summondisabled", "446": "usersdisabled", "451": "notregistered", "461": "needmoreparams", "462": "alreadyregistered", "463": "nopermforhost", "464": "passwdmismatch", "465": "yourebannedcreep", # I love this one... "466": "youwillbebanned", "467": "keyset", "471": "channelisfull", "472": "unknownmode", "473": "inviteonlychan", "474": "bannedfromchan", "475": "badchannelkey", "476": "badchanmask", "477": "nochanmodes", # "Channel doesn't support modes" "478": "banlistfull", "481": "noprivileges", "482": "chanoprivsneeded", "483": "cantkillserver", "484": "restricted", # Connection is restricted "485": "uniqopprivsneeded", "491": "nooperhost", "492": "noservicehost", "501": "umodeunknownflag", "502": "usersdontmatch", } codes = dict((v, k) for k, v in numeric.items()) generated = [ "dcc_connect", "dcc_disconnect", "dccmsg", "disconnect", "ctcp", "ctcpreply", ] protocol = [ "error", "join", "kick", "mode", "part", "ping", "privmsg", "privnotice", "pubmsg", "pubnotice", "quit", "invite", "pong", "action", "topic", "nick", ] all = generated + protocol + list(numeric.values()) python-irc-8.5.3+dfsg/irc/features.py000066400000000000000000000056301302547020000175040ustar00rootroot00000000000000class FeatureSet(object): """ An implementation of features as loaded from an ISUPPORT server directive. Each feature is loaded into an attribute of the same name (but lowercased to match Python sensibilities). >>> f = FeatureSet() >>> f.load(['target', 'PREFIX=(abc)+-/', 'your message sir']) >>> f.prefix == {'+': 'a', '-': 'b', '/': 'c'} True >>> f.load_feature('CHANMODES=foo,bar,baz') >>> f.chanmodes ['foo', 'bar', 'baz'] """ def __init__(self): self._set_rfc1459_prefixes() def _set_rfc1459_prefixes(self): "install standard (RFC1459) prefixes" self.set('PREFIX', { '@': 'o', '+': 'v', }) def set(self, name, value=True): "set a feature value" setattr(self, name.lower(), value) def remove(self, feature_name): if feature_name in vars(self): delattr(self, feature_name) def load(self, arguments): "Load the values from the a ServerConnection arguments" target, features, msg = arguments[:1], arguments[1:-1], arguments[-1:] list(map(self.load_feature, features)) def load_feature(self, feature): # negating if feature[0] == '-': return self.remove(feature[1:].lower()) name, sep, value = feature.partition('=') if not sep: return if not value: self.set(name) return parser = getattr(self, '_parse_' + name, self._parse_other) value = parser(value) self.set(name, value) @staticmethod def _parse_PREFIX(value): "channel user prefixes" channel_modes, channel_chars = value.split(')') channel_modes = channel_modes[1:] return dict(zip(channel_chars, channel_modes)) @staticmethod def _parse_CHANMODES(value): "channel mode letters" return value.split(',') @staticmethod def _parse_TARGMAX(value): """ >>> res = FeatureSet._parse_TARGMAX('a:3,c:,b:2') >>> res['a'] 3 """ return dict(string_int_pair(target, ':') for target in value.split(',')) @staticmethod def _parse_CHANLIMIT(value): """ >>> res = FeatureSet._parse_CHANLIMIT('ibe:250,xyz:100') >>> len(res) 6 >>> res['x'] 100 >>> res['i'] == res['b'] == res['e'] == 250 True """ pairs = map(string_int_pair, value.split(',')) return dict( (target, number) for target_keys, number in pairs for target in target_keys ) _parse_MAXLIST = _parse_CHANLIMIT @staticmethod def _parse_other(value): if value.isdigit(): return int(value) return value def string_int_pair(target, sep=':'): name, value = target.split(sep) value = int(value) if value else None return name, value python-irc-8.5.3+dfsg/irc/functools.py000066400000000000000000000020061302547020000176740ustar00rootroot00000000000000from __future__ import absolute_import, print_function, unicode_literals import functools import collections def save_method_args(method): """ Wrap a method such that when it is called, we save the args and kwargs with which it was called. >>> class MyClass(object): ... @save_method_args ... def method(self, a, b): ... print(a, b) >>> my_ob = MyClass() >>> my_ob.method(1, 2) 1 2 >>> my_ob._saved_method.args (1, 2) >>> my_ob._saved_method.kwargs {} >>> my_ob.method(a=3, b='foo') 3 foo >>> my_ob._saved_method.args () >>> my_ob._saved_method.kwargs == dict(a=3, b='foo') True """ args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') @functools.wraps(method) def wrapper(self, *args, **kwargs): attr_name = '_saved_' + method.__name__ attr = args_and_kwargs(args, kwargs) setattr(self, attr_name, attr) return method(self, *args, **kwargs) return wrapper python-irc-8.5.3+dfsg/irc/logging.py000066400000000000000000000014301302547020000173060ustar00rootroot00000000000000from __future__ import absolute_import import logging def log_level(level_string): """ Return a log level for a string """ return getattr(logging, level_string.upper()) def add_arguments(parser): """ Add arguments to an ArgumentParser or OptionParser for purposes of grabbing a logging level. """ adder = ( getattr(parser, 'add_argument', None) or getattr(parser, 'add_option') ) adder('-l', '--log-level', default=logging.INFO, type=log_level, help="Set log level (DEBUG, INFO, WARNING, ERROR)") def setup(options, **kwargs): """ Setup logging with options or arguments from an OptionParser or ArgumentParser. Also pass any keyword arguments to the basicConfig call. """ params = dict(kwargs) params.update(level=options.log_level) logging.basicConfig(**params) python-irc-8.5.3+dfsg/irc/modes.py000066400000000000000000000046721302547020000170020ustar00rootroot00000000000000def parse_nick_modes(mode_string): """Parse a nick mode string. The function returns a list of lists with three members: sign, mode and argument. The sign is "+" or "-". The argument is always None. Example: >>> parse_nick_modes("+ab-c") [['+', 'a', None], ['+', 'b', None], ['-', 'c', None]] """ return _parse_modes(mode_string, "") def parse_channel_modes(mode_string): """Parse a channel mode string. The function returns a list of lists with three members: sign, mode and argument. The sign is "+" or "-". The argument is None if mode isn't one of "b", "k", "l", "v", "o", "h", or "q". Example: >>> parse_channel_modes("+ab-c foo") [['+', 'a', None], ['+', 'b', 'foo'], ['-', 'c', None]] """ return _parse_modes(mode_string, "bklvohq") def _parse_modes(mode_string, unary_modes=""): """ Parse the mode_string and return a list of triples. If no string is supplied return an empty list. >>> _parse_modes('') [] If no sign is supplied, return an empty list. >>> _parse_modes('ab') [] Discard unused args. >>> _parse_modes('+a foo bar baz') [['+', 'a', None]] Return none for unary args when not provided >>> _parse_modes('+abc foo', unary_modes='abc') [['+', 'a', 'foo'], ['+', 'b', None], ['+', 'c', None]] This function never throws an error: >>> import random >>> import six >>> unichr = chr if six.PY3 else unichr >>> def random_text(min_len = 3, max_len = 80): ... len = random.randint(min_len, max_len) ... chars_to_choose = [unichr(x) for x in range(0,1024)] ... chars = (random.choice(chars_to_choose) for x in range(len)) ... return ''.join(chars) >>> def random_texts(min_len = 3, max_len = 80): ... while True: ... yield random_text(min_len, max_len) >>> import itertools >>> texts = itertools.islice(random_texts(), 1000) >>> set(type(_parse_modes(text)) for text in texts) == set([list]) True """ # mode_string must be non-empty and begin with a sign if not mode_string or not mode_string[0] in '+-': return [] modes = [] parts = mode_string.split() mode_part, args = parts[0], parts[1:] for ch in mode_part: if ch in "+-": sign = ch continue arg = args.pop(0) if ch in unary_modes and args else None modes.append([sign, ch, arg]) return modes python-irc-8.5.3+dfsg/irc/rfc.py000066400000000000000000000012131302547020000164310ustar00rootroot00000000000000import re def get_pages(filename): with open(filename) as f: data = f.read() return data.split('\x0c') header_pattern = re.compile(r'^RFC \d+\s+.*\s+(\w+ \d{4})$', re.M) footer_pattern = re.compile(r'^\w+\s+\w+\s+\[Page \d+\]$', re.M) def remove_header(page): page = header_pattern.sub('', page) return page.lstrip('\n') def remove_footer(page): page = footer_pattern.sub('', page) return page.rstrip() + '\n\n' def clean_pages(): return map(remove_header, map(remove_footer, get_pages('rfc2812.txt'))) def save_clean(): with open('rfc2812-clean.txt', 'w') as f: map(f.write, clean_pages()) if __name__ == '__main__': save_clean() python-irc-8.5.3+dfsg/irc/schedule.py000066400000000000000000000060211302547020000174550ustar00rootroot00000000000000""" Classes for calling functions a schedule. """ import datetime import numbers class DelayedCommand(datetime.datetime): """ A command to be executed after some delay (seconds or timedelta). Clients may override .now() to have dates interpreted in a different manner, such as to use UTC or to have timezone-aware times. """ @classmethod def now(self, tzinfo=None): return datetime.datetime.now(tzinfo) @classmethod def from_datetime(cls, other): return cls(other.year, other.month, other.day, other.hour, other.minute, other.second, other.microsecond, other.tzinfo) @classmethod def after(cls, delay, function): if not isinstance(delay, datetime.timedelta): delay = datetime.timedelta(seconds=delay) due_time = cls.now() + delay cmd = cls.from_datetime(due_time) cmd.delay = delay cmd.function = function return cmd @classmethod def at_time(cls, at, function): """ Construct a DelayedCommand to come due at `at`, where `at` may be a datetime or timestamp. If `at` is a real number, it will be interpreted as a naive local timestamp. """ if isinstance(at, numbers.Real): at = datetime.datetime.fromtimestamp(at) cmd = cls.from_datetime(at) cmd.delay = at - cmd.now() cmd.function = function return cmd def due(self): return self.now() >= self class PeriodicCommand(DelayedCommand): """ Like a delayed command, but expect this command to run every delay seconds. """ def next(self): cmd = self.__class__.from_datetime(self + self.delay) cmd.delay = self.delay cmd.function = self.function return cmd def __setattr__(self, key, value): if key == 'delay' and not value > datetime.timedelta(): raise ValueError("A PeriodicCommand must have a positive, " "non-zero delay.") super(PeriodicCommand, self).__setattr__(key, value) class PeriodicCommandFixedDelay(PeriodicCommand): """ Like a periodic command, but don't calculate the delay based on the current time. Instead use a fixed delay following the initial run. """ @classmethod def at_time(cls, at, delay, function): if isinstance(at, int): at = datetime.datetime.fromtimestamp(at) cmd = cls.from_datetime(at) if not isinstance(delay, datetime.timedelta): delay = datetime.timedelta(seconds=delay) cmd.delay = delay cmd.function = function return cmd @classmethod def daily_at(cls, at, function): """ Schedule a command to run at a specific time each day. """ daily = datetime.timedelta(days=1) # convert when to the next datetime matching this time when = datetime.datetime.combine(datetime.date.today(), at) if when < cls.now(): when += daily return cls.at_time(when, daily, function) python-irc-8.5.3+dfsg/irc/server.py000066400000000000000000000425451302547020000172020ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ irc/server.py Copyright © 2009 Ferry Boender Copyright © 2012 Jason R. Coombs This server has basic support for: * Connecting * Channels * Nicknames * Public/private messages It is MISSING support for notably: * Server linking * Modes (user and channel) * Proper error reporting * Basically everything else It is mostly useful as a testing tool or perhaps for building something like a private proxy on. Do NOT use it in any kind of production code or anything that will ever be connected to by the public. """ # # Very simple hacky ugly IRC server. # # Todo: # - Encode format for each message and reply with events.codes['needmoreparams'] # - starting server when already started doesn't work properly. PID file is not changed, no error messsage is displayed. # - Delete channel if last user leaves. # - [ERROR] (better error msg required) # - Empty channels are left behind # - No Op assigned when new channel is created. # - User can /join multiple times (doesn't add more to channel, does say 'joined') # - PING timeouts # - Allow all numerical commands. # - Users can send commands to channels they are not in (PART) # Not Todo (Won't be supported) # - Server linking. # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # from __future__ import print_function, absolute_import import argparse import logging import socket import select import re import six from . import client from . import logging as log_util from . import events from . import buffer SRV_WELCOME = "Welcome to %s v%s, the ugliest IRC server in the world." % ( __name__, client.VERSION) log = logging.getLogger(__name__) class IRCError(Exception): """ Exception thrown by IRC command handlers to notify client of a server/client error. """ def __init__(self, code, value): self.code = code self.value = value def __str__(self): return repr(self.value) @classmethod def from_name(cls, name, value): return cls(events.codes[name], value) class IRCChannel(object): """ Object representing an IRC channel. """ def __init__(self, name, topic='No topic'): self.name = name self.topic_by = 'Unknown' self.topic = topic self.clients = set() class IRCClient(six.moves.socketserver.BaseRequestHandler): """ IRC client connect and command handling. Client connection is handled by the `handle` method which sets up a two-way communication with the client. It then handles commands sent by the client by dispatching them to the handle_ methods. """ class Disconnect(BaseException): pass def __init__(self, request, client_address, server): self.user = None self.host = client_address # Client's hostname / ip. self.realname = None # Client's real name self.nick = None # Client's currently registered nickname self.send_queue = [] # Messages to send to client (strings) self.channels = {} # Channels the client is in six.moves.socketserver.BaseRequestHandler.__init__(self, request, client_address, server) def handle(self): log.info('Client connected: %s', self.client_ident()) self.buffer = buffer.LineBuffer() try: while True: self._handle_one() except self.Disconnect: self.request.close() def _handle_one(self): """ Handle one read/write cycle. """ ready_to_read, ready_to_write, in_error = select.select( [self.request], [self.request], [self.request], 0.1) if in_error: raise self.Disconnect() # Write any commands to the client while self.send_queue and ready_to_write: msg = self.send_queue.pop(0) self._send(msg) # See if the client has any commands for us. if ready_to_read: self._handle_incoming() def _handle_incoming(self): try: data = self.request.recv(1024) except Exception: raise self.Disconnect() if not data: raise self.Disconnect() self.buffer.feed(data) for line in self.buffer: line = line.decode('utf-8') self._handle_line(line) def _handle_line(self, line): try: log.debug('from %s: %s' % (self.client_ident(), line)) command, sep, params = line.partition(' ') handler = getattr(self, 'handle_%s' % command.lower(), None) if not handler: log.info('No handler for command: %s. ' 'Full line: %s' % (command, line)) raise IRCError.from_name('unknowncommand', '%s :Unknown command' % command) response = handler(params) except AttributeError as e: log.error(six.text_type(e)) raise except IRCError as e: response = ':%s %s %s' % (self.server.servername, e.code, e.value) log.error(response) except Exception as e: response = ':%s ERROR %r' % (self.server.servername, e) log.error(response) raise if response: self._send(response) def _send(self, msg): log.debug('to %s: %s', self.client_ident(), msg) self.request.send(msg.encode('utf-8') + b'\r\n') def handle_nick(self, params): """ Handle the initial setting of the user's nickname and nick changes. """ nick = params # Valid nickname? if re.search('[^a-zA-Z0-9\-\[\]\'`^{}_]', nick): raise IRCError.from_name('erroneusnickname', ':%s' % nick) if self.server.clients.get(nick, None) == self: # Already registered to user return if nick in self.server.clients: # Someone else is using the nick raise IRCError.from_name('nicknameinuse', 'NICK :%s' % (nick)) if not self.nick: # New connection and nick is available; register and send welcome # and MOTD. self.nick = nick self.server.clients[nick] = self response = ':%s %s %s :%s' % (self.server.servername, events.codes['welcome'], self.nick, SRV_WELCOME) self.send_queue.append(response) response = ':%s 376 %s :End of MOTD command.' % ( self.server.servername, self.nick) self.send_queue.append(response) return # Nick is available. Change the nick. message = ':%s NICK :%s' % (self.client_ident(), nick) self.server.clients.pop(self.nick) self.nick = nick self.server.clients[self.nick] = self # Send a notification of the nick change to all the clients in the # channels the client is in. for channel in self.channels.values(): self._send_to_others(message, channel) # Send a notification of the nick change to the client itself return message def handle_user(self, params): """ Handle the USER command which identifies the user to the server. """ params = params.split(' ', 3) if len(params) != 4: raise IRCError.from_name('needmoreparams', 'USER :Not enough parameters') user, mode, unused, realname = params self.user = user self.mode = mode self.realname = realname return '' def handle_ping(self, params): """ Handle client PING requests to keep the connection alive. """ response = ':%s PONG :%s' % (self.server.servername, self.server.servername) return response def handle_join(self, params): """ Handle the JOINing of a user to a channel. Valid channel names start with a # and consist of a-z, A-Z, 0-9 and/or '_'. """ channel_names = params.split(' ', 1)[0] # Ignore keys for channel_name in channel_names.split(','): r_channel_name = channel_name.strip() # Valid channel name? if not re.match('^#([a-zA-Z0-9_])+$', r_channel_name): raise IRCError.from_name('nosuchchannel', '%s :No such channel' % r_channel_name) # Add user to the channel (create new channel if not exists) channel = self.server.channels.setdefault(r_channel_name, IRCChannel(r_channel_name)) channel.clients.add(self) # Add channel to user's channel list self.channels[channel.name] = channel # Send the topic response_join = ':%s TOPIC %s :%s' % (channel.topic_by, channel.name, channel.topic) self.send_queue.append(response_join) # Send join message to everybody in the channel, including yourself and # send user list of the channel back to the user. response_join = ':%s JOIN :%s' % (self.client_ident(), r_channel_name) for client in channel.clients: client.send_queue.append(response_join) nicks = [client.nick for client in channel.clients] response_userlist = ':%s 353 %s = %s :%s' % (self.server.servername, self.nick, channel.name, ' '.join(nicks)) self.send_queue.append(response_userlist) response = ':%s 366 %s %s :End of /NAMES list' % (self.server.servername, self.nick, channel.name) self.send_queue.append(response) def handle_privmsg(self, params): """ Handle sending a private message to a user or channel. """ target, sep, msg = params.partition(' ') if not msg: raise IRCError.from_name('needmoreparams', 'PRIVMSG :Not enough parameters') message = ':%s PRIVMSG %s %s' % (self.client_ident(), target, msg) if target.startswith('#') or target.startswith('$'): # Message to channel. Check if the channel exists. channel = self.server.channels.get(target) if not channel: raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target) if not channel.name in self.channels: # The user isn't in the channel. raise IRCError.from_name('cannotsendtochan', '%s :Cannot send to channel' % channel.name) self._send_to_others(message, channel) else: # Message to user client = self.server.clients.get(target, None) if not client: raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target) client.send_queue.append(message) def _send_to_others(self, message, channel): """ Send the message to all clients in the specified channel except for self. """ other_clients = [client for client in channel.clients if not client == self] for client in other_clients: client.send_queue.append(message) def handle_topic(self, params): """ Handle a topic command. """ channel_name, sep, topic = params.partition(' ') channel = self.server.channels.get(channel_name) if not channel: raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % channel_name) if not channel.name in self.channels: # The user isn't in the channel. raise IRCError.from_name('cannotsendtochan', '%s :Cannot send to channel' % channel.name) if topic: channel.topic = topic.lstrip(':') channel.topic_by = self.nick message = ':%s TOPIC %s :%s' % (self.client_ident(), channel_name, channel.topic) return message def handle_part(self, params): """ Handle a client parting from channel(s). """ for pchannel in params.split(','): if pchannel.strip() in self.server.channels: # Send message to all clients in all channels user is in, and # remove the user from the channels. channel = self.server.channels.get(pchannel.strip()) response = ':%s PART :%s' % (self.client_ident(), pchannel) if channel: for client in channel.clients: client.send_queue.append(response) channel.clients.remove(self) self.channels.pop(pchannel) else: response = ':%s 403 %s :%s' % (self.server.servername, pchannel, pchannel) self.send_queue.append(response) def handle_quit(self, params): """ Handle the client breaking off the connection with a QUIT command. """ response = ':%s QUIT :%s' % (self.client_ident(), params.lstrip(':')) # Send quit message to all clients in all channels user is in, and # remove the user from the channels. for channel in self.channels.values(): for client in channel.clients: client.send_queue.append(response) channel.clients.remove(self) def handle_dump(self, params): """ Dump internal server information for debugging purposes. """ print("Clients:", self.server.clients) for client in self.server.clients.values(): print(" ", client) for channel in client.channels.values(): print(" ", channel.name) print("Channels:", self.server.channels) for channel in self.server.channels.values(): print(" ", channel.name, channel) for client in channel.clients: print(" ", client.nick, client) def client_ident(self): """ Return the client identifier as included in many command replies. """ return client.NickMask.from_params(self.nick, self.user, self.server.servername) def finish(self): """ The client conection is finished. Do some cleanup to ensure that the client doesn't linger around in any channel or the client list, in case the client didn't properly close the connection with PART and QUIT. """ log.info('Client disconnected: %s', self.client_ident()) response = ':%s QUIT :EOF from client' % self.client_ident() for channel in self.channels.values(): if self in channel.clients: # Client is gone without properly QUITing or PARTing this # channel. for client in channel.clients: client.send_queue.append(response) channel.clients.remove(self) self.server.clients.pop(self.nick) log.info('Connection finished: %s', self.client_ident()) def __repr__(self): """ Return a user-readable description of the client """ return '<%s %s!%s@%s (%s)>' % ( self.__class__.__name__, self.nick, self.user, self.host[0], self.realname, ) class IRCServer(six.moves.socketserver.ThreadingMixIn, six.moves.socketserver.TCPServer): daemon_threads = True allow_reuse_address = True channels = {} "Existing channels (IRCChannel instances) by channel name" clients = {} "Connected clients (IRCClient instances) by nick name" def __init__(self, *args, **kwargs): self.servername = 'localhost' self.channels = {} self.clients = {} six.moves.socketserver.TCPServer.__init__(self, *args, **kwargs) def get_args(): parser = argparse.ArgumentParser() parser.add_argument("-a", "--address", dest="listen_address", default='127.0.0.1', help="IP on which to listen") parser.add_argument("-p", "--port", dest="listen_port", default=6667, type=int, help="Port on which to listen") log_util.add_arguments(parser) return parser.parse_args() def main(): options = get_args() log_util.setup(options) log.info("Starting irc.server") # # Start server # try: bind_address = options.listen_address, options.listen_port ircserver = IRCServer(bind_address, IRCClient) log.info('Listening on {listen_address}:{listen_port}'.format( **vars(options))) ircserver.serve_forever() except socket.error as e: log.error(repr(e)) raise SystemExit(-2) if __name__ == "__main__": main() python-irc-8.5.3+dfsg/irc/strings.py000066400000000000000000000041661302547020000173620ustar00rootroot00000000000000from __future__ import absolute_import, unicode_literals import re import string import six # from jaraco.util.string class FoldedCase(six.text_type): """ A case insensitive string class; behaves just like str except compares equal when the only variation is case. >>> s = FoldedCase('hello world') >>> s == 'Hello World' True >>> 'Hello World' == s True >>> s.index('O') 4 >>> s.split('O') == ['hell', ' w', 'rld'] True >>> in_order = sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) >>> in_order == ['alpha', 'Beta', 'GAMMA'] True It's still possible to compare against non-FoldedCase dicts >>> s == None False >>> s == 1 False """ def __lt__(self, other): if hasattr(other, 'lower'): other = other.lower() return self.lower() < other def __gt__(self, other): if hasattr(other, 'lower'): other = other.lower() return self.lower() > other def __eq__(self, other): if hasattr(other, 'lower'): other = other.lower() return self.lower() == other def __hash__(self): return hash(self.lower()) # cache lower since it's likely to be called frequently. def lower(self): self._lower = super(FoldedCase, self).lower() self.lower = lambda: self._lower return self._lower def index(self, sub): return self.lower().index(sub.lower()) def split(self, splitter=' ', maxsplit=0): pattern = re.compile(re.escape(splitter), re.I) return pattern.split(self, maxsplit) class IRCFoldedCase(FoldedCase): """ A version of FoldedCase that honors the IRC specification for lowercased strings (RFC 1459). >>> IRCFoldedCase('Foo^').lower() == 'foo~' True >>> IRCFoldedCase('[this]') == IRCFoldedCase('{THIS}') True """ translation = dict(zip( map(ord, string.ascii_uppercase + r"[]\^"), map(ord, string.ascii_lowercase + r"{}|~"), )) def lower(self): return self.translate(self.translation) def lower(str): return IRCFoldedCase(str).lower() python-irc-8.5.3+dfsg/irc/tests/000077500000000000000000000000001302547020000164525ustar00rootroot00000000000000python-irc-8.5.3+dfsg/irc/tests/__init__.py000066400000000000000000000000001302547020000205510ustar00rootroot00000000000000python-irc-8.5.3+dfsg/irc/tests/test_bot.py000066400000000000000000000047331302547020000206560ustar00rootroot00000000000000 import six import irc.client import irc.bot from irc.bot import ServerSpec class TestServerSpec(object): def test_with_host(self): server_spec = ServerSpec('irc.example.com') assert server_spec.host == 'irc.example.com' assert server_spec.port == 6667 assert server_spec.password is None def test_with_host_and_port(self): server_spec = ServerSpec('irc.example.org', port=6669) assert server_spec.host == 'irc.example.org' assert server_spec.port == 6669 assert server_spec.password is None def test_with_host_and_password(self): server_spec = ServerSpec('irc.example.net', password='heres johnny!') assert server_spec.host == 'irc.example.net' assert server_spec.port == 6667 assert server_spec.password == 'heres johnny!' def test_with_host_and_port_and_password(self): server_spec = ServerSpec('irc.example.gov', port=6668, password='there-is-only-zuul') assert server_spec.host == 'irc.example.gov' assert server_spec.port == 6668 assert server_spec.password == 'there-is-only-zuul' class TestChannel(object): def test_add_remove_nick(self): channel = irc.bot.Channel() channel.add_user('tester1') channel.remove_user('tester1') channel.add_user('tester1') assert 'tester1' in channel.users() def test_change_nick(self): channel = irc.bot.Channel() channel.add_user('tester1') channel.change_nick('tester1', 'was_tester') def test_has_user(self): channel = irc.bot.Channel() channel.add_user('tester1') assert channel.has_user('Tester1') class TestBot(object): def test_construct_bot(self): bot = irc.bot.SingleServerIRCBot( server_list = [('localhost', '9999')], realname = 'irclibbot', nickname = 'irclibbot', ) assert len(bot.server_list) == 1 svr = bot.server_list[0] assert svr.host == 'localhost' assert svr.port == '9999' assert svr.password is None def test_namreply_no_channel(self): """ If channel is '*', _on_namreply should not crash. Regression test for #22 """ event = irc.client.Event(type=None, source=None, target=None, arguments=['*', '*', 'nick']) _on_namreply = six.get_unbound_function( irc.bot.SingleServerIRCBot._on_namreply) _on_namreply(None, None, event) python-irc-8.5.3+dfsg/irc/tests/test_client.py000066400000000000000000000050321302547020000213410ustar00rootroot00000000000000from __future__ import print_function import itertools import time import pytest import mock import six import irc.client def test_version(): assert 'VERSION' in vars(irc.client) assert 'VERSION_STRING' in vars(irc.client) assert isinstance(irc.client.VERSION, tuple) assert irc.client.VERSION, "No VERSION detected." assert isinstance(irc.client.VERSION_STRING, six.string_types) @mock.patch('irc.connection.socket') def test_privmsg_sends_msg(socket_mod): server = irc.client.IRC().server() server.connect('foo', 6667, 'bestnick') # make sure the mock object doesn't have a write method or it will treat # it as an SSL connection and never call .send. del server.socket.write server.privmsg('#best-channel', 'You are great') server.socket.send.assert_called_with( b'PRIVMSG #best-channel :You are great\r\n') @mock.patch('irc.connection.socket') def test_privmsg_fails_on_embedded_carriage_returns(socket_mod): server = irc.client.IRC().server() server.connect('foo', 6667, 'bestnick') with pytest.raises(ValueError): server.privmsg('#best-channel', 'You are great\nSo are you') class TestHandlers(object): def test_handlers_same_priority(self): """ Two handlers of the same priority should still compare. """ handler1 = irc.client.PrioritizedHandler(1, lambda: None) handler2 = irc.client.PrioritizedHandler(1, lambda: 'other') assert not handler1 < handler2 assert not handler2 < handler1 class TestThrottler(object): def test_function_throttled(self): """ Ensure the throttler actually throttles calls. """ # set up a function to be called counter = itertools.count() # set up a version of `next` that is only called 30 times per second limited_next = irc.client.Throttler(next, 30) # for one second, call next as fast as possible deadline = time.time() + 1 while time.time() < deadline: limited_next(counter) # ensure the counter was advanced about 30 times assert 29 <= next(counter) <= 32 # ensure that another burst of calls after some idle period will also # get throttled time.sleep(1) deadline = time.time() + 1 counter = itertools.count() while time.time() < deadline: limited_next(counter) assert 29 <= next(counter) <= 32 def test_reconstruct_unwraps(self): """ The throttler should be re-usable - if one wants to throttle a function that's aready throttled, the original function should be used. """ wrapped = irc.client.Throttler(next, 30) wrapped_again = irc.client.Throttler(wrapped, 60) assert wrapped_again.func is next assert wrapped_again.max_rate == 60 python-irc-8.5.3+dfsg/irc/tests/test_schedule.py000066400000000000000000000032121302547020000216550ustar00rootroot00000000000000import time import random import datetime import pytest from irc import schedule def test_delayed_command_order(): """ delayed commands should be sorted by delay time """ null = lambda: None delays = [random.randint(0, 99) for x in range(5)] cmds = sorted([ schedule.DelayedCommand.after(delay, null) for delay in delays ]) assert [c.delay.seconds for c in cmds] == sorted(delays) def test_periodic_command_delay(): "A PeriodicCommand must have a positive, non-zero delay." with pytest.raises(ValueError) as exc_info: schedule.PeriodicCommand.after(0, None) assert str(exc_info.value) == test_periodic_command_delay.__doc__ def test_periodic_command_fixed_delay(): """ Test that we can construct a periodic command with a fixed initial delay. """ fd = schedule.PeriodicCommandFixedDelay.at_time( at = datetime.datetime.now(), delay = datetime.timedelta(seconds=2), function = lambda: None, ) assert fd.due() is True assert fd.next().due() is False class TestCommands(object): def test_delayed_command_from_timestamp(self): """ Ensure a delayed command can be constructed from a timestamp. """ t = time.time() do_nothing = lambda: None schedule.DelayedCommand.at_time(t, do_nothing) def test_command_at_noon(self): """ Create a periodic command that's run at noon every day. """ when = datetime.time(12,0) cmd = schedule.PeriodicCommandFixedDelay.daily_at(when, function=None) assert cmd.due() is False next_cmd = cmd.next() daily = datetime.timedelta(days=1) day_from_now = datetime.datetime.now() + daily two_days_from_now = day_from_now + daily assert day_from_now < next_cmd < two_days_from_now python-irc-8.5.3+dfsg/irc/util.py000066400000000000000000000021251302547020000166370ustar00rootroot00000000000000from __future__ import division, absolute_import import six # from jaraco.util.itertools def always_iterable(item): """ Given an object, always return an iterable. If the item is not already iterable, return a tuple containing only the item. >>> always_iterable([1,2,3]) [1, 2, 3] >>> always_iterable('foo') ('foo',) >>> always_iterable(None) (None,) >>> import itertools >>> numbers = itertools.count(10) >>> always_iterable(numbers) is numbers True """ if isinstance(item, six.string_types) or not hasattr(item, '__iter__'): item = item, return item def total_seconds(td): """ Python 2.7 adds a total_seconds method to timedelta objects. See http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds >>> import datetime >>> total_seconds(datetime.timedelta(hours=24)) 86400.0 """ try: result = td.total_seconds() except AttributeError: seconds = td.seconds + td.days * 24 * 3600 result = (td.microseconds + seconds * 10**6) / 10**6 return result python-irc-8.5.3+dfsg/pavement.py000066400000000000000000000022321302547020000167230ustar00rootroot00000000000000import os import platform import paver.easy import paver.setuputils from setup import setup_params paver.setuputils.setup(**setup_params) @paver.easy.task def upload_project_web(): """ Generate the project web page at sourceforge using the reStructuredText README. """ import docutils.core docutils.core.publish_file(source_path='README', destination_path='readme.html', writer_name='html') cmd = 'pscp' if platform.system() == 'Windows' else 'scp' paver.easy.sh('{cmd} readme.html web.sourceforge.net:' '/home/project-web/python-irclib/htdocs/index.html' .format(cmd=cmd)) os.remove('readme.html') @paver.easy.task @paver.easy.needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated" def upload_sf(): # this is the technique used to upload the dist to sourceforge raise NotImplementedError('code is not functional - just here for ' 'reference') scp = 'pscp' if platform.system() == 'Windows' else 'scp' sf_dest = 'frs.sourceforge.net:/home/frs/project/python-irclib' cmd = '{scp} dist/{name} {sf_dest}' python-irc-8.5.3+dfsg/scripts/000077500000000000000000000000001302547020000162225ustar00rootroot00000000000000python-irc-8.5.3+dfsg/scripts/dccreceive.py000066400000000000000000000043051302547020000206720ustar00rootroot00000000000000#! /usr/bin/env python # # Example program using irc.client. # # This program is free without restrictions; do anything you like with # it. # # Joel Rosdahl from __future__ import print_function import os import struct import sys import argparse import irc.client import irc.logging class DCCReceive(irc.client.SimpleIRCClient): def __init__(self): irc.client.SimpleIRCClient.__init__(self) self.received_bytes = 0 def on_ctcp(self, connection, event): args = event.arguments[1].split() if args[0] != "SEND": return self.filename = os.path.basename(args[1]) if os.path.exists(self.filename): print("A file named", self.filename,) print("already exists. Refusing to save it.") self.connection.quit() self.file = open(self.filename, "wb") peeraddress = irc.client.ip_numstr_to_quad(args[2]) peerport = int(args[3]) self.dcc = self.dcc_connect(peeraddress, peerport, "raw") def on_dccmsg(self, connection, event): data = event.arguments[0] self.file.write(data) self.received_bytes = self.received_bytes + len(data) self.dcc.send_bytes(struct.pack("!I", self.received_bytes)) def on_dcc_disconnect(self, connection, event): self.file.close() print("Received file %s (%d bytes)." % (self.filename, self.received_bytes)) self.connection.quit() def on_disconnect(self, connection, event): sys.exit(0) def get_args(): parser = argparse.ArgumentParser( description="Receive a single file to the current directory via DCC " "and then exit.", ) parser.add_argument('server') parser.add_argument('nickname') parser.add_argument('-p', '--port', default=6667, type=int) irc.logging.add_arguments(parser) return parser.parse_args() def main(): args = get_args() irc.logging.setup(args) c = DCCReceive() try: c.connect(args.server, args.port, args.nickname) except irc.client.ServerConnectionError as x: print(x) sys.exit(1) c.start() if __name__ == "__main__": main() python-irc-8.5.3+dfsg/scripts/dccsend.py000066400000000000000000000051261302547020000202030ustar00rootroot00000000000000#! /usr/bin/env python # # Example program using irc.client. # # This program is free without restrictions; do anything you like with # it. # # Joel Rosdahl import os import struct import sys import argparse import irc.client import irc.logging class DCCSend(irc.client.SimpleIRCClient): def __init__(self, receiver, filename): irc.client.SimpleIRCClient.__init__(self) self.receiver = receiver self.filename = filename self.filesize = os.path.getsize(self.filename) self.file = open(filename, 'rb') self.sent_bytes = 0 def on_welcome(self, connection, event): self.dcc = self.dcc_listen("raw") self.connection.ctcp("DCC", self.receiver, "SEND %s %s %d %d" % ( os.path.basename(self.filename), irc.client.ip_quad_to_numstr(self.dcc.localaddress), self.dcc.localport, self.filesize)) def on_dcc_connect(self, connection, event): if self.filesize == 0: self.dcc.disconnect() return self.send_chunk() def on_dcc_disconnect(self, connection, event): print("Sent file %s (%d bytes)." % (self.filename, self.filesize)) self.connection.quit() def on_dccmsg(self, connection, event): acked = struct.unpack("!I", event.arguments[0])[0] if acked == self.filesize: self.dcc.disconnect() self.connection.quit() elif acked == self.sent_bytes: self.send_chunk() def on_disconnect(self, connection, event): sys.exit(0) def on_nosuchnick(self, connection, event): print("No such nickname:", event.arguments[0]) self.connection.quit() def send_chunk(self): data = self.file.read(1024) self.dcc.send_bytes(data) self.sent_bytes = self.sent_bytes + len(data) def get_args(): parser = argparse.ArgumentParser( description="Send to via DCC and then exit.", ) parser.add_argument('server') parser.add_argument('nickname') parser.add_argument('receiver', help="the nickname to receive the file") parser.add_argument('filename') parser.add_argument('-p', '--port', default=6667, type=int) irc.logging.add_arguments(parser) return parser.parse_args() def main(): args = get_args() irc.logging.setup(args) c = DCCSend(args.receiver, args.filename) try: c.connect(args.server, args.port, args.nickname) except irc.client.ServerConnectionError as x: print(x) sys.exit(1) c.start() if __name__ == "__main__": main() python-irc-8.5.3+dfsg/scripts/irccat.py000066400000000000000000000032701302547020000200430ustar00rootroot00000000000000#! /usr/bin/env python # # Example program using irc.client. # # This program is free without restrictions; do anything you like with # it. # # Joel Rosdahl import sys import argparse import itertools import irc.client import irc.logging target = None "The nick or channel to which to send messages" def on_connect(connection, event): if irc.client.is_channel(target): connection.join(target) return main_loop(connection) def on_join(connection, event): main_loop(connection) def get_lines(): while True: yield sys.stdin.readline().strip() def main_loop(connection): for line in itertools.takewhile(bool, get_lines()): print(line) connection.privmsg(target, line) connection.quit("Using irc.client.py") def on_disconnect(connection, event): raise SystemExit() def get_args(): parser = argparse.ArgumentParser() parser.add_argument('server') parser.add_argument('nickname') parser.add_argument('target', help="a nickname or channel") parser.add_argument('-p', '--port', default=6667, type=int) irc.logging.add_arguments(parser) return parser.parse_args() def main(): global target args = get_args() irc.logging.setup(args) target = args.target client = irc.client.IRC() try: c = client.server().connect(args.server, args.port, args.nickname) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1) c.add_global_handler("welcome", on_connect) c.add_global_handler("join", on_join) c.add_global_handler("disconnect", on_disconnect) client.process_forever() if __name__ == '__main__': main() python-irc-8.5.3+dfsg/scripts/irccat2.py000066400000000000000000000031021302547020000201170ustar00rootroot00000000000000#! /usr/bin/env python # # Example program using irc.client. # # This program is free without restrictions; do anything you like with # it. # # Joel Rosdahl import irc.client import sys class IRCCat(irc.client.SimpleIRCClient): def __init__(self, target): irc.client.SimpleIRCClient.__init__(self) self.target = target def on_welcome(self, connection, event): if irc.client.is_channel(self.target): connection.join(self.target) else: self.send_it() def on_join(self, connection, event): self.send_it() def on_disconnect(self, connection, event): sys.exit(0) def send_it(self): while 1: line = sys.stdin.readline().strip() if not line: break self.connection.privmsg(self.target, line) self.connection.quit("Using irc.client.py") def main(): if len(sys.argv) != 4: print("Usage: irccat2 ") print("\ntarget is a nickname or a channel.") sys.exit(1) s = sys.argv[1].split(":", 1) server = s[0] if len(s) == 2: try: port = int(s[1]) except ValueError: print("Error: Erroneous port.") sys.exit(1) else: port = 6667 nickname = sys.argv[2] target = sys.argv[3] c = IRCCat(target) try: c.connect(server, port, nickname) except irc.client.ServerConnectionError as x: print(x) sys.exit(1) c.start() if __name__ == "__main__": main() python-irc-8.5.3+dfsg/scripts/servermap.py000066400000000000000000000110761302547020000206050ustar00rootroot00000000000000#! /usr/bin/env python # # Example program using irc.client. # # Copyright (C) 1999-2002 Joel Rosdahl # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Joel Rosdahl # # servermap connects to an IRC server and finds out what other IRC # servers there are in the net and prints a tree-like map of their # interconnections. # # Example: # # % ./servermap irc.dal.net somenickname # Connecting to server... # Getting links... # # 26 servers (18 leaves and 8 hubs) # # splitrock.tx.us.dal.net # `-vader.ny.us.dal.net # |-twisted.ma.us.dal.net # |-sodre.nj.us.dal.net # |-glass.oh.us.dal.net # |-distant.ny.us.dal.net # | |-algo.se.eu.dal.net # | | |-borg.se.eu.dal.net # | | | `-ced.se.eu.dal.net # | | |-viking.no.eu.dal.net # | | |-inco.fr.eu.dal.net # | | |-paranoia.se.eu.dal.net # | | |-gaston.se.eu.dal.net # | | | `-powertech.no.eu.dal.net # | | `-algo-u.se.eu.dal.net # | |-philly.pa.us.dal.net # | |-liberty.nj.us.dal.net # | `-jade.va.us.dal.net # `-journey.ca.us.dal.net # |-ion.va.us.dal.net # |-dragons.ca.us.dal.net # |-toronto.on.ca.dal.net # | `-netropolis-r.uk.eu.dal.net # | |-traced.de.eu.dal.net # | `-lineone.uk.eu.dal.net # `-omega.ca.us.dal.net import irc.client import sys def on_connect(connection, event): sys.stdout.write("\nGetting links...") sys.stdout.flush() connection.links() def on_passwdmismatch(connection, event): print("Password required.") sys.exit(1) def on_links(connection, event): global links links.append((event.arguments[0], event.arguments[1], event.arguments[2])) def on_endoflinks(connection, event): global links print("\n") m = {} for (to_node, from_node, desc) in links: if from_node != to_node: m[from_node] = m.get(from_node, []) + [to_node] if connection.get_server_name() in m: if len(m[connection.get_server_name()]) == 1: hubs = len(m) - 1 else: hubs = len(m) else: hubs = 0 print("%d servers (%d leaves and %d hubs)\n" % (len(links), len(links)-hubs, hubs)) print_tree(0, [], connection.get_server_name(), m) connection.quit("Using irc.client.py") def on_disconnect(connection, event): sys.exit(0) def indent_string(level, active_levels, last): if level == 0: return "" s = "" for i in range(level-1): if i in active_levels: s = s + "| " else: s = s + " " if last: s = s + "`-" else: s = s + "|-" return s def print_tree(level, active_levels, root, map, last=0): sys.stdout.write(indent_string(level, active_levels, last) + root + "\n") if root in map: list = map[root] for r in list[:-1]: print_tree(level+1, active_levels[:]+[level], r, map) print_tree(level+1, active_levels[:], list[-1], map, 1) def main(): global links if len(sys.argv) != 3: print("Usage: servermap ") sys.exit(1) links = [] s = sys.argv[1].split(":", 1) server = s[0] if len(s) == 2: try: port = int(s[1]) except ValueError: print("Error: Erroneous port.") sys.exit(1) else: port = 6667 nickname = sys.argv[2] client = irc.client.IRC() sys.stdout.write("Connecting to server...") sys.stdout.flush() try: c = client.server().connect(server, port, nickname) except irc.client.ServerConnectionError as x: print(x) sys.exit(1) c.add_global_handler("welcome", on_connect) c.add_global_handler("passwdmismatch", on_passwdmismatch) c.add_global_handler("links", on_links) c.add_global_handler("endoflinks", on_endoflinks) c.add_global_handler("disconnect", on_disconnect) client.process_forever() if __name__ == '__main__': main() python-irc-8.5.3+dfsg/scripts/ssl-cat.py000066400000000000000000000034301302547020000201420ustar00rootroot00000000000000#! /usr/bin/env python # # Example program using irc.client for SSL connections. # # This program is free without restrictions; do anything you like with # it. # # Jason R. Coombs import sys import ssl import argparse import itertools import irc.client target = None "The nick or channel to which to send messages" def on_connect(connection, event): if irc.client.is_channel(target): connection.join(target) return main_loop(connection) def on_join(connection, event): main_loop(connection) def get_lines(): while True: yield sys.stdin.readline().strip() def main_loop(connection): for line in itertools.takewhile(bool, get_lines()): print(line) connection.privmsg(target, line) connection.quit("Using irc.client.py") def on_disconnect(connection, event): raise SystemExit() def get_args(): parser = argparse.ArgumentParser() parser.add_argument('server') parser.add_argument('nickname') parser.add_argument('target', help="a nickname or channel") parser.add_argument('-p', '--port', default=6667, type=int) return parser.parse_args() def main(): global target args = get_args() target = args.target ssl_factory = irc.connection.Factory(ssl.wrap_socket) client = irc.client.IRC() try: c = client.server().connect( args.server, args.port, args.nickname, connect_factory=ssl_factory, ) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1) c.add_global_handler("welcome", on_connect) c.add_global_handler("join", on_join) c.add_global_handler("disconnect", on_disconnect) client.process_forever() if __name__ == '__main__': main() python-irc-8.5.3+dfsg/scripts/testbot.py000066400000000000000000000067551302547020000202750ustar00rootroot00000000000000#! /usr/bin/env python # # Example program using irc.bot. # # Joel Rosdahl """A simple example bot. This is an example bot that uses the SingleServerIRCBot class from irc.bot. The bot enters a channel and listens for commands in private messages and channel traffic. Commands in channel messages are given by prefixing the text by the bot name followed by a colon. It also responds to DCC CHAT invitations and echos data sent in such sessions. The known commands are: stats -- Prints some channel information. disconnect -- Disconnect the bot. The bot will try to reconnect after 60 seconds. die -- Let the bot cease to exist. dcc -- Let the bot invite you to a DCC CHAT connection. """ import irc.bot import irc.strings from irc.client import ip_numstr_to_quad, ip_quad_to_numstr class TestBot(irc.bot.SingleServerIRCBot): def __init__(self, channel, nickname, server, port=6667): irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) self.channel = channel def on_nicknameinuse(self, c, e): c.nick(c.get_nickname() + "_") def on_welcome(self, c, e): c.join(self.channel) def on_privmsg(self, c, e): self.do_command(e, e.arguments[0]) def on_pubmsg(self, c, e): a = e.arguments[0].split(":", 1) if len(a) > 1 and irc.strings.lower(a[0]) == irc.strings.lower(self.connection.get_nickname()): self.do_command(e, a[1].strip()) return def on_dccmsg(self, c, e): c.privmsg("You said: " + e.arguments[0]) def on_dccchat(self, c, e): if len(e.arguments) != 2: return args = e.arguments[1].split() if len(args) == 4: try: address = ip_numstr_to_quad(args[2]) port = int(args[3]) except ValueError: return self.dcc_connect(address, port) def do_command(self, e, cmd): nick = e.source.nick c = self.connection if cmd == "disconnect": self.disconnect() elif cmd == "die": self.die() elif cmd == "stats": for chname, chobj in self.channels.items(): c.notice(nick, "--- Channel statistics ---") c.notice(nick, "Channel: " + chname) users = chobj.users() users.sort() c.notice(nick, "Users: " + ", ".join(users)) opers = chobj.opers() opers.sort() c.notice(nick, "Opers: " + ", ".join(opers)) voiced = chobj.voiced() voiced.sort() c.notice(nick, "Voiced: " + ", ".join(voiced)) elif cmd == "dcc": dcc = self.dcc_listen() c.ctcp("DCC", nick, "CHAT chat %s %d" % ( ip_quad_to_numstr(dcc.localaddress), dcc.localport)) else: c.notice(nick, "Not understood: " + cmd) def main(): import sys if len(sys.argv) != 4: print("Usage: testbot ") sys.exit(1) s = sys.argv[1].split(":", 1) server = s[0] if len(s) == 2: try: port = int(s[1]) except ValueError: print("Error: Erroneous port.") sys.exit(1) else: port = 6667 channel = sys.argv[2] nickname = sys.argv[3] bot = TestBot(channel, nickname, server, port) bot.start() if __name__ == "__main__": main() python-irc-8.5.3+dfsg/setup.cfg000066400000000000000000000002621302547020000163540ustar00rootroot00000000000000[pytest] addopts = --doctest-modules --ignore=setup.py --ignore=pavement.py norecursedirs = *.egg build [egg_info] tag_svn_revision = 0 tag_date = 0 tag_build = 8.5.3 python-irc-8.5.3+dfsg/setup.py000066400000000000000000000025251302547020000162510ustar00rootroot00000000000000import sys import setuptools def read_long_description(): with open('README.rst') as f: data = f.read() with open('CHANGES.rst') as f: data += '\n\n' + f.read() return data importlib_req = ['importlib'] if sys.version_info < (2,7) else [] argparse_req = ['argparse'] if sys.version_info < (2,7) else [] setup_params = dict( name="irc", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), use_hg_version=True, packages=setuptools.find_packages(), author="Joel Rosdahl", author_email="joel@rosdahl.net", maintainer="Jason R. Coombs", maintainer_email="jaraco@jaraco.com", url="http://python-irclib.sourceforge.net", license="MIT", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], install_requires=[ 'six', ] + importlib_req + argparse_req, setup_requires=[ 'hgtools', 'pytest-runner', ], tests_require=[ 'pytest', 'mock', ], ) if __name__ == '__main__': setuptools.setup(**setup_params)