[
  {
    "path": ".coveragerc",
    "content": "[run]\ninclude =\n    */irc3/*.py\n    */irc3/*/*.py\nomit =\n    conftest.py\n    .tox/*\n    tests/*\n    docs/conf.py\n    */examples/social*\n    */examples/mycrons*\n    */examples/mycommands*\n    */examples/myextends*\n    */examples/nickserv*\n    */examples/freenode*\n    */irc3/template/plugin*\n    */irc3/_gen_doc*\n    */irc3/_parse_rfc*\n    */site-packages*\n    */lib/python*\n    */lib-python*\n    */lib_pypy*\n\n[report]\nexclude_lines =\n    pragma: no cover\n    def __repr__\n    raise NotImplementedError\n    if __name__ == .__main__.:\n    def parse_args\n"
  },
  {
    "path": ".github/workflows/tox.yml",
    "content": "name: tox\n\non: [push, pull_request]\n\njobs:\n  flake8-and-docs:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - name: Setup Python\n        uses: actions/setup-python@v4\n        with:\n          python-version: 3.12\n      - name: Install Tox and any other packages\n        run: pip install tox\n      - name: Run flake8 / docs\n        run: tox -e flake8,docs\n\n  test:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python: [\"3.11\", \"3.12\", \"3.13\"]\n\n    steps:\n      - uses: actions/checkout@v4\n      - name: Setup Python\n        uses: actions/setup-python@v4\n        with:\n          python-version: ${{ matrix.python }}\n      - name: Start Redis\n        uses: supercharge/redis-github-action@1.8.1\n        with:\n          redis-version: 8\n      - name: Install Tox and any other packages\n        run: pip install tox\n      - name: Run Tox\n        run: tox -e py\n"
  },
  {
    "path": ".gitignore",
    "content": "*~\n*.bck\nbin\nbuild\n_build\n.bzr\n.bzrignore\n.eggs\n.cache\n.chutifab\n.coverage\ncoverage*\ndevelop-eggs\ndist\ndownloads\n*.egg\n*.EGG\n*.egg-info\n*.EGG-INFO\neggs\nfake-eggs\n.hg\n.hgignore\n.idea\n.installed.cfg\nirssi_config\n*.jar\n*.mo\n.mr.developer.cfg\nnosetest*\n*.old\n*.orig\nparts\n*.pyc\n*.pyd\n*.pyo\n.ropeproject/\n*.so\nsrc\n.svn\n*.swp\n.tox\n*.tmp*\nvar\n*.wpr\n"
  },
  {
    "path": "CHANGES.rst",
    "content": "1.1.11 (unreleased)\n===================\n\n- Nothing changed yet.\n\n\n1.1.10 (2023-04-17)\n===================\n\n- fix `shell_command` plugin\n\n\n1.1.9 (2023-02-27)\n==================\n\n- drop support for python 3.5\n\n- python 3.11 compat\n\n\n1.1.8 (2022-07-17)\n==================\n\n- Allow comma-separated chans in server userlist JOIN\n\n- python 3.10 compat\n\n- improve feeds plugin\n\n\n1.1.7 (2021-02-13)\n==================\n\n- Add sqlite storage.\n\n- Escape string that are interpolated into the regular expressions.\n\n\n1.1.6 (2020-05-13)\n==================\n\n- Allow to overrides config values via `os.environ`.\n\n\n1.1.5 (2020-01-18)\n==================\n\n- Allow to use `irc3.rfc.*` as `iotype='out'`\n\n- Use more pop in userlist to avoid bug when a weird event occurs\n\n1.1.4 (2019-11-22)\n==================\n\n- Use pop in userlist to avoid bug when a weird event occurs\n\n- Expend filename path in logger plugin\n\n- Force latest venusian version\n\n\n1.1.3 (2019-08-22)\n==================\n\n- Rename async plugin to asynchronious so we can use it with python3.7\n\n\n1.1.2 (2019-02-28)\n==================\n\n- Allow to have more than one `[bot]` section in config file\n\n- IrcString now allow to retrieve username/hostname from mask\n\n\n1.1.1 (2018-09-22)\n==================\n\n- Do not show builtins command in help. Fixed #167\n\n\n1.1.0 (2018-07-30)\n==================\n\n- Backward incompatibility: async is renamed to asynchronous for py37 compat\n  (thanks to @JulienPalard)\n\n- Except a KeyError on missing twitter configuration in social plugin\n\n1.0.3 (2018-05-08)\n==================\n\n- Add web plugin to allow to POST messages to channel via http\n\n- Add slack plugin\n\n- Avoid bug in userlist when a user parts before join (twitch)\n\n- Drop py33, py34 support\n\n1.0.2 (2017-11-13)\n==================\n\n- Add `irc3.__main__` to allow `python -m irc3 config.ini`\n\n\n1.0.1 (2017-11-11)\n==================\n\n- Add `command(error_format=callable)` argument.\n\n- Add ${#} as a shorter alias for ${hash}.\n\n- Bug fix in fifo plugin. We now remove the file first if it's not a pipe.\n\n- Fix some irc3d issues with QUIT and KICK command\n\n\n1.0.0 (2017-02-05)\n==================\n\n- Added storage.getlist()/setlist()\n\n- Improve autocommands\n\n\n0.9.8 (2017-01-03)\n==================\n\n- Command aliases support (#121)\n\n- Add quakenet plugin (#99)\n\n- Allow dash character in command\n\n\n0.9.7 (2016-12-07)\n==================\n\n- Added ``bot.async_cmds.topic()``\n\n- Use shlex to parse command args by default\n\n\n0.9.6 (2016-10-24)\n==================\n\n- Fixed #118: ssl context.check_hostname must be False when using CERT_NONE\n\n\n0.9.5 (2016-10-15)\n==================\n\n- ``.privmsg(nowait=True)`` now really don't wait\n\n- clean up some old py2/3 compat code\n\n0.9.4 (2016-09-15)\n==================\n\n- Added SASL Auth support\n\n0.9.3 (2016-05-31)\n==================\n\n- New release due to release problem (broken pypi)\n\n\n0.9.2 (2016-05-31)\n==================\n\n- Fixed flood_burst sending one extra line (#92)\n\n0.9.1 (2016-05-22)\n==================\n\n- Added autojoin_delay option. Handle reload in autojoin plugin.\n\n- Added flood_rate_delay option.\n\n- Added --help and --version CLI options.\n\n- Fixed #91 bug with command arguments and spaces\n\n0.9.0 (2016-04-20)\n==================\n\n- WARNING: we do no longer support python2. python3.3+ is required.\n\n- WARNING: realname is now username and userinfo is now realname in config\n\n- Introduce some plugins: fifo, shell_commands, pager\n\n- Add ``flood_burst`` and ``flood_rate`` options. Queue outgoing messages in a\n  single queue handle by ``send_line('...', nowait=False)``.\n\n- ``bot.async`` is now aliased to ``bot.async_cmds`` to be able to use ``await``\n\n0.8.9 (2016-02-23)\n==================\n\n- use re.escape to escape command char\n\n\n0.8.8 (2016-01-27)\n==================\n\n- logger plugin now take care of unicode\n\n\n0.8.7 (2016-01-16)\n==================\n\n- fixed 76: split large messages using textwrap.wrap(). This will avoid RevQ\n  exceeded.\n\n\n0.8.6 (2016-01-07)\n==================\n\n- fix DCC stuff for python3.5\n\n- added DCC examples at https://github.com/gawel/irc3/tree/master/examples\n\n\n0.8.5 (2015-12-22)\n==================\n\n-  ${hash} is now replaced by # in config files. This allow to set real channel\n   names.\n\n\n0.8.4 (2015-11-29)\n==================\n\n- added basic support for IRCv3.2 tags\n\n- fixed #78: plugin can be old style classes\n\n- fixed #75: Ensure we send the PING and PONG data as trailing\n\n- fixed #71: need to pass host and ip to dcc\n\n\n0.8.3 (2015-11-04)\n==================\n\n- fix wheel metadata\n\n- public command was not public if you're using a guard\n\n\n0.8.2 (2015-11-01)\n==================\n\n- Added !help nonexistant error message\n\n- Allow to hide commands from !help\n\n- Don't reject commands with trailing spaces\n\n- Allow to use coroutine guards\n\n- Make commands case insensitive\n\n- Add basic casefolding plugin\n\n- Prevent keyerror when setting keys that don't exist in cache.\n\n0.8.1 (2015-05-14)\n==================\n\n-  Fixes bug in userlist plugin `#59 <https://github.com/gawel/irc3/pull/59>`_\n\n-  Strip out self.context.config.cmd from !help arg. Allow to use !help !cmd\n   `#57 <https://github.com/gawel/irc3/pull/57>`_\n\n\n0.8.0 (2015-04-19)\n==================\n\n- Added dcc send/get/chat implementation\n\n- Improved storage: can now test the existence of a key\n\n- irc.plugins.storage: `db['foo']` now will raise a `KeyError` if the key does\n  not exist to match dictionary behaviour. This will **break** existing\n  implementations that make use of this.\n\n- irc.plugins.storage now supports `db.get(key)`  that will return either `None`\n  or the value of an optional `default` argument.\n\n- irc3.plugins.feeds is now full async\n\n\n0.7.1 (2015-02-26)\n==================\n\n- Storage plugin documentation\n\n- Support python 3.4.1 again\n\n\n0.7.0 (2015-02-24)\n==================\n\n- the cron plugin now require\n  `aiocron <https://pypi.python.org/pypi/aiocron/>`_\n\n- Add `irc3.plugins.async`; Allow to `yield from bot.async.whois('gawel')`\n\n- commands and events can now be coroutines\n\n\n0.6.0 (2015-02-15)\n==================\n\n- Allow to reload modules/plugins\n\n- Add storage plugin\n\n- Fixed #34 Avoid newline injection.\n\n\n0.5.3 (2014-12-09)\n==================\n\n- Bugfix release. Fixed #27 and #30\n\n\n0.5.2 (2014-11-16)\n==================\n\n- Basic irc3d server\n\n- Modules reorganisation\n\n- Add S3 logger\n\n\n0.5.1 (2014-07-21)\n==================\n\n- Fixed #13: venusian 1.0 compat\n\n- Add antiflood option for the command plugin\n\n- commands accept unicode\n\n\n0.5.0 (2014-06-01)\n==================\n\n- Added ``bot.kick()`` and ``bot.mode()``\n\n- Rewrite ctcp plugin so we can ignore flood requests\n\n- Trigger ``{plugin}.server_ready()`` at the end of MOTD\n\n- Fixed #9: The ``command`` plugin uses ``cmd``, not ``cmdchar``.\n\n- Fixed #10. Store server config. Use STATUSMSG config if any in ``userlist``\n\n- ``userlist`` plugin now also store user modes per channel.\n\n- Rename ``add_event`` to ``attach_events`` and added ``detach_events``. This\n  allow to add/remove events on the fly.\n\n- The autojoin plugin now detach motd related events after triggering one of\n  them.\n\n- Fix compatibility with trollius 0.3\n\n\n0.4.10 (2014-05-21)\n===================\n\n- Fixed #5: autojoin on no motd\n\n- allow to show date/times in console log\n\n\n0.4.9 (2014-05-08)\n==================\n\n- Allow to trigger event on output with ``event(iotype='out')``\n\n- Add a channel logger plugin\n\n- autojoins is now a separate plugin\n\n- userlist plugin take care of kicks\n\n- social plugin is now officially supported and tested\n\n\n0.4.7 (2014-04-03)\n==================\n\n- IrcString use unicode with py2\n\n\n0.4.6 (2014-03-11)\n==================\n\n- Bug fix. The cron need a loop sooner as possible.\n\n\n0.4.5 (2014-02-25)\n==================\n\n- Bug fix. An event was run twice if more than one where using the same regexp\n\n\n0.4.4 (2014-02-15)\n==================\n\n- Add cron plugin\n\n- Improve the command plugin. Fix some security issue.\n\n- Add ``--help-page`` option to generate commands help pages\n\n\n0.4.3 (2014-01-10)\n==================\n\n- Fix a bug on connection_lost.\n\n- Send realname in USER command instead of nickname\n\n\n0.4.2 (2014-01-09)\n==================\n\n- python2.7 support.\n\n- add some plugins (ctcp, uptime, feeds, search)\n\n- add some examples/ (twitter, asterisk)\n\n- improve some internals\n\n0.4.1 (2013-12-30)\n==================\n\n- Depends on venusian 1.0a8\n\n\n0.1 (2013-11-30)\n================\n\n- Initial release\n"
  },
  {
    "path": "CONTRIBUTING.rst",
    "content": "Contribute\n==========\n\nFirst, if you want to add a cool plugin, consider submit a pull request to the\n`irc3_plugins <https://github.com/gawel/irc3_plugins>`_ instead of irc3 itself.\n\n\nFeel free to clone the project on `GitHub <https://github.com/gawel/irc3>`_.\n\nTo test your change you can run irc3 in debug mode using::\n\n    $ irc3 --debug path-to-your-conf.ini\n\nOnce you made a change, try to add a test for your feature/fix. At least assume\nthat you have'nt broke anything by running tox::\n\n    $ tox\n    ...\n    py27: commands succeeded\n    py32: commands succeeded\n    py33: commands succeeded\n    py34: commands succeeded\n    flake8: commands succeeded\n    docs: commands succeeded\n    congratulations :)\n\n You can run tests for a specific version::\n\n    $ tox -e py34\n\nThe `irc3.rfc` module is auto generated from `irc3/rfc1459.txt`. If you want to\nhack this file, you need to hack the parser in `irc3/_parse_rfc.py` (warning,\nit's ugly)\n\nYou can regenerate the module and docs by running::\n\n    $ tox -e build\n\nYou can also build the docs with::\n\n    $ tox -e docs\n\nAnd check the result::\n\n    $ firefox .tox/docs/tmp/html/index.html\n\nThe project uses ``setuptools``, you can test-install it using `pip`:\n\n    $ pip install .\n    $ irc3 -h\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2016 Gael Pasgrimaud\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "graft docs\nprune docs/_build\nprune .github/\ngraft examples\ngraft irc3\ngraft irc3d\ngraft tests\ninclude Makefile *.rst *.cfg *.ini *.txt\nglobal-exclude *.pyc *.swp\nglobal-exclude __pycache__\ninclude conftest.py\nexclude .installed.cfg\nexclude .coveragerc\nexclude update.sh\nexclude Dockerfile\nexclude docker\nexclude docker/Dockerfile\nexclude docker/Makefile\ninclude LICENSE\n"
  },
  {
    "path": "Makefile",
    "content": "APP:=$(shell basename `pwd`)\nHOSTNAME:=$(shell hostname)\nHOST:=amandine\nPYTHON?=$(HOME)/.venvs/py3/bin/python3\n\nbuild:\n\tdocker build -t gawel/irc3 .\n\nvenv:\n\t $(PYTHON) -m venv venv\n\t./venv/bin/pip install -e .[test,web]\n\nrun: venv\n\t./venv/bin/irc3 config.ini\n\nupgrade: venv\nifeq ($(HOSTNAME), $(HOST))\n\tgit pull origin master\n\t~/apps/bin/circusctl restart $(APP)\nelse\n\tgit push origin master\n\tssh $(HOST) \"cd ~/apps/$(APP) && make upgrade\"\nendif\n\n\n"
  },
  {
    "path": "README.rst",
    "content": "============================================================\nirc3. pluggable irc client library based on python's asyncio\n============================================================\n\n.. image:: https://github.com/gawel/irc3/actions/workflows/tox.yml/badge.svg\n  :target: https://github.com/gawel/irc3/actions/workflows/tox.yml\n.. image:: https://coveralls.io/repos/gawel/irc3/badge.png?branch=master\n  :target: https://coveralls.io/r/gawel/irc3?branch=master\n\nA pluggable irc client library based on python's `asyncio\n<http://docs.python.org/dev/library/asyncio.html>`_.\n\n\n.. image:: https://raw.githubusercontent.com/gawel/irc3/master/docs/_static/logo.png\n   :width: 100\n   :height: 100\n   :align: center\n   :alt: Ceative Commons – Attribution (CC BY 3.0) - Hydra designed by Huu Nguyen from the Noun Project - http://thenounproject.com/term/hydra/46963/\n   :target: http://thenounproject.com/term/hydra/46963/\n\n\nRequires python 3.11+\n\nPython 2 is no longer supported, but if you don't have a choice you can use\nan older version::\n\n    $ pip install \"irc3<0.9\"\n\nSource: https://github.com/gawel/irc3/\n\nDocs: https://irc3.readthedocs.io/\n\nIrc: irc://irc.freenode.net/irc3 (`www\n<https://kiwiirc.com/client/irc.freenode.net/?nick=irc3|?&theme=basic#irc3>`_)\n\n\nI've spent hours writing this software, with love.\nPlease consider tipping if you like it:\n\nBTC: 1PruQAwByDndFZ7vTeJhyWefAghaZx9RZg\n\nETH: 0xb6418036d8E06c60C4D91c17d72Df6e1e5b15CE6\n\nLTC: LY6CdZcDbxnBX9GFBJ45TqVj8NykBBqsmT\n"
  },
  {
    "path": "conftest.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import testing\nimport pytest\nimport sys\nimport os\n\ntry:\n    from redis.exceptions import ConnectionError\n    from redis.client import StrictRedis\n    StrictRedis().flushdb()\nexcept (ImportError, ConnectionError):\n    import re\n    req_redis = re.compile(r\".*#[^#]*\\s*require?\\s*redis\\s*$\", re.IGNORECASE)\n\n    def pytest_runtest_setup(item):\n        if getattr(item, 'dtest', None):\n            if any(req_redis.match(e.source) for e in item.dtest.examples):\n                pytest.skip(\"No redis server is running\")\n\ndirname = os.path.dirname(__file__)\nsys.path.append(os.path.join(dirname, 'examples'))\n\n\n@pytest.fixture(scope=\"function\")\ndef cls_event_loop(request, event_loop):\n    request.cls.loop = event_loop\n    request.cls.config['loop'] = event_loop\n    yield\n    request.cls.config.pop('loop')\n\n\n@pytest.fixture(scope=\"function\")\ndef irc3_bot_factory(request, event_loop):\n    def _bot(**config):\n        config['loop'] = event_loop\n        _b['b'] = testing.IrcBot(**config)\n        return _b['b']\n    _b = {}\n    yield _bot\n    _b['b'].SIGINT()\n"
  },
  {
    "path": "docker/Dockerfile",
    "content": "FROM python:3.7\n\nRUN adduser --disabled-password --gecos '' irc3\n\nRUN echo build \\\n    && cd /usr/src && git clone https://github.com/gawel/irc3.git \\\n    && cd /usr/src/irc3 && pip install ipython && pip install -e .[test] \\\n    && mkdir -p /usr/src/bot && chown -R irc3:irc3 /usr/src/bot\n\nWORKDIR /usr/src/bot\n\nONBUILD COPY . /usr/src/bot\n\nUSER irc3\n\nCMD [\"/usr/local/bin/irc3\", \"config.ini\"]\n"
  },
  {
    "path": "docker/Makefile",
    "content": "build:\n\tdocker build --rm=true -f Dockerfile -t irc3:latest .\n\nrun:\n\tdocker run -v $(PWD)/../:/usr/src/bot -v $(HOME)/.irc3:/home/irc3/.irc3 irc3:latest irc3 examples/dev.ini\n"
  },
  {
    "path": "docs/Makefile",
    "content": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD   = ../bin/sphinx-build\nPAPER         =\nBUILDDIR      = _build\n\n# Internal variables.\nPAPEROPT_a4     = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n\n.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext\n\nhelp:\n\t@echo \"Please use \\`make <target>' where <target> is one of\"\n\t@echo \"  html       to make standalone HTML files\"\n\t@echo \"  dirhtml    to make HTML files named index.html in directories\"\n\t@echo \"  singlehtml to make a single large HTML file\"\n\t@echo \"  pickle     to make pickle files\"\n\t@echo \"  json       to make JSON files\"\n\t@echo \"  htmlhelp   to make HTML files and a HTML help project\"\n\t@echo \"  qthelp     to make HTML files and a qthelp project\"\n\t@echo \"  devhelp    to make HTML files and a Devhelp project\"\n\t@echo \"  epub       to make an epub\"\n\t@echo \"  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \"  latexpdf   to make LaTeX files and run them through pdflatex\"\n\t@echo \"  text       to make text files\"\n\t@echo \"  man        to make manual pages\"\n\t@echo \"  texinfo    to make Texinfo files\"\n\t@echo \"  info       to make Texinfo files and run them through makeinfo\"\n\t@echo \"  gettext    to make PO message catalogs\"\n\t@echo \"  changes    to make an overview of all changed/added/deprecated items\"\n\t@echo \"  linkcheck  to check all external links for integrity\"\n\t@echo \"  doctest    to run all doctests embedded in the documentation (if enabled)\"\n\nclean:\n\t-rm -rf $(BUILDDIR)/*\n\nhtml:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t      \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t      \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/irc3.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/irc3.qhc\"\n\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/irc3\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/irc3\"\n\t@echo \"# devhelp\"\n\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t      \"(use \\`make latexpdf' here to do that automatically).\"\n\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\ntexinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t      \"(use \\`make info' here to do that automatically).\"\n\ninfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\"\n\ngettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\"\n\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t      \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t      \"results in $(BUILDDIR)/doctest/output.txt.\"\n"
  },
  {
    "path": "docs/conf.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# irc3 documentation build configuration file, created by\n# sphinx-quickstart on Mon Nov 25 01:03:01 2013.\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nimport sys, os\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#sys.path.insert(0, os.path.abspath('.'))\n\n# -- General configuration -----------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be extensions\n# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.\nextensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix of source filenames.\nsource_suffix = '.rst'\n\n# The encoding of source files.\n#source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'irc3'\ncopyright = '2013, Gael Pasgrimaud'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = ''\n# The full version, including alpha/beta/rc tags.\nrelease = ''\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#language = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n#today = ''\n# Else, today_fmt is used as the format for a strftime call.\n#today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = ['_build']\n\n# The reST default role (used for this markup: `text`) to use for all documents.\n#default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n#add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n#add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n#show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# A list of ignored prefixes for module index sorting.\n#modindex_common_prefix = []\n\n\n# -- Options for HTML output ---------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\nhtml_theme = 'nature'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\n#html_theme_path = []\n\n# The name for this set of Sphinx documents.  If None, it defaults to\n# \"<project> v<release> documentation\".\n#html_title = None\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\n#html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n#html_logo = None\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n#html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it.  The value of this option must be the\n# base URL from which the finished HTML is served.\n#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'irc3doc'\n\n\n# -- Options for LaTeX output --------------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title, author, documentclass [howto/manual]).\nlatex_documents = [\n  ('index', 'irc3.tex', 'irc3 Documentation',\n   'Gael Pasgrimaud', 'manual'),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output --------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n    ('index', 'irc3', 'irc3 Documentation',\n     ['Gael Pasgrimaud'], 1)\n]\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n\n# -- Options for Texinfo output ------------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n  ('index', 'irc3', 'irc3 Documentation',\n   'Gael Pasgrimaud', 'irc3', 'One line description of project.',\n   'Miscellaneous'),\n]\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n\nfrom importlib.metadata import version\nversion = version(\"irc3\")\nrelease = version\n"
  },
  {
    "path": "docs/dcc.rst",
    "content": "========================\n:mod:`irc3.dcc` DCC\n========================\n\nSee :func:`~irc3.IrcBot.dcc_chat`, :func:`~irc3.IrcBot.dcc_get` and\n:func:`~irc3.IrcBot.dcc_send`\n\nHere is a simple plugin to send a generated file:\n\n.. literalinclude:: ../examples/dcc_send.py\n\nAPI\n===\n\n.. automodule:: irc3.dcc\n\n.. autoclass:: DCCManager\n  :members:\n\n.. autoclass:: DCCChat\n  :members:\n\n.. autoclass:: DCCSend\n  :members:\n\n.. autoclass:: DCCGet\n  :members:\n"
  },
  {
    "path": "docs/dec.rst",
    "content": "============================\n:mod:`irc3.dec` decorators\n============================\n\n.. automodule:: irc3.dec\n\nplugin\n======\n\n.. autofunction:: plugin\n\nbot event\n=========\n\n.. autoclass:: event\n\nbot extend\n==========\n\n.. autofunction:: extend\n"
  },
  {
    "path": "docs/hack.rst",
    "content": ".. include:: ../CONTRIBUTING.rst\n"
  },
  {
    "path": "docs/index.rst",
    "content": ".. include:: ../README.rst\n\nInstallation\n==============\n\nUsing pip::\n\n    $ pip install irc3\n\nQuick start\n===========\n\nirc3 provides a basic template to help you to quickly test a bot.\nHere is how to create a bot named ``mybot``.\n\nCreate a new directory and cd to it:\n\n.. code-block:: sh\n\n    $ mkdir mybot\n    $ cd mybot\n\nThen use the template:\n\n.. code-block:: sh\n\n    $ python -m irc3.template mybot\n\nThis will create an almost ready to use ``config.ini`` file and a simple\nplugin named ``mybot_plugin.py`` that says «Hi» when the bot or someone else joins a\nchannel and includes an ``echo`` command.\n\nHere is what the config file will looks like:\n\n.. literalinclude:: ../examples/config.ini\n   :language: ini\n\nAnd here is the plugin:\n\n.. literalinclude:: ../examples/mybot_plugin.py\n\nHave a look at those file and edit the config file for your needs.\nYou may have to edit:\n\n- the autojoin channel\n\n- your irc mask in the ``irc3.plugins.command.mask`` section\n\nOnce you're done with editing, run:\n\n.. code-block:: sh\n\n    $ irc3 config.ini\n\nCheck the help of the ``irc3`` command.\n\n.. code-block:: sh\n\n    $ irc3 -h\n\nIf you're enjoying it, you can check for more detailed docs below. And some\nmore examples here: https://github.com/gawel/irc3/tree/master/examples\n\nDocumentation\n=============\n\n.. toctree::\n   :maxdepth: 2\n   :glob:\n\n   dec\n   utils\n   rfc\n   dcc\n   reloadable\n   plugins/*\n   hack\n\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\n"
  },
  {
    "path": "docs/irc3.rst",
    "content": "\n============================\n:mod:`irc3` Irc bot\n============================\n\n.. automodule:: irc3\n\nIrcBot\n======\n\n.. autoclass:: IrcBot\n   :members:\n   :inherited-members:\n\n    .. autoattribute:: defaults\n\nIrcConnection\n=============\n\n.. autoclass:: IrcConnection\n   :members:\n"
  },
  {
    "path": "docs/plugins/asynchronious.rst",
    "content": ".. automodule:: irc3.plugins.asynchronious\n\n"
  },
  {
    "path": "docs/plugins/autocommand.rst",
    "content": ".. automodule:: irc3.plugins.autocommand\n\n"
  },
  {
    "path": "docs/plugins/autojoins.rst",
    "content": ".. automodule:: irc3.plugins.autojoins\n\n"
  },
  {
    "path": "docs/plugins/casefold.rst",
    "content": ".. automodule:: irc3.plugins.casefold\n\n"
  },
  {
    "path": "docs/plugins/command.rst",
    "content": ".. automodule:: irc3.plugins.command\n\n"
  },
  {
    "path": "docs/plugins/core.rst",
    "content": ".. automodule:: irc3.plugins.core\n\n"
  },
  {
    "path": "docs/plugins/cron.rst",
    "content": ".. automodule:: irc3.plugins.cron\n\n"
  },
  {
    "path": "docs/plugins/ctcp.rst",
    "content": ".. automodule:: irc3.plugins.ctcp\n\n"
  },
  {
    "path": "docs/plugins/dcc.rst",
    "content": ".. automodule:: irc3.plugins.dcc\n\n"
  },
  {
    "path": "docs/plugins/feeds.rst",
    "content": ".. automodule:: irc3.plugins.feeds\n\n"
  },
  {
    "path": "docs/plugins/fifo.rst",
    "content": ".. automodule:: irc3.plugins.fifo\n\n"
  },
  {
    "path": "docs/plugins/human.rst",
    "content": ".. automodule:: irc3.plugins.human\n\n"
  },
  {
    "path": "docs/plugins/log.rst",
    "content": ".. automodule:: irc3.plugins.log\n\n"
  },
  {
    "path": "docs/plugins/logger.rst",
    "content": ".. automodule:: irc3.plugins.logger\n\n"
  },
  {
    "path": "docs/plugins/pager.rst",
    "content": ".. automodule:: irc3.plugins.pager\n\n"
  },
  {
    "path": "docs/plugins/quakenet.rst",
    "content": ".. automodule:: irc3.plugins.quakenet\n\n"
  },
  {
    "path": "docs/plugins/sasl.rst",
    "content": ".. automodule:: irc3.plugins.sasl\n\n"
  },
  {
    "path": "docs/plugins/search.rst",
    "content": ".. automodule:: irc3.plugins.search\n\n"
  },
  {
    "path": "docs/plugins/shell_command.rst",
    "content": ".. automodule:: irc3.plugins.shell_command\n\n"
  },
  {
    "path": "docs/plugins/slack.rst",
    "content": ".. automodule:: irc3.plugins.slack\n\n"
  },
  {
    "path": "docs/plugins/social.rst",
    "content": ".. automodule:: irc3.plugins.social\n\n"
  },
  {
    "path": "docs/plugins/storage.rst",
    "content": ".. automodule:: irc3.plugins.storage\n\n"
  },
  {
    "path": "docs/plugins/uptime.rst",
    "content": ".. automodule:: irc3.plugins.uptime\n\n"
  },
  {
    "path": "docs/plugins/userlist.rst",
    "content": ".. automodule:: irc3.plugins.userlist\n\n"
  },
  {
    "path": "docs/plugins/web.rst",
    "content": ".. automodule:: irc3.plugins.web\n\n"
  },
  {
    "path": "docs/reloadable.rst",
    "content": "Reloadable plugins\n==================\n\n.. note:: if you just want the bot to restart when you change a file during\n    development you can use `hupper <https://pypi.python.org/pypi/huppe>`_::\n\n    $ pip install hupper\n    $ hupper -m irc3 config.ini\n\nirc3 provides a way to reload plugins without restarting the bot.\n\nTo do that, your plugin should provide a ``reload`` class method::\n\n    class Plugin(object):\n\n        def __init__(self, bot):\n            self.bot = bot\n\n        @classmethod\n        def reload(cls, old):\n            \"\"\"this method should return a ready to use plugin instance.\n            cls is the newly reloaded class. old is the old instance.\n            \"\"\"\n            return cls(old.bot)\n\nPlugins can also implement a few hooks to help take care of reloads::\n\n    class Plugin(object):\n\n        def __init__(self, bot):\n            self.bot = bot\n\n        def before_reload(self):\n            \"\"\"Do stuff before reload\"\"\"\n\n        def after_reload(self):\n            \"\"\"Do stuff after reload\"\"\"\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> bot = IrcBot(includes=['mycommands'])\n\nTo reload a plugin, just call the :func:`~irc3.IrcBot.reload` method with\nmodule name(s) to reload::\n\n    >>> bot.reload('mycommands')\n"
  },
  {
    "path": "docs/rfc.rst",
    "content": "========================\n:mod:`irc3.rfc` RFC1459\n========================\n\nReplies (REPL)\n==============\n\n259 - RPL_ADMINEMAIL\n--------------------\n\nFormat ``:{srv} 259 {nick} :{admin_info}``\n\nMatch ``^:(?P<srv>\\S+) 259 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ADMINEMAIL)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n257 - RPL_ADMINLOC1\n-------------------\n\nFormat ``:{srv} 257 {nick} :{admin_info}``\n\nMatch ``^:(?P<srv>\\S+) 257 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ADMINLOC1)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n258 - RPL_ADMINLOC2\n-------------------\n\nFormat ``:{srv} 258 {nick} :{admin_info}``\n\nMatch ``^:(?P<srv>\\S+) 258 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ADMINLOC2)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n256 - RPL_ADMINME\n-----------------\n\nFormat ``:{srv} 256 {nick} {server} :Administrative info``\n\nMatch ``^:(?P<srv>\\S+) 256 (?P<me>\\S+) (?P<server>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ADMINME)\n    def myevent(bot, srv=None, me=None, server=None, data=None):\n        # do something\n\n301 - RPL_AWAY\n--------------\n\nFormat ``:{srv} 301 {nick} {nick} :{away_message}``\n\nMatch ``^:(?P<srv>\\S+) 301 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_AWAY)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n367 - RPL_BANLIST\n-----------------\n\nFormat ``:{srv} 367 {nick} {channel} {banid}``\n\nMatch ``^:(?P<srv>\\S+) 367 (?P<me>\\S+) (?P<channel>\\S+) (?P<banid>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_BANLIST)\n    def myevent(bot, srv=None, me=None, channel=None, banid=None):\n        # do something\n\n324 - RPL_CHANNELMODEIS\n-----------------------\n\nFormat ``:{srv} 324 {nick} {channel} {mode} {mode_params}``\n\nMatch ``^:(?P<srv>\\S+) 324 (?P<me>\\S+) (?P<channel>\\S+) (?P<mode>\\S+) (?P<mode_params>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_CHANNELMODEIS)\n    def myevent(bot, srv=None, me=None, channel=None, mode=None, mode_params=None):\n        # do something\n\n368 - RPL_ENDOFBANLIST\n----------------------\n\nFormat ``:{srv} 368 {nick} {channel} :End of channel ban list``\n\nMatch ``^:(?P<srv>\\S+) 368 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFBANLIST)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n374 - RPL_ENDOFINFO\n-------------------\n\nFormat ``:{srv} 374 {nick} :End of /INFO list``\n\nMatch ``^:(?P<srv>\\S+) 374 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFINFO)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n365 - RPL_ENDOFLINKS\n--------------------\n\nFormat ``:{srv} 365 {nick} {mask} :End of /LINKS list``\n\nMatch ``^:(?P<srv>\\S+) 365 (?P<me>\\S+) (?P<mask>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFLINKS)\n    def myevent(bot, srv=None, me=None, mask=None, data=None):\n        # do something\n\n376 - RPL_ENDOFMOTD\n-------------------\n\nFormat ``:{srv} 376 {nick} :End of /MOTD command``\n\nMatch ``^:(?P<srv>\\S+) 376 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFMOTD)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n366 - RPL_ENDOFNAMES\n--------------------\n\nFormat ``:{srv} 366 {nick} {channel} :End of /NAMES list``\n\nMatch ``^:(?P<srv>\\S+) 366 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFNAMES)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n219 - RPL_ENDOFSTATS\n--------------------\n\nFormat ``:{srv} 219 {nick} {stats_letter} :End of /STATS report``\n\nMatch ``^:(?P<srv>\\S+) 219 (?P<me>\\S+) (?P<stats_letter>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFSTATS)\n    def myevent(bot, srv=None, me=None, stats_letter=None, data=None):\n        # do something\n\n394 - RPL_ENDOFUSERS\n--------------------\n\nFormat ``:{srv} 394 {nick} :End of users``\n\nMatch ``^:(?P<srv>\\S+) 394 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFUSERS)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n315 - RPL_ENDOFWHO\n------------------\n\nFormat ``:{srv} 315 {nick} {nick} :End of /WHO list``\n\nMatch ``^:(?P<srv>\\S+) 315 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFWHO)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n318 - RPL_ENDOFWHOIS\n--------------------\n\nFormat ``:{srv} 318 {nick} {nick} :End of /WHOIS list``\n\nMatch ``^:(?P<srv>\\S+) 318 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFWHOIS)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n369 - RPL_ENDOFWHOWAS\n---------------------\n\nFormat ``:{srv} 369 {nick} {nick} :End of WHOWAS``\n\nMatch ``^:(?P<srv>\\S+) 369 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ENDOFWHOWAS)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n371 - RPL_INFO\n--------------\n\nFormat ``:{srv} 371 {nick} :{string}``\n\nMatch ``^:(?P<srv>\\S+) 371 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_INFO)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n341 - RPL_INVITING\n------------------\n\nFormat ``:{srv} 341 {nick} {channel} {nick}``\n\nMatch ``^:(?P<srv>\\S+) 341 (?P<me>\\S+) (?P<channel>\\S+) (?P<nick>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_INVITING)\n    def myevent(bot, srv=None, me=None, channel=None, nick=None):\n        # do something\n\n303 - RPL_ISON\n--------------\n\nFormat ``:{srv} 303 {nick} :{nicknames}``\n\nMatch ``^:(?P<srv>\\S+) 303 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_ISON)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n364 - RPL_LINKS\n---------------\n\nFormat ``:{srv} 364 {nick} {mask} {server} :{hopcount} {server_info}``\n\nMatch ``^:(?P<srv>\\S+) 364 (?P<me>\\S+) (?P<mask>\\S+) (?P<server>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LINKS)\n    def myevent(bot, srv=None, me=None, mask=None, server=None, data=None):\n        # do something\n\n322 - RPL_LIST\n--------------\n\nFormat ``:{srv} 322 {nick} {channel} {visible} :{topic}``\n\nMatch ``^:(?P<srv>\\S+) 322 (?P<me>\\S+) (?P<channel>\\S+) (?P<visible>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LIST)\n    def myevent(bot, srv=None, me=None, channel=None, visible=None, data=None):\n        # do something\n\n323 - RPL_LISTEND\n-----------------\n\nFormat ``:{srv} 323 {nick} :End of /LIST``\n\nMatch ``^:(?P<srv>\\S+) 323 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LISTEND)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n321 - RPL_LISTSTART\n-------------------\n\nFormat ``:{srv} 321 {nick} Channel :Users  Name``\n\nMatch ``^:(?P<srv>\\S+) 321 (?P<me>\\S+) Channel :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LISTSTART)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n254 - RPL_LUSERCHANNELS\n-----------------------\n\nFormat ``:{srv} 254 {nick} {x} :channels formed``\n\nMatch ``^:(?P<srv>\\S+) 254 (?P<me>\\S+) (?P<x>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LUSERCHANNELS)\n    def myevent(bot, srv=None, me=None, x=None, data=None):\n        # do something\n\n251 - RPL_LUSERCLIENT\n---------------------\n\nFormat ``:{srv} 251 {nick} :There are {x} users and {y} invisible on {z} servers``\n\nMatch ``^:(?P<srv>\\S+) 251 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LUSERCLIENT)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n255 - RPL_LUSERME\n-----------------\n\nFormat ``:{srv} 255 {nick} :I have {x} clients and {y}``\n\nMatch ``^:(?P<srv>\\S+) 255 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LUSERME)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n252 - RPL_LUSEROP\n-----------------\n\nFormat ``:{srv} 252 {nick} {x} :operator(s) online``\n\nMatch ``^:(?P<srv>\\S+) 252 (?P<me>\\S+) (?P<x>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LUSEROP)\n    def myevent(bot, srv=None, me=None, x=None, data=None):\n        # do something\n\n253 - RPL_LUSERUNKNOWN\n----------------------\n\nFormat ``:{srv} 253 {nick} {x} :unknown connection(s)``\n\nMatch ``^:(?P<srv>\\S+) 253 (?P<me>\\S+) (?P<x>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_LUSERUNKNOWN)\n    def myevent(bot, srv=None, me=None, x=None, data=None):\n        # do something\n\n372 - RPL_MOTD\n--------------\n\nFormat ``:{srv} 372 {nick} :- {text}``\n\nMatch ``^:(?P<srv>\\S+) 372 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_MOTD)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n375 - RPL_MOTDSTART\n-------------------\n\nFormat ``:{srv} 375 {nick} :- {server} Message of the day -``\n\nMatch ``^:(?P<srv>\\S+) 375 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_MOTDSTART)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n353 - RPL_NAMREPLY\n------------------\n\nFormat ``:{srv} 353 {nick} {m} {channel} :{nicknames}``\n\nMatch ``^:(?P<srv>\\S+) 353 (?P<me>\\S+) (?P<m>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_NAMREPLY)\n    def myevent(bot, srv=None, me=None, m=None, channel=None, data=None):\n        # do something\n\n331 - RPL_NOTOPIC\n-----------------\n\nFormat ``:{srv} 331 {nick} {channel} :No topic is set``\n\nMatch ``^:(?P<srv>\\S+) 331 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_NOTOPIC)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n395 - RPL_NOUSERS\n-----------------\n\nFormat ``:{srv} 395 {nick} :Nobody logged in``\n\nMatch ``^:(?P<srv>\\S+) 395 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_NOUSERS)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n306 - RPL_NOWAWAY\n-----------------\n\nFormat ``:{srv} 306 {nick} :You have been marked as being away``\n\nMatch ``^:(?P<srv>\\S+) 306 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_NOWAWAY)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n382 - RPL_REHASHING\n-------------------\n\nFormat ``:{srv} 382 {nick} {config_file} :Rehashing``\n\nMatch ``^:(?P<srv>\\S+) 382 (?P<me>\\S+) (?P<config_file>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_REHASHING)\n    def myevent(bot, srv=None, me=None, config_file=None, data=None):\n        # do something\n\n213 - RPL_STATSCLINE\n--------------------\n\nFormat ``:{srv} 213 {nick} C {host} * {nick} {port} {class}``\n\nMatch ``^:(?P<srv>\\S+) 213 (?P<me>\\S+) C (?P<host>\\S+) . (?P<nick>\\S+) (?P<port>\\S+) (?P<class>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSCLINE)\n    def myevent(bot, srv=None, me=None, host=None, nick=None, port=None, class=None):\n        # do something\n\n212 - RPL_STATSCOMMANDS\n-----------------------\n\nFormat ``:{srv} 212 {nick} {cmd} {count}``\n\nMatch ``^:(?P<srv>\\S+) 212 (?P<me>\\S+) (?P<cmd>\\S+) (?P<count>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSCOMMANDS)\n    def myevent(bot, srv=None, me=None, cmd=None, count=None):\n        # do something\n\n244 - RPL_STATSHLINE\n--------------------\n\nFormat ``:{srv} 244 {nick} H {hostmask} * {servername}``\n\nMatch ``^:(?P<srv>\\S+) 244 (?P<me>\\S+) H (?P<hostmask>\\S+) . (?P<servername>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSHLINE)\n    def myevent(bot, srv=None, me=None, hostmask=None, servername=None):\n        # do something\n\n215 - RPL_STATSILINE\n--------------------\n\nFormat ``:{srv} 215 {nick} I {host} * {host1} {port} {class}``\n\nMatch ``^:(?P<srv>\\S+) 215 (?P<me>\\S+) I (?P<host>\\S+) . (?P<host1>\\S+) (?P<port>\\S+) (?P<class>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSILINE)\n    def myevent(bot, srv=None, me=None, host=None, host1=None, port=None, class=None):\n        # do something\n\n216 - RPL_STATSKLINE\n--------------------\n\nFormat ``:{srv} 216 {nick} K {host} * {username} {port} {class}``\n\nMatch ``^:(?P<srv>\\S+) 216 (?P<me>\\S+) K (?P<host>\\S+) . (?P<username>\\S+) (?P<port>\\S+) (?P<class>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSKLINE)\n    def myevent(bot, srv=None, me=None, host=None, username=None, port=None, class=None):\n        # do something\n\n211 - RPL_STATSLINKINFO\n-----------------------\n\nFormat ``:{srv} 211 {nick} :{linkname} {sendq} {sent_messages} {received_bytes} {time_open}``\n\nMatch ``^:(?P<srv>\\S+) 211 (?P<me>\\S+) (?P<linkname>\\S+) (?P<sendq>\\S+) (?P<sent_messages>\\S+) (?P<received_bytes>\\S+) (?P<time_open>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSLINKINFO)\n    def myevent(bot, srv=None, me=None, linkname=None, sendq=None, sent_messages=None, received_bytes=None, time_open=None):\n        # do something\n\n241 - RPL_STATSLLINE\n--------------------\n\nFormat ``:{srv} 241 {nick} L {hostmask} * {servername} {maxdepth}``\n\nMatch ``^:(?P<srv>\\S+) 241 (?P<me>\\S+) L (?P<hostmask>\\S+) . (?P<servername>\\S+) (?P<maxdepth>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSLLINE)\n    def myevent(bot, srv=None, me=None, hostmask=None, servername=None, maxdepth=None):\n        # do something\n\n214 - RPL_STATSNLINE\n--------------------\n\nFormat ``:{srv} 214 {nick} N {host} * {nick} {port} {class}``\n\nMatch ``^:(?P<srv>\\S+) 214 (?P<me>\\S+) N (?P<host>\\S+) . (?P<nick>\\S+) (?P<port>\\S+) (?P<class>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSNLINE)\n    def myevent(bot, srv=None, me=None, host=None, nick=None, port=None, class=None):\n        # do something\n\n243 - RPL_STATSOLINE\n--------------------\n\nFormat ``:{srv} 243 {nick} O {hostmask} * {nick}``\n\nMatch ``^:(?P<srv>\\S+) 243 (?P<me>\\S+) O (?P<hostmask>\\S+) . (?P<nick>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSOLINE)\n    def myevent(bot, srv=None, me=None, hostmask=None, nick=None):\n        # do something\n\n242 - RPL_STATSUPTIME\n---------------------\n\nFormat ``:{srv} 242 {nick} :Server Up{days}days {hours}``\n\nMatch ``^:(?P<srv>\\S+) 242 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSUPTIME)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n218 - RPL_STATSYLINE\n--------------------\n\nFormat ``:{srv} 218 {nick} frequency> {max_sendq}``\n\nMatch ``^:(?P<srv>\\S+) 218 (?P<me>\\S+) frequency> (?P<max_sendq>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_STATSYLINE)\n    def myevent(bot, srv=None, me=None, max_sendq=None):\n        # do something\n\n342 - RPL_SUMMONING\n-------------------\n\nFormat ``:{srv} 342 {nick} {nick} :Summoning user to IRC``\n\nMatch ``^:(?P<srv>\\S+) 342 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_SUMMONING)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n391 - RPL_TIME\n--------------\n\nFormat ``:{srv} 391 {nick} {server} :{string_showing_server's_local_time}``\n\nMatch ``^:(?P<srv>\\S+) 391 (?P<me>\\S+) (?P<server>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TIME)\n    def myevent(bot, srv=None, me=None, server=None, data=None):\n        # do something\n\n332 - RPL_TOPIC\n---------------\n\nFormat ``:{srv} 332 {nick} {channel} :{topic}``\n\nMatch ``^:(?P<srv>\\S+) 332 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TOPIC)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n201 - RPL_TRACECONNECTING\n-------------------------\n\nFormat ``:{srv} 201 {nick} Try. {class} {server}``\n\nMatch ``^:(?P<srv>\\S+) 201 (?P<me>\\S+) Try. (?P<class>\\S+) (?P<server>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACECONNECTING)\n    def myevent(bot, srv=None, me=None, class=None, server=None):\n        # do something\n\n202 - RPL_TRACEHANDSHAKE\n------------------------\n\nFormat ``:{srv} 202 {nick} H.S. {class} {server}``\n\nMatch ``^:(?P<srv>\\S+) 202 (?P<me>\\S+) H.S. (?P<class>\\S+) (?P<server>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACEHANDSHAKE)\n    def myevent(bot, srv=None, me=None, class=None, server=None):\n        # do something\n\n200 - RPL_TRACELINK\n-------------------\n\nFormat ``:{srv} 200 {nick} {next_server}``\n\nMatch ``^:(?P<srv>\\S+) 200 (?P<me>\\S+) (?P<next_server>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACELINK)\n    def myevent(bot, srv=None, me=None, next_server=None):\n        # do something\n\n261 - RPL_TRACELOG\n------------------\n\nFormat ``:{srv} 261 {nick} File {logfile} {debug_level}``\n\nMatch ``^:(?P<srv>\\S+) 261 (?P<me>\\S+) File (?P<logfile>\\S+) (?P<debug_level>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACELOG)\n    def myevent(bot, srv=None, me=None, logfile=None, debug_level=None):\n        # do something\n\n208 - RPL_TRACENEWTYPE\n----------------------\n\nFormat ``:{srv} 208 {nick} {newtype} 0 {client}``\n\nMatch ``^:(?P<srv>\\S+) 208 (?P<me>\\S+) (?P<newtype>\\S+) 0 (?P<client>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACENEWTYPE)\n    def myevent(bot, srv=None, me=None, newtype=None, client=None):\n        # do something\n\n204 - RPL_TRACEOPERATOR\n-----------------------\n\nFormat ``:{srv} 204 {nick} Oper {class} {nick}``\n\nMatch ``^:(?P<srv>\\S+) 204 (?P<me>\\S+) Oper (?P<class>\\S+) (?P<nick>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACEOPERATOR)\n    def myevent(bot, srv=None, me=None, class=None, nick=None):\n        # do something\n\n206 - RPL_TRACESERVER\n---------------------\n\nFormat ``:{srv} 206 {nick} {mask}``\n\nMatch ``^:(?P<srv>\\S+) 206 (?P<me>\\S+) (?P<mask>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACESERVER)\n    def myevent(bot, srv=None, me=None, mask=None):\n        # do something\n\n203 - RPL_TRACEUNKNOWN\n----------------------\n\nFormat ``:{srv} 203 {nick} ???? {class} [{clientip}]``\n\nMatch ``^:(?P<srv>\\S+) 203 (?P<me>\\S+) \\S+ (?P<class>\\S+) [(?P<clientip>\\S+)]``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACEUNKNOWN)\n    def myevent(bot, srv=None, me=None, class=None, clientip=None):\n        # do something\n\n205 - RPL_TRACEUSER\n-------------------\n\nFormat ``:{srv} 205 {nick} User {class} {nick}``\n\nMatch ``^:(?P<srv>\\S+) 205 (?P<me>\\S+) User (?P<class>\\S+) (?P<nick>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_TRACEUSER)\n    def myevent(bot, srv=None, me=None, class=None, nick=None):\n        # do something\n\n221 - RPL_UMODEIS\n-----------------\n\nFormat ``:{srv} 221 {nick} {user_mode_string}``\n\nMatch ``^:(?P<srv>\\S+) 221 (?P<me>\\S+) (?P<user_mode_string>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_UMODEIS)\n    def myevent(bot, srv=None, me=None, user_mode_string=None):\n        # do something\n\n305 - RPL_UNAWAY\n----------------\n\nFormat ``:{srv} 305 {nick} :You are no longer marked as being away``\n\nMatch ``^:(?P<srv>\\S+) 305 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_UNAWAY)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n302 - RPL_USERHOST\n------------------\n\nFormat ``:{srv} 302 {nick} :[{reply}{{space}{reply}}]``\n\nMatch ``^:(?P<srv>\\S+) 302 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_USERHOST)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n393 - RPL_USERS\n---------------\n\nFormat ``:{srv} 393 {nick} {x} {y} {z}``\n\nMatch ``^:(?P<srv>\\S+) 393 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_USERS)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n392 - RPL_USERSSTART\n--------------------\n\nFormat ``:{srv} 392 {nick} :UserID   Terminal  Host``\n\nMatch ``^:(?P<srv>\\S+) 392 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_USERSSTART)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n351 - RPL_VERSION\n-----------------\n\nFormat ``:{srv} 351 {nick} {version}.{debuglevel} {server} :{comments}``\n\nMatch ``^:(?P<srv>\\S+) 351 (?P<me>\\S+) (?P<version>\\S+).(?P<debuglevel>\\S+) (?P<server>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_VERSION)\n    def myevent(bot, srv=None, me=None, version=None, debuglevel=None, server=None, data=None):\n        # do something\n\n319 - RPL_WHOISCHANNELS\n-----------------------\n\nFormat ``:{srv} 319 {nick} :{channels}``\n\nMatch ``^:(?P<srv>\\S+) 319 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_WHOISCHANNELS)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n317 - RPL_WHOISIDLE\n-------------------\n\nFormat ``:{srv} 317 {nick} {nick} {x} :seconds idle``\n\nMatch ``^:(?P<srv>\\S+) 317 (?P<me>\\S+) (?P<nick>\\S+) (?P<x>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_WHOISIDLE)\n    def myevent(bot, srv=None, me=None, nick=None, x=None, data=None):\n        # do something\n\n313 - RPL_WHOISOPERATOR\n-----------------------\n\nFormat ``:{srv} 313 {nick} {nick} :is an IRC operator``\n\nMatch ``^:(?P<srv>\\S+) 313 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_WHOISOPERATOR)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n312 - RPL_WHOISSERVER\n---------------------\n\nFormat ``:{srv} 312 {nick} {nick} {server} :{server_info}``\n\nMatch ``^:(?P<srv>\\S+) 312 (?P<me>\\S+) (?P<nick>\\S+) (?P<server>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_WHOISSERVER)\n    def myevent(bot, srv=None, me=None, nick=None, server=None, data=None):\n        # do something\n\n311 - RPL_WHOISUSER\n-------------------\n\nFormat ``:{srv} 311 {nick} {nick} {username} {host} {m} :{realname}``\n\nMatch ``^:(?P<srv>\\S+) 311 (?P<me>\\S+) (?P<nick>\\S+) (?P<username>\\S+) (?P<host>\\S+) (?P<m>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_WHOISUSER)\n    def myevent(bot, srv=None, me=None, nick=None, username=None, host=None, m=None, data=None):\n        # do something\n\n352 - RPL_WHOREPLY\n------------------\n\nFormat ``:{srv} 352 {nick} :{channel} {username} {host} {server} {nick} {modes} :{hopcount} {realname}``\n\nMatch ``^:(?P<srv>\\S+) 352 (?P<me>\\S+) (?P<channel>\\S+) (?P<username>\\S+) (?P<host>\\S+) (?P<server>\\S+) (?P<nick>\\S+) (?P<modes>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_WHOREPLY)\n    def myevent(bot, srv=None, me=None, channel=None, username=None, host=None, server=None, nick=None, modes=None, data=None):\n        # do something\n\n314 - RPL_WHOWASUSER\n--------------------\n\nFormat ``:{srv} 314 {nick} {nick} {username} {host} * :{realname}``\n\nMatch ``^:(?P<srv>\\S+) 314 (?P<me>\\S+) (?P<nick>\\S+) (?P<username>\\S+) (?P<host>\\S+) . :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_WHOWASUSER)\n    def myevent(bot, srv=None, me=None, nick=None, username=None, host=None, data=None):\n        # do something\n\n381 - RPL_YOUREOPER\n-------------------\n\nFormat ``:{srv} 381 {nick} :You are now an IRC operator``\n\nMatch ``^:(?P<srv>\\S+) 381 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.RPL_YOUREOPER)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\nErrors (ERR)\n============\n\n462 - ERR_ALREADYREGISTRED\n--------------------------\n\nFormat ``:{srv} 462 {nick} :You may not reregister``\n\nMatch ``^:(?P<srv>\\S+) 462 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_ALREADYREGISTRED)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n475 - ERR_BADCHANNELKEY\n-----------------------\n\nFormat ``:{srv} 475 {nick} {channel} :Cannot join channel (+k)``\n\nMatch ``^:(?P<srv>\\S+) 475 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_BADCHANNELKEY)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n474 - ERR_BANNEDFROMCHAN\n------------------------\n\nFormat ``:{srv} 474 {nick} {channel} :Cannot join channel (+b)``\n\nMatch ``^:(?P<srv>\\S+) 474 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_BANNEDFROMCHAN)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n404 - ERR_CANNOTSENDTOCHAN\n--------------------------\n\nFormat ``:{srv} 404 {nick} {channel} :Cannot send to channel``\n\nMatch ``^:(?P<srv>\\S+) 404 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_CANNOTSENDTOCHAN)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n483 - ERR_CANTKILLSERVER\n------------------------\n\nFormat ``:{srv} 483 {nick} :You cant kill a server!``\n\nMatch ``^:(?P<srv>\\S+) 483 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_CANTKILLSERVER)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n471 - ERR_CHANNELISFULL\n-----------------------\n\nFormat ``:{srv} 471 {nick} {channel} :Cannot join channel (+l)``\n\nMatch ``^:(?P<srv>\\S+) 471 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_CHANNELISFULL)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n482 - ERR_CHANOPRIVSNEEDED\n--------------------------\n\nFormat ``:{srv} 482 {nick} {channel} :You're not channel operator``\n\nMatch ``^:(?P<srv>\\S+) 482 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_CHANOPRIVSNEEDED)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n432 - ERR_ERRONEUSNICKNAME\n--------------------------\n\nFormat ``:{srv} 432 {nick} {nick} :Erroneus nickname``\n\nMatch ``^:(?P<srv>\\S+) 432 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_ERRONEUSNICKNAME)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n473 - ERR_INVITEONLYCHAN\n------------------------\n\nFormat ``:{srv} 473 {nick} {channel} :Cannot join channel (+i)``\n\nMatch ``^:(?P<srv>\\S+) 473 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_INVITEONLYCHAN)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n467 - ERR_KEYSET\n----------------\n\nFormat ``:{srv} 467 {nick} {channel} :Channel key already set``\n\nMatch ``^:(?P<srv>\\S+) 467 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_KEYSET)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n461 - ERR_NEEDMOREPARAMS\n------------------------\n\nFormat ``:{srv} 461 {nick} {cmd} :Not enough parameters``\n\nMatch ``^:(?P<srv>\\S+) 461 (?P<me>\\S+) (?P<cmd>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NEEDMOREPARAMS)\n    def myevent(bot, srv=None, me=None, cmd=None, data=None):\n        # do something\n\nERR_NICK\n--------\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<srv>\\S+) (?P<retcode>(432|433|436)) (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NICK)\n    def myevent(bot, srv=None, retcode=None, me=None, nick=None, data=None, tags=None):\n        # do something\n\n436 - ERR_NICKCOLLISION\n-----------------------\n\nFormat ``:{srv} 436 {nick} {nick} :Nickname collision KILL``\n\nMatch ``^:(?P<srv>\\S+) 436 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NICKCOLLISION)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n433 - ERR_NICKNAMEINUSE\n-----------------------\n\nFormat ``:{srv} 433 {nick} {nick} :Nickname is already in use``\n\nMatch ``^:(?P<srv>\\S+) 433 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NICKNAMEINUSE)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n423 - ERR_NOADMININFO\n---------------------\n\nFormat ``:{srv} 423 {nick} {server} :No administrative info available``\n\nMatch ``^:(?P<srv>\\S+) 423 (?P<me>\\S+) (?P<server>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOADMININFO)\n    def myevent(bot, srv=None, me=None, server=None, data=None):\n        # do something\n\n444 - ERR_NOLOGIN\n-----------------\n\nFormat ``:{srv} 444 {nick} {nick} :User not logged in``\n\nMatch ``^:(?P<srv>\\S+) 444 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOLOGIN)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n422 - ERR_NOMOTD\n----------------\n\nFormat ``:{srv} 422 {nick} :MOTD File is missing``\n\nMatch ``^:(?P<srv>\\S+) 422 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOMOTD)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n431 - ERR_NONICKNAMEGIVEN\n-------------------------\n\nFormat ``:{srv} 431 {nick} :No nickname given``\n\nMatch ``^:(?P<srv>\\S+) 431 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NONICKNAMEGIVEN)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n491 - ERR_NOOPERHOST\n--------------------\n\nFormat ``:{srv} 491 {nick} :No O-lines for your host``\n\nMatch ``^:(?P<srv>\\S+) 491 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOOPERHOST)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n409 - ERR_NOORIGIN\n------------------\n\nFormat ``:{srv} 409 {nick} :No origin specified``\n\nMatch ``^:(?P<srv>\\S+) 409 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOORIGIN)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n463 - ERR_NOPERMFORHOST\n-----------------------\n\nFormat ``:{srv} 463 {nick} :Your host isn't among the privileged``\n\nMatch ``^:(?P<srv>\\S+) 463 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOPERMFORHOST)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n481 - ERR_NOPRIVILEGES\n----------------------\n\nFormat ``:{srv} 481 {nick} :Permission Denied- You're not an IRC operator``\n\nMatch ``^:(?P<srv>\\S+) 481 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOPRIVILEGES)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n411 - ERR_NORECIPIENT\n---------------------\n\nFormat ``:{srv} 411 {nick} :No recipient given ({cmd})``\n\nMatch ``^:(?P<srv>\\S+) 411 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NORECIPIENT)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n403 - ERR_NOSUCHCHANNEL\n-----------------------\n\nFormat ``:{srv} 403 {nick} {channel} :No such channel``\n\nMatch ``^:(?P<srv>\\S+) 403 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOSUCHCHANNEL)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n401 - ERR_NOSUCHNICK\n--------------------\n\nFormat ``:{srv} 401 {nick} {nick} :No such nick/channel``\n\nMatch ``^:(?P<srv>\\S+) 401 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOSUCHNICK)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n402 - ERR_NOSUCHSERVER\n----------------------\n\nFormat ``:{srv} 402 {nick} {server} :No such server``\n\nMatch ``^:(?P<srv>\\S+) 402 (?P<me>\\S+) (?P<server>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOSUCHSERVER)\n    def myevent(bot, srv=None, me=None, server=None, data=None):\n        # do something\n\n412 - ERR_NOTEXTTOSEND\n----------------------\n\nFormat ``:{srv} 412 {nick} :No text to send``\n\nMatch ``^:(?P<srv>\\S+) 412 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOTEXTTOSEND)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n442 - ERR_NOTONCHANNEL\n----------------------\n\nFormat ``:{srv} 442 {nick} {channel} :You're not on that channel``\n\nMatch ``^:(?P<srv>\\S+) 442 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOTONCHANNEL)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n413 - ERR_NOTOPLEVEL\n--------------------\n\nFormat ``:{srv} 413 {nick} {mask} :No toplevel domain specified``\n\nMatch ``^:(?P<srv>\\S+) 413 (?P<me>\\S+) (?P<mask>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOTOPLEVEL)\n    def myevent(bot, srv=None, me=None, mask=None, data=None):\n        # do something\n\n451 - ERR_NOTREGISTERED\n-----------------------\n\nFormat ``:{srv} 451 {nick} :You have not registered``\n\nMatch ``^:(?P<srv>\\S+) 451 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_NOTREGISTERED)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n464 - ERR_PASSWDMISMATCH\n------------------------\n\nFormat ``:{srv} 464 {nick} :Password incorrect``\n\nMatch ``^:(?P<srv>\\S+) 464 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_PASSWDMISMATCH)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n445 - ERR_SUMMONDISABLED\n------------------------\n\nFormat ``:{srv} 445 {nick} :SUMMON has been disabled``\n\nMatch ``^:(?P<srv>\\S+) 445 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_SUMMONDISABLED)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n405 - ERR_TOOMANYCHANNELS\n-------------------------\n\nFormat ``:{srv} 405 {nick} {channel} :You have joined too many channels``\n\nMatch ``^:(?P<srv>\\S+) 405 (?P<me>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_TOOMANYCHANNELS)\n    def myevent(bot, srv=None, me=None, channel=None, data=None):\n        # do something\n\n407 - ERR_TOOMANYTARGETS\n------------------------\n\nFormat ``:{srv} 407 {nick} {target} :Duplicate recipients. No message delivered``\n\nMatch ``^:(?P<srv>\\S+) 407 (?P<me>\\S+) (?P<target>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_TOOMANYTARGETS)\n    def myevent(bot, srv=None, me=None, target=None, data=None):\n        # do something\n\n501 - ERR_UMODEUNKNOWNFLAG\n--------------------------\n\nFormat ``:{srv} 501 {nick} :Unknown MODE flag``\n\nMatch ``^:(?P<srv>\\S+) 501 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_UMODEUNKNOWNFLAG)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n421 - ERR_UNKNOWNCOMMAND\n------------------------\n\nFormat ``:{srv} 421 {nick} {cmd} :Unknown command``\n\nMatch ``^:(?P<srv>\\S+) 421 (?P<me>\\S+) (?P<cmd>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_UNKNOWNCOMMAND)\n    def myevent(bot, srv=None, me=None, cmd=None, data=None):\n        # do something\n\n472 - ERR_UNKNOWNMODE\n---------------------\n\nFormat ``:{srv} 472 {nick} {char} :is unknown mode char to me``\n\nMatch ``^:(?P<srv>\\S+) 472 (?P<me>\\S+) (?P<char>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_UNKNOWNMODE)\n    def myevent(bot, srv=None, me=None, char=None, data=None):\n        # do something\n\n441 - ERR_USERNOTINCHANNEL\n--------------------------\n\nFormat ``:{srv} 441 {nick} {nick} {channel} :They aren't on that channel``\n\nMatch ``^:(?P<srv>\\S+) 441 (?P<me>\\S+) (?P<nick>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_USERNOTINCHANNEL)\n    def myevent(bot, srv=None, me=None, nick=None, channel=None, data=None):\n        # do something\n\n443 - ERR_USERONCHANNEL\n-----------------------\n\nFormat ``:{srv} 443 {nick} {nick} {channel} :is already on channel``\n\nMatch ``^:(?P<srv>\\S+) 443 (?P<me>\\S+) (?P<nick>\\S+) (?P<channel>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_USERONCHANNEL)\n    def myevent(bot, srv=None, me=None, nick=None, channel=None, data=None):\n        # do something\n\n446 - ERR_USERSDISABLED\n-----------------------\n\nFormat ``:{srv} 446 {nick} :USERS has been disabled``\n\nMatch ``^:(?P<srv>\\S+) 446 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_USERSDISABLED)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n502 - ERR_USERSDONTMATCH\n------------------------\n\nFormat ``:{srv} 502 {nick} :Cant change mode for other users``\n\nMatch ``^:(?P<srv>\\S+) 502 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_USERSDONTMATCH)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\n406 - ERR_WASNOSUCHNICK\n-----------------------\n\nFormat ``:{srv} 406 {nick} {nick} :There was no such nickname``\n\nMatch ``^:(?P<srv>\\S+) 406 (?P<me>\\S+) (?P<nick>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_WASNOSUCHNICK)\n    def myevent(bot, srv=None, me=None, nick=None, data=None):\n        # do something\n\n414 - ERR_WILDTOPLEVEL\n----------------------\n\nFormat ``:{srv} 414 {nick} {mask} :Wildcard in toplevel domain``\n\nMatch ``^:(?P<srv>\\S+) 414 (?P<me>\\S+) (?P<mask>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_WILDTOPLEVEL)\n    def myevent(bot, srv=None, me=None, mask=None, data=None):\n        # do something\n\n465 - ERR_YOUREBANNEDCREEP\n--------------------------\n\nFormat ``:{srv} 465 {nick} :You are banned from this server``\n\nMatch ``^:(?P<srv>\\S+) 465 (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.ERR_YOUREBANNEDCREEP)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\nMisc\n====\n\nCONNECTED\n---------\n\nMatch ``^:(?P<srv>\\S+) (376|422) (?P<me>\\S+) :(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.CONNECTED)\n    def myevent(bot, srv=None, me=None, data=None):\n        # do something\n\nCTCP\n----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) (?P<event>(PRIVMSG|NOTICE)) {nick} :\u0001(?P<ctcp>.*)\u0001$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.CTCP)\n    def myevent(bot, mask=None, event=None, ctcp=None, tags=None):\n        # do something\n\nOut Match ``^(?P<event>(PRIVMSG|NOTICE)) (?P<target>\\S+) :\u0001(?P<ctcp>.*)\u0001$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.CTCP, iotype=\"out\")\n    def myevent(bot, event=None, target=None, ctcp=None):\n        # do something\n\nINVITE\n------\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) INVITE {nick} :?(?P<channel>\\S+)$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.INVITE)\n    def myevent(bot, mask=None, channel=None, tags=None):\n        # do something\n\nJOIN\n----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) JOIN :?(?P<channel>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.JOIN)\n    def myevent(bot, mask=None, channel=None, tags=None):\n        # do something\n\nOut Match ``^JOIN :?(?P<channel>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.JOIN, iotype=\"out\")\n    def myevent(bot, channel=None):\n        # do something\n\nJOIN_PART_QUIT\n--------------\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) (?P<event>JOIN|PART|QUIT)\\s*:*(?P<channel>\\S*)(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.JOIN_PART_QUIT)\n    def myevent(bot, mask=None, event=None, channel=None, data=None, tags=None):\n        # do something\n\nOut Match ``^(?P<event>JOIN|PART|QUIT)\\s*:*(?P<channel>\\S*)(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.JOIN_PART_QUIT, iotype=\"out\")\n    def myevent(bot, event=None, channel=None, data=None):\n        # do something\n\nKICK\n----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) (?P<event>KICK)\\s+(?P<channel>\\S+)\\s*(?P<target>\\S+)(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.KICK)\n    def myevent(bot, mask=None, event=None, channel=None, target=None, data=None, tags=None):\n        # do something\n\nOut Match ``^(?P<event>KICK)\\s+(?P<channel>\\S+)\\s*(?P<target>\\S+)(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.KICK, iotype=\"out\")\n    def myevent(bot, event=None, channel=None, target=None, data=None):\n        # do something\n\nMODE\n----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) (?P<event>MODE)\\s+(?P<target>\\S+)\\s+(?P<modes>\\S+)(\\s+(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.MODE)\n    def myevent(bot, mask=None, event=None, target=None, modes=None, data=None, tags=None):\n        # do something\n\nOut Match ``^(?P<event>MODE)\\s+(?P<target>\\S+)\\s+(?P<modes>\\S+)(\\s+(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.MODE, iotype=\"out\")\n    def myevent(bot, event=None, target=None, modes=None, data=None):\n        # do something\n\nMY_PRIVMSG\n----------\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) (?P<event>(PRIVMSG|NOTICE)) (?P<target>(#\\S+|{nick})) :{nick}[:,\\s]\\s*(?P<data>\\S+.*)$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.MY_PRIVMSG)\n    def myevent(bot, mask=None, event=None, target=None, data=None, tags=None):\n        # do something\n\nOut Match ``^(?P<event>(PRIVMSG|NOTICE)) (?P<target>\\S+) :(?P<data>.*)$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.MY_PRIVMSG, iotype=\"out\")\n    def myevent(bot, event=None, target=None, data=None):\n        # do something\n\nNEW_NICK\n--------\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<nick>\\S+) NICK :?(?P<new_nick>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.NEW_NICK)\n    def myevent(bot, nick=None, new_nick=None, tags=None):\n        # do something\n\nOut Match ``^NICK :?(?P<new_nick>\\S+)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.NEW_NICK, iotype=\"out\")\n    def myevent(bot, new_nick=None):\n        # do something\n\nPART\n----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) PART (?P<channel>\\S+)(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.PART)\n    def myevent(bot, mask=None, channel=None, data=None, tags=None):\n        # do something\n\nOut Match ``PART (?P<channel>\\S+)(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.PART, iotype=\"out\")\n    def myevent(bot, channel=None, data=None):\n        # do something\n\nPING\n----\n\nMatch ``^PING :?(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.PING)\n    def myevent(bot, data=None):\n        # do something\n\nPONG\n----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<server>\\S+) PONG (?P=server) :?(?P<data>.*)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.PONG)\n    def myevent(bot, server=None, data=None, tags=None):\n        # do something\n\nPRIVMSG\n-------\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) (?P<event>(PRIVMSG|NOTICE)) (?P<target>\\S+) :(?P<data>.*)$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.PRIVMSG)\n    def myevent(bot, mask=None, event=None, target=None, data=None, tags=None):\n        # do something\n\nOut Match ``^(?P<event>(PRIVMSG|NOTICE)) (?P<target>\\S+) :(?P<data>.*)$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.PRIVMSG, iotype=\"out\")\n    def myevent(bot, event=None, target=None, data=None):\n        # do something\n\nQUIT\n----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) QUIT(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.QUIT)\n    def myevent(bot, mask=None, data=None, tags=None):\n        # do something\n\nOut Match ``^QUIT(\\s+:(?P<data>.*)|$)``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.QUIT, iotype=\"out\")\n    def myevent(bot, data=None):\n        # do something\n\nTOPIC\n-----\n\nMatch ``^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) TOPIC (?P<channel>\\S+) :(?P<data>.*)$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.TOPIC)\n    def myevent(bot, mask=None, channel=None, data=None, tags=None):\n        # do something\n\nOut Match ``^TOPIC (?P<channel>\\S+) :(?P<data>.*)$``\n\nExample:\n\n.. code-block:: python\n\n    @irc3.event(rfc.TOPIC, iotype=\"out\")\n    def myevent(bot, channel=None, data=None):\n        # do something\n\n"
  },
  {
    "path": "docs/utils.rst",
    "content": "========================\n:mod:`irc3.utils` Utils\n========================\n\n.. automodule:: irc3.utils\n\n.. autoclass:: IrcString\n  :members:\n\n.. autofunction:: as_list\n\n.. autofunction:: as_channel\n\n.. autofunction:: split_message\n\n.. autoclass:: Logger\n  :members:\n\n.. autoclass:: Config\n\n.. autofunction:: parse_config\n\n.. autofunction:: extract_config\n\n.. autofunction:: maybedotted\n\n"
  },
  {
    "path": "examples/async_command.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nfrom irc3.compat import Queue\nimport irc3\n\n\n@irc3.plugin\nclass AsyncCommands(object):\n    \"\"\"Async commands example. This is what it's look like on irc::\n\n        <gawel> !get\n        <gawel> !put item\n        <irc3> items added to queue\n        <irc3> item\n    \"\"\"\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.queue = Queue()\n\n    @command\n    def put(self, mask, target, args):\n        \"\"\"Put items in queue\n\n            %%put <words>...\n        \"\"\"\n        for w in args['<words>']:\n            self.queue.put_nowait(w)\n        yield 'items added to queue'\n\n    @command\n    async def get(self, mask, target, args):\n        \"\"\"Async get items from the queue\n\n            %%get\n        \"\"\"\n        messages = []\n        message = await self.queue.get()\n        messages.append(message)\n        while not self.queue.empty():\n            message = await self.queue.get()\n            messages.append(message)\n        return messages\n"
  },
  {
    "path": "examples/benches.ini",
    "content": "[bot]\nnick = malkovitch\nusername = malkovitch\nhost = localhost\nport = 6667\nname = malkovitch\nuser = malkovitch\nrealname = I'm the real John Malkovitch\nchannel = head\nincludes =\n    benches\n\n[server]\nservername = malkovitch\nclient_amount = 500\nincludes =\n    irc3d.plugins.core\n\n[opers]\ngawel=passwd\n"
  },
  {
    "path": "examples/benches.py",
    "content": "# -*- coding: utf-8 -*-\nimport random\nfrom irc3.compat import asyncio\nfrom irc3d import IrcServer\nimport irc3\n\n\n@irc3.plugin\nclass Plugin(object):\n\n    def __init__(self, context):\n        self.log = context.log\n        self.context = context\n        self.name = context.config.name\n        self.channel = '#' + context.config.channel\n\n    @irc3.event(irc3.rfc.CONNECTED)\n    def connected(self, **kw):\n        self.context.join(self.channel)\n\n    def msg(self):\n        s = ' '.join([self.name for i in range(random.randint(1, 10))])\n        s += random.choice([' ?', '', ' !', ' #@!', ' '])\n        self.context.privmsg(self.channel, s)\n        self.context.loop.call_later(\n            random.randint(3, 20), self.msg)\n\n    @irc3.event(irc3.rfc.JOIN)\n    def join(self, mask=None, **kw):\n        if mask.nick == self.context.nick:\n            self.context.loop.call_later(\n                random.randint(3, 20), self.msg)\n\n\ndef main():\n    loop = asyncio.get_event_loop()\n\n    server = IrcServer.from_argv(loop=loop)\n    bot = irc3.IrcBot.from_argv(loop=loop)\n\n    def factory(i):\n        irc3.IrcBot.from_argv(\n            loop=loop, i=i,\n            nick=bot.nick + str(i),\n            realname=bot.config.realname + str(i),\n        )\n\n    for i in range(1, server.config.client_amount):\n        loop.call_later(.1 * i, factory, i)\n\n    loop.run_forever()\n"
  },
  {
    "path": "examples/bot.ini",
    "content": "[bot]\nnick = irc3\nusername = irc3\n\nhost = irc.freenode.net\nport = 7000\nssl = true\n\nincludes =\n    irc3.plugins.core\n    irc3.plugins.ctcp\n    irc3.plugins.cron\n    irc3.plugins.autojoins\n    irc3.plugins.userlist\n    irc3.plugins.command\n    irc3.plugins.human\n    irc3.plugins.search\n    irc3.plugins.uptime\n    irc3.plugins.feeds\n    irc3.plugins.social\n    irc3.plugins.fifo\n    freenode_irc3\n    nickserv\n\n# channels to join\nautojoins =\n    irc3\n\n[irc3.plugins.command]\n# command plugin configuration\n\n# set command char\ncmd = !\n# enable antiflood on commands\nantiflood = true\n# set guard policy\nguard = irc3.plugins.command.mask_based_policy\n\n[irc3.plugins.command.masks]\n*!~gael@amandine.bearstech.com = all_permissions\n\n[irc3.plugins.feeds]\n# feeds plugin configuration\ndirectory = ~/.irc3/feeds/\nhook = freenode_irc3.FeedsHook\nchannels = irc3\ndelay = 5\n\ngithub/irc3 = https://github.com/gawel/irc3/commits/master.atom\ngithub/irc3.fmt = [{feed.name}] New commit by {entry.author}: {entry.title} - {entry.link}\ngithub/irc3.delay = 5\n\ntravis/irc3 = https://api.travis-ci.org/repos/gawel/irc3/builds.atom\ntravis/irc3.fmt = [{feed.name}] {entry.title} - {entry.link}\ntravis/irc3.channels = irc3\ntravis/irc3.delay = 10\n\npypi/irc3 = https://pypi.python.org/pypi?:action=rss\npypi/irc3.fmt = {entry.title} is out! - {entry.link}\npypi/irc3.delay = 60\n\n[irc3.plugins.fifo]\nrunpath = /tmp/run/irc3\n"
  },
  {
    "path": "examples/commands.rst",
    "content": "===============================================\nAvailable Commands for irc3 at irc.freenode.net\n===============================================\n\n.. contents::\n\nirc3.plugins.command\n====================\n\nhelp\n----\n\nShow help\n\n    ``!help [<cmd>]``\n\n\nping\n----\n\nping/pong\n\n    ``!ping``\n\n*Require admin permission.*\n*Only available in private.*\n\nirc3.plugins.search\n===================\n\nddg\n---\n\nSearch using https://duckduckgo.com/api\n\n    ``!ddg <query>...``\n\n*Require view permission.*\n\nirc3.plugins.social\n===================\n\nretweet\n-------\n\nRetweet\n\n    ``!retweet [--id=<id>] <url_or_id>``\n\n*Require edit permission.*\n\ntweet\n-----\n\nPost to social networks\n\n    ``!tweet [--id=<id>] <message>...``\n\n*Require edit permission.*\n\nirc3.plugins.uptime\n===================\n\nuptime\n------\n\nShow uptimes\n\n    ``!uptime``\n\n*Require view permission.*\n\n"
  },
  {
    "path": "examples/config.ini",
    "content": "[bot]\nnick = mybot\nusername = mybot\n\nhost = localhost\nport = 6667\n\n# uncomment this if you want ssl support\n# ssl = true\n# uncomment this if you don't want to check the certificate\n# ssl_verify = CERT_NONE\n\n# uncomment this if you want to use sasl authentication\n# sasl_username = mybot\n# sasl_password = yourpassword\n\nincludes =\n    irc3.plugins.command\n#    irc3.plugins.uptime\n#    irc3.plugins.ctcp\n    mybot_plugin\n\n# the bot will join #mybot_channel\n# ${#} is replaced by the # char\nautojoins =\n    ${#}mybot_channel\n\n# Autojoin delay, disabled by default\n# float or int value\n# autojoin_delay = 3.1\n\n# The maximum amount of lines irc3 sends at once.\n# Default to 4, set to 0 to disable\n# flood_burst = 10\n\n# The number of lines per $flood_rate_delay seconds irc3 sends after reaching\n# the $flood_burst limit.\n# Default to 1\n# flood_rate = 2\n\n# The bot will send $flood_rate messages per $flood_rate_delay seconds\n# Default to 1\n# flood_rate_delay = 5\n\n[irc3.plugins.command]\n# command plugin configuration\n\n# set command char\ncmd = !\n\n# set guard policy\nguard = irc3.plugins.command.mask_based_policy\n\n[irc3.plugins.command.masks]\n# this section is used by the guard to secure the bot's command\n# change your nickname and uncomment the line below\n# mynick!*@* = all_permissions\n* = view\n"
  },
  {
    "path": "examples/dcc_chat.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.compat import asyncio\nfrom irc3d import IrcServer\nimport irc3\n\n\n@irc3.plugin\nclass Plugin(object):\n\n    def __init__(self, context):\n        self.log = context.log\n        self.context = context\n\n    @irc3.event(irc3.rfc.CONNECTED)\n    def connected(self, **kw):\n        self.context.join('#dcc')\n\n    @irc3.event(irc3.rfc.JOIN)\n    async def join(self, mask=None, **kw):\n        if mask.nick != self.context.nick and mask.nick == 'receiver':\n            # receiver joined the chan. offer a chat\n            conn = await self.context.dcc_chat(mask)\n            # wait for my buddy\n            await conn.started\n            # say hi\n            conn.send_line('Hi!')\n            await conn.closed\n            self.context.log.info('chat with %s closed', mask.nick)\n\n    @irc3.event(irc3.rfc.CTCP)\n    async def on_ctcp(self, mask=None, **kwargs):\n        # parse ctcp message\n        print(kwargs)\n        host, port = kwargs['ctcp'].split()[3:]\n        self.context.log.info('%s is offering a chat', mask.nick)\n        # open the chat\n        conn = await self.context.dcc_chat(mask, host, port)\n        conn.send_line('youhou')\n        # end the loop after a few seconds\n        self.context.loop.call_later(1,\n                                     self.context.config.end_chat.set_result,\n                                     True)\n        await conn.closed\n        self.context.log.info('chat with %s closed', mask.nick)\n\n    @irc3.dcc_event(r'(?P<data>.*)')\n    def on_dcc(self, client=None, data=None):\n        \"\"\"event to catch everything in dcc chats\"\"\"\n        self.context.log.info('%r sent %s', client, data)\n\n\ndef main():\n    loop = asyncio.get_event_loop()\n\n    # run a test server\n    server = IrcServer.from_config(dict(\n        loop=loop,\n        servername='test',\n        includes=['irc3d.plugins.core'],\n    ))\n    server.run(forever=False)\n\n    end_chat = asyncio.Future()\n\n    cfg = dict(\n        host='localhost',\n        port=6667,\n        nick='sender',\n        includes=['irc3.plugins.dcc', __name__],\n        loop=loop,\n        end_chat=end_chat,\n    )\n    # this bot will send the file\n    sender = irc3.IrcBot.from_config(cfg)\n    sender.run(forever=False)\n\n    def f():\n        # this bot will receive the file\n        receiver.run(forever=False)\n    # assume receiver is created *after* sender\n    receiver = irc3.IrcBot.from_config(cfg, nick='receiver')\n    loop.call_later(.2, receiver.run, False)\n\n    loop.run_until_complete(end_chat)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/dcc_send.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport string\nimport tempfile\nimport irc3\nfrom irc3.plugins.command import command\n\n\n@irc3.plugin\nclass DCC(object):\n\n    filename = os.path.join(tempfile.gettempdir(), 'to_send')\n\n    def __init__(self, bot):\n        self.bot = bot\n        if not os.path.isfile(self.filename):\n            # create a file to send\n            with open(self.filename, 'wb') as fd:\n                for i in range(64 * 2048):\n                    fd.write(string.ascii_letters.encode('utf8'))\n\n    @command\n    async def send(self, mask, target, args):\n        \"\"\" DCC SEND command\n\n            %%send\n        \"\"\"\n        conn = await self.bot.dcc_send(mask, self.filename)\n        self.bot.log.debug('%s ready', conn)\n"
  },
  {
    "path": "examples/dcc_send_and_get.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.compat import asyncio\nfrom irc3d import IrcServer\nimport irc3\n\n\n@irc3.plugin\nclass Plugin(object):\n\n    def __init__(self, context):\n        self.log = context.log\n        self.context = context\n\n    @irc3.event(irc3.rfc.CONNECTED)\n    def connected(self, **kw):\n        self.context.join('#dcc')\n\n    @irc3.event(irc3.rfc.JOIN)\n    async def join(self, mask=None, **kw):\n        if mask.nick != self.context.nick and mask.nick == 'receiver':\n            # receiver joined the chan. offer a file\n            conn = await self.context.dcc_send(mask, __file__)\n            await conn.closed\n            self.context.log.info('file sent to %s', mask.nick)\n\n    @irc3.event(irc3.rfc.CTCP)\n    async def on_ctcp(self, mask=None, **kwargs):\n        # parse ctcp message\n        name, host, port, size = kwargs['ctcp'].split()[2:]\n        self.context.log.info('%s is offering %s', mask.nick, name)\n        # get the file\n        conn = await self.context.create_task(self.context.dcc_get(\n            mask, host, port, '/tmp/sent.py', int(size)))\n        await conn.closed\n        self.context.log.info('file received from %s', mask.nick)\n\n        # end loop by setting future's result\n        self.context.config.file_received.set_result(True)\n\n\ndef main():\n    loop = asyncio.get_event_loop()\n\n    # run a test server\n    server = IrcServer.from_config(dict(\n        loop=loop,\n        servername='test',\n        includes=['irc3d.plugins.core'],\n    ))\n    server.run(forever=False)\n\n    cfg = dict(\n        host='localhost',\n        port=6667,\n        nick='sender',\n        includes=[__name__],\n        loop=loop,\n    )\n    # this bot will send the file\n    sender = irc3.IrcBot.from_config(cfg)\n    sender.run(forever=False)\n\n    file_received = asyncio.Future()\n\n    def f():\n        # this bot will receive the file\n        receiver.run(forever=False)\n    # assume receiver is created *after* sender\n    receiver = irc3.IrcBot.from_config(cfg,\n                                       nick='receiver',\n                                       file_received=file_received)\n    loop.call_later(.2, receiver.run, False)\n\n    loop.run_until_complete(file_received)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/dev.ini",
    "content": "[bot]\nnick = irc3_dev\nusername = irc3\nhost = irc.freenode.net\nport = 7000\nssl = true\nincludes =\n    irc3.plugins.core\n    irc3.plugins.userlist\n    irc3.plugins.ctcp\n    irc3.plugins.autojoins\n    irc3.plugins.log\n    irc3.plugins.command\n    irc3.plugins.human\n    irc3.plugins.search\n    irc3.plugins.uptime\n    irc3.plugins.cron\n    irc3.plugins.social\n    irc3.plugins.feeds\n    irc3.plugins.fifo\n    freenode_irc3\n    paginate\n    topic\n    mybot\n#    nickserv\ncmd = .\nautojoins = #irc3_dev\n\n[irc3.plugins.command]\nantiflood = true\nguard = irc3.plugins.command.mask_based_policy\n\n[irc3.plugins.command.masks]\ngawel!*@*=all_permissions\n\n[irc3.plugins.feeds]\ndelay = 1\ndirectory = ~/.irc3/feeds/\nhook = freenode_irc3.FeedsHook\nchannels = irc3_dev\n\ngithub/irc3 = https://github.com/gawel/irc3/commits/master.atom\ngithub/irc3.fmt = [{feed.name}] New commit by {entry.author}: {entry.title} - {entry.link}\ngithub/irc3.delay = 1\n\ntravis/irc3 = https://api.travis-ci.org/repos/gawel/irc3/builds.atom\ntravis/irc3.fmt = [{feed.name}] {entry.title} - {entry.link}\ntravis/irc3.channels = #irc3-dev\ntravis/irc3.delay = 1\n\npypi/irc3 = https://pypi.python.org/pypi?:action=rss\npypi/irc3.fmt = {entry.title} is out! - {entry.link}\npypi/irc3.delay = 3\n\n[irc3.plugins.fifo]\nrunpath = /tmp/run/irc3\n"
  },
  {
    "path": "examples/freenode_irc3.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.cron import cron\nimport os\n\n\nclass FeedsHook(object):\n    \"\"\"Custom hook for irc3.plugins.feeds\"\"\"\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.packages = [\n            'asyncio', 'irc3', 'panoramisk',\n            'requests', 'trollius', 'webtest',\n            'pyramid',\n        ]\n\n    def filter_travis(self, entry):\n        \"\"\"Only show the latest entry iif this entry is in a new state\"\"\"\n        fstate = entry.filename + '.state'\n        if os.path.isfile(fstate):\n            with open(fstate) as fd:\n                state = fd.read().strip()\n        else:\n            state = None\n        if 'failed' in entry.summary:\n            nstate = 'failed'\n        else:\n            nstate = 'success'\n        with open(fstate, 'w') as fd:\n            fd.write(nstate)\n        if state != nstate:\n            build = entry.title.split('#')[1]\n            entry['title'] = 'Build #{0} {1}'.format(build, nstate)\n            return True\n\n    def filter_pypi(self, entry):\n        \"\"\"Show only usefull packages\"\"\"\n        for package in self.packages:\n            if entry.title.lower().startswith(package):\n                return entry\n\n    def __call__(self, entries):\n        travis = {}\n        for entry in entries:\n            if entry.feed.name.startswith('travis/'):\n                travis[entry.feed.name] = entry\n            elif entry.feed.name.startswith('pypi/'):\n                yield self.filter_pypi(entry)\n            else:\n                yield entry\n        for entry in travis.values():\n            if self.filter_travis(entry):\n                yield entry\n\n\n@cron('*/15 * * * *')\ndef auto_retweet(bot):\n    \"\"\"retweet author tweets about irc3 and pypi releases\"\"\"\n    conn = bot.get_social_connection(id='twitter')\n    dirname = os.path.expanduser('~/.irc3/twitter/{nick}'.format(**bot.config))\n\n    if not os.path.isdir(dirname):\n        os.makedirs(dirname)\n\n    filename = os.path.join(dirname, 'retweeted')\n    if os.path.isfile(filename):\n        with open(filename) as fd:\n            retweeted = [i.strip() for i in fd.readlines()]\n    else:\n        retweeted = []\n\n    for user in ('pypi', 'gawel_'):\n        results = conn.search.tweets(\n            q=user + ' AND irc3',\n            result_type='recent')\n        for item in results.get('statuses', []):\n            if item['user']['screen_name'] == user:\n                if item['id_str'] not in retweeted:\n                    res = conn(getattr(conn.statuses.retweet, item['id_str']))\n                    if 'id' in res:\n                        with open(filename, 'a+') as fd:\n                            fd.write(item['id_str'] + '\\n')\n\n\n@cron('*/2 * * * *', venusian_category='irc3.debug')\ndef test_cron(bot):\n    bot.log.info('Running test_cron')\n\n\n@cron('*/3 * * * *', venusian_category='irc3.debug')\ndef test_cron_raise(bot):\n    raise OSError('test_cron_raise')\n"
  },
  {
    "path": "examples/humans.py",
    "content": "# -*- coding: utf-8 -*-\nimport asyncio\nimport irc3\n\n\n@irc3.event(irc3.rfc.JOIN)\ndef greetings(bot, mask=None, channel=None, **kw):\n    if not mask.nick.startswith(bot.nick):\n        bot.privmsg(channel, '%s: Hi dude!' % mask.nick)\n\n\ndef main():\n    loop = asyncio.get_event_loop()\n\n    config = dict(\n        autojoins=['#irc3'],\n        host='irc.freenode.net', port=7000, ssl=True,\n        timeout=30,\n        includes=[\n            'irc3.plugins.core',\n            'irc3.plugins.human',\n            __name__,  # this register this module\n        ],\n        loop=loop)\n\n    # instanciate two bot\n    irc3.IrcBot(nick='bobirc', **config).run(forever=False)\n    irc3.IrcBot(nick='jackyrc', **config).run(forever=False)\n\n    loop.run_forever()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/mybot.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nimport irc3\n\n\n@irc3.plugin\nclass MyPlugin:\n    \"\"\"A plugin is a class which take the IrcBot as argument\n    \"\"\"\n\n    requires = [\n        'irc3.plugins.core',\n        'irc3.plugins.userlist',\n        'irc3.plugins.command',\n        'irc3.plugins.human',\n    ]\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.log = self.bot.log\n\n    def connection_made(self):\n        \"\"\"triggered when connection is up\"\"\"\n\n    def server_ready(self):\n        \"\"\"triggered after the server sent the MOTD (require core plugin)\"\"\"\n\n    def connection_lost(self):\n        \"\"\"triggered when connection is lost\"\"\"\n\n    @irc3.event(irc3.rfc.JOIN)\n    def welcome(self, mask, channel, **kw):\n        \"\"\"Welcome people who join a channel\"\"\"\n        if mask.nick != self.bot.nick:\n            self.bot.call_with_human_delay(\n                self.bot.privmsg, channel, 'Welcome %s!' % mask.nick)\n        else:\n            self.bot.call_with_human_delay(\n                self.bot.privmsg, channel, \"Hi guys!\")\n\n    @command\n    def echo(self, mask, target, args):\n        \"\"\"Echo command\n\n            %%echo <words>...\n        \"\"\"\n        self.bot.privmsg(mask.nick, ' '.join(args['<words>']))\n\n    @command\n    def stats(self, mask, target, args):\n        \"\"\"Show stats of the channel using the userlist plugin\n\n            %%stats [<channel>]\n        \"\"\"\n        if args['<channel>']:\n            channel = args['<channel>']\n            target = mask.nick\n        else:\n            channel = target\n        if channel in self.bot.channels:\n            channel = self.bot.channels[channel]\n            message = '{0} users'.format(len(channel))\n            for mode, nicknames in sorted(channel.modes.items()):\n                message += ' - {0}({1})'.format(mode, len(nicknames))\n            self.bot.privmsg(target, message)\n\n    @irc3.extend\n    def my_usefull_method(self):\n        \"\"\"The extend decorator will allow you to call::\n\n            bot.my_usefull_method()\n\n        \"\"\"\n\n\ndef main():\n    # instanciate a bot\n    config = dict(\n        nick='irc3', autojoins=['#irc3'],\n        host='irc.undernet.org', port=6667, ssl=False,\n        includes=[\n            'irc3.plugins.core',\n            'irc3.plugins.command',\n            'irc3.plugins.human',\n            __name__,  # this register MyPlugin\n        ]\n    )\n    bot = irc3.IrcBot.from_config(config)\n    bot.run(forever=True)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/mybot_plugin.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nimport irc3\n\n\n@irc3.plugin\nclass Plugin:\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @irc3.event(irc3.rfc.JOIN)\n    def say_hi(self, mask, channel, **kw):\n        \"\"\"Say hi when someone join a channel\"\"\"\n        if mask.nick != self.bot.nick:\n            self.bot.privmsg(channel, 'Hi %s!' % mask.nick)\n        else:\n            self.bot.privmsg(channel, 'Hi!')\n\n    @command(permission='view')\n    def echo(self, mask, target, args):\n        \"\"\"Echo\n\n            %%echo <message>...\n        \"\"\"\n        yield ' '.join(args['<message>'])\n"
  },
  {
    "path": "examples/mycommands.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\n\n\n@command\ndef echo(bot, mask, target, args):\n    \"\"\"Echo command\n\n        %%echo <words>...\n    \"\"\"\n    yield ' '.join(args['<words>'])\n\n\n@command(permission='admin', public=False)\ndef adduser(bot, mask, target, args):\n    \"\"\"Add a user\n\n        %%adduser <name> <password>\n    \"\"\"\n    bot.privmsg(mask.nick, 'User added')\n\n\n@command(show_in_help_list=False)\ndef my_secret_operation(bot, mask, target, args):\n    \"\"\"Do something you don't want in !help all the time\n\n        %%my_secret_operation\n    \"\"\"\n    yield \"I like turtles\"\n"
  },
  {
    "path": "examples/mycrons.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.cron import cron\n\n\n@cron('30 8 * * *')\ndef wakeup(bot):\n    bot.privmsg('#irc3', \"It's time to wake up!\")\n\n\n@cron('0 */2 * * *')\ndef take_a_break(bot):\n    bot.privmsg('#irc3', \"It's time to take a break!\")\n"
  },
  {
    "path": "examples/myextends.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\n\n\n@irc3.extend\ndef my_usefull_function(bot, *args):\n    return 'my_usefull_function(*%s)' % (args,)\n\n\n@irc3.plugin\nclass MyPlugin(object):\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @irc3.extend\n    def my_usefull_method(self, *args):\n        return 'my_usefull_method(*%s)' % (args,)\n"
  },
  {
    "path": "examples/nickserv.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\n\n\n@irc3.event(r'(@(?P<tags>\\S+) )?:(?P<ns>NickServ)!NickServ@services.'\n            r' NOTICE (?P<nick>irc3) :This nickname is registered.*')\ndef register(bot, ns=None, nick=None, **kw):\n    try:\n        password = bot.config[bot.config.host][nick]\n    except KeyError:\n        pass\n    else:\n        bot.privmsg(ns, 'identify %s %s' % (nick, password))\n"
  },
  {
    "path": "examples/paginate.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\nimport requests\nfrom irc3.plugins.command import command\n\n\n@irc3.plugin\nclass SendFile(object):\n\n    requires = [\n        'irc3.plugins.command',\n        'irc3.plugins.pager',\n    ]\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @command\n    def cat(self, mask, target, args):\n        \"\"\"Cat a file with pagination\n\n            %%cat\n        \"\"\"\n        fd = open(__file__)\n        for msg in self.bot.paginate(mask, fd, lines_per_page=10):\n            yield msg\n\n    @command\n    def url(self, mask, target, args):\n        \"\"\"Cat an url with pagination\n\n            %%url <url>\n        \"\"\"\n        def iterator(url):\n            resp = requests.get(url)\n            for chunk in resp.iter_content(255):\n                yield chunk.decode('utf8')\n        for msg in self.bot.paginate(mask, iterator(args['<url>'])):\n            yield msg\n"
  },
  {
    "path": "examples/proxy.py",
    "content": "# -*- coding: utf-8 -*-\nimport socks\nimport irc3\n\n\ndef sock_factory(bot, host, port):\n    sock = socks.socksocket()\n    sock.set_proxy(socks.SOCKS5, \"localhost\", 6969)\n    sock.connect((host, 6667))\n    return sock\n\n\ndef main():\n    bot = irc3.IrcBot.from_argv(sock_factory=sock_factory)\n    bot.run()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "examples/slack.ini",
    "content": "[bot]\nnick = <nick>\nhost = chat.freenode.net\nport = 6697\nssl = true\nsasl_username = <username>\nsasl_password = <password>\nincludes =\n    irc3.plugins.slack\n[irc3.plugins.slack]\ntoken = <xoxb-slackbottoken>\n[irc3.plugins.slack.channels]\n<slackchannel1> =\n    ${#}<ircchannel1>\n    ${#}<ircchannel2>\n<slackchannel2> =\n    ${#}<ircchannel3>\n"
  },
  {
    "path": "examples/spy.ini",
    "content": "[bot]\nnick = spyer\nusername = spyer\nhost = localhost\nport = 6667\nchannel = gov\nincludes =\n    spy\n\n[bot_chater]\nnick = chater\nusername = chater\nchannel = irc3\n\n[server]\nservername = spy\n\n"
  },
  {
    "path": "examples/spy.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\n\n\n@irc3.plugin\nclass Plugin(object):\n\n    chater = None\n\n    def __init__(self, context):\n        self.log = context.log\n        self.context = context\n        self.channel = context.config.channel\n\n    @irc3.event(irc3.rfc.CONNECTED)\n    def connected(self, **kw):\n        chater = self.context.config.botnet['bot_chater']\n        if chater is self.context:\n            self.chater = None\n            self.log.info(\"I'm a chater\")\n        else:\n            self.chater = chater\n            self.log.info(\"I'm a spyer\")\n        self.context.join(self.channel)\n\n    @irc3.event(irc3.rfc.PRIVMSG)\n    def on_privmsg(self, mask=None, data=None, **kw):\n        print(self.chater, mask, data)\n        if self.chater:\n            self.chater.privmsg(self.chater.config.channel,\n                                '{0}: {1}'.format(mask.nick, data))\n"
  },
  {
    "path": "examples/topic.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\nfrom irc3.plugins.command import command\nfrom irc3.plugins.cron import cron\n\n\n@irc3.plugin\nclass TopicPlugin:\n\n    requires = ['irc3.plugins.async']\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @irc3.event(irc3.rfc.TOPIC)\n    @irc3.event(irc3.rfc.RPL_TOPIC)\n    def get_topic(self, channel=None, data=None, **kwargs):\n        \"\"\"check the topic on join or on user action\"\"\"\n        self.bot.log.warn('Topic for %s is %s', channel, data)\n\n    @cron('* * * * *')\n    async def cron_topic(self):\n        \"\"\"check the topic each minute\"\"\"\n        result = await self.bot.async_cmds.topic('#irc3_dev')\n        self.bot.log.warn('Topic for #irc3_dev is %(topic)s', result)\n\n    @command\n    def topic(self, mask, target, args):\n        \"\"\"Set topic\n\n        %%topic <topic>...\n        \"\"\"\n        if target.is_channel:\n            self.bot.topic(target, ' '.join(args['<topic>']))\n\n    @command\n    async def aiotopic(self, mask, target, args):\n        \"\"\"Set topic and get result the async way\n\n        %%aiotopic [<topic>...]\n        \"\"\"\n        if target.is_channel:\n            result = await self.bot.async_cmds.topic(\n                target, ' '.join(args['<topic>']))\n            return result['topic']\n"
  },
  {
    "path": "examples/wsgiapp.py",
    "content": "# -*- coding: utf-8 -*-\nimport asyncio\nfrom aiohttp_wsgi import wsgi\nfrom irc3 import plugin\nimport json\n\n\n@plugin\nclass Webapp:\n\n    requires = ['irc3.plugins.userlist']\n\n    def __init__(self, bot):\n        def server():\n            return wsgi.WSGIServerHttpProtocol(self.wsgi)\n        self.bot = bot\n        loop = asyncio.get_event_loop()\n        self.bot.log.info('Starting webapp')\n        asyncio.Task(loop.create_server(\n            server, '127.0.0.1', 5000))\n\n    def wsgi(self, environ, start_response):\n        start_response('200 OK', [('Content-Type', 'application/json')])\n        plugin = self.bot.get_plugin('userlist')\n        data = json.dumps(list(plugin.channels.keys()))\n        return [data.encode('utf8')]\n"
  },
  {
    "path": "irc3/__init__.py",
    "content": "# -*- coding: utf-8 -*-\nfrom urllib.request import urlopen\nfrom ipaddress import ip_address\nfrom collections import deque\nfrom .dcc import DCCManager\nfrom .dcc import DCCChat\nfrom .dec import dcc_event\nfrom .dec import event\nfrom .dec import extend\nfrom .dec import plugin\nfrom . import config\nfrom . import utils\nfrom . import rfc\nfrom . import base\nfrom .compat import asyncio\nfrom .compat import Queue\nimport venusian\nimport time\n\n\nclass IrcConnection(asyncio.Protocol):\n    \"\"\"asyncio protocol to handle an irc connection\"\"\"\n\n    def connection_made(self, transport):\n        self.transport = transport\n        self.closed = False\n        self.queue = deque()\n\n    def decode(self, data):\n        \"\"\"Decode data with bot's encoding\"\"\"\n        encoding = getattr(self, 'encoding', 'ascii')\n        return data.decode(encoding, 'ignore')\n\n    def data_received(self, data):\n        data = self.decode(data)\n        if self.queue:\n            data = self.queue.popleft() + data\n        lines = data.split('\\r\\n')\n        self.queue.append(lines.pop(-1))\n        for line in lines:\n            self.factory.dispatch(line)\n\n    def write(self, data):\n        if data is not None:\n            data = data.encode(self.encoding)\n            if not data.endswith(b'\\r\\n'):\n                data = data + b'\\r\\n'\n            self.transport.write(data)\n\n    def connection_lost(self, exc):\n        self.factory.log.critical('connection lost (%s): %r',\n                                  id(self.transport),\n                                  exc)\n        self.factory.notify('connection_lost')\n        if not self.closed:\n            self.close()\n            # wait a few before reconnect\n            self.factory.loop.call_later(\n                2, self.factory.create_connection)\n\n    def close(self):\n        if not self.closed:\n            self.factory.log.critical('closing old transport (%r)',\n                                      id(self.transport))\n            try:\n                self.transport.close()\n            finally:\n                self.closed = True\n\n\nclass IrcBot(base.IrcObject):\n    \"\"\"An IRC bot\"\"\"\n\n    _pep8 = [dcc_event, event, extend, plugin, rfc, config]\n    venusian = venusian\n    venusian_categories = [\n        'irc3',\n        'irc3.dcc',\n        'irc3.extend',\n        'irc3.rfc1459',\n        'irc3.plugins.cron',\n        'irc3.plugins.command',\n    ]\n\n    logging_config = config.LOGGING\n\n    defaults = dict(\n        base.IrcObject.defaults,\n        nick='irc3',\n        username='irc3',\n        realname='Irc bot based on irc3 http://irc3.readthedocs.io',\n        host='localhost',\n        mode=0,\n        url='https://irc3.readthedocs.io/',\n        passwords={},\n        flood_burst=4,\n        flood_rate=1,\n        flood_rate_delay=1,\n        ctcp=dict(\n            version='irc3 {version} - {url}',\n            userinfo='{realname}',\n            time='{now:%c}',\n        ),\n        # freenode config as default for testing\n        server_config=dict(\n            STATUSMSG='+@',\n            PREFIX='(ov)@+',\n            CHANTYPES='#',\n            CHANMODES='eIbq,k,flj,CFLMPQScgimnprstz',\n        ),\n        connection=IrcConnection,\n    )\n\n    def __init__(self, *ini, **config):\n        update_config_needed = False\n        if 'userinfo' in config or \\\n           ('realname' in config and 'username' not in config):\n            update_config_needed = True  # pragma: no cover\n        super(IrcBot, self).__init__(*ini, **config)\n        if update_config_needed:  # pragma: no cover\n            # Backward compat. Remove me in 2017\n            self.log.fatal('realname has been renamed to username.')\n            self.log.fatal('userinfo has been renamed to realname.')\n            self.log.fatal('Please update your config with something like:.')\n            if 'realname' in self.config:\n                self.log.fatal('username = %(realname)s', self.config)\n            if 'userinfo' in self.config:\n                self.log.fatal('realname = %(userinfo)s', self.config)\n            import sys\n            sys.exit(-1)\n        self.queue = None\n        if self.config.asynchronous:\n            self.queue = Queue(loop=self.loop)\n            self.awaiting_queue = self.create_task(self.process_queue())\n        self._ip = self._dcc = None\n        # auto include the sasl plugin if needed\n        if 'sasl_username' in self.config and \\\n           'irc3.plugins.sasl' not in self.registry.includes:\n            self.include('irc3.plugins.sasl')\n        # auto include the autojoins plugin if needed (for backward compat)\n        if 'autojoins' in self.config and \\\n           'irc3.plugins.autojoins' not in self.registry.includes:\n            self.include('irc3.plugins.autojoins')\n\n    @property\n    def server_config(self):\n        \"\"\"return server configuration (rfc rpl 005)::\n\n            >>> bot = IrcBot()\n            >>> print(bot.server_config['STATUSMSG'])\n            +@\n\n        The real values are only available after the server sent them.\n        \"\"\"\n        return self.config.server_config\n\n    def connection_made(self, f):  # pragma: no cover\n        if getattr(self, 'protocol', None):\n            self.protocol.close()\n        try:\n            transport, protocol = f.result()\n        except Exception as e:\n            self.log.exception(e)\n            self.loop.call_later(3, self.create_connection)\n        else:\n            self.log.debug('Connected')\n            self.protocol = protocol\n            self.protocol.queue = deque()\n            self.protocol.factory = self\n            self.protocol.encoding = self.encoding\n            if self.config.get('password'):\n                self._send('PASS {password}'.format(**self.config))\n            self.notify('connection_ready')\n            self.send((\n                'USER {username} {mode} * :{realname}\\r\\n'\n                'NICK {nick}\\r\\n'\n            ).format(**self.config))\n            self.notify('connection_made')\n\n    def send_line(self, data, nowait=False):\n        \"\"\"send a line to the server. replace CR by spaces\"\"\"\n        data = data.replace('\\n', ' ').replace('\\r', ' ')\n        f = self.loop.create_future()\n        if self.queue is not None and nowait is False:\n            self.queue.put_nowait((f, data))\n        else:\n            self.send(data.replace('\\n', ' ').replace('\\r', ' '))\n            f.set_result(True)\n        return f\n\n    async def process_queue(self):\n        flood_burst = self.config.flood_burst\n        delay = float(self.config.flood_rate_delay)\n        flood_rate = delay / float(self.config.flood_rate)\n        while True:\n            if flood_burst == 0:\n                future, data = await self.queue.get()\n                future.set_result(True)\n                self.send(data)\n                await asyncio.sleep(.001, loop=self.loop)\n            else:\n                lines = []\n                for i in range(flood_burst):\n                    future, data = await self.queue.get()\n                    future.set_result(True)\n                    lines.append(data)\n                    if self.queue.empty():\n                        break\n                if lines:\n                    self.send('\\r\\n'.join(lines))\n                while not self.queue.empty():\n                    await asyncio.sleep(flood_rate, loop=self.loop)\n                    future, data = await self.queue.get()\n                    future.set_result(True)\n                    self.send(data)\n\n    def send(self, data):\n        \"\"\"send data to the server\"\"\"\n        self._send(data)\n\n    def _send(self, data):\n        self.protocol.write(data)\n        self.dispatch(data, iotype='out')\n\n    def privmsg(self, target, message, nowait=False):\n        \"\"\"send a privmsg to target\"\"\"\n        if message:\n            is_dcc = isinstance(target, DCCChat)\n            prefix = '' if is_dcc else 'PRIVMSG %s :' % target\n            messages = utils.split_message(\n                message,\n                self.config.max_length,\n                self.encoding,\n                prefix=prefix,\n            )\n            if is_dcc:\n                for message in messages:\n                    target.send_line(message)\n            elif target:\n                f = None\n                for message in messages:\n                    f = self.send_line(prefix + message,\n                                       nowait=nowait)\n                return f\n\n    def action(self, target, message, nowait=False):\n        return self.privmsg(target, '\\x01ACTION %s\\x01' % message,\n                            nowait=nowait)\n\n    def notice(self, target, message, nowait=False):\n        \"\"\"send a notice to target\"\"\"\n        if message:\n            is_dcc = isinstance(target, DCCChat)\n            prefix = '' if is_dcc else 'NOTICE %s :' % target\n            messages = utils.split_message(\n                message,\n                self.config.max_length,\n                self.encoding,\n                prefix=prefix,\n            )\n            if is_dcc:\n                for message in messages:\n                    target.send_line(message)\n            elif target:\n                f = None\n                for message in messages:\n                    f = self.send_line(prefix + message,\n                                       nowait=nowait)\n                return f\n\n    def ctcp(self, target, message, nowait=False):\n        \"\"\"send a ctcp to target\"\"\"\n        if target and message:\n            messages = utils.split_message(\n                message,\n                self.config.max_length,\n                self.encoding,\n            )\n            f = None\n            for message in messages:\n                f = self.send_line('PRIVMSG %s :\\x01%s\\x01' % (target,\n                                                               message),\n                                   nowait=nowait)\n            return f\n\n    def ctcp_reply(self, target, message, nowait=False):\n        \"\"\"send a ctcp reply to target\"\"\"\n        if target and message:\n            messages = utils.split_message(\n                message,\n                self.config.max_length,\n                self.encoding,\n            )\n            f = None\n            for message in messages:\n                f = self.send_line('NOTICE %s :\\x01%s\\x01' % (target, message),\n                                   nowait=nowait)\n            return f\n\n    def mode(self, target, *data):\n        \"\"\"set user or channel mode\"\"\"\n        self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True)\n\n    def join(self, target):\n        \"\"\"join a channel\"\"\"\n        password = self.config.passwords.get(\n            target.strip(self.server_config['CHANTYPES']))\n        if password:\n            target += ' ' + password\n        self.send_line('JOIN %s' % target)\n\n    def part(self, target, reason=None):\n        \"\"\"quit a channel\"\"\"\n        if reason:\n            target += ' :' + reason\n        self.send_line('PART %s' % target)\n\n    def kick(self, channel, target, reason=None):\n        \"\"\"kick target from channel\"\"\"\n        if reason:\n            target += ' :' + reason\n        self.send_line('KICK %s %s' % (channel, target), nowait=True)\n\n    def invite(self, target, channel):\n        \"\"\"invite target to a channel\"\"\"\n        self.send_line('INVITE %s %s' % (target, channel))\n\n    def topic(self, channel, topic=None):\n        \"\"\"change or request the topic of a channel\"\"\"\n        if topic:\n            channel += ' :' + topic\n        self.send_line('TOPIC %s' % channel)\n\n    def away(self, message=None):\n        \"\"\"mark ourself as away\"\"\"\n        cmd = 'AWAY'\n        if message:\n            cmd += ' :' + message\n        self.send_line(cmd)\n\n    def unaway(self):\n        \"\"\"mask ourself as no longer away\"\"\"\n        self.away()\n\n    def quit(self, reason=None):\n        \"\"\"disconnect\"\"\"\n        if not reason:\n            reason = 'bye'\n        else:\n            reason = reason\n        self.send_line('QUIT :%s' % reason)\n\n    def get_nick(self):\n        return self.config.nick\n\n    def set_nick(self, nick):\n        self.send_line('NICK ' + nick, nowait=True)\n\n    nick = property(get_nick, set_nick, doc='nickname get/set')\n\n    @property\n    def ip(self):\n        \"\"\"return bot's ip as an ``ip_address`` object\"\"\"\n        if not self._ip:\n            if 'ip' in self.config:\n                ip = self.config['ip']\n            else:\n                ip = self.protocol.transport.get_extra_info('sockname')[0]\n            ip = ip_address(ip)\n            if ip.version == 4:\n                self._ip = ip\n            else:  # pragma: no cover\n                response = urlopen('http://ipv4.icanhazip.com/')\n                ip = response.read().strip().decode()\n                ip = ip_address(ip)\n                self._ip = ip\n        return self._ip\n\n    @property\n    def dcc(self):\n        \"\"\"return the :class:`~irc3.dcc.DCCManager`\"\"\"\n        if self._dcc is None:\n            self._dcc = DCCManager(self)\n        return self._dcc\n\n    async def dcc_chat(self, mask, host=None, port=None):\n        \"\"\"Open a DCC CHAT whith mask. If host/port are specified then connect\n        to a server. Else create a server\"\"\"\n        conn = self.dcc.create(\n            'chat', mask, host=host, port=port)\n        await conn.ready\n        return conn\n\n    async def dcc_get(self, mask, host, port, filepath, filesize=None):\n        \"\"\"DCC GET a file from mask. filepath must be an absolute path with an\n        existing directory. filesize is the expected file size.\"\"\"\n        conn = self.dcc.create(\n            'get', mask, filepath=filepath, filesize=filesize,\n            host=host, port=port)\n        await conn.ready\n        return conn\n\n    async def dcc_send(self, mask, filepath):\n        \"\"\"DCC SEND a file to mask. filepath must be an absolute path to\n        existing file\"\"\"\n        conn = self.dcc.create('send', mask, filepath=filepath)\n        await conn.ready\n        return conn\n\n    async def dcc_accept(self, mask, filepath, port, pos):\n        \"\"\"accept a DCC RESUME for an axisting DCC SEND. filepath is the\n        filename to sent.  port is the port opened on the server.\n        pos is the expected offset\"\"\"\n        return self.dcc.resume(mask, filepath, port, pos)\n\n    def SIGHUP(self):\n        self.reload()\n\n    def SIGINT(self):\n        self.notify('SIGINT')\n        if getattr(self, 'protocol', None):\n            self.quit('INT')\n            time.sleep(1)\n        self.loop.stop()\n\n\ndef run(argv=None):\n    bots = {}\n    bot = IrcBot.from_argv(argv, botnet=bots)\n    bots['bot'] = bot\n    for section in list(bot.config):\n        if section.startswith('bot_'):\n            config = bot.config.pop(section)\n            bots[section] = IrcBot.from_argv(argv, botnet=bots, **config)\n    bot.loop.run_forever()\n    return bots\n"
  },
  {
    "path": "irc3/__main__.py",
    "content": "from irc3 import run\n\nif __name__ == '__main__':\n    run()\n"
  },
  {
    "path": "irc3/_gen_doc.py",
    "content": "# -*- coding: utf-8 -*-\nfrom . import rfc\nfrom . import template\nimport os\n\n\ndef render_attrs(title, attrs, out):\n    out.write(title + '\\n')\n    out.write(len(title) * '=' + '\\n')\n    out.write('\\n')\n    for attr in attrs:\n        name = attr.name\n        title = name\n        if isinstance(attr, int):\n            title = '%s - %s' % (attr, title)\n        out.write(title + '\\n')\n        out.write(len(title) * '-' + '\\n\\n')\n        if hasattr(attr, 'tpl'):\n            out.write('Format ``%s``\\n\\n' % attr.tpl.replace('{c.', '{'))\n        out.write('Match ``%s``\\n\\n' % attr.re)\n        out.write('Example:\\n\\n')\n        out.write('.. code-block:: python\\n\\n')\n        out.write('    @irc3.event(rfc.%s)\\n' % name)\n        params = getattr(attr, 'params', [])\n        if params:\n            params = '=None, '.join(params)\n            out.write('    def myevent(bot, %s=None):\\n' % params)\n        else:\n            out.write('    def myevent(bot):\\n' % params)\n        out.write('        # do something\\n')\n        out.write('\\n')\n        re_out = getattr(attr, 're_out', None)\n        if re_out is not None:\n            out.write('Out Match ``%s``\\n\\n' % re_out.re)\n            out.write('Example:\\n\\n')\n            out.write('.. code-block:: python\\n\\n')\n            out.write('    @irc3.event(rfc.%s, iotype=\"out\")\\n' % name)\n            params = getattr(re_out, 'params', [])\n            if params:\n                params = '=None, '.join(params)\n                out.write('    def myevent(bot, %s=None):\\n' % params)\n            else:\n                raise RuntimeError('regexp %s as no params' % re_out)\n            out.write('        # do something\\n')\n            out.write('\\n')\n\n\ndef main():\n    print('Generate docs...')\n\n    attrs = [getattr(rfc, attr) for attr in dir(rfc)\n             if attr.isupper() and attr not in ('RETCODES',)]\n    repls = [attr for attr in attrs if attr.name.startswith('RPL_')]\n    errs = [attr for attr in attrs if attr.name.startswith('ERR_')]\n    misc = [attr for attr in attrs\n            if not attr.name.startswith(('ERR_', 'RPL_'))]\n    out = open('docs/rfc.rst', 'w')\n    out.write('========================\\n')\n    out.write(':mod:`irc3.rfc` RFC1459\\n')\n    out.write('========================\\n\\n')\n    render_attrs('Replies (REPL)', repls, out)\n    render_attrs('Errors (ERR)', errs, out)\n    render_attrs('Misc', misc, out)\n\n    try:\n        os.makedirs('docs/plugins')\n    except OSError:\n        pass\n\n    for filename in os.listdir('irc3/plugins'):\n        if filename.startswith('_'):\n            continue\n        if not filename.endswith('.py'):\n            continue\n        filename = filename.replace('.py', '')\n        modname = 'irc3.plugins.%s' % filename\n        out = open('docs/plugins/' + filename + '.rst', 'w')\n        out.write('.. automodule:: ' + modname + '\\n')\n        out.write('\\n')\n\n    template.main(nick='mybot',\n                  dest=os.path.join(os.getcwd(), 'examples'))\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "irc3/_parse_rfc.py",
    "content": "# -*- coding: utf-8 -*-\nfrom collections import defaultdict\nimport pprint\nimport re\n\n_re_num = re.compile(r'\\s(?P<num>\\d+)\\s+(?P<name>(RPL|ERR)_\\w+)\\s*(?P<_>.*)')\n_re_mask = re.compile(r'^\\s{24,25}(?P<_>(\"(<|:).*|\\S.*\"$))')\n\n\ndef main():\n    print('Parsing rfc file...')\n    item = None\n    items = []\n\n    out = open('irc3/_rfc.py', 'w')\n\n    with open('irc3/rfc1459.txt') as fd:\n        for line in fd:\n            line = line.replace('<host> * <host>', '<host> * <host1>')\n            line = line.replace('<# visible>', '<visible>')\n            line = line.replace('<H|G>[*][@|+]', '<modes>')\n            line = line.replace('<nick!user|*!*>@<host|server>', '<mask>')\n\n            match = _re_num.search(line)\n            if match is not None:\n                if item:\n                    items.append((int(item['num']), item))\n                item = defaultdict(list)\n                match = match.groupdict()\n                if '_' in match:\n                    match.pop('_')\n                item.update(match)\n            match = _re_mask.search(line)\n            if match is not None:\n                item['mask'].append(match.groupdict()['_'])\n\n    _re_sub = re.compile('(?P<m><[^>]+>)')\n\n    out.write('''\nclass retcode(int):\n    name = None\n    re = None\n\n'''.lstrip())\n\n    valids = set()\n    for i, item in sorted(items):\n        mask = item['mask']\n        if mask:\n            num = item['num']\n            valids.add(i)\n            out.write('\\n')\n            out.write('%(name)s = retcode(%(num)s)\\n' % item)\n            out.write('%(name)s.name = \"%(name)s\"\\n' % item)\n            mask = [s.strip('\"\\\\ ') for s in mask]\n            omask = ' '.join(mask)\n\n            params = []\n\n            def repl(v):\n                v = v.lower()\n                v = v.replace('nickname', 'nick')\n                v = v.replace('nicks', 'nicknames')\n                for c in '!@*':\n                    v = v.replace(c, '')\n                for c in '| ':\n                    v = v.replace(c, '_')\n                v = v.strip(' _')\n                if v.endswith('_name'):\n                    v = v[:-5]\n                if v == 'client_ip_address_in_dot_form':\n                    v = 'clientip'\n                if v == 'integer':\n                    for k in 'xyz':\n                        if k not in params:\n                            v = k\n                            break\n                if v == 'command':\n                    v = 'cmd'\n                if v == 'real':\n                    v = 'realname'\n                if v == 'name' and 'nick' not in params:\n                    v = 'nick'\n                if v == 'user':\n                    if 'nick' not in params and num not in ('352',):\n                        v = 'nick'\n                    else:\n                        v = 'username'\n                return v\n\n            def tsub(m):\n                v = m.groupdict()['m'].strip('<>')\n                v = repl(v)\n                params.append(v)\n                return '{%s}' % v\n\n            if item['num'] == '303':\n                omask = ':<nicknames>'\n            elif item['num'] == '311':\n                omask = omask.replace('*', '<m>')\n            elif item['num'] == '319':\n                omask = ':<channels>'\n            elif item['num'] == '353':\n                omask = '<m> <channel> :<nicknames>'\n\n            tpl = _re_sub.sub(tsub, omask)\n            for v in ((' %d ', '{days}'),\n                      ('%d:%02d:%02d', '{hours}'),\n                      (':%-8s %-9s %-8s', '{x} {y} {z}')):\n                tpl = tpl.replace(*v)\n            tpl_ = [':{c.srv} ' + item['num'] + ' {c.nick} ']\n            if len(tpl) > 60:\n                tpl_.extend([':' + s for s in tpl.split(':', 1)])\n            else:\n                tpl_.append(tpl)\n            tpl = '\\n    '.join([repr(v) for v in tpl_])\n\n            params = []\n\n            def msub(m):\n                v = m.groupdict()['m'].strip('<>')\n                v = repl(v)\n                params.append(v)\n                return r'(?P<%s>\\S+)' % v\n\n            mask = _re_sub.sub(msub, omask)\n            if '???? ' in mask:\n                mask = mask.replace('???? ', r'\\S+ ')\n            if ' * ' in mask:\n                mask = mask.replace(' * ', r' . ')\n            if ':' in mask:\n                mask = mask.split(':', 1)[0]\n                mask += ':(?P<data>.*)'\n            mask = r'(?P<srv>\\S+) ' + str(i) + ' (?P<me>\\\\S+) \"\\n    r\"' + mask\n            mask = mask.replace(\n                r' (?P<server>\\S+)',\n                ' \"\\n    r\"(?P<server>\\\\S+)')\n            mask = mask.replace(\n                r' (?P<sent_messages>\\S+)',\n                ' \"\\n    r\"(?P<sent_messages>\\\\S+)')\n            item['mask'] = mask\n            params = [p for p in params if '<%s>' % p in mask]\n            if '<data>' in mask and 'data' not in params:\n                params.append('data')\n            out.write('%(name)s.re = (\\n    r\"^:%(mask)s\")\\n' % item)\n            params = pprint.pformat(\n                ['srv', 'me'] + params, width=60, indent=4)\n            if len(params) > 60:\n                params = params.replace('[', '[\\n ')\n            out.write('%(name)s.tpl = (\\n' % dict(item))\n            out.write('    %s)\\n' % tpl)\n            out.write('%(name)s.params = %(p)s\\n' % dict(item, p=params))\n\n    out.write('\\n')\n    out.write('RETCODES = {\\n')\n    for i, item in sorted(items):\n        if i in valids:\n            out.write('    %(num)s: %(name)s,\\n' % item)\n    out.write('}\\n')\n    out.close()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "irc3/_rfc.py",
    "content": "class retcode(int):\n    name = None\n    re = None\n\n\nRPL_TRACELINK = retcode(200)\nRPL_TRACELINK.name = \"RPL_TRACELINK\"\nRPL_TRACELINK.re = (\n    r\"^:(?P<srv>\\S+) 200 (?P<me>\\S+) \"\n    r\"(?P<next_server>\\S+)\")\nRPL_TRACELINK.tpl = (\n    ':{c.srv} 200 {c.nick} '\n    '{next_server}')\nRPL_TRACELINK.params = ['srv', 'me', 'next_server']\n\nRPL_TRACECONNECTING = retcode(201)\nRPL_TRACECONNECTING.name = \"RPL_TRACECONNECTING\"\nRPL_TRACECONNECTING.re = (\n    r\"^:(?P<srv>\\S+) 201 (?P<me>\\S+) \"\n    r\"Try. (?P<class>\\S+) \"\n    r\"(?P<server>\\S+)\")\nRPL_TRACECONNECTING.tpl = (\n    ':{c.srv} 201 {c.nick} '\n    'Try. {class} {server}')\nRPL_TRACECONNECTING.params = ['srv', 'me', 'class', 'server']\n\nRPL_TRACEHANDSHAKE = retcode(202)\nRPL_TRACEHANDSHAKE.name = \"RPL_TRACEHANDSHAKE\"\nRPL_TRACEHANDSHAKE.re = (\n    r\"^:(?P<srv>\\S+) 202 (?P<me>\\S+) \"\n    r\"H.S. (?P<class>\\S+) \"\n    r\"(?P<server>\\S+)\")\nRPL_TRACEHANDSHAKE.tpl = (\n    ':{c.srv} 202 {c.nick} '\n    'H.S. {class} {server}')\nRPL_TRACEHANDSHAKE.params = ['srv', 'me', 'class', 'server']\n\nRPL_TRACEUNKNOWN = retcode(203)\nRPL_TRACEUNKNOWN.name = \"RPL_TRACEUNKNOWN\"\nRPL_TRACEUNKNOWN.re = (\n    r\"^:(?P<srv>\\S+) 203 (?P<me>\\S+) \"\n    r\"\\S+ (?P<class>\\S+) [(?P<clientip>\\S+)]\")\nRPL_TRACEUNKNOWN.tpl = (\n    ':{c.srv} 203 {c.nick} '\n    '???? {class} [{clientip}]')\nRPL_TRACEUNKNOWN.params = ['srv', 'me', 'class', 'clientip']\n\nRPL_TRACEOPERATOR = retcode(204)\nRPL_TRACEOPERATOR.name = \"RPL_TRACEOPERATOR\"\nRPL_TRACEOPERATOR.re = (\n    r\"^:(?P<srv>\\S+) 204 (?P<me>\\S+) \"\n    r\"Oper (?P<class>\\S+) (?P<nick>\\S+)\")\nRPL_TRACEOPERATOR.tpl = (\n    ':{c.srv} 204 {c.nick} '\n    'Oper {class} {nick}')\nRPL_TRACEOPERATOR.params = ['srv', 'me', 'class', 'nick']\n\nRPL_TRACEUSER = retcode(205)\nRPL_TRACEUSER.name = \"RPL_TRACEUSER\"\nRPL_TRACEUSER.re = (\n    r\"^:(?P<srv>\\S+) 205 (?P<me>\\S+) \"\n    r\"User (?P<class>\\S+) (?P<nick>\\S+)\")\nRPL_TRACEUSER.tpl = (\n    ':{c.srv} 205 {c.nick} '\n    'User {class} {nick}')\nRPL_TRACEUSER.params = ['srv', 'me', 'class', 'nick']\n\nRPL_TRACESERVER = retcode(206)\nRPL_TRACESERVER.name = \"RPL_TRACESERVER\"\nRPL_TRACESERVER.re = (\n    r\"^:(?P<srv>\\S+) 206 (?P<me>\\S+) \"\n    r\"(?P<mask>\\S+)\")\nRPL_TRACESERVER.tpl = (\n    ':{c.srv} 206 {c.nick} '\n    '{mask}')\nRPL_TRACESERVER.params = ['srv', 'me', 'mask']\n\nRPL_TRACENEWTYPE = retcode(208)\nRPL_TRACENEWTYPE.name = \"RPL_TRACENEWTYPE\"\nRPL_TRACENEWTYPE.re = (\n    r\"^:(?P<srv>\\S+) 208 (?P<me>\\S+) \"\n    r\"(?P<newtype>\\S+) 0 (?P<client>\\S+)\")\nRPL_TRACENEWTYPE.tpl = (\n    ':{c.srv} 208 {c.nick} '\n    '{newtype} 0 {client}')\nRPL_TRACENEWTYPE.params = ['srv', 'me', 'newtype', 'client']\n\nRPL_STATSLINKINFO = retcode(211)\nRPL_STATSLINKINFO.name = \"RPL_STATSLINKINFO\"\nRPL_STATSLINKINFO.re = (\n    r\"^:(?P<srv>\\S+) 211 (?P<me>\\S+) \"\n    r\"(?P<linkname>\\S+) (?P<sendq>\\S+) \"\n    r\"(?P<sent_messages>\\S+) (?P<received_bytes>\\S+) (?P<time_open>\\S+)\")\nRPL_STATSLINKINFO.tpl = (\n    ':{c.srv} 211 {c.nick} '\n    ':{linkname} {sendq} {sent_messages} {received_bytes} {time_open}')\nRPL_STATSLINKINFO.params = [\n    'srv',\n    'me',\n    'linkname',\n    'sendq',\n    'sent_messages',\n    'received_bytes',\n    'time_open']\n\nRPL_STATSCOMMANDS = retcode(212)\nRPL_STATSCOMMANDS.name = \"RPL_STATSCOMMANDS\"\nRPL_STATSCOMMANDS.re = (\n    r\"^:(?P<srv>\\S+) 212 (?P<me>\\S+) \"\n    r\"(?P<cmd>\\S+) (?P<count>\\S+)\")\nRPL_STATSCOMMANDS.tpl = (\n    ':{c.srv} 212 {c.nick} '\n    '{cmd} {count}')\nRPL_STATSCOMMANDS.params = ['srv', 'me', 'cmd', 'count']\n\nRPL_STATSCLINE = retcode(213)\nRPL_STATSCLINE.name = \"RPL_STATSCLINE\"\nRPL_STATSCLINE.re = (\n    r\"^:(?P<srv>\\S+) 213 (?P<me>\\S+) \"\n    r\"C (?P<host>\\S+) . (?P<nick>\\S+) (?P<port>\\S+) (?P<class>\\S+)\")\nRPL_STATSCLINE.tpl = (\n    ':{c.srv} 213 {c.nick} '\n    'C {host} * {nick} {port} {class}')\nRPL_STATSCLINE.params = ['srv', 'me', 'host', 'nick', 'port', 'class']\n\nRPL_STATSNLINE = retcode(214)\nRPL_STATSNLINE.name = \"RPL_STATSNLINE\"\nRPL_STATSNLINE.re = (\n    r\"^:(?P<srv>\\S+) 214 (?P<me>\\S+) \"\n    r\"N (?P<host>\\S+) . (?P<nick>\\S+) (?P<port>\\S+) (?P<class>\\S+)\")\nRPL_STATSNLINE.tpl = (\n    ':{c.srv} 214 {c.nick} '\n    'N {host} * {nick} {port} {class}')\nRPL_STATSNLINE.params = ['srv', 'me', 'host', 'nick', 'port', 'class']\n\nRPL_STATSILINE = retcode(215)\nRPL_STATSILINE.name = \"RPL_STATSILINE\"\nRPL_STATSILINE.re = (\n    r\"^:(?P<srv>\\S+) 215 (?P<me>\\S+) \"\n    r\"I (?P<host>\\S+) . (?P<host1>\\S+) (?P<port>\\S+) (?P<class>\\S+)\")\nRPL_STATSILINE.tpl = (\n    ':{c.srv} 215 {c.nick} '\n    'I {host} * {host1} {port} {class}')\nRPL_STATSILINE.params = ['srv', 'me', 'host', 'host1', 'port', 'class']\n\nRPL_STATSKLINE = retcode(216)\nRPL_STATSKLINE.name = \"RPL_STATSKLINE\"\nRPL_STATSKLINE.re = (\n    r\"^:(?P<srv>\\S+) 216 (?P<me>\\S+) \"\n    r\"K (?P<host>\\S+) . (?P<username>\\S+) (?P<port>\\S+) (?P<class>\\S+)\")\nRPL_STATSKLINE.tpl = (\n    ':{c.srv} 216 {c.nick} '\n    'K {host} * {username} {port} {class}')\nRPL_STATSKLINE.params = ['srv', 'me', 'host', 'username', 'port', 'class']\n\nRPL_STATSYLINE = retcode(218)\nRPL_STATSYLINE.name = \"RPL_STATSYLINE\"\nRPL_STATSYLINE.re = (\n    r\"^:(?P<srv>\\S+) 218 (?P<me>\\S+) \"\n    r\"frequency> (?P<max_sendq>\\S+)\")\nRPL_STATSYLINE.tpl = (\n    ':{c.srv} 218 {c.nick} '\n    'frequency> {max_sendq}')\nRPL_STATSYLINE.params = ['srv', 'me', 'max_sendq']\n\nRPL_ENDOFSTATS = retcode(219)\nRPL_ENDOFSTATS.name = \"RPL_ENDOFSTATS\"\nRPL_ENDOFSTATS.re = (\n    r\"^:(?P<srv>\\S+) 219 (?P<me>\\S+) \"\n    r\"(?P<stats_letter>\\S+) :(?P<data>.*)\")\nRPL_ENDOFSTATS.tpl = (\n    ':{c.srv} 219 {c.nick} '\n    '{stats_letter} :End of /STATS report')\nRPL_ENDOFSTATS.params = ['srv', 'me', 'stats_letter', 'data']\n\nRPL_UMODEIS = retcode(221)\nRPL_UMODEIS.name = \"RPL_UMODEIS\"\nRPL_UMODEIS.re = (\n    r\"^:(?P<srv>\\S+) 221 (?P<me>\\S+) \"\n    r\"(?P<user_mode_string>\\S+)\")\nRPL_UMODEIS.tpl = (\n    ':{c.srv} 221 {c.nick} '\n    '{user_mode_string}')\nRPL_UMODEIS.params = ['srv', 'me', 'user_mode_string']\n\nRPL_STATSLLINE = retcode(241)\nRPL_STATSLLINE.name = \"RPL_STATSLLINE\"\nRPL_STATSLLINE.re = (\n    r\"^:(?P<srv>\\S+) 241 (?P<me>\\S+) \"\n    r\"L (?P<hostmask>\\S+) . (?P<servername>\\S+) (?P<maxdepth>\\S+)\")\nRPL_STATSLLINE.tpl = (\n    ':{c.srv} 241 {c.nick} '\n    'L {hostmask} * {servername} {maxdepth}')\nRPL_STATSLLINE.params = ['srv', 'me', 'hostmask', 'servername', 'maxdepth']\n\nRPL_STATSUPTIME = retcode(242)\nRPL_STATSUPTIME.name = \"RPL_STATSUPTIME\"\nRPL_STATSUPTIME.re = (\n    r\"^:(?P<srv>\\S+) 242 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_STATSUPTIME.tpl = (\n    ':{c.srv} 242 {c.nick} '\n    ':Server Up{days}days {hours}')\nRPL_STATSUPTIME.params = ['srv', 'me', 'data']\n\nRPL_STATSOLINE = retcode(243)\nRPL_STATSOLINE.name = \"RPL_STATSOLINE\"\nRPL_STATSOLINE.re = (\n    r\"^:(?P<srv>\\S+) 243 (?P<me>\\S+) \"\n    r\"O (?P<hostmask>\\S+) . (?P<nick>\\S+)\")\nRPL_STATSOLINE.tpl = (\n    ':{c.srv} 243 {c.nick} '\n    'O {hostmask} * {nick}')\nRPL_STATSOLINE.params = ['srv', 'me', 'hostmask', 'nick']\n\nRPL_STATSHLINE = retcode(244)\nRPL_STATSHLINE.name = \"RPL_STATSHLINE\"\nRPL_STATSHLINE.re = (\n    r\"^:(?P<srv>\\S+) 244 (?P<me>\\S+) \"\n    r\"H (?P<hostmask>\\S+) . (?P<servername>\\S+)\")\nRPL_STATSHLINE.tpl = (\n    ':{c.srv} 244 {c.nick} '\n    'H {hostmask} * {servername}')\nRPL_STATSHLINE.params = ['srv', 'me', 'hostmask', 'servername']\n\nRPL_LUSERCLIENT = retcode(251)\nRPL_LUSERCLIENT.name = \"RPL_LUSERCLIENT\"\nRPL_LUSERCLIENT.re = (\n    r\"^:(?P<srv>\\S+) 251 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_LUSERCLIENT.tpl = (\n    ':{c.srv} 251 {c.nick} '\n    ':There are {x} users and {y} invisible on {z} servers')\nRPL_LUSERCLIENT.params = ['srv', 'me', 'data']\n\nRPL_LUSEROP = retcode(252)\nRPL_LUSEROP.name = \"RPL_LUSEROP\"\nRPL_LUSEROP.re = (\n    r\"^:(?P<srv>\\S+) 252 (?P<me>\\S+) \"\n    r\"(?P<x>\\S+) :(?P<data>.*)\")\nRPL_LUSEROP.tpl = (\n    ':{c.srv} 252 {c.nick} '\n    '{x} :operator(s) online')\nRPL_LUSEROP.params = ['srv', 'me', 'x', 'data']\n\nRPL_LUSERUNKNOWN = retcode(253)\nRPL_LUSERUNKNOWN.name = \"RPL_LUSERUNKNOWN\"\nRPL_LUSERUNKNOWN.re = (\n    r\"^:(?P<srv>\\S+) 253 (?P<me>\\S+) \"\n    r\"(?P<x>\\S+) :(?P<data>.*)\")\nRPL_LUSERUNKNOWN.tpl = (\n    ':{c.srv} 253 {c.nick} '\n    '{x} :unknown connection(s)')\nRPL_LUSERUNKNOWN.params = ['srv', 'me', 'x', 'data']\n\nRPL_LUSERCHANNELS = retcode(254)\nRPL_LUSERCHANNELS.name = \"RPL_LUSERCHANNELS\"\nRPL_LUSERCHANNELS.re = (\n    r\"^:(?P<srv>\\S+) 254 (?P<me>\\S+) \"\n    r\"(?P<x>\\S+) :(?P<data>.*)\")\nRPL_LUSERCHANNELS.tpl = (\n    ':{c.srv} 254 {c.nick} '\n    '{x} :channels formed')\nRPL_LUSERCHANNELS.params = ['srv', 'me', 'x', 'data']\n\nRPL_LUSERME = retcode(255)\nRPL_LUSERME.name = \"RPL_LUSERME\"\nRPL_LUSERME.re = (\n    r\"^:(?P<srv>\\S+) 255 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_LUSERME.tpl = (\n    ':{c.srv} 255 {c.nick} '\n    ':I have {x} clients and {y}')\nRPL_LUSERME.params = ['srv', 'me', 'data']\n\nRPL_ADMINME = retcode(256)\nRPL_ADMINME.name = \"RPL_ADMINME\"\nRPL_ADMINME.re = (\n    r\"^:(?P<srv>\\S+) 256 (?P<me>\\S+) \"\n    r\"(?P<server>\\S+) :(?P<data>.*)\")\nRPL_ADMINME.tpl = (\n    ':{c.srv} 256 {c.nick} '\n    '{server} :Administrative info')\nRPL_ADMINME.params = ['srv', 'me', 'server', 'data']\n\nRPL_ADMINLOC1 = retcode(257)\nRPL_ADMINLOC1.name = \"RPL_ADMINLOC1\"\nRPL_ADMINLOC1.re = (\n    r\"^:(?P<srv>\\S+) 257 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_ADMINLOC1.tpl = (\n    ':{c.srv} 257 {c.nick} '\n    ':{admin_info}')\nRPL_ADMINLOC1.params = ['srv', 'me', 'data']\n\nRPL_ADMINLOC2 = retcode(258)\nRPL_ADMINLOC2.name = \"RPL_ADMINLOC2\"\nRPL_ADMINLOC2.re = (\n    r\"^:(?P<srv>\\S+) 258 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_ADMINLOC2.tpl = (\n    ':{c.srv} 258 {c.nick} '\n    ':{admin_info}')\nRPL_ADMINLOC2.params = ['srv', 'me', 'data']\n\nRPL_ADMINEMAIL = retcode(259)\nRPL_ADMINEMAIL.name = \"RPL_ADMINEMAIL\"\nRPL_ADMINEMAIL.re = (\n    r\"^:(?P<srv>\\S+) 259 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_ADMINEMAIL.tpl = (\n    ':{c.srv} 259 {c.nick} '\n    ':{admin_info}')\nRPL_ADMINEMAIL.params = ['srv', 'me', 'data']\n\nRPL_TRACELOG = retcode(261)\nRPL_TRACELOG.name = \"RPL_TRACELOG\"\nRPL_TRACELOG.re = (\n    r\"^:(?P<srv>\\S+) 261 (?P<me>\\S+) \"\n    r\"File (?P<logfile>\\S+) (?P<debug_level>\\S+)\")\nRPL_TRACELOG.tpl = (\n    ':{c.srv} 261 {c.nick} '\n    'File {logfile} {debug_level}')\nRPL_TRACELOG.params = ['srv', 'me', 'logfile', 'debug_level']\n\nRPL_AWAY = retcode(301)\nRPL_AWAY.name = \"RPL_AWAY\"\nRPL_AWAY.re = (\n    r\"^:(?P<srv>\\S+) 301 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nRPL_AWAY.tpl = (\n    ':{c.srv} 301 {c.nick} '\n    '{nick} :{away_message}')\nRPL_AWAY.params = ['srv', 'me', 'nick', 'data']\n\nRPL_USERHOST = retcode(302)\nRPL_USERHOST.name = \"RPL_USERHOST\"\nRPL_USERHOST.re = (\n    r\"^:(?P<srv>\\S+) 302 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_USERHOST.tpl = (\n    ':{c.srv} 302 {c.nick} '\n    ':[{reply}{{space}{reply}}]')\nRPL_USERHOST.params = ['srv', 'me', 'data']\n\nRPL_ISON = retcode(303)\nRPL_ISON.name = \"RPL_ISON\"\nRPL_ISON.re = (\n    r\"^:(?P<srv>\\S+) 303 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_ISON.tpl = (\n    ':{c.srv} 303 {c.nick} '\n    ':{nicknames}')\nRPL_ISON.params = ['srv', 'me', 'data']\n\nRPL_UNAWAY = retcode(305)\nRPL_UNAWAY.name = \"RPL_UNAWAY\"\nRPL_UNAWAY.re = (\n    r\"^:(?P<srv>\\S+) 305 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_UNAWAY.tpl = (\n    ':{c.srv} 305 {c.nick} '\n    ':You are no longer marked as being away')\nRPL_UNAWAY.params = ['srv', 'me', 'data']\n\nRPL_NOWAWAY = retcode(306)\nRPL_NOWAWAY.name = \"RPL_NOWAWAY\"\nRPL_NOWAWAY.re = (\n    r\"^:(?P<srv>\\S+) 306 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_NOWAWAY.tpl = (\n    ':{c.srv} 306 {c.nick} '\n    ':You have been marked as being away')\nRPL_NOWAWAY.params = ['srv', 'me', 'data']\n\nRPL_WHOISUSER = retcode(311)\nRPL_WHOISUSER.name = \"RPL_WHOISUSER\"\nRPL_WHOISUSER.re = (\n    r\"^:(?P<srv>\\S+) 311 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) (?P<username>\\S+) (?P<host>\\S+) (?P<m>\\S+) :(?P<data>.*)\")\nRPL_WHOISUSER.tpl = (\n    ':{c.srv} 311 {c.nick} '\n    '{nick} {username} {host} {m} :{realname}')\nRPL_WHOISUSER.params = ['srv', 'me', 'nick', 'username', 'host', 'm', 'data']\n\nRPL_WHOISSERVER = retcode(312)\nRPL_WHOISSERVER.name = \"RPL_WHOISSERVER\"\nRPL_WHOISSERVER.re = (\n    r\"^:(?P<srv>\\S+) 312 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) \"\n    r\"(?P<server>\\S+) :(?P<data>.*)\")\nRPL_WHOISSERVER.tpl = (\n    ':{c.srv} 312 {c.nick} '\n    '{nick} {server} :{server_info}')\nRPL_WHOISSERVER.params = ['srv', 'me', 'nick', 'server', 'data']\n\nRPL_WHOISOPERATOR = retcode(313)\nRPL_WHOISOPERATOR.name = \"RPL_WHOISOPERATOR\"\nRPL_WHOISOPERATOR.re = (\n    r\"^:(?P<srv>\\S+) 313 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nRPL_WHOISOPERATOR.tpl = (\n    ':{c.srv} 313 {c.nick} '\n    '{nick} :is an IRC operator')\nRPL_WHOISOPERATOR.params = ['srv', 'me', 'nick', 'data']\n\nRPL_WHOWASUSER = retcode(314)\nRPL_WHOWASUSER.name = \"RPL_WHOWASUSER\"\nRPL_WHOWASUSER.re = (\n    r\"^:(?P<srv>\\S+) 314 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) (?P<username>\\S+) (?P<host>\\S+) . :(?P<data>.*)\")\nRPL_WHOWASUSER.tpl = (\n    ':{c.srv} 314 {c.nick} '\n    '{nick} {username} {host} * :{realname}')\nRPL_WHOWASUSER.params = ['srv', 'me', 'nick', 'username', 'host', 'data']\n\nRPL_ENDOFWHO = retcode(315)\nRPL_ENDOFWHO.name = \"RPL_ENDOFWHO\"\nRPL_ENDOFWHO.re = (\n    r\"^:(?P<srv>\\S+) 315 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nRPL_ENDOFWHO.tpl = (\n    ':{c.srv} 315 {c.nick} '\n    '{nick} :End of /WHO list')\nRPL_ENDOFWHO.params = ['srv', 'me', 'nick', 'data']\n\nRPL_WHOISIDLE = retcode(317)\nRPL_WHOISIDLE.name = \"RPL_WHOISIDLE\"\nRPL_WHOISIDLE.re = (\n    r\"^:(?P<srv>\\S+) 317 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) (?P<x>\\S+) :(?P<data>.*)\")\nRPL_WHOISIDLE.tpl = (\n    ':{c.srv} 317 {c.nick} '\n    '{nick} {x} :seconds idle')\nRPL_WHOISIDLE.params = ['srv', 'me', 'nick', 'x', 'data']\n\nRPL_ENDOFWHOIS = retcode(318)\nRPL_ENDOFWHOIS.name = \"RPL_ENDOFWHOIS\"\nRPL_ENDOFWHOIS.re = (\n    r\"^:(?P<srv>\\S+) 318 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nRPL_ENDOFWHOIS.tpl = (\n    ':{c.srv} 318 {c.nick} '\n    '{nick} :End of /WHOIS list')\nRPL_ENDOFWHOIS.params = ['srv', 'me', 'nick', 'data']\n\nRPL_WHOISCHANNELS = retcode(319)\nRPL_WHOISCHANNELS.name = \"RPL_WHOISCHANNELS\"\nRPL_WHOISCHANNELS.re = (\n    r\"^:(?P<srv>\\S+) 319 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_WHOISCHANNELS.tpl = (\n    ':{c.srv} 319 {c.nick} '\n    ':{channels}')\nRPL_WHOISCHANNELS.params = ['srv', 'me', 'data']\n\nRPL_LISTSTART = retcode(321)\nRPL_LISTSTART.name = \"RPL_LISTSTART\"\nRPL_LISTSTART.re = (\n    r\"^:(?P<srv>\\S+) 321 (?P<me>\\S+) \"\n    r\"Channel :(?P<data>.*)\")\nRPL_LISTSTART.tpl = (\n    ':{c.srv} 321 {c.nick} '\n    'Channel :Users  Name')\nRPL_LISTSTART.params = ['srv', 'me', 'data']\n\nRPL_LIST = retcode(322)\nRPL_LIST.name = \"RPL_LIST\"\nRPL_LIST.re = (\n    r\"^:(?P<srv>\\S+) 322 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) (?P<visible>\\S+) :(?P<data>.*)\")\nRPL_LIST.tpl = (\n    ':{c.srv} 322 {c.nick} '\n    '{channel} {visible} :{topic}')\nRPL_LIST.params = ['srv', 'me', 'channel', 'visible', 'data']\n\nRPL_LISTEND = retcode(323)\nRPL_LISTEND.name = \"RPL_LISTEND\"\nRPL_LISTEND.re = (\n    r\"^:(?P<srv>\\S+) 323 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_LISTEND.tpl = (\n    ':{c.srv} 323 {c.nick} '\n    ':End of /LIST')\nRPL_LISTEND.params = ['srv', 'me', 'data']\n\nRPL_CHANNELMODEIS = retcode(324)\nRPL_CHANNELMODEIS.name = \"RPL_CHANNELMODEIS\"\nRPL_CHANNELMODEIS.re = (\n    r\"^:(?P<srv>\\S+) 324 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) (?P<mode>\\S+) (?P<mode_params>\\S+)\")\nRPL_CHANNELMODEIS.tpl = (\n    ':{c.srv} 324 {c.nick} '\n    '{channel} {mode} {mode_params}')\nRPL_CHANNELMODEIS.params = ['srv', 'me', 'channel', 'mode', 'mode_params']\n\nRPL_NOTOPIC = retcode(331)\nRPL_NOTOPIC.name = \"RPL_NOTOPIC\"\nRPL_NOTOPIC.re = (\n    r\"^:(?P<srv>\\S+) 331 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nRPL_NOTOPIC.tpl = (\n    ':{c.srv} 331 {c.nick} '\n    '{channel} :No topic is set')\nRPL_NOTOPIC.params = ['srv', 'me', 'channel', 'data']\n\nRPL_TOPIC = retcode(332)\nRPL_TOPIC.name = \"RPL_TOPIC\"\nRPL_TOPIC.re = (\n    r\"^:(?P<srv>\\S+) 332 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nRPL_TOPIC.tpl = (\n    ':{c.srv} 332 {c.nick} '\n    '{channel} :{topic}')\nRPL_TOPIC.params = ['srv', 'me', 'channel', 'data']\n\nRPL_INVITING = retcode(341)\nRPL_INVITING.name = \"RPL_INVITING\"\nRPL_INVITING.re = (\n    r\"^:(?P<srv>\\S+) 341 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) (?P<nick>\\S+)\")\nRPL_INVITING.tpl = (\n    ':{c.srv} 341 {c.nick} '\n    '{channel} {nick}')\nRPL_INVITING.params = ['srv', 'me', 'channel', 'nick']\n\nRPL_SUMMONING = retcode(342)\nRPL_SUMMONING.name = \"RPL_SUMMONING\"\nRPL_SUMMONING.re = (\n    r\"^:(?P<srv>\\S+) 342 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nRPL_SUMMONING.tpl = (\n    ':{c.srv} 342 {c.nick} '\n    '{nick} :Summoning user to IRC')\nRPL_SUMMONING.params = ['srv', 'me', 'nick', 'data']\n\nRPL_VERSION = retcode(351)\nRPL_VERSION.name = \"RPL_VERSION\"\nRPL_VERSION.re = (\n    r\"^:(?P<srv>\\S+) 351 (?P<me>\\S+) \"\n    r\"(?P<version>\\S+).(?P<debuglevel>\\S+) \"\n    r\"(?P<server>\\S+) :(?P<data>.*)\")\nRPL_VERSION.tpl = (\n    ':{c.srv} 351 {c.nick} '\n    '{version}.{debuglevel} {server} :{comments}')\nRPL_VERSION.params = ['srv', 'me', 'version', 'debuglevel', 'server', 'data']\n\nRPL_WHOREPLY = retcode(352)\nRPL_WHOREPLY.name = \"RPL_WHOREPLY\"\nRPL_WHOREPLY.re = (\n    r\"^:(?P<srv>\\S+) 352 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) (?P<username>\\S+) (?P<host>\\S+) \"\n    r\"(?P<server>\\S+) (?P<nick>\\S+) (?P<modes>\\S+) :(?P<data>.*)\")\nRPL_WHOREPLY.tpl = (\n    ':{c.srv} 352 {c.nick} '\n    ':{channel} {username} {host} {server} {nick} {modes} '\n    ':{hopcount} {realname}')\nRPL_WHOREPLY.params = [\n    'srv',\n    'me',\n    'channel',\n    'username',\n    'host',\n    'server',\n    'nick',\n    'modes',\n    'data']\n\nRPL_NAMREPLY = retcode(353)\nRPL_NAMREPLY.name = \"RPL_NAMREPLY\"\nRPL_NAMREPLY.re = (\n    r\"^:(?P<srv>\\S+) 353 (?P<me>\\S+) \"\n    r\"(?P<m>\\S+) (?P<channel>\\S+) :(?P<data>.*)\")\nRPL_NAMREPLY.tpl = (\n    ':{c.srv} 353 {c.nick} '\n    '{m} {channel} :{nicknames}')\nRPL_NAMREPLY.params = ['srv', 'me', 'm', 'channel', 'data']\n\nRPL_LINKS = retcode(364)\nRPL_LINKS.name = \"RPL_LINKS\"\nRPL_LINKS.re = (\n    r\"^:(?P<srv>\\S+) 364 (?P<me>\\S+) \"\n    r\"(?P<mask>\\S+) \"\n    r\"(?P<server>\\S+) :(?P<data>.*)\")\nRPL_LINKS.tpl = (\n    ':{c.srv} 364 {c.nick} '\n    '{mask} {server} :{hopcount} {server_info}')\nRPL_LINKS.params = ['srv', 'me', 'mask', 'server', 'data']\n\nRPL_ENDOFLINKS = retcode(365)\nRPL_ENDOFLINKS.name = \"RPL_ENDOFLINKS\"\nRPL_ENDOFLINKS.re = (\n    r\"^:(?P<srv>\\S+) 365 (?P<me>\\S+) \"\n    r\"(?P<mask>\\S+) :(?P<data>.*)\")\nRPL_ENDOFLINKS.tpl = (\n    ':{c.srv} 365 {c.nick} '\n    '{mask} :End of /LINKS list')\nRPL_ENDOFLINKS.params = ['srv', 'me', 'mask', 'data']\n\nRPL_ENDOFNAMES = retcode(366)\nRPL_ENDOFNAMES.name = \"RPL_ENDOFNAMES\"\nRPL_ENDOFNAMES.re = (\n    r\"^:(?P<srv>\\S+) 366 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nRPL_ENDOFNAMES.tpl = (\n    ':{c.srv} 366 {c.nick} '\n    '{channel} :End of /NAMES list')\nRPL_ENDOFNAMES.params = ['srv', 'me', 'channel', 'data']\n\nRPL_BANLIST = retcode(367)\nRPL_BANLIST.name = \"RPL_BANLIST\"\nRPL_BANLIST.re = (\n    r\"^:(?P<srv>\\S+) 367 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) (?P<banid>\\S+)\")\nRPL_BANLIST.tpl = (\n    ':{c.srv} 367 {c.nick} '\n    '{channel} {banid}')\nRPL_BANLIST.params = ['srv', 'me', 'channel', 'banid']\n\nRPL_ENDOFBANLIST = retcode(368)\nRPL_ENDOFBANLIST.name = \"RPL_ENDOFBANLIST\"\nRPL_ENDOFBANLIST.re = (\n    r\"^:(?P<srv>\\S+) 368 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nRPL_ENDOFBANLIST.tpl = (\n    ':{c.srv} 368 {c.nick} '\n    '{channel} :End of channel ban list')\nRPL_ENDOFBANLIST.params = ['srv', 'me', 'channel', 'data']\n\nRPL_ENDOFWHOWAS = retcode(369)\nRPL_ENDOFWHOWAS.name = \"RPL_ENDOFWHOWAS\"\nRPL_ENDOFWHOWAS.re = (\n    r\"^:(?P<srv>\\S+) 369 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nRPL_ENDOFWHOWAS.tpl = (\n    ':{c.srv} 369 {c.nick} '\n    '{nick} :End of WHOWAS')\nRPL_ENDOFWHOWAS.params = ['srv', 'me', 'nick', 'data']\n\nRPL_INFO = retcode(371)\nRPL_INFO.name = \"RPL_INFO\"\nRPL_INFO.re = (\n    r\"^:(?P<srv>\\S+) 371 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_INFO.tpl = (\n    ':{c.srv} 371 {c.nick} '\n    ':{string}')\nRPL_INFO.params = ['srv', 'me', 'data']\n\nRPL_MOTD = retcode(372)\nRPL_MOTD.name = \"RPL_MOTD\"\nRPL_MOTD.re = (\n    r\"^:(?P<srv>\\S+) 372 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_MOTD.tpl = (\n    ':{c.srv} 372 {c.nick} '\n    ':- {text}')\nRPL_MOTD.params = ['srv', 'me', 'data']\n\nRPL_ENDOFINFO = retcode(374)\nRPL_ENDOFINFO.name = \"RPL_ENDOFINFO\"\nRPL_ENDOFINFO.re = (\n    r\"^:(?P<srv>\\S+) 374 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_ENDOFINFO.tpl = (\n    ':{c.srv} 374 {c.nick} '\n    ':End of /INFO list')\nRPL_ENDOFINFO.params = ['srv', 'me', 'data']\n\nRPL_MOTDSTART = retcode(375)\nRPL_MOTDSTART.name = \"RPL_MOTDSTART\"\nRPL_MOTDSTART.re = (\n    r\"^:(?P<srv>\\S+) 375 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_MOTDSTART.tpl = (\n    ':{c.srv} 375 {c.nick} '\n    ':- {server} Message of the day -')\nRPL_MOTDSTART.params = ['srv', 'me', 'data']\n\nRPL_ENDOFMOTD = retcode(376)\nRPL_ENDOFMOTD.name = \"RPL_ENDOFMOTD\"\nRPL_ENDOFMOTD.re = (\n    r\"^:(?P<srv>\\S+) 376 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_ENDOFMOTD.tpl = (\n    ':{c.srv} 376 {c.nick} '\n    ':End of /MOTD command')\nRPL_ENDOFMOTD.params = ['srv', 'me', 'data']\n\nRPL_YOUREOPER = retcode(381)\nRPL_YOUREOPER.name = \"RPL_YOUREOPER\"\nRPL_YOUREOPER.re = (\n    r\"^:(?P<srv>\\S+) 381 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_YOUREOPER.tpl = (\n    ':{c.srv} 381 {c.nick} '\n    ':You are now an IRC operator')\nRPL_YOUREOPER.params = ['srv', 'me', 'data']\n\nRPL_REHASHING = retcode(382)\nRPL_REHASHING.name = \"RPL_REHASHING\"\nRPL_REHASHING.re = (\n    r\"^:(?P<srv>\\S+) 382 (?P<me>\\S+) \"\n    r\"(?P<config_file>\\S+) :(?P<data>.*)\")\nRPL_REHASHING.tpl = (\n    ':{c.srv} 382 {c.nick} '\n    '{config_file} :Rehashing')\nRPL_REHASHING.params = ['srv', 'me', 'config_file', 'data']\n\nRPL_TIME = retcode(391)\nRPL_TIME.name = \"RPL_TIME\"\nRPL_TIME.re = (\n    r\"^:(?P<srv>\\S+) 391 (?P<me>\\S+) \"\n    r\"(?P<server>\\S+) :(?P<data>.*)\")\nRPL_TIME.tpl = (\n    ':{c.srv} 391 {c.nick} '\n    \"{server} :{string_showing_server's_local_time}\")\nRPL_TIME.params = ['srv', 'me', 'server', 'data']\n\nRPL_USERSSTART = retcode(392)\nRPL_USERSSTART.name = \"RPL_USERSSTART\"\nRPL_USERSSTART.re = (\n    r\"^:(?P<srv>\\S+) 392 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_USERSSTART.tpl = (\n    ':{c.srv} 392 {c.nick} '\n    ':UserID   Terminal  Host')\nRPL_USERSSTART.params = ['srv', 'me', 'data']\n\nRPL_USERS = retcode(393)\nRPL_USERS.name = \"RPL_USERS\"\nRPL_USERS.re = (\n    r\"^:(?P<srv>\\S+) 393 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_USERS.tpl = (\n    ':{c.srv} 393 {c.nick} '\n    '{x} {y} {z}')\nRPL_USERS.params = ['srv', 'me', 'data']\n\nRPL_ENDOFUSERS = retcode(394)\nRPL_ENDOFUSERS.name = \"RPL_ENDOFUSERS\"\nRPL_ENDOFUSERS.re = (\n    r\"^:(?P<srv>\\S+) 394 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_ENDOFUSERS.tpl = (\n    ':{c.srv} 394 {c.nick} '\n    ':End of users')\nRPL_ENDOFUSERS.params = ['srv', 'me', 'data']\n\nRPL_NOUSERS = retcode(395)\nRPL_NOUSERS.name = \"RPL_NOUSERS\"\nRPL_NOUSERS.re = (\n    r\"^:(?P<srv>\\S+) 395 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nRPL_NOUSERS.tpl = (\n    ':{c.srv} 395 {c.nick} '\n    ':Nobody logged in')\nRPL_NOUSERS.params = ['srv', 'me', 'data']\n\nERR_NOSUCHNICK = retcode(401)\nERR_NOSUCHNICK.name = \"ERR_NOSUCHNICK\"\nERR_NOSUCHNICK.re = (\n    r\"^:(?P<srv>\\S+) 401 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nERR_NOSUCHNICK.tpl = (\n    ':{c.srv} 401 {c.nick} '\n    '{nick} :No such nick/channel')\nERR_NOSUCHNICK.params = ['srv', 'me', 'nick', 'data']\n\nERR_NOSUCHSERVER = retcode(402)\nERR_NOSUCHSERVER.name = \"ERR_NOSUCHSERVER\"\nERR_NOSUCHSERVER.re = (\n    r\"^:(?P<srv>\\S+) 402 (?P<me>\\S+) \"\n    r\"(?P<server>\\S+) :(?P<data>.*)\")\nERR_NOSUCHSERVER.tpl = (\n    ':{c.srv} 402 {c.nick} '\n    '{server} :No such server')\nERR_NOSUCHSERVER.params = ['srv', 'me', 'server', 'data']\n\nERR_NOSUCHCHANNEL = retcode(403)\nERR_NOSUCHCHANNEL.name = \"ERR_NOSUCHCHANNEL\"\nERR_NOSUCHCHANNEL.re = (\n    r\"^:(?P<srv>\\S+) 403 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_NOSUCHCHANNEL.tpl = (\n    ':{c.srv} 403 {c.nick} '\n    '{channel} :No such channel')\nERR_NOSUCHCHANNEL.params = ['srv', 'me', 'channel', 'data']\n\nERR_CANNOTSENDTOCHAN = retcode(404)\nERR_CANNOTSENDTOCHAN.name = \"ERR_CANNOTSENDTOCHAN\"\nERR_CANNOTSENDTOCHAN.re = (\n    r\"^:(?P<srv>\\S+) 404 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_CANNOTSENDTOCHAN.tpl = (\n    ':{c.srv} 404 {c.nick} '\n    '{channel} :Cannot send to channel')\nERR_CANNOTSENDTOCHAN.params = ['srv', 'me', 'channel', 'data']\n\nERR_TOOMANYCHANNELS = retcode(405)\nERR_TOOMANYCHANNELS.name = \"ERR_TOOMANYCHANNELS\"\nERR_TOOMANYCHANNELS.re = (\n    r\"^:(?P<srv>\\S+) 405 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_TOOMANYCHANNELS.tpl = (\n    ':{c.srv} 405 {c.nick} '\n    '{channel} :You have joined too many channels')\nERR_TOOMANYCHANNELS.params = ['srv', 'me', 'channel', 'data']\n\nERR_WASNOSUCHNICK = retcode(406)\nERR_WASNOSUCHNICK.name = \"ERR_WASNOSUCHNICK\"\nERR_WASNOSUCHNICK.re = (\n    r\"^:(?P<srv>\\S+) 406 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nERR_WASNOSUCHNICK.tpl = (\n    ':{c.srv} 406 {c.nick} '\n    '{nick} :There was no such nickname')\nERR_WASNOSUCHNICK.params = ['srv', 'me', 'nick', 'data']\n\nERR_TOOMANYTARGETS = retcode(407)\nERR_TOOMANYTARGETS.name = \"ERR_TOOMANYTARGETS\"\nERR_TOOMANYTARGETS.re = (\n    r\"^:(?P<srv>\\S+) 407 (?P<me>\\S+) \"\n    r\"(?P<target>\\S+) :(?P<data>.*)\")\nERR_TOOMANYTARGETS.tpl = (\n    ':{c.srv} 407 {c.nick} '\n    '{target} :Duplicate recipients. No message delivered')\nERR_TOOMANYTARGETS.params = ['srv', 'me', 'target', 'data']\n\nERR_NOORIGIN = retcode(409)\nERR_NOORIGIN.name = \"ERR_NOORIGIN\"\nERR_NOORIGIN.re = (\n    r\"^:(?P<srv>\\S+) 409 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NOORIGIN.tpl = (\n    ':{c.srv} 409 {c.nick} '\n    ':No origin specified')\nERR_NOORIGIN.params = ['srv', 'me', 'data']\n\nERR_NORECIPIENT = retcode(411)\nERR_NORECIPIENT.name = \"ERR_NORECIPIENT\"\nERR_NORECIPIENT.re = (\n    r\"^:(?P<srv>\\S+) 411 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NORECIPIENT.tpl = (\n    ':{c.srv} 411 {c.nick} '\n    ':No recipient given ({cmd})')\nERR_NORECIPIENT.params = ['srv', 'me', 'data']\n\nERR_NOTEXTTOSEND = retcode(412)\nERR_NOTEXTTOSEND.name = \"ERR_NOTEXTTOSEND\"\nERR_NOTEXTTOSEND.re = (\n    r\"^:(?P<srv>\\S+) 412 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NOTEXTTOSEND.tpl = (\n    ':{c.srv} 412 {c.nick} '\n    ':No text to send')\nERR_NOTEXTTOSEND.params = ['srv', 'me', 'data']\n\nERR_NOTOPLEVEL = retcode(413)\nERR_NOTOPLEVEL.name = \"ERR_NOTOPLEVEL\"\nERR_NOTOPLEVEL.re = (\n    r\"^:(?P<srv>\\S+) 413 (?P<me>\\S+) \"\n    r\"(?P<mask>\\S+) :(?P<data>.*)\")\nERR_NOTOPLEVEL.tpl = (\n    ':{c.srv} 413 {c.nick} '\n    '{mask} :No toplevel domain specified')\nERR_NOTOPLEVEL.params = ['srv', 'me', 'mask', 'data']\n\nERR_WILDTOPLEVEL = retcode(414)\nERR_WILDTOPLEVEL.name = \"ERR_WILDTOPLEVEL\"\nERR_WILDTOPLEVEL.re = (\n    r\"^:(?P<srv>\\S+) 414 (?P<me>\\S+) \"\n    r\"(?P<mask>\\S+) :(?P<data>.*)\")\nERR_WILDTOPLEVEL.tpl = (\n    ':{c.srv} 414 {c.nick} '\n    '{mask} :Wildcard in toplevel domain')\nERR_WILDTOPLEVEL.params = ['srv', 'me', 'mask', 'data']\n\nERR_UNKNOWNCOMMAND = retcode(421)\nERR_UNKNOWNCOMMAND.name = \"ERR_UNKNOWNCOMMAND\"\nERR_UNKNOWNCOMMAND.re = (\n    r\"^:(?P<srv>\\S+) 421 (?P<me>\\S+) \"\n    r\"(?P<cmd>\\S+) :(?P<data>.*)\")\nERR_UNKNOWNCOMMAND.tpl = (\n    ':{c.srv} 421 {c.nick} '\n    '{cmd} :Unknown command')\nERR_UNKNOWNCOMMAND.params = ['srv', 'me', 'cmd', 'data']\n\nERR_NOMOTD = retcode(422)\nERR_NOMOTD.name = \"ERR_NOMOTD\"\nERR_NOMOTD.re = (\n    r\"^:(?P<srv>\\S+) 422 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NOMOTD.tpl = (\n    ':{c.srv} 422 {c.nick} '\n    ':MOTD File is missing')\nERR_NOMOTD.params = ['srv', 'me', 'data']\n\nERR_NOADMININFO = retcode(423)\nERR_NOADMININFO.name = \"ERR_NOADMININFO\"\nERR_NOADMININFO.re = (\n    r\"^:(?P<srv>\\S+) 423 (?P<me>\\S+) \"\n    r\"(?P<server>\\S+) :(?P<data>.*)\")\nERR_NOADMININFO.tpl = (\n    ':{c.srv} 423 {c.nick} '\n    '{server} :No administrative info available')\nERR_NOADMININFO.params = ['srv', 'me', 'server', 'data']\n\nERR_NONICKNAMEGIVEN = retcode(431)\nERR_NONICKNAMEGIVEN.name = \"ERR_NONICKNAMEGIVEN\"\nERR_NONICKNAMEGIVEN.re = (\n    r\"^:(?P<srv>\\S+) 431 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NONICKNAMEGIVEN.tpl = (\n    ':{c.srv} 431 {c.nick} '\n    ':No nickname given')\nERR_NONICKNAMEGIVEN.params = ['srv', 'me', 'data']\n\nERR_ERRONEUSNICKNAME = retcode(432)\nERR_ERRONEUSNICKNAME.name = \"ERR_ERRONEUSNICKNAME\"\nERR_ERRONEUSNICKNAME.re = (\n    r\"^:(?P<srv>\\S+) 432 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nERR_ERRONEUSNICKNAME.tpl = (\n    ':{c.srv} 432 {c.nick} '\n    '{nick} :Erroneus nickname')\nERR_ERRONEUSNICKNAME.params = ['srv', 'me', 'nick', 'data']\n\nERR_NICKNAMEINUSE = retcode(433)\nERR_NICKNAMEINUSE.name = \"ERR_NICKNAMEINUSE\"\nERR_NICKNAMEINUSE.re = (\n    r\"^:(?P<srv>\\S+) 433 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nERR_NICKNAMEINUSE.tpl = (\n    ':{c.srv} 433 {c.nick} '\n    '{nick} :Nickname is already in use')\nERR_NICKNAMEINUSE.params = ['srv', 'me', 'nick', 'data']\n\nERR_NICKCOLLISION = retcode(436)\nERR_NICKCOLLISION.name = \"ERR_NICKCOLLISION\"\nERR_NICKCOLLISION.re = (\n    r\"^:(?P<srv>\\S+) 436 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nERR_NICKCOLLISION.tpl = (\n    ':{c.srv} 436 {c.nick} '\n    '{nick} :Nickname collision KILL')\nERR_NICKCOLLISION.params = ['srv', 'me', 'nick', 'data']\n\nERR_USERNOTINCHANNEL = retcode(441)\nERR_USERNOTINCHANNEL.name = \"ERR_USERNOTINCHANNEL\"\nERR_USERNOTINCHANNEL.re = (\n    r\"^:(?P<srv>\\S+) 441 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) (?P<channel>\\S+) :(?P<data>.*)\")\nERR_USERNOTINCHANNEL.tpl = (\n    ':{c.srv} 441 {c.nick} '\n    \"{nick} {channel} :They aren't on that channel\")\nERR_USERNOTINCHANNEL.params = ['srv', 'me', 'nick', 'channel', 'data']\n\nERR_NOTONCHANNEL = retcode(442)\nERR_NOTONCHANNEL.name = \"ERR_NOTONCHANNEL\"\nERR_NOTONCHANNEL.re = (\n    r\"^:(?P<srv>\\S+) 442 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_NOTONCHANNEL.tpl = (\n    ':{c.srv} 442 {c.nick} '\n    \"{channel} :You're not on that channel\")\nERR_NOTONCHANNEL.params = ['srv', 'me', 'channel', 'data']\n\nERR_USERONCHANNEL = retcode(443)\nERR_USERONCHANNEL.name = \"ERR_USERONCHANNEL\"\nERR_USERONCHANNEL.re = (\n    r\"^:(?P<srv>\\S+) 443 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) (?P<channel>\\S+) :(?P<data>.*)\")\nERR_USERONCHANNEL.tpl = (\n    ':{c.srv} 443 {c.nick} '\n    '{nick} {channel} :is already on channel')\nERR_USERONCHANNEL.params = ['srv', 'me', 'nick', 'channel', 'data']\n\nERR_NOLOGIN = retcode(444)\nERR_NOLOGIN.name = \"ERR_NOLOGIN\"\nERR_NOLOGIN.re = (\n    r\"^:(?P<srv>\\S+) 444 (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\nERR_NOLOGIN.tpl = (\n    ':{c.srv} 444 {c.nick} '\n    '{nick} :User not logged in')\nERR_NOLOGIN.params = ['srv', 'me', 'nick', 'data']\n\nERR_SUMMONDISABLED = retcode(445)\nERR_SUMMONDISABLED.name = \"ERR_SUMMONDISABLED\"\nERR_SUMMONDISABLED.re = (\n    r\"^:(?P<srv>\\S+) 445 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_SUMMONDISABLED.tpl = (\n    ':{c.srv} 445 {c.nick} '\n    ':SUMMON has been disabled')\nERR_SUMMONDISABLED.params = ['srv', 'me', 'data']\n\nERR_USERSDISABLED = retcode(446)\nERR_USERSDISABLED.name = \"ERR_USERSDISABLED\"\nERR_USERSDISABLED.re = (\n    r\"^:(?P<srv>\\S+) 446 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_USERSDISABLED.tpl = (\n    ':{c.srv} 446 {c.nick} '\n    ':USERS has been disabled')\nERR_USERSDISABLED.params = ['srv', 'me', 'data']\n\nERR_NOTREGISTERED = retcode(451)\nERR_NOTREGISTERED.name = \"ERR_NOTREGISTERED\"\nERR_NOTREGISTERED.re = (\n    r\"^:(?P<srv>\\S+) 451 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NOTREGISTERED.tpl = (\n    ':{c.srv} 451 {c.nick} '\n    ':You have not registered')\nERR_NOTREGISTERED.params = ['srv', 'me', 'data']\n\nERR_NEEDMOREPARAMS = retcode(461)\nERR_NEEDMOREPARAMS.name = \"ERR_NEEDMOREPARAMS\"\nERR_NEEDMOREPARAMS.re = (\n    r\"^:(?P<srv>\\S+) 461 (?P<me>\\S+) \"\n    r\"(?P<cmd>\\S+) :(?P<data>.*)\")\nERR_NEEDMOREPARAMS.tpl = (\n    ':{c.srv} 461 {c.nick} '\n    '{cmd} :Not enough parameters')\nERR_NEEDMOREPARAMS.params = ['srv', 'me', 'cmd', 'data']\n\nERR_ALREADYREGISTRED = retcode(462)\nERR_ALREADYREGISTRED.name = \"ERR_ALREADYREGISTRED\"\nERR_ALREADYREGISTRED.re = (\n    r\"^:(?P<srv>\\S+) 462 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_ALREADYREGISTRED.tpl = (\n    ':{c.srv} 462 {c.nick} '\n    ':You may not reregister')\nERR_ALREADYREGISTRED.params = ['srv', 'me', 'data']\n\nERR_NOPERMFORHOST = retcode(463)\nERR_NOPERMFORHOST.name = \"ERR_NOPERMFORHOST\"\nERR_NOPERMFORHOST.re = (\n    r\"^:(?P<srv>\\S+) 463 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NOPERMFORHOST.tpl = (\n    ':{c.srv} 463 {c.nick} '\n    \":Your host isn't among the privileged\")\nERR_NOPERMFORHOST.params = ['srv', 'me', 'data']\n\nERR_PASSWDMISMATCH = retcode(464)\nERR_PASSWDMISMATCH.name = \"ERR_PASSWDMISMATCH\"\nERR_PASSWDMISMATCH.re = (\n    r\"^:(?P<srv>\\S+) 464 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_PASSWDMISMATCH.tpl = (\n    ':{c.srv} 464 {c.nick} '\n    ':Password incorrect')\nERR_PASSWDMISMATCH.params = ['srv', 'me', 'data']\n\nERR_YOUREBANNEDCREEP = retcode(465)\nERR_YOUREBANNEDCREEP.name = \"ERR_YOUREBANNEDCREEP\"\nERR_YOUREBANNEDCREEP.re = (\n    r\"^:(?P<srv>\\S+) 465 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_YOUREBANNEDCREEP.tpl = (\n    ':{c.srv} 465 {c.nick} '\n    ':You are banned from this server')\nERR_YOUREBANNEDCREEP.params = ['srv', 'me', 'data']\n\nERR_KEYSET = retcode(467)\nERR_KEYSET.name = \"ERR_KEYSET\"\nERR_KEYSET.re = (\n    r\"^:(?P<srv>\\S+) 467 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_KEYSET.tpl = (\n    ':{c.srv} 467 {c.nick} '\n    '{channel} :Channel key already set')\nERR_KEYSET.params = ['srv', 'me', 'channel', 'data']\n\nERR_CHANNELISFULL = retcode(471)\nERR_CHANNELISFULL.name = \"ERR_CHANNELISFULL\"\nERR_CHANNELISFULL.re = (\n    r\"^:(?P<srv>\\S+) 471 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_CHANNELISFULL.tpl = (\n    ':{c.srv} 471 {c.nick} '\n    '{channel} :Cannot join channel (+l)')\nERR_CHANNELISFULL.params = ['srv', 'me', 'channel', 'data']\n\nERR_UNKNOWNMODE = retcode(472)\nERR_UNKNOWNMODE.name = \"ERR_UNKNOWNMODE\"\nERR_UNKNOWNMODE.re = (\n    r\"^:(?P<srv>\\S+) 472 (?P<me>\\S+) \"\n    r\"(?P<char>\\S+) :(?P<data>.*)\")\nERR_UNKNOWNMODE.tpl = (\n    ':{c.srv} 472 {c.nick} '\n    '{char} :is unknown mode char to me')\nERR_UNKNOWNMODE.params = ['srv', 'me', 'char', 'data']\n\nERR_INVITEONLYCHAN = retcode(473)\nERR_INVITEONLYCHAN.name = \"ERR_INVITEONLYCHAN\"\nERR_INVITEONLYCHAN.re = (\n    r\"^:(?P<srv>\\S+) 473 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_INVITEONLYCHAN.tpl = (\n    ':{c.srv} 473 {c.nick} '\n    '{channel} :Cannot join channel (+i)')\nERR_INVITEONLYCHAN.params = ['srv', 'me', 'channel', 'data']\n\nERR_BANNEDFROMCHAN = retcode(474)\nERR_BANNEDFROMCHAN.name = \"ERR_BANNEDFROMCHAN\"\nERR_BANNEDFROMCHAN.re = (\n    r\"^:(?P<srv>\\S+) 474 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_BANNEDFROMCHAN.tpl = (\n    ':{c.srv} 474 {c.nick} '\n    '{channel} :Cannot join channel (+b)')\nERR_BANNEDFROMCHAN.params = ['srv', 'me', 'channel', 'data']\n\nERR_BADCHANNELKEY = retcode(475)\nERR_BADCHANNELKEY.name = \"ERR_BADCHANNELKEY\"\nERR_BADCHANNELKEY.re = (\n    r\"^:(?P<srv>\\S+) 475 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_BADCHANNELKEY.tpl = (\n    ':{c.srv} 475 {c.nick} '\n    '{channel} :Cannot join channel (+k)')\nERR_BADCHANNELKEY.params = ['srv', 'me', 'channel', 'data']\n\nERR_NOPRIVILEGES = retcode(481)\nERR_NOPRIVILEGES.name = \"ERR_NOPRIVILEGES\"\nERR_NOPRIVILEGES.re = (\n    r\"^:(?P<srv>\\S+) 481 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NOPRIVILEGES.tpl = (\n    ':{c.srv} 481 {c.nick} '\n    \":Permission Denied- You're not an IRC operator\")\nERR_NOPRIVILEGES.params = ['srv', 'me', 'data']\n\nERR_CHANOPRIVSNEEDED = retcode(482)\nERR_CHANOPRIVSNEEDED.name = \"ERR_CHANOPRIVSNEEDED\"\nERR_CHANOPRIVSNEEDED.re = (\n    r\"^:(?P<srv>\\S+) 482 (?P<me>\\S+) \"\n    r\"(?P<channel>\\S+) :(?P<data>.*)\")\nERR_CHANOPRIVSNEEDED.tpl = (\n    ':{c.srv} 482 {c.nick} '\n    \"{channel} :You're not channel operator\")\nERR_CHANOPRIVSNEEDED.params = ['srv', 'me', 'channel', 'data']\n\nERR_CANTKILLSERVER = retcode(483)\nERR_CANTKILLSERVER.name = \"ERR_CANTKILLSERVER\"\nERR_CANTKILLSERVER.re = (\n    r\"^:(?P<srv>\\S+) 483 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_CANTKILLSERVER.tpl = (\n    ':{c.srv} 483 {c.nick} '\n    ':You cant kill a server!')\nERR_CANTKILLSERVER.params = ['srv', 'me', 'data']\n\nERR_NOOPERHOST = retcode(491)\nERR_NOOPERHOST.name = \"ERR_NOOPERHOST\"\nERR_NOOPERHOST.re = (\n    r\"^:(?P<srv>\\S+) 491 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_NOOPERHOST.tpl = (\n    ':{c.srv} 491 {c.nick} '\n    ':No O-lines for your host')\nERR_NOOPERHOST.params = ['srv', 'me', 'data']\n\nERR_UMODEUNKNOWNFLAG = retcode(501)\nERR_UMODEUNKNOWNFLAG.name = \"ERR_UMODEUNKNOWNFLAG\"\nERR_UMODEUNKNOWNFLAG.re = (\n    r\"^:(?P<srv>\\S+) 501 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_UMODEUNKNOWNFLAG.tpl = (\n    ':{c.srv} 501 {c.nick} '\n    ':Unknown MODE flag')\nERR_UMODEUNKNOWNFLAG.params = ['srv', 'me', 'data']\n\nERR_USERSDONTMATCH = retcode(502)\nERR_USERSDONTMATCH.name = \"ERR_USERSDONTMATCH\"\nERR_USERSDONTMATCH.re = (\n    r\"^:(?P<srv>\\S+) 502 (?P<me>\\S+) \"\n    r\":(?P<data>.*)\")\nERR_USERSDONTMATCH.tpl = (\n    ':{c.srv} 502 {c.nick} '\n    ':Cant change mode for other users')\nERR_USERSDONTMATCH.params = ['srv', 'me', 'data']\n\nRETCODES = {\n    200: RPL_TRACELINK,\n    201: RPL_TRACECONNECTING,\n    202: RPL_TRACEHANDSHAKE,\n    203: RPL_TRACEUNKNOWN,\n    204: RPL_TRACEOPERATOR,\n    205: RPL_TRACEUSER,\n    206: RPL_TRACESERVER,\n    208: RPL_TRACENEWTYPE,\n    211: RPL_STATSLINKINFO,\n    212: RPL_STATSCOMMANDS,\n    213: RPL_STATSCLINE,\n    214: RPL_STATSNLINE,\n    215: RPL_STATSILINE,\n    216: RPL_STATSKLINE,\n    218: RPL_STATSYLINE,\n    219: RPL_ENDOFSTATS,\n    221: RPL_UMODEIS,\n    241: RPL_STATSLLINE,\n    242: RPL_STATSUPTIME,\n    243: RPL_STATSOLINE,\n    244: RPL_STATSHLINE,\n    251: RPL_LUSERCLIENT,\n    252: RPL_LUSEROP,\n    253: RPL_LUSERUNKNOWN,\n    254: RPL_LUSERCHANNELS,\n    255: RPL_LUSERME,\n    256: RPL_ADMINME,\n    257: RPL_ADMINLOC1,\n    258: RPL_ADMINLOC2,\n    259: RPL_ADMINEMAIL,\n    261: RPL_TRACELOG,\n    301: RPL_AWAY,\n    302: RPL_USERHOST,\n    303: RPL_ISON,\n    305: RPL_UNAWAY,\n    306: RPL_NOWAWAY,\n    311: RPL_WHOISUSER,\n    312: RPL_WHOISSERVER,\n    313: RPL_WHOISOPERATOR,\n    314: RPL_WHOWASUSER,\n    315: RPL_ENDOFWHO,\n    317: RPL_WHOISIDLE,\n    318: RPL_ENDOFWHOIS,\n    319: RPL_WHOISCHANNELS,\n    321: RPL_LISTSTART,\n    322: RPL_LIST,\n    323: RPL_LISTEND,\n    324: RPL_CHANNELMODEIS,\n    331: RPL_NOTOPIC,\n    332: RPL_TOPIC,\n    341: RPL_INVITING,\n    342: RPL_SUMMONING,\n    351: RPL_VERSION,\n    352: RPL_WHOREPLY,\n    353: RPL_NAMREPLY,\n    364: RPL_LINKS,\n    365: RPL_ENDOFLINKS,\n    366: RPL_ENDOFNAMES,\n    367: RPL_BANLIST,\n    368: RPL_ENDOFBANLIST,\n    369: RPL_ENDOFWHOWAS,\n    371: RPL_INFO,\n    372: RPL_MOTD,\n    374: RPL_ENDOFINFO,\n    375: RPL_MOTDSTART,\n    376: RPL_ENDOFMOTD,\n    381: RPL_YOUREOPER,\n    382: RPL_REHASHING,\n    391: RPL_TIME,\n    392: RPL_USERSSTART,\n    393: RPL_USERS,\n    394: RPL_ENDOFUSERS,\n    395: RPL_NOUSERS,\n    401: ERR_NOSUCHNICK,\n    402: ERR_NOSUCHSERVER,\n    403: ERR_NOSUCHCHANNEL,\n    404: ERR_CANNOTSENDTOCHAN,\n    405: ERR_TOOMANYCHANNELS,\n    406: ERR_WASNOSUCHNICK,\n    407: ERR_TOOMANYTARGETS,\n    409: ERR_NOORIGIN,\n    411: ERR_NORECIPIENT,\n    412: ERR_NOTEXTTOSEND,\n    413: ERR_NOTOPLEVEL,\n    414: ERR_WILDTOPLEVEL,\n    421: ERR_UNKNOWNCOMMAND,\n    422: ERR_NOMOTD,\n    423: ERR_NOADMININFO,\n    431: ERR_NONICKNAMEGIVEN,\n    432: ERR_ERRONEUSNICKNAME,\n    433: ERR_NICKNAMEINUSE,\n    436: ERR_NICKCOLLISION,\n    441: ERR_USERNOTINCHANNEL,\n    442: ERR_NOTONCHANNEL,\n    443: ERR_USERONCHANNEL,\n    444: ERR_NOLOGIN,\n    445: ERR_SUMMONDISABLED,\n    446: ERR_USERSDISABLED,\n    451: ERR_NOTREGISTERED,\n    461: ERR_NEEDMOREPARAMS,\n    462: ERR_ALREADYREGISTRED,\n    463: ERR_NOPERMFORHOST,\n    464: ERR_PASSWDMISMATCH,\n    465: ERR_YOUREBANNEDCREEP,\n    467: ERR_KEYSET,\n    471: ERR_CHANNELISFULL,\n    472: ERR_UNKNOWNMODE,\n    473: ERR_INVITEONLYCHAN,\n    474: ERR_BANNEDFROMCHAN,\n    475: ERR_BADCHANNELKEY,\n    481: ERR_NOPRIVILEGES,\n    482: ERR_CHANOPRIVSNEEDED,\n    483: ERR_CANTKILLSERVER,\n    491: ERR_NOOPERHOST,\n    501: ERR_UMODEUNKNOWNFLAG,\n    502: ERR_USERSDONTMATCH,\n}\n"
  },
  {
    "path": "irc3/asynchronous.py",
    "content": "# -*- coding: utf-8 -*-\nfrom .compat import asyncio\nimport re\n\n\nclass event:\n\n    iotype = 'in'\n    iscoroutine = True\n\n    def __init__(self, **kwargs):\n        # kwargs get interpolated into the regex.\n        # Any kwargs not ending in _re get escaped\n        self.meta = kwargs.get('meta')\n        regexp = self.meta['match'].format(**{\n            k: v if k.endswith('_re') else re.escape(v)\n            for (k, v) in kwargs.items()\n            if k != 'meta'\n        })\n        self.regexp = regexp\n        regexp = getattr(self.regexp, 're', self.regexp)\n        self.cregexp = re.compile(regexp).match\n\n    def compile(self, *args, **kwargs):\n        return self.cregexp\n\n    def __repr__(self):\n        s = getattr(self.regexp, 'name', self.regexp)\n        name = self.__class__.__name__\n        return '<temp_event {0} {1}>'.format(name, s)\n\n    def __call__(self, callback):\n        async def wrapper(*args, **kwargs):\n            return await callback(self, *args, **kwargs)\n        self.callback = wrapper\n        return self\n\n\ndef default_result_processor(self, results=None, **value):  # pragma: no cover\n    value['results'] = results\n    if len(results) == 1:\n        value.update(results[0])\n    return value\n\n\ndef async_events(context, events, send_line=None,\n                 process_results=default_result_processor,\n                 timeout=30, **params):\n\n    loop = context.loop\n    task = loop.create_future()  # async result\n    results = []  # store events results\n    events_ = []  # reference registered events\n\n    # async timeout\n    timeout = asyncio.ensure_future(\n        asyncio.sleep(timeout, loop=loop), loop=loop)\n\n    def end(t=None):\n        \"\"\"t can be a future (timeout done) or False (result success)\"\"\"\n        if not task.done():\n            # cancel timeout if needed\n            if t is False:\n                timeout.cancel()\n            # detach events\n            context.detach_events(*events_)\n            # clean refs\n            events_[:] = []\n            # set results\n            task.set_result(process_results(results=results, timeout=bool(t)))\n\n    # end on timeout\n    timeout.add_done_callback(end)\n\n    async def callback(e, **kw):\n        \"\"\"common callback for all events\"\"\"\n        results.append(kw)\n        if e.meta.get('multi') is not True:\n            context.detach_events(e)\n            events_.remove(e)\n        if e.meta.get('final') is True:\n            # end on success\n            end(False)\n\n    events_.extend([event(meta=kw, **params)(callback) for kw in events])\n\n    context.attach_events(*events_, insert=True)\n\n    if send_line:\n        context.send_line(send_line.format(**params))\n\n    return task\n\n\nclass AsyncEvents:\n    \"\"\"Asynchronious events\"\"\"\n\n    timeout = 30\n    send_line = None\n    events = []\n\n    def __init__(self, context):\n        self.context = context\n\n    def process_results(self, results=None, **value):  # pragma: no cover\n        \"\"\"Process results.\n        results is a list of dict catched during event.\n        value is a dict containing some metadata (like timeout=(True/False).\n        \"\"\"\n        return default_result_processor(results=results, **value)\n\n    def __call__(self, **kwargs):\n        \"\"\"Register events; and callbacks then return a `asyncio.Future`.\n        Events regexp are compiled with `params`\"\"\"\n        kwargs.setdefault('timeout', self.timeout)\n        kwargs.setdefault('send_line', self.send_line)\n        kwargs['process_results'] = self.process_results\n        return async_events(self.context, self.events, **kwargs)\n"
  },
  {
    "path": "irc3/base.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport ssl\nimport signal\nimport logging\nimport logging.config\nfrom importlib import metadata\nfrom . import utils\nfrom . import config\nfrom .compat import asyncio\nfrom .compat import reload_module\nfrom collections import defaultdict\n\n\nversion = metadata.version('irc3')\n\n\nclass Registry:\n    \"\"\"Store (and hide from api) plugins events and stuff\"\"\"\n\n    def __init__(self):\n        self.reset(reloading=False)\n\n    def reset(self, reloading=True):\n        self.events_re = {\n            'in': [], 'out': [],\n            'dcc_in': [], 'dcc_out': [],\n        }\n        self.events = {\n            'in': defaultdict(list),\n            'out': defaultdict(list),\n            'dcc_in': defaultdict(list),\n            'dcc_out': defaultdict(list),\n        }\n\n        self.scanned = []\n        self.includes = set()\n\n        if reloading:\n            self.reloading = self.plugins.copy()\n        else:\n            self.reloading = {}\n            self.plugins = {}\n\n    def get_event_matches(self, data, iotype='in'):\n        events = self.events[iotype]\n        for regexp, cregexp in self.events_re[iotype]:\n            match = cregexp(data)\n            if match is not None:\n                yield match, events[regexp]\n\n\nclass IrcObject:\n\n    nick = None\n    server = False\n    plugin_category = '__irc3_plugin__'\n    logging_config = config.LOGGING\n\n    defaults = dict(\n        port=6667,\n        timeout=320,\n        max_lag=60,\n        asynchronous=True,\n        max_length=512,\n        testing=False,\n        ssl=False,\n        ssl_verify=False,\n        encoding='utf8',\n        loop=None,\n    )\n\n    def __init__(self, *ini, **config):\n        config['version'] = version\n        self.config = utils.Config(dict(self.defaults, *ini, **config))\n        logging.config.dictConfig(self.logging_config)\n        if self.server:\n            self.log = logging.getLogger('irc3d')\n        else:\n            self.log = logging.getLogger('irc3.' + (self.nick or 'd'))\n        self.original_nick = self.nick\n        if config.get('verbose') or config.get('debug'):\n            logging.getLogger('irc3').setLevel(logging.DEBUG)\n            logging.getLogger('irc3d').setLevel(logging.DEBUG)\n        else:\n            level = config.get('level')\n            if level is not None:\n                level = getattr(logging, str(level), level)\n                self.log.setLevel(level)\n        self.encoding = self.config['encoding']\n\n        self.loop = self.config.loop\n        if self.loop is None:\n            try:\n                self.loop = asyncio.get_event_loop()\n            except RuntimeError:\n                self.loop = asyncio.new_event_loop()\n                asyncio.set_event_loop(self.loop)\n\n        self.create_task = self.loop.create_task\n\n        self.registry = Registry()\n\n        self.include(*self.config.get('includes', []))\n\n    def get_plugin(self, ob):\n        plugins = self.registry.plugins\n        includes = self.registry.includes\n        reloading = self.registry.reloading\n\n        if isinstance(ob, str):\n            ob_name = ob\n            ob = utils.maybedotted(ob_name)\n            if ob_name not in plugins:\n                names = list(plugins)\n                raise LookupError(\n                    'Plugin %s not found in %s' % (ob_name, names))\n        else:\n            ob_name = ob.__module__ + '.' + ob.__name__\n        if ob_name not in plugins:\n            self.log.debug(\"Register plugin '%s'\", ob_name)\n            for dotted in getattr(ob, 'requires', []):\n                if dotted not in includes:\n                    self.include(dotted)\n            plugins[ob_name] = ob(self)\n        elif ob_name in reloading and hasattr(ob, 'reload'):\n            instance = reloading.pop(ob_name)\n            if instance.__class__ is not ob:\n                self.log.debug(\"Reloading plugin '%s'\", ob_name)\n                plugins[ob_name] = ob.reload(instance)\n        return plugins[ob_name]\n\n    def recompile(self):\n        events_re = self.registry.events_re\n        for iotype in ('in', 'out'):\n            events = self.registry.events[iotype]\n            for i, (regexp, cregexp) in enumerate(events_re[iotype]):\n                e = events[regexp][0]\n                events_re[i] = (regexp, e.compile(self.config))\n\n    def attach_events(self, *events, **kwargs):\n        \"\"\"Attach one or more events to the bot instance\"\"\"\n        reg = self.registry\n        insert = 'insert' in kwargs\n        for e in events:\n            cregexp = e.compile(self.config)\n            regexp = getattr(e.regexp, 're', e.regexp)\n            if regexp not in reg.events[e.iotype]:\n                if insert:\n                    reg.events_re[e.iotype].insert(0, (regexp, cregexp))\n                else:\n                    reg.events_re[e.iotype].append((regexp, cregexp))\n            if insert:\n                reg.events[e.iotype][regexp].insert(0, e)\n            else:\n                reg.events[e.iotype][regexp].append(e)\n\n    def detach_events(self, *events):\n        \"\"\"Detach one or more events from the bot instance\"\"\"\n        reg = self.registry\n        delete = defaultdict(list)\n\n        # remove from self.events\n        all_events = reg.events\n        for e in events:\n            regexp = getattr(e.regexp, 're', e.regexp)\n            iotype = e.iotype\n            if e in all_events[iotype].get(regexp, []):\n                all_events[iotype][regexp].remove(e)\n                if not all_events[iotype][regexp]:\n                    del all_events[iotype][regexp]\n                    # need to delete from self.events_re\n                    delete[iotype].append(regexp)\n\n        # delete from events_re\n        for iotype, regexps in delete.items():\n            reg.events_re[iotype] = [r for r in reg.events_re[iotype]\n                                     if r[0] not in regexps]\n\n    def include(self, *modules, **kwargs):\n        reg = self.registry\n        categories = kwargs.get('venusian_categories',\n                                self.venusian_categories)\n        scanner = self.venusian.Scanner(context=self)\n        for module in modules:\n            if module in reg.includes:\n                self.log.warning('%s included twice', module)\n            else:\n                reg.includes.add(module)\n                try:\n                    module = utils.maybedotted(module)\n                except LookupError as exc:\n                    try:\n                        (module,) = metadata.entry_points(group='irc3.loader',\n                                                          name=module)\n                        module = module.load()\n                    except (ImportError, ValueError):\n                        raise exc\n                # we have to manualy check for plugins. venusian no longer\n                # support to attach both a class and methods\n                for klass in list(module.__dict__.values()):\n                    if not isinstance(klass, type):\n                        continue\n                    if klass.__module__ == module.__name__:\n                        if getattr(klass, self.plugin_category, False) is True:\n                            self.get_plugin(klass)\n                reg.scanned.append((module.__name__, categories))\n                scanner.scan(module, categories=categories)\n\n    def reload(self, *modules):\n        \"\"\"Reload one or more plugins\"\"\"\n        self.notify('before_reload')\n\n        if 'configfiles' in self.config:\n            # reload configfiles\n            self.log.info('Reloading configuration...')\n            cfg = utils.parse_config(\n                self.server and 'server' or 'bot', *self.config['configfiles'])\n            self.config.update(cfg)\n\n        self.log.info('Reloading python code...')\n        if not modules:\n            modules = self.registry.includes\n        scanned = list(reversed(self.registry.scanned))\n\n        # reset includes and events\n        self.registry.reset()\n\n        to_scan = []\n        for module_name, categories in scanned:\n            if module_name in modules:\n                module = utils.maybedotted(module_name)\n                reload_module(module)\n            to_scan.append((module_name, categories))\n\n        # rescan all modules\n        for module_name, categories in to_scan:\n            self.include(module_name, venusian_categories=categories)\n\n        self.registry.reloading = {}\n\n        self.notify('after_reload')\n\n    def notify(self, event, exc=None, client=None):\n        for p in self.registry.plugins.values():\n            meth = getattr(p, event, None)\n            if meth is not None:\n                if client is not None:\n                    meth(client=client)\n                else:\n                    meth()\n\n    def dispatch(self, data, iotype='in', client=None):\n        str = utils.IrcString\n        create_task = self.create_task\n        call_soon = self.loop.call_soon\n        for match, events in self.registry.get_event_matches(data, iotype):\n            match = match.groupdict()\n            for key, value in match.items():\n                if value is not None:\n                    match[key] = str(value)\n            # backwards compatibility fix for IRCv3.2 tag support:\n            # If no tags (None-value), exclude from dictionary\n            if match.get(\"tags\", True) is None:\n                del match[\"tags\"]\n            if client is not None:\n                # server / dcc chat\n                match['client'] = client\n            for e in events:\n                if e.iscoroutine is True:\n                    create_task(e.callback(**match))\n                else:\n                    call_soon(e.async_callback, match)\n\n    def call_many(self, callback, args):\n        \"\"\"callback is run with each arg but run a call per second\"\"\"\n        if isinstance(callback, str):\n            callback = getattr(self, callback)\n        f = None\n        for arg in args:\n            f = callback(*arg)\n        return f\n\n    def get_ssl_context(self):\n        if self.config.ssl:  # pragma: no cover\n            try:\n                create_default_context = ssl.create_default_context\n            except AttributeError:  # py < 2.7.9\n                return True\n            else:\n                if self.server:\n                    context = create_default_context(ssl.Purpose.CLIENT_AUTH)\n                else:\n                    context = create_default_context(ssl.Purpose.SERVER_AUTH)\n                verify_mode = self.config.ssl_verify\n                if verify_mode is not False:\n                    if not isinstance(verify_mode, int):\n                        # CERT_NONE / CERT_OPTIONAL / CERT_REQUIRED\n                        verify_mode = getattr(ssl, verify_mode.upper())\n                    if verify_mode == ssl.CERT_NONE:\n                        context.check_hostname = False\n                    context.verify_mode = verify_mode\n                return context\n        return None\n\n    def create_connection(self):\n        protocol = utils.maybedotted(self.config.connection)\n        protocol = type(protocol.__name__, (protocol,), {'factory': self})\n        if self.server:  # pragma: no cover\n            self.log.debug('Starting {servername}...'.format(**self.config))\n            factory = self.loop.create_server\n        else:\n            self.log.debug('Starting {nick}...'.format(**self.config))\n            factory = self.loop.create_connection\n        if self.config.get('sock_factory'):\n            sock_factory = utils.maybedotted(self.config.sock_factory)\n            args = dict(\n                sock=sock_factory(self, self.config.host, self.config.port),\n                ssl=self.get_ssl_context(),\n            )\n            if args.get('ssl'):\n                args[\"server_hostname\"] = self.config.host\n        else:\n            args = dict(\n                host=self.config.host,\n                port=self.config.port,\n                ssl=self.get_ssl_context()\n            )\n            if self.config.get('vhost'):\n                args[\"local_addr\"] = (self.config.vhost, 0)\n        t = asyncio.Task(factory(protocol, **args), loop=self.loop)\n        t.add_done_callback(self.connection_made)\n        return self.loop\n\n    def add_signal_handlers(self):\n        \"\"\"Register handlers for UNIX signals (SIGHUP/SIGINT)\"\"\"\n        try:\n            self.loop.add_signal_handler(signal.SIGHUP, self.SIGHUP)\n        except (RuntimeError, AttributeError):  # pragma: no cover\n            # windows\n            pass\n        try:\n            self.loop.add_signal_handler(signal.SIGINT, self.SIGINT)\n        except (RuntimeError, NotImplementedError):  # pragma: no cover\n            # annaconda\n            pass\n\n    def run(self, forever=True):\n        \"\"\"start the bot\"\"\"\n        loop = self.create_connection()\n        self.add_signal_handlers()\n        if forever:\n            loop.run_forever()\n\n    @classmethod\n    def from_config(cls, cfg, **kwargs):\n        \"\"\"return an instance configured with the ``cfg`` dict\"\"\"\n        cfg = dict(cfg, **kwargs)\n        pythonpath = cfg.get('pythonpath', [])\n        if 'here' in cfg:\n            pythonpath.append(cfg['here'])\n        for path in pythonpath:\n            sys.path.append(os.path.expanduser(path))\n        prog = cls.server and 'irc3d' or 'irc3'\n        if cfg.get('debug'):\n            cls.venusian_categories.append(prog + '.debug')\n        if cfg.get('interactive'):  # pragma: no cover\n            import irc3.testing\n            context = getattr(irc3.testing, cls.__name__)(**cfg)\n        else:\n            context = cls(**cfg)\n        if cfg.get('raw'):\n            context.include('irc3.plugins.log',\n                            venusian_categories=[prog + '.debug'])\n        return context\n\n    @classmethod\n    def from_argv(cls, argv=None, **kwargs):\n        prog = cls.server and 'irc3d' or 'irc3'\n        doc = \"\"\"\n        Run an {prog} instance from a config file\n\n        Usage: {prog} [options] <config>...\n\n        Options:\n\n        -h, --help          Display this help and exit\n        --version           Output version information and exit\n        --logdir DIRECTORY  Log directory to use instead of stderr\n        --logdate           Show datetimes in console output\n        --host HOST         Server name or ip\n        --port PORT         Server port\n        -v,--verbose        Increase verbosity\n        -r,--raw            Show raw irc log on the console\n        -d,--debug          Add some debug commands/utils\n        -i,--interactive    Load a ipython console with a bot instance\n        \"\"\".format(prog=prog)\n        if not cls.server:\n            doc += \"\"\"\n            --help-page         Output a reST page containing commands help\n            \"\"\".strip()\n        import os\n        import docopt\n        import textwrap\n        args = argv or sys.argv[1:]\n        args = docopt.docopt(textwrap.dedent(doc), args, version=version)\n        cfg = utils.parse_config(\n            cls.server and 'server' or 'bot', *args['<config>'])\n        cfg.update(\n            verbose=args['--verbose'],\n            debug=args['--debug'],\n        )\n        cfg.update(kwargs)\n        if args['--host']:  # pragma: no cover\n            host = args['--host']\n            cfg['host'] = host\n            if host in ('127.0.0.1', 'localhost'):\n                cfg['ssl'] = False\n        if args['--port']:  # pragma: no cover\n            cfg['port'] = args['--port']\n        if args['--logdir'] or 'logdir' in cfg:\n            logdir = os.path.expanduser(args['--logdir'] or cfg.get('logdir'))\n            cls.logging_config = config.get_file_config(logdir)\n        if args['--logdate']:  # pragma: no cover\n            fmt = cls.logging_config['formatters']['console']\n            fmt['format'] = config.TIMESTAMPED_FMT\n        if args.get('--help-page'):  # pragma: no cover\n            for v in cls.logging_config['handlers'].values():\n                v['level'] = 'ERROR'\n        if args['--raw']:\n            cfg['raw'] = True\n        context = cls.from_config(cfg)\n        if args.get('--help-page'):  # pragma: no cover\n            context.print_help_page()\n        elif args['--interactive']:  # pragma: no cover\n            import IPython\n            IPython.embed()\n            sys.exit(0)\n        else:\n            context.run(forever=not bool(kwargs))\n        if kwargs or argv:\n            return context\n"
  },
  {
    "path": "irc3/compat.py",
    "content": "# -*- coding: utf-8 -*-\nimport sys\nimport types\n\nPY37 = bool(sys.version_info[0:2] >= (3, 7))\n\n\ntry:  # pragma: no cover\n    from importlib import reload as reload_module\nexcept ImportError:  # pragma: no cover\n    from imp import reload as reload_module  # NOQA\n\nimport asyncio\nfrom asyncio.queues import Queue as BaseQueue\nfrom asyncio.queues import QueueFull  # NOQA\nfrom asyncio import sleep as _original_sleep\nfrom asyncio import wait as _original_wait\n\n\ndef __sleep(*args, **kwargs):\n    if PY37 and \"loop\" in kwargs:\n        del kwargs[\"loop\"]\n    return _original_sleep(*args, **kwargs)\n\n\ndef __wait(*args, **kwargs):\n    if PY37 and \"loop\" in kwargs:\n        del kwargs[\"loop\"]\n    return _original_wait(*args, **kwargs)\n\n\nasyncio.sleep = __sleep\nasyncio.wait = __wait\n\nclass Queue(BaseQueue):\n    def __init__(self, *args, **kwargs):\n        if PY37 and \"loop\" in kwargs:\n            del kwargs[\"loop\"]\n\n        super().__init__(*args, **kwargs)\n"
  },
  {
    "path": "irc3/config.py",
    "content": "# -*- coding: utf-8 -*-\n\nTIMESTAMPED_FMT = '%(asctime)s %(levelname)-4s %(name)-10s %(message)s'\n\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'formatters': {\n        'console': {\n            'format': '%(levelname)-4s %(name)-10s %(message)s',\n            'datefmt': '%Y-%m-%d %H:%M:%S',\n        },\n        'console_plus': {\n            'datefmt': '%Y-%m-%d %H:%M:%S',\n        },\n        'irc': {\n            'format': '%(levelname)-4s %(message)s',\n            'datefmt': '%Y-%m-%d %H:%M:%S',\n        },\n        'file': {\n            'format': TIMESTAMPED_FMT,\n            'datefmt': '%Y-%m-%d %H:%M:%S',\n        },\n    },\n    'handlers': {\n        'console': {\n            'level': 'DEBUG',\n            'class': 'logging.StreamHandler',\n            'stream': 'ext://sys.stderr',\n            'formatter': 'console',\n        },\n        'irc': {\n            'level': 'INFO',\n            'class': 'logging.NullHandler',\n            'formatter': 'irc',\n        },\n        'logs': {\n            'level': 'DEBUG',\n            'class': 'logging.StreamHandler',\n            'stream': 'ext://sys.stderr',\n            'formatter': 'console',\n        }\n    },\n    'loggers': {\n        'asyncio': {\n            'handlers': ['console'],\n            'level': 'ERROR',\n            'propagate': False,\n        },\n        'trollius': {\n            'handlers': ['console'],\n            'level': 'ERROR',\n            'propagate': False,\n        },\n        'requests': {\n            'handlers': ['console'],\n            'level': 'ERROR',\n            'propagate': False,\n        },\n        'irc': {\n            'handlers': ['irc'],\n            'level': 'INFO',\n            'propagate': False,\n        },\n        'irc3': {\n            'handlers': ['console'],\n            'level': 'INFO',\n            'propagate': False,\n        },\n        'irc3d': {\n            'handlers': ['console'],\n            'level': 'INFO',\n            'propagate': False,\n        },\n        'raw': {\n            'handlers': ['logs'],\n            'level': 'INFO',\n            'propagate': False,\n        },\n    }\n}\n\n\ndef get_file_config(logdir='~/.irc3/logs'):\n    import os\n    if not os.path.isdir(logdir):\n        os.makedirs(logdir)\n    config = LOGGING.copy()\n    config['handlers'] = {\n        'console': {\n            'level': 'INFO',\n            'class': 'logging.handlers.RotatingFileHandler',\n            'filename': os.path.join(logdir, 'irc3.log'),\n            'backupCount': 5,\n            'maxBytes': 1024 * 5,\n            'formatter': 'file',\n        },\n        'irc': {\n            'level': 'INFO',\n            'class': 'logging.NullHandler',\n            'formatter': 'irc',\n        },\n        'logs': {\n            'level': 'INFO',\n            'class': 'logging.handlers.RotatingFileHandler',\n            'filename': os.path.join(logdir, 'logs.log'),\n            'backupCount': 5,\n            'maxBytes': 1024 * 5,\n            'formatter': 'file',\n        }\n    }\n    return config\n"
  },
  {
    "path": "irc3/dcc/__init__.py",
    "content": "# -*- coding: utf-8 -*-\nfrom .manager import DCCManager  # NOQA\nfrom .manager import DCCChat  # NOQA\nfrom .manager import DCCGet  # NOQA\nfrom .manager import DCCSend  # NOQA\n"
  },
  {
    "path": "irc3/dcc/client.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport struct\nfrom collections import deque\nfrom functools import partial\nfrom irc3.compat import asyncio\n\n\nclass DCCBase(asyncio.Protocol):\n\n    idle_handle = None\n    idle_timeout = None\n    fd = None\n\n    def __init__(self, **kwargs):\n        for k, v in kwargs.items():\n            setattr(self, k, v)\n        self.ready = self.loop.create_future()\n        self.started = self.loop.create_future()\n        self.closed = self.loop.create_future()\n        self.timeout_handle = None\n\n    def factory(self):\n        return self\n\n    def connection_made(self, transport):\n        self.transport = transport\n        self.started.set_result(self)\n\n    def connection_lost(self, exc):\n        self.close(exc)\n\n    def close(self, result=None):\n        if self.idle_handle is not None:\n            self.idle_handle.cancel()\n        if self.transport:\n            self.transport.close()\n        info = self.bot.dcc.connections[self.type]\n        if self.port in info['masks'][self.mask]:\n            info['total'] -= 1\n            del info['masks'][self.mask][self.port]\n        if not self.closed.done():\n            self.closed.set_result(result)\n        self.bot.log.debug('%s closed', self)\n\n    def set_timeout(self):\n        if self.idle_handle is not None:\n            self.idle_handle.cancel()\n        if self.idle_timeout:\n            self.idle_handle = self.loop.call_later(\n                self.idle_timeout, self.idle_timeout_reached)\n\n    def idle_timeout_reached(self, *args):\n        if self.type == 'chat':\n            msg = \"Your idle is too high. Closing connection.\"\n            self.send_line(msg)\n        self.close()\n\n    def __str__(self):\n        return '%s with %s' % (self.__class__.__name__, self.mask)\n\n    def __repr__(self):\n        return '<%s with %s>' % (self.__class__.__name__, self.mask)\n\n\nclass DCCChat(DCCBase):\n    \"\"\"DCC CHAT implementation\"\"\"\n\n    type = 'chat'\n    ctcp = 'DCC CHAT chat {0.ip} {0.port}'\n\n    def connection_made(self, transport):\n        super(DCCChat, self).connection_made(transport)\n        self.encoding = getattr(self.bot, 'encoding', 'ascii')\n        self.set_timeout()\n        self.queue = deque()\n\n    def decode(self, data):\n        \"\"\"Decode data with bot's encoding\"\"\"\n        return data.decode(self.encoding, 'ignore')\n\n    def data_received(self, data):\n        \"\"\"data received\"\"\"\n        self.set_timeout()\n        data = self.decode(data)\n        if self.queue:\n            data = self.queue.popleft() + data\n        lines = data.replace('\\r', '').split('\\n')\n        self.queue.append(lines.pop(-1))\n        for line in lines:\n            self.bot.dispatch(line, iotype='dcc_in', client=self)\n\n    def write(self, data):\n        if data is not None:\n            data = data.encode(self.encoding)\n            if not data.endswith(b'\\r\\n'):\n                data = data + b'\\r\\n'\n            self.transport.write(data)\n\n    def send_line(self, message):\n        self.write(message)\n        self.bot.dispatch(message, iotype='dcc_out', client=self)\n\n    def send(self, *messages):\n        for message in messages:\n            self.send_line(message)\n\n    def action(self, message):\n        message = '\\x01ACTION ' + message + '\\x01'\n        self.send_line(message)\n\n    def actions(self, *messages):\n        for message in messages:\n            self.action(message)\n\n\nclass DCCGet(DCCBase):\n    \"\"\"DCC GET implementation\"\"\"\n    type = 'get'\n    ctcp = None\n\n    def connection_made(self, transport):\n        super(DCCGet, self).connection_made(transport)\n        if self.resume:\n            self.bytes_received = self.offset\n        else:\n            self.bytes_received = 0\n        self.fd = open(self.filepath, 'ab')\n\n    def data_received(self, data):\n        self.set_timeout()\n        self.fd.write(data)\n        self.bytes_received += len(data)\n        self.transport.write(struct.pack('!I', self.bytes_received))\n\n    def close(self, *args, **kwargs):\n        if self.fd:\n            self.fd.close()\n            self.fd = None\n        super(DCCGet, self).close(*args, **kwargs)\n\n\nclass DCCSend(DCCBase):\n    \"\"\"DCC SEND implementation\"\"\"\n\n    type = 'send'\n    ctcp = 'DCC SEND {0.filename_safe} {0.ip} {0.port} {0.filesize}'\n    block_size = 1024 * 64\n    limit_rate = None\n    filepath = None\n\n    def connection_made(self, transport):\n        super(DCCSend, self).connection_made(transport)\n        self.delay = 1. / (self.limit_rate / 64.) if self.limit_rate else None\n        socket = self.transport.get_extra_info('socket')\n        self.socket = socket\n        self.sendfile = getattr(self.socket, 'sendfile', None)\n        if self.sendfile:\n            try:\n                self.socket.setblocking(1)\n            except ValueError:\n                # py38 does not allow this. use it anyway\n                self.socket._sock.setblocking(1)\n        self.fd = open(self.filepath, 'rb')\n        self.fd_fileno = self.fd.fileno()\n        # remove existing transport ref. It shouldn't read/write anything\n        transports = getattr(self.loop, '_transports', None)\n        if transports is not None:\n            del self.loop._transports[transport._sock_fd]\n        self.loop.remove_writer(socket)\n        self.loop.add_writer(socket, self.next_chunk)\n\n    def write(self, *args):  # pragma: no cover\n        raise NotImplementedError('write is not available during DCCSend')\n\n    def send_chunk(self):\n        sent = os.sendfile(self.socket.fileno(), self.fd_fileno,\n                           self.offset, self.block_size)\n        return sent\n\n    def next_chunk(self):\n        try:\n            sent = self.send_chunk()\n        except Exception as e:  # pragma: no cover\n            self.bot.log.exception(e)\n            self.fd.close()\n            sent = 0\n        if sent != 0:\n            self.offset += sent\n            cb = partial(self.loop.add_writer, self.socket, self.next_chunk)\n            if self.delay is not None:\n                self.loop.call_later(self.delay, cb)\n            else:\n                cb()\n        else:\n            self.loop.remove_writer(self.socket)\n\n    def data_received(self, data):\n        self.set_timeout()\n        bytes_received = (\n            struct.unpack('!I', data[i:i + 4])[0]\n            for i in range(0, len(data), 4))\n        for recv in bytes_received:\n            if recv == self.filesize:\n                self.transport.close()\n\n    def close(self, *args, **kwargs):\n        if self.fd:\n            self.fd.close()\n            self.fd = None\n        super(DCCSend, self).close(*args, **kwargs)\n"
  },
  {
    "path": "irc3/dcc/manager.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nfrom functools import partial\nfrom collections import defaultdict\nfrom irc3.utils import slugify\nfrom irc3.utils import maybedotted\nfrom irc3.dcc.client import DCCChat\nfrom irc3.dcc.client import DCCGet\nfrom irc3.dcc.client import DCCSend\n\nDCC_TYPES = ('chat', 'get', 'send')\n\n\nclass DCCManager:\n    \"\"\"Manage DCC connections\"\"\"\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.loop = bot.loop\n        self.config = cfg = bot.config.get('dcc', {})\n        self.config.update(\n            send_limit_rate=int(cfg.get('send_limit_rate', 0)),\n            send_block_size=int(cfg.get('send_block_size', DCCSend.block_size))\n        )\n        self.connections = {}\n        self.protocols = {}\n        for klass in (DCCChat, DCCGet, DCCSend):\n            n = klass.type\n            self.config.update({\n                n + '_limit': int(cfg.get(n + '_limit', 100)),\n                n + '_user_limit': int(cfg.get(n + '_user_limit', 1)),\n                n + '_accept_timeout': int(cfg.get(n + '_accept_timeout', 60)),\n                n + '_idle_timeout': int(cfg.get(n + '_idle_timeout', 60 * 5)),\n            })\n            klass = maybedotted(self.config.get(n + '_protocol', klass))\n            self.connections[n] = {'total': 0, 'masks': defaultdict(dict)}\n            self.protocols[n] = klass\n        self.seeks = {}\n\n    def created(self, protocol, future):\n        if protocol.port is None:\n            server = future.result()\n            protocol.port = server.sockets[0].getsockname()[1]\n            protocol.idle_handle = self.loop.call_later(\n                self.config[protocol.type + '_accept_timeout'],\n                server.close)\n            ctcp_msg = protocol.ctcp.format(protocol)\n            self.bot.ctcp(protocol.mask.nick, ctcp_msg)\n        else:\n            transport, protocol = future.result()\n            protocol.idle_handle = self.loop.call_later(\n                self.config[protocol.type + '_accept_timeout'],\n                protocol.close)\n        info = self.connections[protocol.type]\n        info['total'] += 1\n        info['masks'][protocol.mask][protocol.port] = protocol\n        protocol.ready.set_result(protocol)\n\n    def create(self, name_or_class, mask, filepath=None, **kwargs):\n        \"\"\"Create a new DCC connection. Return an ``asyncio.Protocol``\"\"\"\n        if isinstance(name_or_class, type):\n            name = name_or_class.type\n            protocol = name_or_class\n        else:\n            name = name_or_class\n            protocol = self.protocols[name]\n        assert name in DCC_TYPES\n        if filepath:\n            kwargs.setdefault('limit_rate',\n                              self.config['send_limit_rate'])\n            kwargs['filepath'] = filepath\n            if protocol.type == DCCSend.type:\n                kwargs.setdefault('offset', 0)\n                kwargs.update(\n                    filename_safe=slugify(os.path.basename(filepath)),\n                    filesize=os.path.getsize(filepath),\n                )\n            elif protocol.type == DCCGet.type:\n                try:\n                    offset = os.path.getsize(filepath)\n                except OSError:\n                    offset = 0\n                kwargs.setdefault('offset', offset)\n                kwargs.setdefault('resume', False)\n        kwargs.setdefault('port', None)\n        f = protocol(\n            mask=mask, ip=int(self.bot.ip),\n            bot=self.bot, loop=self.loop, **kwargs)\n\n        if kwargs['port']:\n            if self.bot.config.get('dcc_sock_factory'):\n                sock_factory = maybedotted(self.bot.config.dcc_sock_factory)\n                args = dict(sock=sock_factory(self.bot, f.host, f.port))\n            else:\n                args = dict(host=f.host, port=f.port)\n            task = self.bot.create_task(\n                self.loop.create_connection(f.factory, **args))\n            task.add_done_callback(partial(self.created, f))\n        else:\n            task = self.bot.create_task(\n                self.loop.create_server(\n                    f.factory, '0.0.0.0', 0, backlog=1))\n            task.add_done_callback(partial(self.created, f))\n        return f\n\n    def resume(self, mask, filename, port, pos):\n        \"\"\"Resume a DCC send\"\"\"\n        self.connections['send']['masks'][mask][port].offset = pos\n        message = 'DCC ACCEPT %s %d %d' % (filename, port, pos)\n        self.bot.ctcp(mask, message)\n\n    def is_allowed(self, name_or_class, mask):  # pragma: no cover\n        \"\"\"Return True is a new connection is allowed\"\"\"\n        if isinstance(name_or_class, type):\n            name = name_or_class.type\n        else:\n            name = name_or_class\n        info = self.connections[name]\n        limit = self.config[name + '_limit']\n        if limit and info['total'] >= limit:\n            msg = (\n                \"Sorry, there is too much DCC %s active. Please try again \"\n                \"later.\") % name.upper()\n            self.bot.notice(mask, msg)\n            return False\n        if mask not in info['masks']:\n            return True\n        limit = self.config[name + '_user_limit']\n        if limit and info['masks'][mask] >= limit:\n            msg = (\n                \"Sorry, you have too many DCC %s active. Close the other \"\n                \"connection(s) or wait a few seconds and try again.\"\n            ) % name.upper()\n            self.bot.notice(mask, msg)\n            return False\n        return True\n"
  },
  {
    "path": "irc3/dec.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.utils import wraps_with_context\nfrom irc3.compat import asyncio\nimport venusian\nimport re\n\n\ndef plugin(wrapped):\n    \"\"\"register a class as plugin\"\"\"\n    setattr(wrapped, '__irc3_plugin__', True)\n    setattr(wrapped, '__irc3d_plugin__', False)\n    return wrapped\n\n\nclass event:\n    r\"\"\"register a method or function an irc event callback::\n\n        >>> @event(r'^:\\S+ 353 [^&#]+(?P<channel>\\S+) :(?P<nicknames>.*)')\n        ... def on_names(bot, channel=None, nicknames=None):\n        ...     '''this will catch nickname when you enter a channel'''\n        ...     print(channel, nicknames.split(':'))\n\n    The callback can be either a function or a plugin method\n\n    If you specify the `iotype` parameter to `\"out\"` then the event will be\n    triggered when the regexp match something **sent** by the bot.\n\n    For example this event will repeat private messages sent by the bot to the\n    `#irc3` channel::\n\n        >>> @event(r'PRIVMSG (?P<target>[^#]+) :(?P<data>.*)', iotype='out')\n        ... def msg3(bot, target=None, data=None):\n        ...     bot.privmsg('#irc3',\n        ...                 '<{0}> {1}: {2}'.format(bot.nick, target, data))\n    \"\"\"\n\n    venusian = venusian\n\n    def __init__(self, regexp, callback=None, iotype='in',\n                 venusian_category='irc3.rfc1459'):\n        if iotype == 'out':\n            re_out = getattr(regexp, 're_out', None)\n            if re_out is not None:\n                regexp = re_out\n        try:\n            re.compile(getattr(regexp, 're', regexp))\n        except Exception as e:\n            raise e.__class__(str(e) + ' in ' + getattr(regexp, 're', regexp))\n        self.regexp = regexp\n        self.iotype = iotype\n        self.callback = callback\n        self.venusian_category = venusian_category\n        self.iscoroutine = False\n        if callback is not None:\n            self.iscoroutine = asyncio.iscoroutinefunction(callback)\n\n    def async_callback(self, kwargs):  # pragma: no cover\n        return self.callback(**kwargs)\n\n    def compile(self, config):\n        regexp = getattr(self.regexp, 're', self.regexp)\n        if config:\n            regexp = regexp.format(**config)\n        return re.compile(regexp).match\n\n    def __call__(self, func):\n        def callback(context, name, ob):\n            obj = context.context\n            if info.scope == 'class':\n                self.callback = getattr(obj.get_plugin(ob), func.__name__)\n            else:\n                self.callback = wraps_with_context(func, obj)\n            # a new instance is needed to keep this related to *one* bot\n            # instance\n            e = self.__class__(self.regexp, self.callback,\n                               venusian_category=self.venusian_category,\n                               iotype=self.iotype)\n            obj.attach_events(e)\n        info = self.venusian.attach(func, callback,\n                                    category=self.venusian_category)\n        return func\n\n    def __repr__(self):\n        s = getattr(self.regexp, 'name', self.regexp)\n        name = self.__class__.__name__\n        return '<bound {0} {1} to {2}>'.format(name, s, self.callback)\n\n\ndef dcc_event(regexp, callback=None, iotype='in',\n              venusian_category='irc3.dcc'):\n    \"\"\"Work like :class:`~irc3.dec.event` but occurs during DCC CHATs\"\"\"\n    return event(regexp, callback=callback, iotype='dcc_' + iotype,\n                 venusian_category=venusian_category)\n\n\ndef extend(func):\n    \"\"\"Allow to extend a bot:\n\n    Create a module with some useful routine:\n\n    .. literalinclude:: ../examples/myextends.py\n    ..\n        >>> import sys\n        >>> sys.path.append('examples')\n        >>> from irc3 import IrcBot\n        >>> IrcBot.defaults.update(asynchronous=False, testing=True)\n\n    Now you can use those routine in your bot::\n\n        >>> bot = IrcBot()\n        >>> bot.include('myextends')\n        >>> print(bot.my_usefull_function(1))\n        my_usefull_function(*(1,))\n        >>> print(bot.my_usefull_method(2))\n        my_usefull_method(*(2,))\n\n    \"\"\"\n    def callback(context, name, ob):\n        obj = context.context\n        if info.scope == 'class':\n            instance = obj.get_plugin(ob)\n            f = getattr(instance, func.__name__)\n        else:\n            instance = obj\n            f = func\n        setattr(obj, f.__name__, f.__get__(instance, instance.__class__))\n    info = venusian.attach(func, callback, category='irc3.extend')\n    return func\n"
  },
  {
    "path": "irc3/plugins/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "irc3/plugins/asynchronious.py",
    "content": "# -*- coding: utf-8 -*-\nfrom collections import OrderedDict\nimport re\nfrom irc3.asynchronous import AsyncEvents\nfrom irc3 import utils\nfrom irc3 import dec\n__doc__ = \"\"\"\n======================================================\n:mod:`irc3.plugins.asynchronious` Asynchronious events\n======================================================\n\nThis module provide a way to catch data from various predefined events.\n\nUsage\n=====\n\nYou'll have to define a subclass of :class:`~irc3.asynchronous.AsyncEvents`:\n\n.. literalinclude:: ../../irc3/plugins/asynchronious.py\n  :pyobject: Whois\n\nNotice that regexps and send_line contains some `{nick}`. This will be\nsubstitued later with the keyword arguments passed to the instance.\n\nThen you're able to use it in a plugin:\n\n.. code-block:: py\n\n    class MyPlugin:\n\n        def __init__(self, bot):\n            self.bot = bot\n            self.whois = Whois(bot)\n\n        def do_whois(self):\n            # remember {nick} in the regexp? Here it is\n            whois = await self.whois(nick='gawel')\n            if int(whois['idle']) / 60 > 10:\n                self.bot.privmsg('gawel', 'Wake up dude')\n\n.. warning::\n\n    Your code should always check if the result has been set before timeout by\n    using `result['timeout']` which is True when the bot failed to get a result\n    before 30s (you can override the default value per call)\n\n.. warning::\n\n    Do not over use this feature. If you're making a lot of calls at the same\n    time you should experience some weird behavior since irc do not allow\n    to identify responses for a command. That's why the exemple use {nick} in\n    the regexp to filter events efficiently. But two concurent call for the\n    same nick can still fail.\n\nAPI\n===\n\n.. autoclass:: irc3.asynchronous.AsyncEvents\n  :members: process_results, __call__\n\n.. autoclass:: Async\n  :members:\n\n\"\"\"\n\n\nclass Whois(AsyncEvents):\n\n    # the command will fail if we do not have a result after 30s\n    timeout = 20\n\n    # send this line before listening to events\n    send_line = 'WHOIS {nick} {nick}'\n\n    # when those events occurs, we can add them to the result list\n    events = (\n        # (?i) is for IGNORECASE. This will match either NicK or nick\n        {'match': r\"(?i)^:\\S+ 301 \\S+ {nick} :(?P<away>.*)\"},\n        {'match': r\"(?i)^:\\S+ 311 \\S+ {nick} (?P<username>\\S+) \"\n                  r\"(?P<host>\\S+) . :(?P<realname>.*)\"},\n        {'match': r\"(?i)^:\\S+ 312 \\S+ {nick} (?P<server>\\S+) \"\n                  r\":(?P<server_desc>.*)\"},\n        {'match': r\"(?i)^:\\S+ 317 \\S+ {nick} (?P<idle>[0-9]+).*\"},\n        {'match': r\"(?i)^:\\S+ 319 \\S+ {nick} :(?P<channels>.*)\",\n         'multi': True},\n        {'match': r\"(?i)^:\\S+ 330 \\S+ {nick} (?P<account>\\S+) \"\n                  r\":(?P<account_desc>.*)\"},\n        {'match': r\"(?i)^:\\S+ 671 \\S+ {nick} :(?P<connection>.*)\"},\n        # if final=True then a result is returned when the event occurs\n        {'match': r\"(?i)^:\\S+ (?P<retcode>(318|401)) \\S+ (?P<nick>{nick}) :.*\",\n         'final': True},\n    )\n\n    def process_results(self, results=None, **value):\n        \"\"\"take results list of all events and put them in a dict\"\"\"\n        channels = []\n        for res in results:\n            channels.extend(res.pop('channels', '').split())\n            value.update(res)\n        value['channels'] = channels\n        value['success'] = value.get('retcode') == '318'\n        return value\n\n\nclass WhoChannel(AsyncEvents):\n\n    send_line = 'WHO {channel}'\n\n    events = (\n        {\"match\": r\"(?i)^:\\S+ 352 \\S+ {channel} (?P<user>\\S+) \"\n                  r\"(?P<host>\\S+) (?P<server>\\S+) (?P<nick>\\S+) \"\n                  r\"(?P<modes>\\S+) :(?P<hopcount>\\S+) (?P<realname>.*)\",\n         \"multi\": True},\n        {\"match\": r\"(?i)^:\\S+ (?P<retcode>(315|401)) \\S+ {channel} :.*\",\n         \"final\": True},\n    )\n\n    def process_results(self, results=None, **value):\n        users = []\n        for res in results:\n            if 'retcode' in res:\n                value.update(res)\n            else:\n                res['mask'] = utils.IrcString(\n                    '{nick}!{user}@{host}'.format(**res))\n                users.append(res)\n        value['users'] = users\n        value['success'] = value.get('retcode') == '315'\n        return value\n\n\nclass WhoChannelFlags(AsyncEvents):\n\n    flags = OrderedDict([\n        (\"u\", r\"(?P<user>\\S+)\"),\n        (\"i\", r\"(?P<ip>\\S+)\"),\n        (\"h\", r\"(?P<host>\\S+)\"),\n        (\"s\", r\"(?P<server>\\S+)\"),\n        (\"n\", r\"(?P<nick>\\S+)\"),\n        (\"a\", r\"(?P<account>\\S+)\"),\n        (\"r\", r\":(?P<realname>.*)\"),\n    ])\n\n    send_line = \"WHO {channel} c%{flags}\"\n\n    events = (\n        {\"match\": r\"(?i)^:\\S+ (?P<retcode>(315|401)) \\S+ {channel} :.*\",\n         \"final\": True},\n    )\n\n    def process_results(self, results=None, **value):\n        users = []\n        for res in results:\n            if 'retcode' in res:\n                value.update(res)\n            else:\n                # Works in QuakeNet, don't know about other networks\n                if res.get('account') == '0':\n                    res['account'] = None\n                users.append(res)\n        value['users'] = users\n        value['success'] = value.get('retcode') == '315'\n        return value\n\n\nclass WhoNick(AsyncEvents):\n\n    send_line = 'WHO {nick}'\n\n    events = (\n        {\"match\": r\"(?i)^:\\S+ 352 \\S+ (?P<channel>\\S+) (?P<user>\\S+) \"\n                  r\"(?P<host>\\S+) (?P<server>\\S+) (?P<nick>{nick}) \"\n                  r\"(?P<modes>\\S+) :(?P<hopcount>\\S+)\\s*(?P<realname>.*)\"},\n        {\"match\": r\"(?i)^:\\S+ (?P<retcode>(315|401)) \\S+ {nick} :.*\",\n         \"final\": True},\n    )\n\n    def process_results(self, results=None, **value):\n        for res in results:\n            if 'retcode' not in res:\n                res['mask'] = utils.IrcString(\n                    '{nick}!{user}@{host}'.format(**res))\n            value.update(res)\n        value['success'] = value.get('retcode') == '315'\n        return value\n\n\nclass IsOn(AsyncEvents):\n\n    events = (\n        {\"match\": r\"(?i)^:\\S+ 303 \\S+ :(?P<nicknames>({nicknames_re}.*|$))\",\n         \"final\": True},\n    )\n\n    def process_results(self, results=None, **value):\n        nicknames = []\n        for res in results:\n            nicknames.extend(res.pop('nicknames', '').split())\n        value['names'] = nicknames\n        return value\n\n\nclass Topic(AsyncEvents):\n\n    send_line = 'TOPIC {channel}{topic}'\n\n    events = (\n        {\"match\": (r\"(?i)^:\\S+ (?P<retcode>(331|332|TOPIC))\"\n                   r\"(:?\\s+\\S+\\s+|\\s+){channel} :(?P<topic>.*)\"),\n         \"final\": True},\n    )\n\n    def process_results(self, results=None, **value):\n        for res in results:\n            status = res.get('retcode', '')\n            if status.upper() in ('332', 'TOPIC'):\n                value['topic'] = res.get('topic')\n            else:\n                value['topic'] = None\n            return value\n\n\nclass Names(AsyncEvents):\n\n    send_line = 'NAMES {channel}'\n\n    events = (\n        {\"match\": r\"(?i)^:\\S+ 353 .*{channel} :(?P<nicknames>.*)\",\n         'multi': True},\n        {'match': r\"(?i)^:\\S+ (?P<retcode>(366|401)) \\S+ {channel} :.*\",\n         'final': True},\n    )\n\n    def process_results(self, results=None, **value):\n        nicknames = []\n        for res in results:\n            nicknames.extend(res.pop('nicknames', '').split())\n        value['names'] = nicknames\n        value['success'] = value.get('retcode') == '366'\n        return value\n\n\nclass ChannelBans(AsyncEvents):\n\n    send_line = 'MODE {channel} +b'\n\n    events = (\n        {\"match\": r\"(?i)^:\\S+ 367 \\S+ {channel} (?P<mask>\\S+) (?P<user>\\S+) \"\n                  r\"(?P<timestamp>\\d+)\",\n         \"multi\": True},\n        {\"match\": r\"(?i)^:\\S+ 368 \\S+ {channel} :.*\",\n         \"final\": True},\n    )\n\n    def process_results(self, results=None, **value):\n        bans = []\n        for res in results:\n            # TODO: fix event so this one isn't needed\n            if not res:\n                continue\n            res['timestamp'] = int(res['timestamp'])\n            bans.append(res)\n        value['bans'] = bans\n        return value\n\n\nclass CTCP(AsyncEvents):\n\n    send_line = 'PRIVMSG {nick} :\\x01{ctcp}\\x01'\n\n    events = (\n        {\"match\": \"(?i):(?P<mask>\\\\S+) NOTICE \\\\S+ :\\x01(?P<ctcp>\\\\S+) \"\n                  \"(?P<reply>.*)\\x01\",\n         \"final\": True},\n        {\"match\": r\"(?i)^:\\S+ (?P<retcode>486) \\S+ :(?P<reply>.*)\",\n         \"final\": True}\n    )\n\n    def process_results(self, results=None, **value):\n        \"\"\"take results list of all events and return first dict\"\"\"\n        for res in results:\n            if 'mask' in res:\n                res['mask'] = utils.IrcString(res['mask'])\n            value['success'] = res.pop('retcode', None) != '486'\n            value.update(res)\n        return value\n\n\n@dec.plugin\nclass Async:\n    \"\"\"Asynchronious plugin.\n    Extend the bot with some common commands using\n    :class:`~irc3.asynchronous.AsyncEvents`\n    \"\"\"\n\n    def __init__(self, context):\n        self.context = context\n        self.context.async_cmds = self\n        self.async_whois = Whois(context)\n        self.async_who_channel = WhoChannel(context)\n        self.async_who_nick = WhoNick(context)\n        self.async_topic = Topic(context)\n        self.async_ison = IsOn(context)\n        self.async_names = Names(context)\n        self.async_channel_bans = ChannelBans(context)\n        self.async_ctcp = CTCP(context)\n\n    def async_who_channel_flags(self, channel, flags, timeout):\n        \"\"\"\n        Creates and calls a class from WhoChannelFlags with needed match rule\n        for WHO command on channels with flags.\n        \"\"\"\n        # Lowercase flags and sort based on WhoChannelFlags.flags, otherwise\n        # resulting dict is wrong. Also join flags if it's a sequence.\n        flags = ''.join([f.lower() for f in WhoChannelFlags.flags\n                         if f in flags])\n        regex = [WhoChannelFlags.flags[f] for f in flags]\n        channel = channel.lower()\n        cls = type(\n            WhoChannelFlags.__name__,\n            (WhoChannelFlags,),\n            {\"events\": WhoChannelFlags.events + (\n                {\"match\": r\"(?i)^:\\S+ 354 \\S+ {0}\".format(' '.join(regex)),\n                 \"multi\": True},\n            )}\n        )\n        return cls(self.context)(channel=channel, flags=flags, timeout=timeout)\n\n    @dec.extend\n    def whois(self, nick, timeout=20):\n        \"\"\"Send a WHOIS and return a Future which will contain recieved data:\n\n        .. code-block:: py\n\n            result = await bot.async_cmds.whois('gawel')\n        \"\"\"\n        return self.async_whois(nick=nick.lower(), timeout=timeout)\n\n    @dec.extend\n    def who(self, target, flags=None, timeout=20):\n        \"\"\"Send a WHO and return a Future which will contain recieved data:\n\n        .. code-block:: py\n\n            result = await bot.async_cmds.who('gawel')\n            result = await bot.async_cmds.who('#irc3')\n            result = await bot.async_cmds.who('#irc3', 'an')\n            # or\n            result = await bot.async_cmds.who('#irc3', ['a', 'n'])\n        \"\"\"\n        target = target.lower()\n        if target.startswith('#'):\n            if flags:\n                return self.async_who_channel_flags(channel=target,\n                                                    flags=flags,\n                                                    timeout=timeout)\n            return self.async_who_channel(channel=target, timeout=timeout)\n        else:\n            return self.async_who_nick(nick=target, timeout=timeout)\n\n    def topic(self, channel, topic=None, timeout=20):\n        if not topic:\n            topic = ''\n        else:\n            topic = ' ' + topic.strip()\n        return self.async_topic(channel=channel, topic=topic, timeout=timeout)\n\n    @dec.extend\n    def ison(self, *nicknames, **kwargs):\n        \"\"\"Send a ISON and return a Future which will contain recieved data:\n\n        .. code-block:: py\n\n            result = await bot.async_cmds.ison('gawel', 'irc3')\n        \"\"\"\n        nicknames = [n.lower() for n in nicknames]\n        self.context.send_line('ISON :{0}'.format(' '.join(nicknames)))\n        nicknames = [re.escape(n) for n in nicknames]\n        return self.async_ison(nicknames_re='(%s)' % '|'.join(nicknames),\n                               **kwargs)\n\n    @dec.extend\n    def names(self, channel, timeout=20):\n        \"\"\"Send a NAMES and return a Future which will contain recieved data:\n\n        .. code-block:: py\n\n            result = await bot.async_cmds.names('#irc3')\n        \"\"\"\n        return self.async_names(channel=channel.lower(), timeout=timeout)\n\n    @dec.extend\n    def channel_bans(self, channel, timeout=20):\n        \"\"\"Send a MODE +b and return a Future which will contain recieved data:\n        .. code-block:: py\n            result = await bot.async_cmds.channel_bans('#irc3')\n        \"\"\"\n        return self.async_channel_bans(channel=channel.lower(),\n                                       timeout=timeout)\n\n    @dec.extend\n    def ctcp_async(self, nick, ctcp, timeout=20):\n        \"\"\"Send a CTCP and return a Future which will contain recieved data:\n\n        .. code-block:: py\n\n            result = await bot.async_cmds.ctcp('irc3', 'version')\n        \"\"\"\n        return self.async_ctcp(nick=nick, ctcp=ctcp.upper(), timeout=timeout)\n"
  },
  {
    "path": "irc3/plugins/autocommand.py",
    "content": "import irc3\nfrom irc3 import utils, asyncio\nimport re\n\n__doc__ = '''\n==================================================\n:mod:`irc3.plugins.autocommand` Autocommand plugin\n==================================================\n\nThis plugin allows to send IRC commands to the server after connecting.\nThis could be usable for authorization, cloaking, requesting invite to invite\nonly channel and other use cases.\nIt also allows to set delays between IRC commands via the ``/sleep`` command.\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n\nUsage::\n\nThis example will authorize on Freenode:\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.autocommand\n    ...\n    ... autocommands =\n    ...     PRIVMSG NickServ :IDENTIFY nick password\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nHere's another, more complicated example:\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.autocommand\n    ...\n    ... autocommands =\n    ...     AUTH user password\n    ...     MODE {nick} +x\n    ...     /sleep 2\n    ...     PRIVMSG Q :INVITE #inviteonly\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nIt will authorize on QuakeNet, cloak and request an invite to ``#inviteonly``\nafter a 2 second delay.\n'''\n\n\nclass SimpleCommand:\n\n    def __init__(self, cmd):\n        self.cmd = cmd\n\n    async def execute(self, bot):\n        send_cmd = self.cmd.format(nick=bot.nick)\n        bot.send_line(send_cmd)\n\n\nclass SleepCommand:\n\n    SLEEP_RE = re.compile(r\"^/sleep\\s+(?P<time>[\\d\\.]+)\\s*$\", re.IGNORECASE)\n    IS_SLEEP_RE = re.compile(r\"/sleep\\b\", re.IGNORECASE)\n\n    def __init__(self, time):\n        if isinstance(time, (int, float)):\n            self.time = time\n        else:\n            raise TypeError(\"Wrong type of argument\")\n\n    @classmethod\n    def is_match(cls, test_str):\n        return bool(cls.IS_SLEEP_RE.match(test_str))\n\n    @classmethod\n    def parse(cls, cmd_str):\n        sleep_m = cls.SLEEP_RE.match(cmd_str)\n        if sleep_m is not None:\n            try:\n                val = float(sleep_m.groupdict()['time'])\n            except ValueError:\n                raise ValueError(\"Wrong argument for /sleep command\")\n            else:\n                return cls(val)\n        else:\n            raise ValueError(\"Wrong usage of /sleep command\")\n\n    async def execute(self, bot):\n        await asyncio.sleep(self.time, loop=bot.loop)\n\n\n@irc3.plugin\nclass AutoCommand:\n\n    requires = [\n        'irc3.plugins.core',\n    ]\n\n    def __init__(self, bot):\n        self.bot = bot\n        cmds = utils.as_list(self.bot.config.get('autocommands', []))\n        self.commands = [self.parse_command(cmd) for cmd in cmds]\n\n    @staticmethod\n    def parse_command(command):\n        if not command:\n            return\n\n        if command.startswith('/'):\n            if SleepCommand.is_match(command):\n                return SleepCommand.parse(command)\n            else:\n                raise ValueError(\"Unknown command {cmd}\".format(cmd=command))\n        else:\n            return SimpleCommand(command)\n\n    def server_ready(self):\n        self.bot.create_task(self.execute_commands())\n\n    async def execute_commands(self):\n        for command in self.commands:\n            await command.execute(self.bot)\n"
  },
  {
    "path": "irc3/plugins/autojoins.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\nfrom irc3 import utils\n__doc__ = '''\n==============================================\n:mod:`irc3.plugins.autojoins` Auto join plugin\n==============================================\n\nAuto join channels. The bot will retry to join when kicked and will retry to\njoin each 30s when an error occurs.\n\n..\n    >>> from irc3.testing import IrcBot\n\nUsage::\n\n    >>> bot = IrcBot(autojoins=['#chan1', '#chan2'])\n    >>> bot.include('irc3.plugins.autojoins')\n'''\n\n\n@irc3.plugin\nclass AutoJoins:\n\n    requires = [\n        'irc3.plugins.core',\n    ]\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.channels = utils.as_list(self.bot.config.get('autojoins', []))\n        self.delay = self.bot.config.get('autojoin_delay', 0)\n        self.handles = {}\n        self.timeout = 240\n        self.joined = set()\n        self.delayed_join = None\n        if not isinstance(self.delay, (int, float)):  # pragma: no cover\n            self.bot.log.error('Wrong autojoin_delay value: %r', self.delay)\n            self.delay = 0\n\n    @classmethod\n    def reload(cls, old):\n        if hasattr(old, \"joined\"):\n            old_channels = old.joined\n        else:  # pragma: no cover\n            # old version of plugin\n            old_channels = frozenset(old.channels)\n\n        new = cls(old.bot)\n        new_channels = frozenset(new.channels)\n        part_channels = old_channels - new_channels\n        join_channels = new_channels - old_channels\n        # join to new channels\n        for channel in join_channels:\n            new.join(channel)\n\n        # part from old channels\n        for channel in part_channels:\n            new.part(channel)\n        return new\n\n    def before_reload(self):  # pragma: no cover\n        self.stop_tasks()\n\n    def stop_tasks(self):  # pragma: no cover\n        if self.delayed_join is not None:\n            self.delayed_join.cancel()\n            self.delayed_join = None\n\n        for timeout, handle in self.handles.values():\n            handle.cancel()\n        self.handles = {}\n\n    def connection_lost(self):  # pragma: no cover\n        self.stop_tasks()\n\n    def server_ready(self):\n        if not self.delay:\n            self.join()\n        else:\n            task = self.bot.loop.call_later(self.delay, self.join)\n            self.delayed_join = task\n\n    def join(self, channel=None):\n        if channel is None:\n            channels = self.channels\n        else:\n            channels = [channel]\n        for channel in channels:\n            channel = utils.as_channel(channel)\n            if channel in self.handles:\n                timeout, handle = self.handles[channel]\n                self.bot.log.info('Re-trying to join %s after %ss',\n                                  channel, timeout)\n            else:\n                self.bot.log.info('Trying to join %s', channel)\n            self.bot.join(channel)\n            self.joined.add(channel)\n\n    def part(self, channel):\n        channel = utils.as_channel(channel)\n        self.bot.log.info('Leaving channel %s', channel)\n        self.bot.part(channel)\n        if channel in self.joined:  # pragma: no cover\n            self.joined.remove(channel)\n\n    @irc3.event(irc3.rfc.KICK)\n    def on_kick(self, mask, channel, target, **kwargs):\n        \"\"\"bot must rejoin when kicked from a channel\"\"\"\n        if channel in self.handles:\n            timeout, handle = self.handles[channel]\n            handle.cancel()\n            del self.handles[channel]\n        if target.nick == self.bot.nick:\n            self.join(channel)\n\n    @irc3.event(r\"^:\\S+ 47[1234567] \\S+ (?P<channel>\\S+).*\")\n    def on_err_join(self, channel, **kwargs):\n        \"\"\"bot must try to rejoin later when he can't join\"\"\"\n        if channel in self.handles:\n            timeout, handle = self.handles[channel]\n            handle.cancel()\n            timeout = timeout * 4\n            if timeout > self.timeout:  # pragma: no cover\n                timeout = self.timeout\n        else:\n            timeout = 2\n        handle = self.bot.loop.call_later(timeout, self.join, channel)\n        self.handles[channel] = timeout, handle\n        if channel in self.joined:\n            self.joined.remove(channel)\n"
  },
  {
    "path": "irc3/plugins/casefold.py",
    "content": "# -*- coding: utf-8 -*-\nimport functools\nimport string\nimport irc3\n__doc__ = '''\n================================================\n:mod:`irc3.plugins.casefold` casefolding plugin\n================================================\n\nThis command introduces a `bot.casefold` function that casefolds strings based\non the current casemapping of the IRC server.\n\nThis lets you casefold nicks and channel names so that on a server using\nrfc1459 casemapping, `#cool[chan]` and `#Cool{Chan}` are seen as the same\nchannel.\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n\nUsage::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.casefold\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nReturning casefolded strings::\n\n    >>> bot.casefold('ThisIsANick')\n    'thisisanick'\n    >>> bot.casefold('#WeirdChannelNames[]')\n    '#weirdchannelnames{}'\n'''\n\n\n@irc3.plugin\nclass Casefold:\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.recalculate_casemaps()\n        self.bot.casefold = functools.partial(self.casefold)\n\n    # casemapping\n    @irc3.event(r'^:\\S+ 005 \\S+ .+CASEMAPPING.*')\n    def recalculate_casemaps(self):\n        casemapping = self.bot.config['server_config'].get('CASEMAPPING',\n                                                           'rfc1459')\n\n        if casemapping == 'rfc1459':\n            lower_chars = (\n                string.ascii_lowercase + ''.join(\n                    chr(i) for i in range(123, 127))\n            )\n            upper_chars = (\n                string.ascii_uppercase + ''.join(chr(i) for i in range(91, 95))\n            )\n\n        elif casemapping == 'ascii':\n            lower_chars = string.ascii_lowercase\n            upper_chars = string.ascii_uppercase\n\n        table_in = (ord(char) for char in upper_chars)\n        self._lower_trans = dict(zip(table_in, lower_chars))\n        return\n\n    def casefold(self, in_str):\n        \"\"\"Casefold the given string, with the current server's casemapping.\"\"\"\n        folded = in_str.translate(self._lower_trans)\n        return folded\n"
  },
  {
    "path": "irc3/plugins/command.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.compat import asyncio\nfrom irc3 import utils\nfrom collections import defaultdict\nimport functools\nimport venusian\nimport fnmatch\nimport logging\nimport docopt\nimport shlex\nimport irc3\nimport sys\nimport re\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.command` Command plugin\n==========================================\n\nIntroduce a ``@command`` decorator\n\nThe decorator use `docopts <http://docopt.org/>`_ to parse command arguments.\n\nUsage\n=====\n\nCreate a python module with some commands:\n\n.. literalinclude:: ../../examples/mycommands.py\n\n..\n    >>> import sys\n    >>> sys.path.append('examples')\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n\nAnd register it::\n\n    >>> bot = IrcBot()\n    >>> bot.include('irc3.plugins.command')  # register the plugin\n    >>> bot.include('mycommands')            # register your commands\n\n\nCheck the result::\n\n    >>> bot.test(':gawel!user@host PRIVMSG #chan :!echo foo')\n    PRIVMSG #chan :foo\n\nIn the docstring, ``%%`` is replaced by the command character. ``!`` by\ndefault. You can override it by passing a ``cmd`` parameter to bot's config.\n\nWhen a command is not public, you can't use it on a channel::\n\n    >>> bot.test(':gawel!user@host PRIVMSG #chan :!adduser foo pass')\n    PRIVMSG gawel :You can only use the 'adduser' command in private.\n\nIf a command is tagged with ``show_in_help_list=False``, it won't be shown\non the result of ``!help``.\n\n    >>> bot.test(':gawel!user@host PRIVMSG #chan :!help')\n    PRIVMSG #chan :Available commands: !adduser, !echo, !help\n\nView extra info about a command by specifying it to ``!help``.\n\n    >>> bot.test(':gawel!user@host PRIVMSG #chan :!help echo')\n    PRIVMSG #chan :Echo command\n    PRIVMSG #chan :!echo <words>...\n    >>> bot.test(':gawel!user@host PRIVMSG #chan :!help nonexistant')\n    PRIVMSG #chan :No such command. Try !help for an overview of all commands.\n\nGuard\n=====\n\nYou can use a guard to prevent untrusted users to run some commands. The\n:class:`free_policy` is used by default.\n\nThere is two builtin policy:\n\n.. autoclass:: free_policy\n\n\n.. autoclass:: mask_based_policy\n\nMask based guard using permissions::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... nick = nono\n    ... includes =\n    ...     irc3.plugins.command\n    ...     mycommands\n    ... [irc3.plugins.command]\n    ... guard = irc3.plugins.command.mask_based_policy\n    ... [irc3.plugins.command.masks]\n    ... gawel!*@* = all_permissions\n    ... foo!*@* = help\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nfoo is allowed to use command without permissions::\n\n    >>> bot.test(':foo!u@h PRIVMSG nono :!echo got the power')\n    PRIVMSG foo :got the power\n\nfoo is not allowed to use command except those with the help permission::\n\n    >>> bot.test(':foo!u@h PRIVMSG nono :!ping')\n    PRIVMSG foo :You are not allowed to use the 'ping' command\n\ngawel is allowed::\n\n    >>> bot.test(':gawel!u@h PRIVMSG nono :!ping')\n    NOTICE gawel :PONG gawel!\n\nAsync commands\n==============\n\nCommands can be coroutines:\n\n.. literalinclude:: ../../examples/async_command.py\n  :language: py\n\nAvailable options\n=================\n\nThe plugin accept the folowing options:\n\n.. code-block:: ini\n\n    [irc3.plugins.command]\n    cmd = !\n    use_shlex = true\n    antiflood = true\n    casesensitive = true\n    guard = irc3.plugins.command.mask_based_policy\n\n\nCommand arguments\n=================\n\nThe :func:`command` decorator accept the folowing arguments:\n\n**name**: if set, use this name as the command name instead of the function\nname.\n\n**permission**: if set, this permission will be required to run the command.\nSee Guard section\n\n**use_shlex**: if `False`, do not use `shlex` to parse command line.\n\n**options_first**: if `True` use docopt's options_first options. Allow to have\nargs that starts with `-` as arguments.\n\n**error_format**: allow to customize error messages. must be a callable that\naccept keyword arguments `cmd`, `args` and `exc`.\nFor example, `error_format=\"Error for {cmd}\".format` will work.\n\n**quiet**: if `True` don't show errors\n\n**aliases**: this argument, when present, should be a list of strings. All\nthose strings will become alternative command names (i.e. aliases).\nFor example, command 'mycmd' with aliases=['theircmd', 'noonescmd'] could\nbe called via all three names.\n\n\n'''\n\n\nclass free_policy:\n    \"\"\"Default policy\"\"\"\n    def __init__(self, bot):\n        self.context = bot\n\n    def __call__(self, predicates, meth, client, target, args, **kwargs):\n        return meth(client, target, args)\n\n\nclass mask_based_policy:\n    \"\"\"Allow only valid masks. Able to take care or permissions\"\"\"\n\n    key = __name__ + '.masks'\n\n    def __init__(self, bot):\n        self.context = bot\n        self.log = logging.getLogger(__name__)\n        self.log.debug('Masks: %r', self.masks)\n\n    @property\n    def masks(self):\n        masks = self.context.config[self.key]\n        if hasattr(self.context, 'db'):\n            # update config with storage values\n            try:\n                value = self.context.db[self]\n            except KeyError:\n                pass\n            else:\n                if isinstance(value, dict):\n                    masks.update(value)\n        return masks\n\n    def has_permission(self, mask, permission):\n        if permission is None:\n            return True\n        for pattern in self.masks:\n            if fnmatch.fnmatch(mask, pattern):\n                if not isinstance(self.masks, dict):\n                    return True\n                perms = self.masks[pattern]\n                if permission in perms or 'all_permissions' in perms:\n                    return True\n        return False\n\n    def __call__(self, predicates, meth, client, target, args, **kwargs):\n        if self.has_permission(client, predicates.get('permission')):\n            return meth(client, target, args)\n        cmd_name = predicates.get('name', meth.__name__)\n        self.context.privmsg(\n            client.nick,\n            'You are not allowed to use the %r command' % cmd_name)\n\n\ndef attach_command(func, depth=2, **predicates):\n    commands = predicates.pop('commands',\n                              'irc3.plugins.command.Commands')\n    category = predicates.pop('venusian_category',\n                              'irc3.plugins.command')\n\n    def callback(context, name, ob):\n        obj = context.context\n        if info.scope == 'class':\n            callback = func.__get__(obj.get_plugin(ob), ob)\n        else:\n            callback = utils.wraps_with_context(func, obj)\n        plugin = obj.get_plugin(utils.maybedotted(commands))\n        predicates.update(module=func.__module__)\n        cmd_name = predicates.get('name', func.__name__)\n        if not plugin.case_sensitive:\n            cmd_name = cmd_name.lower()\n        plugin[cmd_name] = (predicates, callback)\n        aliases = predicates.get('aliases', None)\n        if aliases is not None:\n            for alias in aliases:\n                plugin.aliases[alias] = cmd_name\n            obj.log.debug('Register command %r %r', cmd_name, aliases)\n        else:\n            obj.log.debug('Register command %r', cmd_name)\n    info = venusian.attach(func, callback,\n                           category=category, depth=depth)\n\n\ndef command(*func, **predicates):\n    if func:\n        func = func[0]\n        attach_command(func, **predicates)\n        return func\n    else:\n        def wrapper(func):\n            attach_command(func, **predicates)\n            return func\n        return wrapper\n\n\n@irc3.plugin\nclass Commands(dict):\n\n    __reloadable__ = False\n\n    requires = [\n        __name__.replace('command', 'core'),\n    ]\n    default_policy = free_policy\n    case_sensitive = False\n\n    def __init__(self, context):\n        self.context = context\n        module = self.__class__.__module__\n        self.config = config = context.config.get(module, {})\n        self.log = logging.getLogger(module)\n        self.log.debug('Config: %r', config)\n\n        if 'cmd' in context.config:  # in case of\n            config['cmd'] = context.config['cmd']\n        context.config['cmd'] = self.cmd = config.get('cmd', '!')\n        context.config['re_cmd'] = re.escape(self.cmd)\n\n        self.use_shlex = self.config.get('use_shlex', True)\n        self.antiflood = self.config.get('antiflood', False)\n        self.case_sensitive = self.config.get('casesensitive',\n                                              self.case_sensitive)\n\n        guard = utils.maybedotted(config.get('guard', self.default_policy))\n        self.log.debug('Guard: %s', guard.__name__)\n        self.guard = guard(context)\n\n        self.error_format = utils.maybedotted(config.get('error_format',\n                                              \"Invalid arguments.\".format))\n        self.handles = defaultdict(Done)\n        self.tasks = defaultdict(Done)\n\n        self.aliases = {}\n\n    def split_command(self, data, use_shlex=None):\n        if not data:\n            return []\n        return shlex.split(data) if use_shlex else data.split(' ')\n\n    @irc3.event((r'(@(?P<tags>\\S+) )?:(?P<mask>\\S+) PRIVMSG (?P<target>\\S+) '\n                 r':{re_cmd}(?P<cmd>[\\w-]+)(\\s+(?P<data>\\S.*)|(\\s*$))'))\n    def on_command(self, cmd, mask=None, target=None, client=None, **kw):\n        if not self.case_sensitive:\n            cmd = cmd.lower()\n        cmd = self.aliases.get(cmd, cmd)\n        predicates, meth = self.get(cmd, (None, None))\n        if meth is not None:\n            if predicates.get('public', True) is False and target.is_channel:\n                self.context.privmsg(\n                    mask.nick,\n                    'You can only use the %r command in private.' % str(cmd))\n            else:\n                return self.do_command(predicates, meth, mask, target, **kw)\n\n    def do_command(self, predicates, meth, client, target, data=None, **kw):\n        nick = self.context.nick or '-'\n        to = client.nick if target == nick else target\n        doc = meth.__doc__ or ''\n        doc = [line.strip() for line in doc.strip().split('\\n')]\n        doc = [nick + ' ' + line.strip('%%')\n               for line in doc if line.startswith('%%')]\n        doc = 'Usage:' + '\\n    ' + '\\n    '.join(doc)\n        if data:\n            if not isinstance(data, str):  # pragma: no cover\n                encoding = self.context.encoding\n                data = data.encode(encoding)\n        try:\n            data = self.split_command(\n                data, use_shlex=predicates.get('use_shlex', self.use_shlex))\n        except ValueError as e:\n            if not predicates.get('quiet', False):\n                self.context.privmsg(to, 'Invalid arguments: {}.'.format(e))\n            return\n        docopt_args = dict(help=False)\n        if \"options_first\" in predicates:\n            docopt_args.update(options_first=predicates[\"options_first\"])\n        cmd_name = predicates.get('name', meth.__name__)\n        try:\n            args = docopt.docopt(doc, [cmd_name] + data, **docopt_args)\n        except docopt.DocoptExit as exc:\n            if not predicates.get('quiet', False):\n                args = {'cmd': cmd_name, 'args': data,\n                        'args_str': \" \".join(data), 'exc': exc}\n                error_format = predicates.get('error_format',\n                                              self.error_format)\n                self.context.privmsg(to, error_format(**args))\n        else:\n            uid = (cmd_name, to)\n            use_client = isinstance(client, asyncio.Protocol)\n            if not self.tasks[uid].done():\n                self.context.notice(\n                    client if use_client else client.nick,\n                    \"Another task is already running. \"\n                    \"Please be patient and don't flood me\", nowait=True)\n            elif not self.handles[uid].done() and self.antiflood:\n                self.context.notice(\n                    client if use_client else client.nick,\n                    \"Please be patient and don't flood me\", nowait=True)\n            else:\n                # get command result\n                res = self.guard(predicates, meth, client, target, args=args)\n\n                callback = functools.partial(self.command_callback, uid, to)\n                if res is not None:\n                    coros = (\n                        asyncio.iscoroutinefunction(meth),\n                        asyncio.iscoroutinefunction(self.guard.__call__)\n                    )\n                    if any(coros):\n                        task = asyncio.ensure_future(\n                            res, loop=self.context.loop)\n                        # use a callback if command is a coroutine\n                        task.add_done_callback(callback)\n                        self.tasks[uid] = task\n                        return task\n                    else:\n                        # no callback needed\n                        callback(res)\n\n    def command_callback(self, uid, to, msgs):\n        if isinstance(msgs, asyncio.Future):  # pragma: no cover\n            msgs = msgs.result()\n        if msgs is not None:\n            def iterator(msgs):\n                for msg in msgs:\n                    yield to, msg\n            if isinstance(msgs, str):\n                msgs = [msgs]\n            handle = self.context.call_many('privmsg', iterator(msgs))\n            if handle is not None:\n                self.handles[uid] = handle\n\n    @command\n    def help(self, mask, target, args):\n        \"\"\"Show help\n\n            %%help [<cmd>]\n        \"\"\"\n        if args['<cmd>']:\n            args = args['<cmd>']\n            # Strip out self.context.config.cmd from args so we can use\n            # both !help !foo and !help foo\n            if args.startswith(self.context.config.cmd):\n                args = args[len(self.context.config.cmd):]\n            args = self.aliases.get(args, args)\n            predicates, meth = self.get(args, (None, None))\n            if meth is not None:\n                doc = meth.__doc__ or ''\n                doc = [\n                    line.strip() for line in doc.split('\\n')\n                    if line.strip()\n                ]\n                buf = ''\n                for line in doc:\n                    if '%%' not in line and buf is not None:\n                        buf += line + ' '\n                    else:\n                        if buf is not None:\n                            for b in utils.split_message(\n                                buf,\n                                160,\n                                self.context.encoding,\n                            ):\n                                yield b\n                            buf = None\n                        line = line.replace('%%', self.context.config.cmd)\n                        yield line\n                aliases = predicates.get('aliases', None)\n                if aliases is not None:\n                    yield 'Aliases: {0}'.format(','.join(sorted(aliases)))\n            else:\n                yield ('No such command. Try %shelp for an '\n                       'overview of all commands.'\n                       % self.context.config.cmd)\n        else:\n            cmds = sorted((k for (k, (p, m)) in self.items()\n                           if p.get('show_in_help_list', True)))\n            cmds_str = ', '.join([self.cmd + k for k in cmds])\n            lines = utils.split_message(\n                'Available commands: %s ' % cmds_str,\n                160,\n                self.context.encoding,\n            )\n            for line in lines:\n                yield line\n            url = self.config.get('url')\n            if url:\n                yield 'Full help is available at ' + url\n\n    def __repr__(self):\n        return '<Commands %s>' % sorted([self.cmd + k for k in self.keys()])\n\n\nclass Done:\n\n    def done(self):\n        return True\n\n\n@command(permission='admin', show_in_help_list=False, public=False)\ndef ping(bot, mask, target, args):\n    \"\"\"ping/pong\n\n        %%ping\n    \"\"\"\n    bot.send('NOTICE %(nick)s :PONG %(nick)s!' % dict(nick=mask.nick))\n\n\n@command(venusian_category='irc3.debug', show_in_help_list=False)\ndef quote(bot, mask, target, args):\n    \"\"\"send quote to the server\n\n        %%quote <args>...\n    \"\"\"\n    msg = ' '.join(args['<args>'])\n    bot.log.info('quote> %r', msg)\n    bot.send(msg)\n\n\n@command(venusian_category='irc3.debug', show_in_help_list=False)\ndef reconnect(bot, mask, target, args):\n    \"\"\"force reconnect\n\n        %%reconnect\n    \"\"\"\n    plugin = bot.get_plugin(utils.maybedotted('irc3.plugins.core.Core'))\n    bot.loop.call_soon(plugin.reconnect)\n\n\n@irc3.extend\ndef print_help_page(bot, file=sys.stdout):\n    \"\"\"print help page\"\"\"\n    def p(text):\n        print(text, file=file)\n    plugin = bot.get_plugin(Commands)\n    title = \"Available Commands for {nick} at {host}\".format(**bot.config)\n    p(\"=\" * len(title))\n    p(title)\n    p(\"=\" * len(title))\n    p('')\n    p('.. contents::')\n    p('')\n    modules = {}\n    for name, (predicates, callback) in plugin.items():\n        commands = modules.setdefault(callback.__module__, [])\n        commands.append((name, callback, predicates))\n\n    for module in sorted(modules):\n        p(module)\n        p('=' * len(module))\n        p('')\n        for name, callback, predicates in sorted(modules[module]):\n            p(name)\n            p('-' * len(name))\n            p('')\n            doc = callback.__doc__\n            doc = doc.replace('%%', bot.config.cmd)\n            for line in doc.split('\\n'):\n                line = line.strip()\n                if line.startswith(bot.config.cmd):\n                    line = '    ``{}``'.format(line)\n                p(line)\n            if 'permission' in predicates:\n                p('*Require {0[permission]} permission.*'.format(predicates))\n            if predicates.get('public', True) is False:\n                p('*Only available in private.*')\n            p('')\n"
  },
  {
    "path": "irc3/plugins/core.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import event\nfrom irc3 import rfc\n__doc__ = '''\n==============================================\n:mod:`irc3.plugins.core` Core plugin\n==============================================\n\nCore events\n\n.. autoclass:: Core\n   :members:\n\n..\n    >>> from irc3.testing import IrcBot\n\nUsage::\n\n    >>> bot = IrcBot()\n    >>> bot.include('irc3.plugins.core')\n'''\n\n\nclass Core:\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.timeout = int(self.bot.config.get('timeout'))\n        self.max_lag = int(self.bot.config.get('max_lag'))\n        self.reconn_handle = None\n        self.ping_handle = None\n        self.nick_handle = None\n        self.before_connect_events = [\n            event(rfc.CONNECTED, self.connected),\n            event(r\"^:\\S+ 005 \\S+ (?P<data>.+) :\\S+.*\",\n                  self.set_config),\n        ]\n\n    def connection_made(self, client=None):\n        # handle server config\n        config = self.bot.defaults['server_config'].copy()\n        self.bot.config['server_config'] = config\n        self.bot.detach_events(*self.before_connect_events)\n        self.bot.attach_events(insert=True, *self.before_connect_events)\n\n        # ping/ping\n        self.connection_made_at = self.bot.loop.time()\n        self.pong(event='CONNECT', data='')\n\n    def connected(self, **kwargs):\n        \"\"\"triger the server_ready event\"\"\"\n        self.bot.log.info('Server config: %r', self.bot.server_config)\n\n        # recompile when I'm sure of my nickname\n        self.bot.config['nick'] = kwargs['me']\n        self.bot.recompile()\n\n        # Let all plugins know that server can handle commands\n        self.bot.notify('server_ready')\n\n        # detach useless events\n        self.bot.detach_events(*self.before_connect_events)\n\n    def reconnect(self):  # pragma: no cover\n        self.bot.log.info(\n            \"We're waiting a ping for too long. Trying to reconnect...\")\n        self.bot.loop.call_soon(\n            self.bot.protocol.connection_lost,\n            'No pong reply'\n        )\n        self.pong(event='RECONNECT', data='')\n\n    @event(rfc.PONG)\n    def pong(self, event='PONG', data='', **kw):  # pragma: no cover\n        \"\"\"P0NG/PING\"\"\"\n        self.bot.log.debug('%s ping-pong (%s)', event, data)\n        if self.reconn_handle is not None:\n            self.reconn_handle.cancel()\n        self.reconn_handle = self.bot.loop.call_later(self.timeout,\n                                                      self.reconnect)\n        if self.ping_handle is not None:\n            self.ping_handle.cancel()\n        self.ping_handle = self.bot.loop.call_later(\n            self.timeout - self.max_lag, self.bot.send,\n            'PING :%s' % int(self.bot.loop.time()))\n\n    @event(rfc.PING)\n    def ping(self, data):\n        \"\"\"PING reply\"\"\"\n        self.bot.send('PONG :' + data)\n        self.pong(event='PING', data=data)\n\n    @event(rfc.NEW_NICK)\n    def recompile(self, nick=None, new_nick=None, **kw):\n        \"\"\"recompile regexp on new nick\"\"\"\n        if self.bot.nick == nick.nick:\n            self.bot.config['nick'] = new_nick\n            self.bot.recompile()\n\n    @event(rfc.ERR_NICK)\n    def badnick(self, me=None, nick=None, **kw):\n        \"\"\"Use alt nick on nick error\"\"\"\n        if me == '*':\n            self.bot.set_nick(self.bot.nick + '_')\n        self.bot.log.debug('Trying to regain nickname in 30s...')\n        self.nick_handle = self.bot.loop.call_later(\n            30, self.bot.set_nick, self.bot.original_nick)\n\n    def set_config(self, data=None, **kwargs):\n        \"\"\"Store server config\"\"\"\n        config = self.bot.config['server_config']\n        for opt in data.split(' '):\n            if '=' in opt:\n                opt, value = opt.split('=', 1)\n            else:\n                value = True\n            if opt.isupper():\n                config[opt] = value\n"
  },
  {
    "path": "irc3/plugins/cron.py",
    "content": "# -*- coding: utf-8 -*-\nimport venusian\nimport logging\nimport irc3\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.cron` Cron plugin\n==========================================\n\nIntroduce a ``@cron`` decorator\n\nInstall aiocron::\n\n    $ pip install aiocron\n\nCreate a python module with some crons:\n\n.. literalinclude:: ../../examples/mycrons.py\n\n..\n    >>> import sys\n    >>> sys.path.append('examples')\n    >>> from irc3.testing import IrcBot\n\nAnd register it::\n\n    >>> context = IrcBot()\n    >>> context.include('mycrons')    # register your crons\n\n'''\n\n\n@irc3.plugin\nclass Crons(list):\n\n    def __init__(self, context):\n        self.context = context\n        self.log = logging.getLogger(__name__)\n        self.factory = irc3.utils.maybedotted('aiocron.Cron')\n        self.debug = self.log.getEffectiveLevel() == logging.DEBUG\n        self.started = False\n\n    def connection_made(self):\n        if not self.started:\n            self.start()\n\n    def before_reload(self):\n        self.stop()\n        self[:] = []\n\n    def after_reload(self):\n        self.start()\n\n    @irc3.extend\n    def add_cron(self, cronline, callback, uuid=None):\n        cron = self.factory(cronline, callback, start=False, uuid=uuid,\n                            loop=self.context.loop)\n        self.append(cron)\n        if self.started:\n            cron.start()\n        return cron\n\n    @irc3.extend\n    def remove_cron(self, cron=None):\n        cron.stop()\n        self.remove(cron)\n\n    def start(self):\n        self.started = True\n        for cron in self:\n            cron.start()\n\n    def stop(self):\n        self.context.log.info('Stoping existing crons...')\n        self.started = False\n        for cron in self:\n            cron.stop()\n\n    def __repr__(self):\n        return '<Crons ({0}) at {1}>'.format(len(self), id(self))\n\n\ndef cron(cronline, venusian_category='irc3.plugins.cron'):\n    \"\"\"main decorator\"\"\"\n    def wrapper(func):\n        def callback(context, name, ob):\n            obj = context.context\n            crons = obj.get_plugin(Crons)\n            if info.scope == 'class':\n                callback = getattr(\n                    obj.get_plugin(ob),\n                    func.__name__)\n            else:\n                callback = irc3.utils.wraps_with_context(func, obj)\n            crons.add_cron(cronline, callback)\n        info = venusian.attach(func, callback, category=venusian_category)\n        return func\n    return wrapper\n"
  },
  {
    "path": "irc3/plugins/ctcp.py",
    "content": "# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom irc3.compat import Queue\nfrom irc3.compat import QueueFull\nimport irc3\n__doc__ = '''\n==============================================\n:mod:`irc3.plugins.ctcp` CTCP replies\n==============================================\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n\nUsage::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.ctcp\n    ... [ctcp]\n    ... foo = bar\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nTry to send a ``CTCP FOO``::\n\n    >>> bot.test(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01', show=False)\n    >>> # remove escape char for testing..\n    >>> print(bot.sent[0].replace('\\x01', '01'))\n    NOTICE gawel :01FOO bar01\n'''\n\n\n@irc3.plugin\nclass CTCP:\n    \"\"\"ctcp replies\"\"\"\n\n    def __init__(self, bot):\n        maxsize = int(bot.config.get('ctcp_max_replies', 3))\n        self.queue = Queue(loop=bot.loop, maxsize=maxsize)\n        self.handle = None\n        self.event = irc3.event(irc3.rfc.CTCP, self.on_ctcp)\n        bot.attach_events(self.event)\n        self.bot = bot\n\n    def clear_queue(self):\n        self.bot.log.info('CTCP clear queue')\n        while not self.queue.empty():\n            self.queue.get_nowait()\n        self.handle = None\n\n    def handle_flood(self):\n        self.bot.log.warn('CTCP Flood detected. '\n                          'Ignoring requests for 30s')\n        # ignore events for 30s\n        self.bot.detach_events(self.event)\n        self.bot.loop.call_later(30, self.bot.attach_events, self.event)\n\n    def on_ctcp(self, mask=None, target=None, ctcp=None, **kw):\n        lctcp = ctcp.split(' ')[0].lower()\n        if lctcp in self.bot.config.ctcp:\n            try:\n                self.queue.put_nowait((mask.nick, lctcp))\n            except QueueFull:\n                self.handle_flood()\n            else:\n                if self.handle is None:\n                    self.handle = self.bot.loop.call_later(1, self.clear_queue)\n                data = self.bot.config.ctcp[lctcp].format(now=datetime.now(),\n                                                          **self.bot.config)\n                self.bot.ctcp_reply(mask.nick, '%s %s' % (lctcp.upper(), data))\n"
  },
  {
    "path": "irc3/plugins/dcc.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\nfrom irc3.plugins import command\n__doc__ = \"\"\"\n==============================================\n:mod:`irc3.plugins.dcc` DCC Chat plugin\n==============================================\n\nThis module provide a command to start a DCC CHAT with the bot and extend it\nwith CHAT commands.\n\nCHAT Commands\n=============\n\nAdding new commands::\n\n    >>> @dcc_command\n    ... def echo(bot, mask, client, args):\n    ...     '''echo command\n    ...         %%echo <words>...\n    ...     '''\n    ...     yield ' '.join(args['words'])\n\nbot is the bot instance. mask is the irc mask of the user connected via dcc.\nclient is an instance of :class:`~irc3.dcc.DCCChat`\n\n\nAPI\n===\n\n.. autofunction:: dcc_command\n\n.. autoclass:: Commands\n   :members:\n\n\"\"\"\n\n\ndef dcc_command(*func, **predicates):\n    \"\"\"DCC CHAT command decorator\"\"\"\n    predicates['commands'] = 'irc3.plugins.dcc.Commands'\n    if func:\n        func = func[0]\n        command.attach_command(func, **predicates)\n        return func\n    else:\n        def wrapper(func):\n            command.attach_command(func, **predicates)\n            return func\n        return wrapper\n\n\n@irc3.plugin\nclass Commands(command.Commands):\n    \"\"\"DCC CHAT commands plugin\"\"\"\n\n    requires = [command.__name__]\n\n    @irc3.dcc_event(r'(\\x01ACTION\\s+|{re_cmd})(?P<cmd>\\w+)'\n                    r'((\\s(?P<data>\\S.*)|\\x01)|(\\x01|$))')\n    def on_command(self, cmd, client=None, **kw):\n        predicates, meth = self.get(cmd, (None, None))\n        if meth is not None:\n            return self.do_command(predicates, meth, client.mask, client, **kw)\n\n    @dcc_command\n    def help(self, *args):\n        \"\"\"Show help\n\n            %%help [<cmd>]\n        \"\"\"\n        return super(Commands, self).help(*args)\n\n    @command.command(public=False, permission='dcc_chat')\n    def chat(self, mask, *args):\n        \"\"\"DCC CHAT\n\n            %%chat\n        \"\"\"\n        self.context.create_task(self.context.dcc_chat(mask))\n"
  },
  {
    "path": "irc3/plugins/feeds.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport time\nimport irc3\nimport datetime\nfrom irc3.compat import asyncio\nfrom concurrent.futures import ThreadPoolExecutor\n\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.feeds` Feeds plugin\n==========================================\n\nSend a notification on channel on new feed entry.\n\nYour config must looks like this:\n\n.. code-block:: ini\n\n    [bot]\n    includes =\n        irc3.plugins.feeds\n\n    [irc3.plugins.feeds]\n    channels = #irc3                             # global channel to notify\n    delay = 5                                    # delay to check feeds\n    directory = ~/.irc3/feeds                    # directory to store feeds\n    hook = irc3.plugins.feeds.default_hook       # dotted name to a callable\n    fmt = [{name}] {entry.title} - {entry.link}  # formatter\n\n    # some feeds: name = url\n    github/irc3 = https://github.com/gawel/irc3/commits/master.atom#irc3\n    # custom formatter for the feed\n    github/irc3.fmt = [{feed.name}] New commit: {entry.title} - {entry.link}\n    # custom channels\n    github/irc3.channels = #irc3dev #irc3\n    # custom delay\n    github/irc3.delay = 10\n\nHook is a dotted name refering to a callable (function or class) wich take a\nlist of entries as argument. It should yield the entries you want really show:\n\n.. code-block:: python\n\n    >>> def hook(entries):\n    ...     for entry in entries:\n    ...         if 'something bad' not in entry.title:\n    ...             yield entry\n\n    >>> class Hook:\n    ...     def __init__(self, bot):\n    ...         self.bot = bot\n    ...     def __call__(self, entries):\n    ...         for entry in entries:\n    ...             if 'something bad' not in entry.title:\n    ...                 yield entry\n\n\nHere is a more complete hook used on freenode#irc3:\n\n.. literalinclude:: ../../examples/freenode_irc3.py\n   :pyobject: FeedsHook\n\n'''\n\nHEADERS = {\n    'User-Agent': 'python-requests/irc3/feeds',\n    'Cache-Control': 'max-age=0',\n    'Pragma': 'no-cache',\n}\n\n\ndef default_hook(entries):\n    \"\"\"Default hook called for each entry\"\"\"\n    return entries\n\n\ndef default_dispatcher(bot):  # pragma: no cover\n    \"\"\"Default messages dispatcher\"\"\"\n    def dispatcher(messages):\n        bot.call_many('privmsg', messages)\n    return dispatcher\n\n\ndef fetch(args):\n    \"\"\"fetch a feed\"\"\"\n    requests = args['requests']\n    for feed, filename in zip(args['feeds'], args['filenames']):\n        try:\n            resp = requests.get(feed, timeout=5, headers=HEADERS)\n            content = resp.content\n        except Exception:  # pragma: no cover\n            pass\n        else:\n            with open(filename, 'wb') as fd:\n                fd.write(content)\n    return args['name']\n\n\nISO_FORMAT = \"%Y-%m-%dT%H:%M:%S\"\n\n\ndef parse(feedparser, args):\n    \"\"\"parse a feed using feedparser\"\"\"\n    entries = []\n    args = irc3.utils.Config(args)\n    max_date = datetime.datetime.now() - datetime.timedelta(days=2)\n\n    for filename in args['filenames']:\n        try:\n            with open(filename + '.updated') as fd:\n                updated = datetime.datetime.strptime(\n                    fd.read()[:len(\"YYYY-MM-DDTHH:MM:SS\")], ISO_FORMAT\n                )\n        except (OSError, IOError, ValueError):\n            updated = datetime.datetime(datetime.MINYEAR, 1, 1)\n\n        feed = feedparser.parse(filename)\n        for e in feed.entries:\n            try:\n                updated_parsed = datetime.datetime(*e.updated_parsed[:6])\n            except AttributeError:\n                continue\n            if updated_parsed <= updated:\n                # skip already sent entries\n                continue\n            if updated_parsed < max_date:\n                # skip entries older than 2 days\n                continue\n            e['filename'] = filename\n            e['feed'] = args\n            entries.append((e.updated, e))\n        if entries:\n            most_recent_entry = max(\n                entries, key=lambda entry: entry[1].updated_parsed\n            )\n            most_recent_date = datetime.datetime(\n                *most_recent_entry[1].updated_parsed[:6]\n            )\n            with open(filename + '.updated', 'w') as fd:\n                fd.write(most_recent_date.isoformat())\n    return entries\n\n\n@irc3.plugin\nclass Feeds:\n    \"\"\"Feeds plugin\"\"\"\n\n    PoolExecutor = ThreadPoolExecutor\n\n    def __init__(self, bot):\n        bot.feeds = self\n        self.bot = bot\n\n        config = bot.config.get(__name__, {})\n\n        self.directory = os.path.expanduser(\n            config.get('directory', '~/.irc3/feeds'))\n        if not os.path.isdir(self.directory):\n            os.makedirs(self.directory)\n\n        hook = config.get('hook', default_hook)\n        hook = irc3.utils.maybedotted(hook)\n        if isinstance(hook, type):\n            hook = hook(bot)\n        self.hook = hook\n\n        dispatcher = config.get('dispatcher', default_dispatcher)\n        dispatcher = irc3.utils.maybedotted(dispatcher)\n        self.dispatcher = dispatcher(bot)\n\n        self.max_workers = int(config.get('max_workers', 5))\n        delay = int(config.get('delay', 5))\n        self.delay = delay * 60\n\n        feed_config = dict(\n            fmt=config.get('fmt', '[{feed.name}] {entry.title} {entry.link}'),\n            delay=delay,\n            channels=config.get('channels', ''),\n            time=0,\n        )\n\n        self.feeds = {}\n        for name, feed in config.items():\n            if str(feed).startswith('http'):\n                feeds = []\n                filenames = []\n                for i, feed in enumerate(irc3.utils.as_list(feed)):\n                    filename = os.path.join(self.directory,\n                                            name.replace('/', '_'))\n                    filenames.append('{0}.{1}.feed'.format(filename, i))\n                    feeds.append(feed)\n                feed = dict(\n                    feed_config,\n                    name=str(name),\n                    feeds=feeds,\n                    filenames=filenames,\n                    **irc3.utils.extract_config(config, str(name))\n                )\n                feed['delay'] = feed['delay'] * 60\n                channels = irc3.utils.as_list(feed['channels'])\n                feed['channels'] = [irc3.utils.as_channel(c) for c in channels]\n                self.bot.log.debug(feed)\n                self.feeds[name] = feed\n\n        self.imports()\n\n    def connection_made(self):\n        \"\"\"Initialize checkings\"\"\"\n        self.bot.loop.call_later(10, self.update)\n\n    def imports(self):\n        \"\"\"show some warnings if needed\"\"\"\n        try:\n            import feedparser\n            self.feedparser = feedparser\n        except ImportError:  # pragma: no cover\n            self.bot.log.critical('feedparser is not installed')\n            self.feedparser = None\n        try:\n            import requests\n        except ImportError:  # pragma: no cover\n            self.bot.log.critical('requests is not installed')\n            self.requests = None\n        else:\n            self.requests = requests\n\n    def parse(self, *args):\n        \"\"\"parse pre-fetched feeds and notify new entries\"\"\"\n        entries = []\n        for feed in self.feeds.values():\n            self.bot.log.debug('Parsing feed %s', feed['name'])\n            entries.extend(parse(self.feedparser, feed))\n\n        def messages():\n            for entry in self.hook([e for u, e in sorted(entries)]):\n                if entry:\n                    feed = entry.feed\n                    message = feed['fmt'].format(feed=feed, entry=entry)\n                    for c in feed['channels']:\n                        yield c, message\n\n        self.dispatcher(messages())\n\n    def update_time(self, future):\n        name = future.result()\n        self.bot.log.debug('Feed %s fetched', name)\n        feed = self.feeds[name]\n        feed['time'] = time.time()\n\n    def update(self):\n        \"\"\"update feeds\"\"\"\n        loop = self.bot.loop\n        loop.call_later(self.delay, self.update)\n\n        now = time.time()\n        feeds = [dict(f, requests=self.requests) for f in self.feeds.values()\n                 if f['time'] < now - f['delay']]\n        if feeds:\n            self.bot.log.info('Fetching feeds %s',\n                              ', '.join([f['name'] for f in feeds]))\n            tasks = []\n            for feed in feeds:\n                task = loop.run_in_executor(None, fetch, feed)\n                task.add_done_callback(self.update_time)\n                tasks.append(task)\n            task = self.bot.create_task(\n                asyncio.wait(tasks, timeout=len(feeds) * 2, loop=loop))\n            task.add_done_callback(self.parse)\n"
  },
  {
    "path": "irc3/plugins/fifo.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport irc3\nfrom stat import S_ISFIFO\n__doc__ = r'''\n==========================================\n:mod:`irc3.plugins.fifo` Fifo plugin\n==========================================\n\nAllow to cat something to a channel using Unix's fifo\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n    >>> import shutil\n    >>> import os\n    >>> try:\n    ...     shutil.rmtree('/tmp/run/irc3')\n    ... except:\n    ...     pass\n\nUsage::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.fifo\n    ... [irc3.plugins.fifo]\n    ... runpath = /tmp/run/irc3\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nWhen your bot will join a channel it will create a fifo::\n\n    >>> bot.test(':irc3!user@host JOIN #channel')\n    >>> print(sorted(os.listdir('/tmp/run/irc3')))\n    [':raw', 'channel']\n\nYou'll be able to print stuff to a channel from a shell::\n\n    $ cat /etc/passwd > /tmp/run/irc3/channel\n\nYou can also send raw irc commands using the ``:raw`` file::\n\n    $ echo JOIN \\#achannel > /tmp/run/irc3/:raw\n'''\n\n\n@irc3.plugin\nclass Fifo:\n\n    BLOCK_SIZE = 1024\n    MAX_BUFFER_SIZE = 800\n\n    def __init__(self, context):\n        self.context = context\n        self.config = self.context.config[__name__]\n        self.send_blank_line = self.config.get('send_blank_line', True)\n\n        self.runpath = self.config.get('runpath', '/run/irc3')\n        if not os.path.exists(self.runpath):\n            os.makedirs(self.runpath)\n\n        self.loop = self.context.loop\n        self.fifos = {}\n        self.buffers = {}\n        self.create_fifo(None)\n\n    @classmethod\n    def read_fd(cls, fd):  # pragma: no cover\n        # this required for python < 3.5\n        # for more info see https://www.python.org/dev/peps/pep-0475/\n        while True:\n            try:\n                return os.read(fd, cls.BLOCK_SIZE)\n            except InterruptedError:\n                continue\n            except BlockingIOError:\n                return b\"\"\n\n    def handle_line(self, line, channel):\n        if not line:\n            return\n\n        line = line.decode(\"utf8\")\n        if not self.send_blank_line and not line.strip():\n            return\n\n        if channel is None:\n            self.context.send_line(line)\n        else:\n            self.context.privmsg(channel, line)\n\n    def data_received(self, data, channel):\n        if not data:\n            return\n\n        prev = self.buffers.get(channel, b\"\")\n        lines = (prev + data).splitlines(True)\n        last = lines[-1]\n        for line in lines[:-1]:\n            line = line.rstrip(b'\\r\\n')\n            self.handle_line(line, channel)\n\n        if last.endswith(b'\\n'):\n            line = last.rstrip(b'\\r\\n')\n            self.handle_line(line, channel)\n            self.buffers[channel] = b\"\"\n            return\n\n        if len(last) > self.MAX_BUFFER_SIZE:\n            self.handle_line(last, channel)\n            self.buffers[channel] = b\"\"\n        else:\n            self.buffers[channel] = last\n\n    def watch_fd(self, fd, channel):\n        reading = True\n\n        while reading:\n            data = self.read_fd(fd)\n            reading = len(data) == self.BLOCK_SIZE\n            self.data_received(data, channel)\n\n    def create_fifo(self, channel):\n        if channel is None:\n            path = os.path.join(self.runpath, ':raw')\n        else:\n            path = os.path.join(self.runpath, channel.strip('#&+'))\n        try:\n            mode = os.stat(path).st_mode\n        except OSError:\n            pass\n        else:\n            if not S_ISFIFO(mode):\n                self.context.log.warn(\n                    'file %s created without mkfifo. remove it',\n                    path)\n                os.remove(path)\n        if not os.path.exists(path):\n            os.mkfifo(path)\n        fd = os.open(path, os.O_RDWR | os.O_NONBLOCK)\n        self.loop.add_reader(fd, self.watch_fd, fd, channel)\n        self.context.log.debug(\"%s's fifo is %s %r\",\n                               channel or ':raw', path, fd)\n        return fd\n\n    @irc3.event(irc3.rfc.JOIN)\n    def join(self, mask=None, channel=None, **kwargs):\n        if mask.nick == self.context.nick:\n            if channel not in self.fifos:\n                self.fifos[channel] = self.create_fifo(channel)\n"
  },
  {
    "path": "irc3/plugins/human.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport irc3\nimport stat\nimport json\nimport codecs\nimport random\nfrom urllib.request import urlopen\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.human` Human plugin\n==========================================\n\nStore public message addressed to the bot in a file and reply a random message\nextracted from this file.\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> with open('/tmp/human.db', 'wb') as fd:\n    ...     s = fd.write(b'Yo!\\\\nYo!\\\\nYo!\\\\nYo!\\\\n')\n\nRegister the plugin::\n\n    >>> bot = IrcBot(human='/tmp/human.db', nick='nono')\n    >>> bot.include('irc3.plugins.human')\n\nAnd it should work::\n\n    >>> bot.test(':foo!m@h PRIVMSG nono :nono: Yo!')\n    PRIVMSG foo :Yo!\n\n    >>> bot.test(':foo!m@h PRIVMSG #chan :nono: Yo!')\n    PRIVMSG #chan :foo: Yo!\n\n..\n    >>> bot.test(':foo!m@h PRIVMSG #chan :!ping')\n\n'''\n\n\n@irc3.plugin\nclass Human:\n\n    requires = [\n        __name__.replace('human', 'core'),\n    ]\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.db = os.path.expanduser(\n            bot.config.get('human', '~/.irc3/human.db'))\n        self.delay = (2, 5)\n        try:\n            os.makedirs(os.path.dirname(self.db))\n        except OSError:\n            pass\n        if not os.path.isfile(self.db):  # pragma: no cover\n            self.initialize(15)\n\n    def initialize(self, amount):  # pragma: no cover\n        try:\n            page = urlopen('http://api.icndb.com/jokes/random/15')\n            data = page.read()\n            if isinstance(data, bytes):\n                data = data.decode('utf8')\n            quotes = json.loads(data)\n            quotes = [v['joke'] for v in quotes['value']]\n        except Exception:\n            self.bot.log.error('Failed to get quotes from api.icndb.com')\n            quotes = ['Hi!', 'lol']\n        self.bot.log.info('Initialise %s with %s quotes',\n                          self.db, len(quotes))\n        with codecs.open(self.db, 'w', 'utf8') as fd:\n            fd.write('\\n'.join(quotes))\n\n    @irc3.event(irc3.rfc.MY_PRIVMSG)\n    def on_message(self, mask=None, event=None, target=None, data=None, **kw):\n        with codecs.open(self.db, 'ab+', encoding=self.bot.encoding) as fd:\n            fd.write(data + '\\n')\n\n        pos = random.randint(0, os.stat(self.db)[stat.ST_SIZE])\n        with codecs.open(self.db, encoding=self.bot.encoding) as fd:\n            fd.seek(pos)\n            fd.readline()\n            try:\n                message = fd.readline().strip()\n            except Exception:  # pragma: no cover\n                pass\n\n        message = message or 'Yo!'\n        if target.is_channel:\n            message = '{0}: {1}'.format(mask.nick, message)\n        else:\n            target = mask.nick\n        self.call_with_human_delay(self.bot.privmsg, target, message)\n\n    @irc3.extend\n    def call_with_human_delay(self, func, *args, **kwargs):\n        delay = random.randint(*self.delay)\n        self.bot.loop.call_later(delay, func, *args, **kwargs)\n"
  },
  {
    "path": "irc3/plugins/log.py",
    "content": "# -*- coding: utf-8 -*-\nimport logging\nimport irc3d\nimport irc3\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.log` Log plugin\n==========================================\n\nLogging / debuging plugin\n\n..\n    >>> from irc3.testing import IrcBot\n\nUsage::\n\n    >>> bot = IrcBot()\n    >>> bot.include('irc3.plugins.log')\n'''\n\n\nclass RawLog:\n\n    def __init__(self, context):\n        self.context = context\n        name = 'raw.%s' % (context.nick or 'irc3d')\n        self.log_in = logging.getLogger(name + ' <<')\n        self.log_in.setLevel(logging.DEBUG)\n        self.log_out = logging.getLogger(name + ' >>')\n        self.log_out.setLevel(logging.DEBUG)\n\n    @irc3d.event(r'^(?P<raw>.*)', venusian_category='irc3d.debug')\n    @irc3.event(r'^(?P<raw>.*)', venusian_category='irc3.debug')\n    @irc3.dcc_event(r'^(?P<raw>.*)', venusian_category='irc3.debug')\n    def debug_input(self, raw=None, client=None, iotype='in', **kwargs):\n        self.log(raw, client, iotype)\n\n    @irc3d.event(r'^(?P<raw>.*)', iotype='out',\n                 venusian_category='irc3d.debug')\n    @irc3.event(r'^(?P<raw>.*)', iotype='out', venusian_category='irc3.debug')\n    @irc3.dcc_event(r'^(?P<raw>.*)', iotype='out',\n                    venusian_category='irc3.debug')\n    def debug_output(self, raw=None, client=None, iotype='out', **kwargs):\n        self.log(raw, client, iotype)\n\n    def log(self, raw, client=None, iotype=None):\n        if raw.strip():\n            log = getattr(self, 'log_' + iotype)\n            if client is not None:\n                log.debug('[%-7r] %s', client, raw)\n            else:\n                log.debug(raw)\n"
  },
  {
    "path": "irc3/plugins/logger.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport irc3\nimport logging\nimport codecs\nfrom datetime import datetime\n__doc__ = '''\n================================================\n:mod:`irc3.plugins.logger` Channel logger plugin\n================================================\n\nLog channels\n\n..\n    >>> from irc3.testing import IrcBot\n\nUsage::\n\n    >>> bot = IrcBot(**{\n    ...     'irc3.plugins.logger': {\n    ...         'handler': 'irc3.plugins.logger.file_handler',\n    ...     },\n    ... })\n    >>> bot.include('irc3.plugins.logger')\n\n\nAvailable handlers:\n\n.. autoclass:: file_handler\n'''\n\n\nclass file_handler:\n    \"\"\"Write logs to file in ~/.irc3/logs\n    \"\"\"\n\n    formatters = {\n        'privmsg': '{date:%H:%M} <{mask.nick}> {data}',\n        'join': '{date:%H:%M} {mask.nick} joined {channel}',\n        'part': '{date:%H:%M} {mask.nick} has left {channel} ({data})',\n        'quit': '{date:%H:%M} {mask.nick} has quit ({data})',\n        'topic': '{date:%H:%M} {mask.nick} has set topic to: {data}',\n    }\n\n    def __init__(self, bot):\n        config = {\n            'filename': '~/.irc3/logs/{host}/{channel}-{date:%Y-%m-%d}.log',\n            'channels': [],\n        }\n        config.update(bot.config.get(__name__, {}))\n        self.filename = os.path.expanduser(config['filename'])\n        self.encoding = bot.encoding\n        self.formatters = bot.config.get(\n            __name__ + '.formatters',\n            self.formatters)\n\n    def __call__(self, event):\n        filename = self.filename.format(**event)\n        if not os.path.isfile(filename):\n            dirname = os.path.dirname(filename)\n            if not os.path.isdir(dirname):  # pragma: no cover\n                os.makedirs(dirname)\n        fmt = self.formatters.get(event['event'].lower())\n        if fmt:\n            with codecs.open(filename, 'a+', self.encoding) as fd:\n                fd.write(fmt.format(**event) + '\\r\\n')\n\n\n@irc3.plugin\nclass Logger:\n    \"\"\"Logger plugin. Use the :class:~file_handler handler by default\n    \"\"\"\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.config = bot.config.get(__name__, {})\n        self.log = logging.getLogger(__name__)\n        hdl = irc3.utils.maybedotted(self.config.get('handler', file_handler))\n        self.log.debug('Handler: %s', hdl.__name__)\n        self.handler = hdl(bot)\n\n    def process(self, **kwargs):\n        kw = dict(host=self.bot.config.host, date=datetime.now(),\n                  **kwargs)\n        self.handler(kw)\n\n    @irc3.event((r'''(@(?P<tags>\\S+) )?:(?P<mask>\\S+) (?P<event>[A-Z]+)'''\n                 r''' (?P<target>#\\S+)(\\s:(?P<data>.*)|$)'''))\n    def on_input(self, mask, event, target=None, data=None, **kwargs):\n        if target and target.is_channel:\n            self.process(event=event, mask=mask,\n                         channel=target, data=data, **kwargs)\n\n    @irc3.event((r'''(@(?P<tags>\\S+) )?(?P<event>[A-Z]+) (?P<target>#\\S+)'''\n                 r'''(\\s:(?P<data>.*)|$)'''), iotype='out')\n    def on_output(self, event, target=None, data=None, **kwargs):\n        if target and target.is_channel:\n            self.process(event=event, mask=irc3.utils.IrcString(self.bot.nick),\n                         channel=target, data=data, **kwargs)\n\n    @irc3.event(irc3.rfc.JOIN_PART_QUIT)\n    def on_quit(self, mask, event, channel=None, data=None, **kwargs):\n        if event.lower() == 'quit':\n            channels = getattr(self.bot, 'channels', None)\n            if channels:\n                nick = mask.nick\n                for name, channel in channels.items():\n                    if nick in channel:\n                        self.process(event=event, mask=mask,\n                                     channel=name, data=data, **kwargs)\n\n    @irc3.event(irc3.rfc.RPL_TOPIC)\n    def on_topic(self, srv=None, **kwargs):\n        self.process(event='TOPIC', mask=srv, **kwargs)\n"
  },
  {
    "path": "irc3/plugins/pager.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nfrom irc3 import asyncio\nimport irc3\nimport time\n__doc__ = '''\n===============================================\n:mod:`irc3.plugins.pager` Paginate large output\n===============================================\n\nUsage\n=====\n\n.. literalinclude:: ../../examples/paginate.py\n\nAPI\n===\n\n.. autoclass:: Paginate\n\n'''\n\n\nclass Page:\n\n    def __init__(self, mask, iterator, first_page=4, lines_per_page=10):\n        self.mask = mask\n        self.iterator = iterator\n        self.first_page = first_page\n        self.lines_per_page = lines_per_page\n        self.page = 0\n        self.ended = False\n        self.time = time.time()\n\n    def get(self):\n        self.time = time.time()\n        self.ended = True\n        i = 0\n        if not self.page:\n            size = self.first_page\n        else:\n            size = self.lines_per_page\n        self.page += 1\n        for msg in self.iterator:\n            yield msg\n            i += 1\n            if size and i >= size:\n                self.ended = False\n                break\n        if self.ended:\n            self.close()\n            yield '.'\n\n    def close(self):\n        try:\n            self.iterator.close()\n        except Exception:\n            pass\n\n\n@irc3.plugin\nclass Paginate:\n    \"\"\"Pagination plugin\"\"\"\n\n    requires = [command.__module__]\n\n    def __init__(self, context):\n        self.context = context\n        self.pages = {}\n        self.expiration_delay = 60\n        self.context.create_task(self.clean_old_pages())\n\n    async def clean_old_pages(self):  # pragma: no cover\n        self.context.log.debug('Cleaning old pages...')\n        t = time.time()\n        d = []\n        for k, v in self.pages.items():\n            if v.time + self.expiration_delay > t:\n                d.append(k)\n        for k in d:\n            page = self.pages[k]\n            page.close()\n        await asyncio.sleep(60, loop=self.context.loop)\n        await self.clean_old_pages()\n\n    @irc3.extend\n    def paginate(self, mask, iterator, first_page=None, lines_per_page=10):\n        \"\"\"Paginate large output. Available as ``IrcBot.paginate()``\"\"\"\n        first_page = first_page or self.context.config.flood_burst\n        lines_per_page = lines_per_page or 0\n        page = Page(mask, iterator,\n                    first_page=first_page, lines_per_page=lines_per_page)\n        for msg in page.get():\n            yield msg\n        if not page.ended:\n            self.pages[mask] = page\n\n    @command\n    def more(self, mask, target, args):\n        '''Get more data from the latest command\n\n        %%more\n        '''\n        page = self.pages.get(mask)\n        if page is None:\n            yield 'Sorry. I have nothing left for you'\n        else:\n            for msg in page.get():\n                yield msg\n            if page.ended:\n                del self.pages[mask]\n"
  },
  {
    "path": "irc3/plugins/quakenet.py",
    "content": "import hashlib\nimport hmac\nimport irc3\n\n__doc__ = '''\n====================================================\n:mod:`irc3.plugins.quakenet` QuakeNet authorization\n====================================================\n\nPlugin supports both simple and\n`challenge based <https://www.quakenet.org/development/challengeauth>`_\nauthorization.  Challenge based auth is used by default, since it is more\nsecure than simple.  Also, plugin can hide your IP after authorization\nby applying ``+x`` mode.\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n\nUsage::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.quakenet\n    ... [quakenet]\n    ... user = login\n    ... password = passw\n    ... # optional, false by default\n    ... hidehost = true\n    ... # optional, true by default\n    ... challenge_auth = true\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\n'''\n\nQ_NICK = \"Q@CServe.quakenet.org\"\nCHALLENGE_PATTERN = (r\"^:Q![a-zA-Z]+@CServe.quakenet.org NOTICE \"\n                     r\"(?P<nick>\\S+) :CHALLENGE (?P<challenge>[a-z0-9]+) \")\n\n\ndef get_digest(digest):\n    if not isinstance(digest, str):  # pragma: no cover\n        raise ValueError(\"Wrong type of digest\")\n\n    digest = digest.lower()\n    if digest in (\"sha256\", \"sha1\", \"md5\"):\n        return getattr(hashlib, digest)\n    else:  # pragma: no cover\n        raise ValueError(\"Wrong value for digest\")\n\n\ndef challenge_auth(username, password, challenge, lower, digest='sha256'):\n    \"\"\"Calculates quakenet's challenge auth hash\n\n    .. code-block:: python\n\n        >>> challenge_auth(\"mooking\", \"0000000000\",\n        ...     \"12345678901234567890123456789012\", str.lower, \"md5\")\n        '2ed1a1f1d2cd5487d2e18f27213286b9'\n    \"\"\"\n    def hdig(x):\n        return fdigest(x).hexdigest()\n\n    fdigest = get_digest(digest)\n    luser = lower(username)\n    tpass = password[:10].encode(\"ascii\")\n    hvalue = hdig(\"{0}:{1}\".format(luser, hdig(tpass)).encode(\"ascii\"))\n    bhvalue = hvalue.encode(\"ascii\")\n    bchallenge = challenge.encode(\"ascii\")\n    return hmac.HMAC(bhvalue, bchallenge, digestmod=fdigest).hexdigest()\n\n\n@irc3.plugin\nclass QuakeNet(object):\n\n    requires = [\n        'irc3.plugins.core',\n        'irc3.plugins.casefold'\n    ]\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.config = bot.config.get(\"quakenet\", {})\n        self.user = self.config.get('user', None)\n        self.password = self.config.get('password', None)\n        self.hidehost = bool(self.config.get('hidehost', False))\n        # secure by default\n        self.challenge_auth = bool(self.config.get('challenge_auth', True))\n        self.pending_auth = False\n\n    def server_ready(self):\n        self.auth()\n\n    def auth(self):\n        if self.user and self.password:\n            if self.challenge_auth:\n                self.bot.log.info(\"Requesting challenge\")\n                self.bot.privmsg(Q_NICK, 'CHALLENGE')\n                self.pending_auth = True\n            else:\n                self.bot.log.info(\"Sending login information to QuakeNet\")\n                self.bot.send_line(\"AUTH {user} {password}\".format(\n                                   user=self.user, password=self.password))\n                self.after_auth()\n\n    def after_auth(self):\n        if self.hidehost:\n            self.bot.mode(self.bot.nick, \"+x\")\n\n    @irc3.event(CHALLENGE_PATTERN)\n    def get_challenge(self, nick, challenge, **kwargs):\n        if nick == self.bot.nick and self.pending_auth:\n            hauth = challenge_auth(self.user, self.password, challenge,\n                                   self.bot.casefold, \"sha256\")\n            cmd = 'CHALLENGEAUTH {user} {response} {algo}'. \\\n                format(user=self.user, response=hauth, algo=\"HMAC-SHA-256\")\n\n            self.bot.log.info(\"Performing challenge authorization on QuakeNet\")\n            self.bot.privmsg(Q_NICK, cmd)\n            self.after_auth()\n"
  },
  {
    "path": "irc3/plugins/sasl.py",
    "content": "# -*- coding: utf-8 -*-\nimport irc3\nfrom irc3 import utils\nimport base64\n__doc__ = '''\n===================================================\n:mod:`irc3.plugins.sasl` SASL authentification\n===================================================\n\nAllow to use sasl authentification\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n\nUsage::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... sasl_username = irc3\n    ... sasl_password = passwd\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\n'''\n\n\n@irc3.plugin\nclass Sasl:\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.events = [\n            irc3.event(r'^:\\S+ CAP \\S+ LS :(?P<data>.*)', self.cap_ls),\n            irc3.event(r'^:\\S+ CAP \\S+ ACK :.*sasl.*', self.cap_ack),\n            irc3.event(r'AUTHENTICATE +', self.authenticate),\n            irc3.event(r'^:\\S+ 903 \\S+ :SASL authentication successful',\n                       self.cap_end),\n        ]\n\n    def connection_ready(self, *args, **kwargs):\n        self.bot.send('CAP LS\\r\\n')\n        self.bot.attach_events(*self.events)\n\n    def cap_ls(self, data=None, **kwargs):\n        if 'sasl' in data.lower():\n            self.bot.send_line('CAP REQ :sasl')\n        else:\n            self.cap_end()\n\n    def cap_ack(self, **kwargs):\n        self.bot.send_line('AUTHENTICATE PLAIN')\n\n    def authenticate(self, **kwargs):\n        auth = ('{sasl_username}\\0'\n                '{sasl_username}\\0'\n                '{sasl_password}').format(**self.bot.config)\n        auth = base64.encodebytes(auth.encode('utf8'))\n        auth = auth.decode('utf8').rstrip('\\n')\n        self.bot.send_line('AUTHENTICATE ' + auth)\n\n    def cap_end(self, **kwargs):\n        self.bot.send_line('CAP END')\n        core = self.bot.get_plugin(utils.maybedotted('irc3.plugins.core.Core'))\n        core.pong(event='PING')\n        self.bot.detach_events(*self.events)\n"
  },
  {
    "path": "irc3/plugins/search.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nimport irc3\n__doc__ = '''\n==============================================\n:mod:`irc3.plugins.search` Search plugin\n==============================================\n\n.. autoclass:: Search\n'''\n\n\n@irc3.plugin\nclass Search:\n\n    requires = [\n        __name__.replace('search', 'command'),\n    ]\n\n    headers = {\n        'User-Agent': 'python-requests/irc3/search',\n        'Cache-Control': 'max-age=0',\n        'Pragma': 'no-cache',\n    }\n\n    def __init__(self, bot):\n        self.bot = bot\n        try:\n            import requests\n            self.session = requests.Session()\n            self.session.headers.update(self.headers)\n        except ImportError:  # pragma: no cover\n            self.session = None\n\n    @command(permission='view')\n    def ddg(self, mask, target, args):\n        \"\"\"Search using https://duckduckgo.com/api\n\n            %%ddg <query>...\n        \"\"\"\n        q = ' '.join(args['<query>'])\n        resp = self.session.get('http://api.duckduckgo.com/',\n                                params=dict(q=q, format='json', t='irc3'),\n                                allow_redirects=False)\n        ctype = resp.headers['content-type']\n        if 'json' in ctype or 'javascript' in ctype:\n            if resp.status_code == 200:\n                data = resp.json()\n                return '{AbstractText} - {AbstractURL}'.format(**data)\n            elif resp.status_code == 303:\n                return 'Redirect to: {0}'.format(resp.headers['location'])\n"
  },
  {
    "path": "irc3/plugins/shell_command.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport irc3\nfrom irc3 import asyncio\nfrom irc3.plugins.command import Commands\n__doc__ = '''\n=================================================\n:mod:`irc3.plugins.shell_command` Shell commands\n=================================================\n\nAllow to quickly add commands map to a shell command.\nThe bot will print stdout/stderr\n\n..\n    >>> import os\n    >>> import shutil\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n    >>> try:\n    ...     shutil.rmtree('/tmp/myscripts')\n    ... except:\n    ...     pass\n    >>> script = '/tmp/myscripts/demo'\n    >>> os.makedirs('/tmp/myscripts')\n    >>> with open(script, 'w') as fd:\n    ...     _ = fd.write('echo $IRC3_COMMAND_ARGS')\n    >>> os.chmod(script, 0o0744)\n\nUsage::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.shell_command\n    ... [irc3.plugins.shell_command]\n    ... myscript = /tmp/myscript\n    ... # optional command configuration\n    ... myscript.permission = runmyscrypt\n    ... myscript.public = false\n    ... # register a directory\n    ... myscripts = /tmp/myscripts\n    ... # optional commands configuration for the directory\n    ... myscripts.permission = runmyscrypts\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nThen the uname command will be available::\n\n    >>> bot.test(':gawel!user@host PRIVMSG irc3 :!help myscript')\n    PRIVMSG gawel :Run $ /tmp/myscript\n    PRIVMSG gawel :!myscript [<args>...]\n\n    >>> bot.test(':gawel!user@host PRIVMSG #chan :!myscript')\n    PRIVMSG gawel :You can only use the 'myscript' command in private.\n\n    >>> bot.test(':gawel!user@host PRIVMSG irc3 :!myscript')\n\nIf the user provides some arguments then those will be available as an\nenvironment var (to avoid shell injection) names ``IRC3_COMMAND_ARGS``\n\n...\n\n    >>> bot.get_plugin(Commands)['demo'][0]\n    {'permission': 'runmyscrypts'}\n'''\n\n\n@irc3.plugin\nclass Shell:\n\n    requires = [Commands.__module__]\n\n    def __init__(self, context):\n        self.log = context.log\n        self.context = context\n        self.config = self.context.config[__name__]\n        for k, v in self.config.items():\n            if (isinstance(v, str) and v.startswith('#')) or '.' in k:\n                continue\n            dirname = os.path.abspath(v)\n            if os.path.isdir(dirname):\n                self.log.debug('Scanning for scripts in %s', dirname)\n                for root, dirs, filenames in os.walk(dirname):\n                    for filename in filenames:\n                        binary = os.path.join(root, filename)\n                        if os.access(binary, os.X_OK):\n                            name = os.path.splitext(filename)[0]\n                            self.register_command(name, binary, skey=k)\n            else:\n                self.register_command(k, v)\n\n    def register_command(self, k, v, skey=None):\n        async def meth(*args, **kwargs):\n            return await self.shell_command(v, *args, **kwargs)\n        meth.__name__ = k\n        meth.__doc__ = '''Run $ %s\n        %%%%%s [<args>...]\n        ''' % (v, k)\n        p = {'permission': 'admin'}\n        for opt in ('permission', 'public'):\n            opt_key = '%s.%s' % (skey or k, opt)\n            if opt_key in self.config:\n                p[opt] = self.config[opt_key]\n        self.log.debug('Register command %s: $ %s', k, v)\n        commands = self.context.get_plugin(Commands)\n        commands[k] = (p, meth)\n\n    async def shell_command(self, command, mask, target, args, **kwargs):\n        env = os.environ.copy()\n        env['IRC3_COMMAND_ARGS'] = ' '.join(args['<args>'])\n        env['IRC3_MASK'] = mask\n        self.log.debug('Running command: $ %s' % command)\n        proc = await asyncio.create_subprocess_shell(\n            command, shell=True, env=env,\n            stdout=asyncio.subprocess.PIPE,\n            stderr=asyncio.subprocess.STDOUT)\n        await proc.wait()\n        lines = await proc.stdout.read()\n        if not isinstance(lines, str):\n            lines = lines.decode('utf8')\n        return lines.split('\\n')\n"
  },
  {
    "path": "irc3/plugins/slack.py",
    "content": "import irc3\nfrom irc3 import asyncio\nimport json\nimport re\nimport random\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.slack` Slack plugin\n==========================================\n\nIntroduce a slack/irc interface to bridge messages between slack and irc.\n\nInstall aiohttp::\n\n    $ pip install aiohttp\n\nUsage\n=====\n\nCreate a bridge between slack and irc\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.slack\n    ... [irc3.plugins.slack]\n    ... token = xoxb-slackbottoken\n    ... notify =\n    ...     U6DT2Q8HM\n    ...     U3090DHMA\n    ... [irc3.plugins.slack.channels]\n    ... slack =\n    ...     ${#}irc\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\n.. note::\n\n    Be sure to invite the bot in slack to the channels it should be bridging\n\n\nConfig Options\n==============\n\nirc3.plugins.slack\n------------------\n\ntoken\n\n    slack api token (user or bot integration)\n\nnotify\n\n    The slack user ids to notify, this needs to be the unique user ids.\n\nirc3.plugins.slack.channels\n---------------------------\n\nThis section is a list of channels that should be bridge.  The first is the\nslack channel that the bot needs to be joined to to bridge slack to irc.\n\nThen assigned to that is the list of irc channels that slack channel should\nforward to.\n'''\n\nEMOJIS = {\n    \"smile\": \":)\",\n    \"simple_smile\": \":)\",\n    \"smiley\": \":-)\",\n    \"grin\": \":D\",\n    \"wink\": \";)\",\n    \"smirk\": \";)\",\n    \"blush\": \":$\",\n    \"stuck_out_tongue\": \":P\",\n    \"stuck_out_tongue_winking_eye\": \";P\",\n    \"stuck_out_tongue_closed_eyes\": \"xP\",\n    \"disappointed\": \":(\",\n    \"astonished\": \":O\",\n    \"open_mouth\": \":O\",\n    \"heart\": \"<3\",\n    \"broken_heart\": \"</3\",\n    \"confused\": \":S\",\n    \"angry\": \">:(\",\n    \"cry\": \":,(\",\n    \"frowning\": \":(\",\n    \"imp\": \"]:(\",\n    \"innocent\": \"o:)\",\n    \"joy\": \":,)\",\n    \"kissing\": \":*\",\n    \"laughing\": \"x)\",\n    \"neutral_face\": \":|\",\n    \"no_mouth\": \":-\",\n    \"rage\": \":@\",\n    \"smiling_imp\": \"]:)\",\n    \"sob\": \":,'(\",\n    \"sunglasses\": \"8)\",\n    \"sweat\": \",:(\",\n    \"sweat_smile\": \",:)\",\n    \"unamused\": \":$\"\n}\n\n\n@irc3.plugin\nclass Slack:\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.client = irc3.utils.maybedotted('aiohttp.ClientSession')\n        self.formdata = irc3.utils.maybedotted('aiohttp.FormData')\n        self.config = self.bot.config.get(__name__, {})\n        self.msgtype = irc3.utils.maybedotted('aiohttp.WSMsgType')\n        self.client_response_error = irc3.utils.maybedotted(\n            'aiohttp.client_exceptions.ClientResponseError'\n        )\n        self.channels = self.bot.config.get(\n            '{0}.channels'.format(__name__), {}\n        )\n        self.clean_channels()  # remove has values from channels\n        autojoins = set().union(*self.channels.values())\n        self.bot.log.debug('Adding to autojoins list: {autojoins}')\n        self.bot.config.setdefault('autojoins', []).extend(autojoins)\n        self.matches = [\n            (r'\\n|\\r\\n|\\r', ''),\n            (r'<!channel>', '@channel'),\n            (r'<!group>', '@group'),\n            (r'<!everyone>', '@everyone'),\n            (\n                r'<#(?P<channelId>C\\w+)\\|?(?P<readable>\\w+)?>',\n                self.get_channel_by_id\n            ),\n            (\n                r'<@(?P<userId>U\\w+)\\|?(?P<readable>\\w+)?>',\n                self.get_user_by_id\n            ),\n            (\n                r':(?P<emoji>\\w+):',\n                self.get_emoji\n            ),\n            (r'<.+?\\|(.+?)>', r'\\g<1>'),\n            (r'&lt', '<'),\n            (r'&gt', '>'),\n            (r'&amp', '&'),\n        ]\n        if 'token' not in self.config:\n            self.bot.log.warning('No slack token is set.')\n\n    def get_channel_by_id(self, matchobj):\n        if matchobj.group('readable'):\n            return matchobj.group('readable')\n        future = asyncio.run_coroutine_threadsafe(\n            self.api_call(\n                'conversation.info',\n                {'channel': matchobj.group('channelId')}\n            ),\n            loop=self.bot.loop\n        )\n        return '#{0}'.format(future.result()['channel']['name'])\n\n    def get_user_by_id(self, matchobj):\n        if matchobj.group('readable'):\n            return matchobj.group('readable')\n        future = asyncio.run_coroutine_threadsafe(\n            self.api_call(\n                'users.info',\n                {'user': matchobj.group('userId')}\n            ),\n            loop=self.bot.loop\n        )\n        return '@{0}'.format(future.result()['user']['name'])\n\n    def get_emoji(self, matchobj):\n        emoji = matchobj.group('emoji')\n        return EMOJIS.get(emoji, emoji)\n\n    def clean_channels(self):\n        self.channels.pop('#', None)\n        self.channels.pop('hash', None)\n\n    async def api_call(self, method, data=None):\n        \"\"\"Slack API call.\"\"\"\n        async with self.client(loop=self.bot.loop) as session:\n            form = self.formdata(data or {})\n            form.add_field('token', self.config['token'])\n            async with session.post(\n                'https://slack.com/api/{0}'.format(method), data=form\n            ) as response:\n                if response.status == 429:\n                    await irc3.asyncio.sleep(\n                        int(response.headers['Retry-After'])\n                    )\n                    return await self.api_call(method, data)\n                if response.status != 200:\n                    self.bot.log.debug('Error: %s', response)\n                    raise Exception(\n                        '{0} with {1} failed.'.format(method, data)\n                    )\n                return await response.json()\n\n    def server_ready(self):\n        self.bot.create_task(self.start())\n\n    async def start(self):\n        outbox = asyncio.Queue()\n        asyncio.ensure_future(self.consumer(outbox.get), loop=self.bot.loop)\n        while True:\n            done, pending = await asyncio.wait(\n                (self.producer(outbox.put), self.ping()),\n                return_when=asyncio.FIRST_COMPLETED,\n            )\n            for task in pending:\n                task.cancel()\n            if hasattr(self, 'ws'):\n                del self.ws\n            await self.notify_restart()\n            await asyncio.sleep(5)\n\n    async def notify_restart(self):\n        if 'notify' not in self.config:\n            return\n        users = self.config['notify']\n        if isinstance(users, str):\n            users = [users]\n        conversation = await self.api_call(\n            'conversations.open',\n            {'users': ','.join(users)}\n        )\n        await self.api_call('chat.postMessage', {\n            'channel': conversation['channel']['id'],\n            'text': 'irc3 has been restarted to reconnect to websocket',\n        })\n\n    async def parse_text(self, message):\n        for match in self.matches:\n            message = await self.bot.loop.run_in_executor(\n                None, re.sub, match[0], match[1], message\n            )\n        return message\n\n    async def ping(self):\n        '''ping websocket'''\n        while not hasattr(self, 'ws'):\n            await asyncio.sleep(1)\n        while True:\n            msgid = random.randrange(10000)\n            self.bot.log.debug('Sending ping message: {0}'.format(msgid))\n            try:\n                await self.ws.send_str(\n                    json.dumps({'type': 'ping', 'id': msgid})\n                )\n            except self.client_response_error:\n                break\n            await asyncio.sleep(20)\n            if msgid != self.msgid:\n                break\n\n    async def producer(self, put):\n        rtm = await self.api_call('rtm.start')\n        if not rtm['ok']:\n            raise ConnectionError('Error connecting to RTM')\n            self.bot.log.debug('Listening to Slack')\n        async with self.client(loop=self.bot.loop) as session:\n            async with session.ws_connect(rtm['url']) as self.ws:\n                self.bot.log.debug('Listening to Slack')\n                async for msg in self.ws:\n                    if msg.type == self.msgtype.TEXT:\n                        await put(json.loads(msg.data))\n                    else:\n                        break\n\n    async def consumer(self, get):\n        while True:\n            message = await get()\n            if message.get('type') == 'message':\n                self.bot.log.debug(\n                    'Message to irc: {0}'.format(message)\n                )\n                user = None\n                if 'user' in message:\n                    user = await self.api_call(\n                        'users.info',\n                        {'user': message['user']}\n                    )\n                    message['user'] = user['user']['name']\n                func = getattr(\n                    self,\n                    '_handle_{0}'.format(message.get('subtype', 'default')),\n                    None\n                )\n                if func is not None:\n                    if 'channel' in message:\n                        channel = await self.api_call(\n                            'conversations.info',\n                            {'channel': message['channel']}\n                        )\n                        message['channel'] = channel['channel']['name']\n                    await func(message)\n            elif message.get('type') == 'pong':\n                self.bot.log.debug(\n                    'Pong received: {0}'.format(message['reply_to'])\n                )\n                self.msgid = message['reply_to']\n            else:\n                self.bot.log.debug('Debug Message: %s', message)\n\n    async def _handle_default(self, msg):\n        for channel in self.channels.get(msg['channel'], []):\n            await self.bot.privmsg(\n                channel,\n                '<{0}> {1}'.format(\n                    msg['user'],\n                    await self.parse_text(msg['text'])\n                )\n            )\n\n    async def _handle_me_message(self, msg):\n        for channel in self.channels.get(msg['channel'], []):\n            await self.bot.action(\n                channel,\n                '<{0}> {1}'.format(\n                    msg['user'],\n                    await self.parse_text(msg['text'])\n                )\n            )\n\n    @irc3.event(r'^(@(?P<tags>\\S+) )?:'\n                r'(?P<nick>\\S+)!(?P<username>\\S+)@(?P<hostmask>\\S+) '\n                r'(?P<event>(PRIVMSG|NOTICE)) '\n                r'(?P<target>\\S+) :(?P<data>.*)$')\n    async def on_message(self, target=None, nick=None, data=None, **kwargs):\n        self.bot.log.debug(\n            'Match Data: {target} {nick} {data} {kwargs}'.format(**locals())\n        )\n        for channel, irc in self.channels.items():\n            if target in irc:\n                payload = {\n                    'channel': channel,\n                    'text': data,\n                    'as_user': False,\n                    'username': nick,\n                    'icon_url': (\n                        'http://api.adorable.io/avatars/48/'\n                        '{0}.jpg'\n                    ).format(nick),\n                }\n                await self.api_call('chat.postMessage', data=payload)\n"
  },
  {
    "path": "irc3/plugins/social.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nimport irc3\nimport json\n__doc__ = '''\n==============================================\n:mod:`irc3.plugins.social` Social networking\n==============================================\n\nAdd ``tweet`` and ``retweet`` commands.\n\nExtend the bot with ``.get_social_connection()`` and ``.search_tweets()``.\n\n..\n    >>> from irc3.testing import IrcBot\n\nUsage::\n\n    >>> bot = IrcBot(\n    ...     includes=['irc3.plugins.social'],\n    ...     twitter=dict(key='yourkey', secret='yoursecret',\n    ...                  token='yourtoken', token_secret='yoursecret')\n    ... )\n    >>> bot.get_social_connection()\n    <TwitterAdapter for <twitter.api.Twitter object at ...>>\n\nApi:\n\n.. autoclass:: Social\n   :members:\n\n'''\n\n\nclass TwitterAdapter:\n\n    def __init__(self, bot, conn):\n        self.bot = bot\n        self.conn = conn\n        self.exc = irc3.utils.maybedotted('twitter.api.TwitterHTTPError')\n\n    def __getattr__(self, attr):\n        return getattr(self.conn, attr)\n\n    def format(self, item):\n        text = item['text'].replace('\\n', ' ')\n        return '@{screen_name}: {text}'.format(text=text, **item['user'])\n\n    def __call__(self, meth, *args, **kwargs):\n        try:\n            res = meth(*args, **kwargs)\n            if isinstance(res, dict):\n                return res\n            return dict(error=res)\n        except self.exc as e:  # pragma: no cover\n            self.bot.log.exception(e)\n            message = ''\n            try:\n                res = json.loads(e.response_data.decode('utf8'))\n            except Exception:\n                pass\n            else:\n                message = ''\n                errors = res.get('errors', [])\n                if isinstance(errors, list):\n                    for error in errors:\n                        message += '{code}: {message}'.format(**error)\n                elif isinstance(errors, str):\n                    message += errors\n            if not message:\n                message = e.response_data\n            return dict(error=message)\n\n    def __repr__(self):\n        return '<TwitterAdapter for %r>' % self.conn\n\n\n@irc3.plugin\nclass Social:\n    \"\"\"The social plugin\"\"\"\n\n    requires = [\n        'irc3.plugins.command',\n    ]\n\n    conn = dict(\n    )\n\n    default_network = 'twitter'\n    networks = dict(\n        twitter_stream=dict(\n            adapter=TwitterAdapter,\n            factory='twitter.TwitterStream',\n            auth_factory='twitter.OAuth',\n            domain='stream.twitter.com',\n            api_version='1.1',\n            secure=True\n        ),\n        twitter=dict(\n            adapter=TwitterAdapter,\n            factory='twitter.Twitter',\n            auth_factory='twitter.OAuth',\n            domain='api.twitter.com',\n            api_version='1.1',\n            secure=True\n        ),\n    )\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.config = bot.config.get(__name__, {})\n        self.conns = irc3.utils.Config()\n        for name, config in self.networks.copy().items():\n            conn = self.twitter_factory(name, config.copy())\n            if conn:\n                self.conns[name] = conn\n                self.bot.log.info('%s initialized', name)\n\n    def twitter_factory(self, name, config):\n        try:\n            auth = irc3.utils.maybedotted(config.pop('auth_factory'))\n            factory = irc3.utils.maybedotted(config.pop('factory'))\n            adapter = irc3.utils.maybedotted(config.pop('adapter'))\n            if name in self.bot.config:\n                c = self.bot.config[name]\n            else:\n                c = self.bot.config[self.default_network]\n            config['auth'] = auth(c['token'], c['token_secret'],\n                                  c['key'], c['secret'])\n        except (LookupError, KeyError) as e:  # pragma: no cover\n            self.bot.log.exception(e)\n        else:\n            return adapter(self.bot, factory(**config))\n\n    @irc3.extend\n    def get_social_connection(self, id=None):\n        \"\"\"return a connection object for the network:\n\n        - A Twitter instance from\n          https://github.com/sixohsix/twitter/tree/master\n\n        \"\"\"\n        if id is None:\n            id = self.default_network\n        return self.conns[id]\n\n    @command(permission='edit')\n    def tweet(self, mask, target, args):\n        \"\"\"Post to social networks\n\n            %%tweet [--id=<id>] <message>...\n        \"\"\"\n        to = target == self.bot.nick and mask.nick or target\n        message = str(' ').join(args['<message>'])\n        if args['--id'] and args['--id'] not in self.conns:\n            return '{0} is an invalid id. Use {1}'.format(\n                args['--id'],\n                ', '.join([k for k in self.conns if 'stream' not in k]))\n        for name, status in self.send_tweet(message, id=args['--id']):\n            self.bot.privmsg(to, '{0} {1}'.format(name, status))\n\n    @irc3.extend\n    def send_tweet(self, message, id=None):\n        \"\"\"Send a tweet to networks\"\"\"\n        for name, conn in self.conns.items():\n            if 'stream' in name:\n                continue\n            if id and id != name:  # pragma: no cover\n                continue\n            status = 'failure'\n            res = conn(conn.statuses.update, status=message)\n            if isinstance(res, dict):\n                if 'error' in res:\n                    status = res['error']\n                elif 'id' in res:\n                    status = 'success'\n            yield name, status\n\n    @command(permission='edit')\n    def retweet(self, mask, target, args):\n        \"\"\"Retweet\n\n            %%retweet [--id=<id>] <url_or_id>\n        \"\"\"\n        if args['--id'] and args['--id'] not in self.conns:\n            return '{0} is an invalid id. Use {1}'.format(\n                args['--id'],\n                ', '.join([k for k in self.conns if 'stream' not in k]))\n        else:\n            args['--id'] = 'twitter'\n        to = target == self.bot.nick and mask.nick or target\n        conn = self.get_social_connection(args['--id'])\n        tid = args['<url_or_id>'].strip('/')\n        tid = tid.split('/')[-1]\n        res = conn(getattr(conn.statuses.retweet, tid))\n        if 'error' in res:\n            self.bot.privmsg(\n                to, '{0}: {1[error]}'.format(args['--id'], res))\n        elif 'id' in res:\n            self.bot.privmsg(\n                to, conn.format(res))\n\n    @irc3.extend\n    def search_tweets(self, q=None, **kwargs):\n        \"\"\"Search for tweets on twitter\"\"\"\n        conn = self.get_social_connection(id=self.default_network)\n        try:\n            results = conn.search.tweets(q=q, **kwargs)\n        except Exception as e:\n            self.bot.log.exception(e)\n        else:\n            if isinstance(results, dict):\n                return results.get('statuses', [])\n        return []\n"
  },
  {
    "path": "irc3/plugins/storage.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\n\ntry:\n    import ujson as json\nexcept ImportError:\n    import json\n\nimport irc3\nimport shelve\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.storage` Storage plugin\n==========================================\n\nAdd a ``db`` attribute to the bot\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n    >>> import tempfile\n    >>> fd = tempfile.NamedTemporaryFile(prefix='irc3', suffix='.db')\n    >>> db_file = fd.name\n    >>> fd.close()\n    >>> fd = tempfile.NamedTemporaryFile(prefix='irc3', suffix='.json')\n    >>> json_file = fd.name\n    >>> fd.close()\n    >>> fd = tempfile.NamedTemporaryFile(prefix='irc3', suffix='.sqlite')\n    >>> sqlite_file = fd.name\n    >>> fd.close()\n\nUsage::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.storage\n    ... storage = json://%s\n    ... \"\"\" % json_file)\n    >>> bot = IrcBot(**config)\n\nThen use it::\n\n    >>> bot.db['mykey'] = dict(key='value')\n    >>> 'mykey' in bot.db\n    True\n    >>> bot.db['mykey']\n    {'key': 'value'}\n    >>> bot.db.setdefault('mykey', key='default')\n    {'key': 'value'}\n    >>> bot.db.setdefault('mykey', item='default')\n    {'item': 'default'}\n    >>> bot.db.set('mykey', item='value')\n    >>> bot.db.setdefault('mykey', item='default')\n    {'item': 'value'}\n    >>> del bot.db['mykey']\n    >>> bot.db.get('mykey')\n    >>> bot.db.get('mykey', 'default')\n    'default'\n    >>> bot.db['mykey']\n    Traceback (most recent call last):\n      ...\n    KeyError: 'mykey'\n    >>> 'mykey' in bot.db\n    False\n    >>> bot.db.setlist('mylist', ['foo', 'bar'])\n    >>> bot.db.getlist('mylist')\n    ['foo', 'bar']\n    >>> del bot.db['mylist']\n\nYou can use an instance as key::\n\n    >>> class MyPlugin:\n    ...     pass\n    >>> plugin = MyPlugin()\n    >>> bot.db[plugin] = dict(key='value')\n    >>> bot.db[plugin]\n    {'key': 'value'}\n    >>> del bot.db[plugin]\n    >>> bot.db.get(plugin)\n\n..\n    >>> bot.db.SIGINT()\n\nYou can also use shelve::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.storage\n    ... storage = shelve://%s\n    ... \"\"\" % db_file)\n    >>> bot = IrcBot(**config)\n    >>> bot.db['mykey'] = dict(key='value')\n    >>> bot.db['mykey']\n    {'key': 'value'}\n    >>> del bot.db['mykey']\n    >>> bot.db.get('mykey')\n    >>> bot.db.setlist('mylist', ['foo', 'bar'])\n    >>> bot.db.getlist('mylist')\n    ['foo', 'bar']\n    >>> del bot.db['mylist']\n\n..\n    >>> bot.db.getlist('mylist', ['foo', 'bar'])\n    ['foo', 'bar']\n    >>> bot.db.setlist('mylist', ['foo', 'bar'])\n    >>> bot.db.setlist('mylist', ['foo', 'bar'])\n    >>> del bot.db['mylist']\n    >>> bot.db.SIGINT()\n\n\nOr redis::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.storage\n    ... storage = redis://localhost:6379/10\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\n..\n    >>> bot.db.backend.flushdb()  # require redis\n    >>> bot.db.SIGINT()\n\nThen use it::\n\n    >>> bot.db['mykey'] = dict(key='value')\n    >>> bot.db['mykey']\n    {'key': 'value'}\n    >>> del bot.db['mykey']\n    >>> bot.db.get('mykey')\n    >>> bot.db['mykey']\n    Traceback (most recent call last):\n      ...\n    KeyError: 'mykey'\n    >>> bot.db.setlist('mylist', ['foo', 'bar'])\n    >>> bot.db.getlist('mylist')\n    ['foo', 'bar']\n    >>> del bot.db['mylist']\n\nOr sqlite::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.storage\n    ... storage = sqlite://%s\n    ... \"\"\" % sqlite_file)\n    >>> bot = IrcBot(**config)\n\n..\n    >>> bot.db.backend.flushdb()  # require redis\n    >>> bot.db.SIGINT()\n\nThen use it::\n\n    >>> bot.db['mykey'] = dict(key='value')\n    >>> bot.db['mykey']\n    {'key': 'value'}\n    >>> del bot.db['mykey']\n    >>> bot.db.get('mykey')\n    >>> bot.db['mykey']\n    Traceback (most recent call last):\n      ...\n    KeyError: 'mykey'\n    >>> bot.db.setlist('mylist', ['foo', 'bar'])\n    >>> bot.db.getlist('mylist')\n    ['foo', 'bar']\n    >>> del bot.db['mylist']\n\nApi\n===\n\n.. autoclass:: Storage\n  :members: __getitem__,__setitem__,__delitem__,__contains__,get,set,setdefault\n\n'''\n\n\nclass Shelve:\n\n    def __init__(self, uri=None, **kwargs):\n        self.filename = uri[9:]\n        self.db = shelve.open(self.filename)\n\n    def set(self, key, value):\n        self.db[key] = value\n        self.db.sync()\n\n    def get(self, key):\n        return self.db[key]\n\n    def delete(self, key):\n        del self.db[key]\n        self.sync()\n\n    def contains(self, key):\n        return key in self.db\n\n    def sync(self):\n        self.db.sync()\n\n    def close(self):\n        self.db.close()\n\n\nclass JSON:\n\n    def __init__(self, uri=None, **kwargs):\n        self.filename = uri[7:]\n        if os.path.isfile(self.filename):  # pragma: no cover\n            with open(self.filename) as fd:\n                self.db = json.load(fd)\n        else:\n            self.db = {}\n\n    def set(self, key, value):\n        self.db[key] = value\n        self.sync()\n\n    def get(self, key):\n        return self.db[key]\n\n    def delete(self, key):\n        del self.db[key]\n        self.sync()\n\n    def contains(self, key):\n        return key in self.db\n\n    def sync(self):\n        with open(self.filename, 'w') as fd:\n            json.dump(self.db, fd, indent=2, sort_keys=True)\n\n    def close(self):\n        self.sync()\n\n\nclass Redis:\n\n    def __init__(self, uri=None, **kwargs):\n        ConnectionPool = irc3.utils.maybedotted(\n            'redis.connection.ConnectionPool')\n        pool = ConnectionPool.from_url(uri)\n        StrictRedis = irc3.utils.maybedotted('redis.client.StrictRedis')\n        self.db = StrictRedis(connection_pool=pool)\n\n    def set(self, key, value):\n        self.db.hmset(key, value)\n\n    def get(self, key):\n        keys = self.db.hkeys(key)\n        if not keys:\n            raise KeyError()\n        values = self.db.hmget(key, keys)\n        keys = [k.decode('utf8') for k in keys]\n        values = [v.decode('utf8') for v in values]\n        values = dict(zip(keys, values))\n        return values\n\n    def delete(self, key):\n        self.db.delete(key)\n\n    def contains(self, key):\n        return self.db.exists(key)\n\n    def flushdb(self):\n        self.db.flushdb()\n\n    def sync(self):\n        self.db.save()\n\n    def close(self):\n        self.sync()\n\n\nclass SQLite:\n\n    CREATE_TABLE = \"\"\"\n        CREATE TABLE IF NOT EXISTS\n            irc3_storage (\n                key text not null,\n                value text default '',\n                PRIMARY KEY (key)\n            );\n        \"\"\"\n    UPSERT = \"\"\"\n    INSERT OR REPLACE INTO irc3_storage(key,value) VALUES(?, ?);\n    \"\"\"\n\n    def __init__(self, uri=None, **kwargs):\n        self.sqlite = irc3.utils.maybedotted('sqlite3')\n        self.uri = uri.split('://')[-1]\n        conn = self.sqlite.connect(self.uri)\n        cursor = conn.cursor()\n        cursor.execute(self.CREATE_TABLE)\n        conn.commit()\n        conn.close()\n\n    def set(self, key, value):\n        conn = self.sqlite.connect(self.uri)\n        cursor = conn.cursor()\n        cursor.execute(self.UPSERT, (key, json.dumps(value)))\n        cursor.fetchall()\n        conn.commit()\n        conn.close()\n\n    def get(self, key):\n        value = None\n        conn = self.sqlite.connect(self.uri)\n        cursor = conn.cursor()\n        cursor.execute(\"SELECT value FROM irc3_storage where key=?;\", (key,))\n        for row in cursor.fetchall():\n            value = json.loads(row[0])\n            break\n        cursor.close()\n        conn.close()\n        if value is None:\n            raise KeyError(key)\n        return value\n\n    def delete(self, key):\n        conn = self.sqlite.connect(self.uri)\n        cursor = conn.cursor()\n        cursor.execute(\"DELETE FROM irc3_storage where key=?;\", (key,))\n        cursor.close()\n        conn.commit()\n        conn.close()\n\n    def contains(self, key):\n        conn = self.sqlite.connect(self.uri)\n        cursor = conn.cursor()\n        cursor.execute(\"SELECT value FROM irc3_storage where key=?;\", (key,))\n        res = False\n        if len(list(cursor.fetchall())) == 1:\n            res = True\n        cursor.close()\n        conn.close()\n        return res\n\n    def flushdb(self):\n        conn = self.sqlite.connect(self.uri)\n        cursor = conn.cursor()\n        cursor.execute(\"DROP TABLE IF EXISTS irc3_storage;\")\n        cursor.execute(self.CREATE_TABLE)\n        cursor.close()\n        conn.commit()\n        conn.close()\n\n    def sync(self):\n        pass\n\n    def close(self):\n        pass\n\n\n@irc3.plugin\nclass Storage:\n\n    backends = {\n        'shelve': Shelve,\n        'json': JSON,\n        'unix': Redis,\n        'redis': Redis,\n        'rediss': Redis,\n        'sqlite': SQLite,\n    }\n\n    def __init__(self, context):\n        uri = context.config.storage\n        name = uri.split('://', 1)[0]\n        try:\n            factory = self.backends[name]\n        except KeyError:  # pragma: no cover\n            raise LookupError('No such backend %s' % name)\n        self.backend = factory(uri)\n        self.context = context\n        self.context.db = self\n\n    async def connection_ready(self):\n        meth = getattr(self.backend, 'connection_ready', None)\n        if meth is not None:\n            await meth()\n\n    def setdefault(self, key_, **kwargs):\n        \"\"\"Update storage value for key with kwargs iif the keys doesn't\n        exist. Return stored values\"\"\"\n        stored = self[key_]\n        changed = False\n        for k, v in kwargs.items():\n            if k not in stored:\n                stored[k] = v\n                changed = True\n            else:\n                kwargs[k] = stored[k]\n        if changed:\n            self[key_] = stored\n        return kwargs\n\n    def get(self, key_, default=None):\n        \"\"\"Get storage value for key or return default\"\"\"\n        if key_ not in self:\n            return default\n        else:\n            return self[key_]\n\n    def getlist(self, key_, default=None):\n        \"\"\"Get storage value (as list) for key or return default\"\"\"\n        if key_ not in self:\n            return default\n        else:\n            value = self[key_]\n            value = [(int(i), v) for i, v in value.items()]\n            return [v for k, v in sorted(value)]\n\n    def set(self, key_, **kwargs):\n        \"\"\"Update storage value for key with kwargs\"\"\"\n        stored = self.get(key_, dict())\n        changed = False\n        for k, v in kwargs.items():\n            if k not in stored or stored[k] != v:\n                stored[k] = v\n                changed = True\n        if changed:\n            self[key_] = stored\n\n    def setlist(self, key_, value):\n        \"\"\"Update storage value (as list)\"\"\"\n        value = dict([(str(i), v) for i, v in enumerate(value)])\n        if key_ in self:\n            del self[key_]\n        self.set(key_, **value)\n\n    def __setitem__(self, key, value):\n        \"\"\"Set storage value for key\"\"\"\n        key = getattr(key, '__module__', key)\n        if not isinstance(value, dict):  # pragma: no cover\n            raise TypeError('value must be a dict')\n        try:\n            return self.backend.set(key, value)\n        except Exception as e:  # pragma: no cover\n            self.context.log.exception(e)\n            raise\n\n    def __getitem__(self, key):\n        \"\"\"Get storage value for key\"\"\"\n        key = getattr(key, '__module__', key)\n        try:\n            return self.backend.get(key)\n        except KeyError:\n            raise KeyError(key)\n        except Exception as e:  # pragma: no cover\n            self.context.log.exception(e)\n            raise\n\n    def __delitem__(self, key):\n        \"\"\"Delete key in storage\"\"\"\n        key = getattr(key, '__module__', key)\n        try:\n            self.backend.delete(key)\n        except Exception as e:  # pragma: no cover\n            self.context.log.exception(e)\n            raise\n\n    def __contains__(self, key):\n        \"\"\"Return True if storage contains key\"\"\"\n        key = getattr(key, '__module__', key)\n        try:\n            return self.backend.contains(key)\n        except Exception as e:  # pragma: no cover\n            self.context.log.exception(e)\n            raise\n\n    def SIGINT(self):\n        self.backend.close()\n"
  },
  {
    "path": "irc3/plugins/uptime.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nimport time\nimport irc3\n__doc__ = '''\n==============================================\n:mod:`irc3.plugins.uptime` Uptime plugin\n==============================================\n\nAdd an ``uptime`` command.\n\n.. autoclass:: Uptime\n   :members:\n\n'''\n\n\n@irc3.plugin\nclass Uptime:\n\n    requires = [\n        __name__.replace('uptime', 'command'),\n    ]\n\n    def __init__(self, bot):\n        self.bot = bot\n        bot.uptime = self\n        self.uptime = time.time()\n        self.connection_uptime = None\n        config = bot.config.get(__name__, {})\n        self.fmt = config.get(\n            'fmt', '{days} days {hours} hours {minutes} minutes')\n        self.privmsg = config.get('privmsg',\n                                  'Up since {0}. Connected since {1}')\n\n    def connection_made(self):\n        self.connection_uptime = time.time()\n\n    def delta(self, value):\n        values = []\n        for base in [3600 * 24, 3600, 60, 1]:\n            d, value = divmod(value, base)\n            values.append(int(d))\n        values = dict(zip(['days', 'hours', 'minutes', 'seconds'], values))\n        return self.fmt.format(**values)\n\n    @command(permission='view')\n    def uptime(self, mask, target, args):\n        \"\"\"Show uptimes\n\n            %%uptime\n        \"\"\"\n        now = time.time()\n        uptime = self.delta(now - self.uptime)\n        connection_uptime = self.delta(now - (self.connection_uptime or now))\n        return self.privmsg.format(uptime, connection_uptime)\n"
  },
  {
    "path": "irc3/plugins/userlist.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import plugin\nfrom irc3 import utils\nfrom irc3 import rfc\nfrom irc3.dec import event\nfrom irc3.utils import IrcString\nfrom collections import defaultdict\n__doc__ = '''\n==============================================\n:mod:`irc3.plugins.userlist` User list plugin\n==============================================\n\nThis plugin maintain a known user list and a channel list.\n\n..\n    >>> from irc3.testing import IrcBot\n\nUsage::\n\n    >>> bot = IrcBot()\n    >>> bot.include('irc3.plugins.userlist')\n    >>> bot.test(':gawel!user@host JOIN #chan')\n\n    >>> print(list(bot.channels['#chan'])[0])\n    gawel\n    >>> print(list(bot.nicks.keys())[0])\n    gawel\n\n    >>> bot.test(':gawel!user@host MODE #chan +o gawel')\n\n    >>> print(list(bot.channels['#chan'].modes['@'])[0])\n    gawel\n\nApi\n===\n\n.. autoclass:: Channel\n\n'''\n\n\nclass Channel(set):\n    \"\"\"A set like object which contains nicknames that are on the channel and\n    user modes:\n\n    .. code-block:: python\n\n        >>> channel = Channel()\n        >>> channel.add('gawel', modes='@')\n        >>> 'gawel' in channel\n        True\n        >>> 'gawel' in channel.modes['@']\n        True\n        >>> channel.remove('gawel')\n        >>> 'gawel' in channel\n        False\n        >>> 'gawel' in channel.modes['@']\n        False\n    \"\"\"\n\n    def __init__(self):\n        set.__init__(self)\n        self.modes = defaultdict(set)\n        self.topic = None\n\n    def add(self, item, modes=''):\n        set.add(self, item)\n        for mode in modes:\n            self.modes[mode].add(item)\n\n    def remove(self, item):\n        try:\n            set.remove(self, item)\n        except KeyError:\n            pass\n        for items in self.modes.values():\n            if item in items:\n                items.remove(item)\n\n    def __repr__(self):\n        return repr(sorted(self))\n\n\n@plugin\nclass Userlist:\n\n    def __init__(self, context):\n        self.context = context\n        self.connection_lost()\n\n    def connection_lost(self, client=None):\n        self.channels = defaultdict(Channel)\n        self.context.channels = self.channels\n        self.nicks = {}\n        self.context.nicks = self.nicks\n\n    def broadcast(self, *args, **kwargs):\n        # only usefull for servers\n        pass\n\n    @event(rfc.JOIN_PART_QUIT)\n    def on_join_part_quit(self, mask=None, event=None, **kwargs):\n        getattr(self, event.lower())(mask.nick, mask, **kwargs)\n\n    @event(rfc.KICK)\n    def on_kick(self, mask=None, event=None, target=None, **kwargs):\n        self.part(target.nick, mask=None, **kwargs)\n\n    def join(self, nick, mask, client=None, **kwargs):\n        channel = self.channels[kwargs['channel']]\n        if nick != self.context.nick:\n            channel.add(mask.nick)\n            self.nicks[mask.nick] = client or mask\n            if client:\n                self.broadcast(client=client, clients=channel, **kwargs)\n\n    def part(self, nick, mask=None, channel=None, client=None, **kwargs):\n        if nick == self.context.nick:\n            self.channels.pop(channel, None)\n        else:\n            channel = self.channels[channel]\n            self.broadcast(client=client, clients=channel, **kwargs)\n            channel.remove(nick)\n            if client is None and all(\n                    nick not in c for c in self.channels.values()):\n                self.nicks.pop(nick, None)\n\n    def quit(self, nick, mask, channel=None, client=None, **kwargs):\n        if nick == self.context.nick:\n            self.connection_lost()\n        else:\n            clients = set()\n            for channel in self.channels.values():\n                if nick in channel:\n                    clients.update(channel)\n                    channel.remove(nick)\n            self.broadcast(client=client, clients=clients, **kwargs)\n            self.nicks.pop(nick, None)\n\n    @event(rfc.NEW_NICK)\n    def new_nick(self, nick=None, new_nick=None, client=None, **kwargs):\n        \"\"\"update list on new nick\"\"\"\n        if client is None:\n            self.nicks[new_nick] = new_nick + '!' + nick.host\n            nick = nick.nick\n        clients = {new_nick}\n        for channel in self.channels.values():\n            if nick in channel:\n                for nicknames in channel.modes.values():\n                    if nick in nicknames:\n                        nicknames.add(new_nick)\n                channel.remove(nick)\n                clients.update(channel)\n                channel.add(new_nick)\n        self.nicks.pop(nick, None)\n        self.broadcast(client=client, clients=clients, **kwargs)\n\n    @event(rfc.RPL_NAMREPLY)\n    def names(self, channel=None, data=None, **kwargs):\n        \"\"\"Initialise channel list and channel.modes\"\"\"\n        statusmsg = self.context.server_config['STATUSMSG']\n        nicknames = data.split(' ')\n        channel = self.channels[channel]\n        for item in nicknames:\n            nick = item.strip(statusmsg)\n            channel.add(nick, modes=item[:-len(nick)])\n            self.nicks[nick] = nick\n\n    @event(rfc.RPL_WHOREPLY)\n    def who(self, channel=None, nick=None, username=None, server=None, **kw):\n        \"\"\"Set nick mask\"\"\"\n        self.channels[channel].add(nick)\n        mask = IrcString(nick + '!' + username + '@' + server)\n        self.nicks[nick] = mask\n\n    @event(rfc.MODE)\n    def mode(self, target=None, modes=None, data=None, client=None, **kw):\n        \"\"\"Add nicknames to channel.modes\"\"\"\n        if target[0] not in self.context.server_config['CHANTYPES'] \\\n           or not data:\n            # not a channel or no user target\n            return\n        noargs = self.context.server_config['CHANMODES'].split(',')[-1]\n        if not isinstance(data, list):\n            data = [d for d in data.split(' ') if d]\n        if not modes.startswith(('+', '-')):\n            modes = '+' + modes\n        modes = utils.parse_modes(modes, data, noargs)\n        prefix = self.context.server_config['PREFIX']\n        prefix = dict(zip(*prefix.strip('(').split(')')))\n        channel = self.channels[target]\n        for char, mode, tgt in modes:\n            if mode in prefix:\n                nicknames = channel.modes[prefix[mode]]\n                if char == '+':\n                    nicknames.add(tgt)\n                elif tgt in nicknames:\n                    nicknames.remove(tgt)\n                if client is not None:\n                    broadcast = (\n                        ':{mask} MODE {target} {char}{mode} {tgt}').format(\n                        char=char, mode=mode, target=target, tgt=tgt,\n                        **client.data)\n                    self.broadcast(client=client, broadcast=broadcast,\n                                   clients=channel)\n\n    @event(rfc.RPL_TOPIC)\n    def topic(self, channel=None, data=None, client=None, **kwargs):\n        self.channels[channel].topic = data\n"
  },
  {
    "path": "irc3/plugins/web.py",
    "content": "import irc3\n__doc__ = '''\n==========================================\n:mod:`irc3.plugins.web` Web plugin\n==========================================\n\nIntroduce a web interface to post messages\n\nInstall aiohttp and aiohttp-wsgi::\n\n    $ pip install aiohttp aiohttp-wsgi\n\n..\n    >>> from irc3.testing import IrcBot\n    >>> from irc3.testing import ini2config\n\nUsage::\n\nThis example show how to define the web server config::\n\n    >>> config = ini2config(\"\"\"\n    ... [bot]\n    ... includes =\n    ...     irc3.plugins.web\n    ...\n    ... [irc3.plugins.web]\n    ... host = 127.0.0.1\n    ... port = 8080\n    ... api_key = toomanysecrets\n    ... \"\"\")\n    >>> bot = IrcBot(**config)\n\nThen you'll be able to post a message to a channel using curl::\n\n    $ curl -H \"X-Api-Key: toomanysecrets\" \\\n      --data Hello \\\n      http://127.0.0.1:8080/channels/irc3\n'''\n\n\n@irc3.plugin\nclass Web:\n\n    def __init__(self, context):\n        self.web = irc3.utils.maybedotted('aiohttp.web')\n        self.context = context\n        self.config = context.config.get(__name__, {})\n        self.api_key = self.config.get('api_key')\n        if not self.api_key:\n            self.context.log.warning(\n                'No web api_key is set. Your web service is insecure')\n        self.channels = {}\n        self.server = None\n\n    def server_ready(self):\n        if self.server is None:\n            server = self.web.Server(self.handler, loop=self.context.loop)\n            host = self.config.get('host', '127.0.0.1')\n            port = int(self.config.get('port', 8080))\n            self.context.log.info(\n                'Starting web interface on %s:%s...', host, port)\n            self.server = self.context.create_task(\n                self.context.loop.create_server(server, host, port))\n\n    @irc3.event(irc3.rfc.JOIN)\n    def join(self, mask=None, channel=None, **kwargs):\n        if mask.nick == self.context.nick:\n            key = channel.strip('#&+')\n            if key not in self.channels:\n                self.channels[key] = channel\n\n    async def handler(self, req):\n        if req.method == 'POST':\n            if self.api_key:\n                if req.headers.get('X-Api-Key') != self.api_key:\n                    return self.web.Response(status=403)\n            if req.path.startswith('/channels/'):\n                channel = req.path.strip('/').split('/')[-1]\n                if channel in self.channels:\n                    message = await req.text()\n                    self.context.privmsg(self.channels[channel], message)\n                    return self.web.Response(status=201)\n                return self.web.Response(status=404)\n        return self.web.Response()\n"
  },
  {
    "path": "irc3/rfc.py",
    "content": "# -*- coding: utf-8 -*-\nfrom re import compile\nfrom ._rfc import *  # NOQA\n\n_re_params = compile(r'P<([^>]+)>')\n\n\ndef _extract_params(regexp):\n    \"\"\"extract parameters from regexp\"\"\"\n    params = _re_params.findall(regexp)\n    if params and params[0] == 'tags':\n        params.pop(0)\n        params.append('tags')\n    return params\n\n\nclass raw(str):\n    name = None\n    re = None\n    re_out = None\n    server = None\n\n    @classmethod\n    def new(cls, name, regexp, regexp_out=None):\n        r = cls(name)\n        r.name = name\n        r.re = regexp\n        r.params = _extract_params(r.re)\n        if regexp_out is not None:\n            out_name = 'OUT_' + name\n            r.re_out = cls(out_name)\n            r.re_out.name = out_name\n            r.re_out.re = regexp_out\n            r.re_out.params = _extract_params(regexp_out)\n        if regexp.startswith((':', '^:', '(@', '^(@')):\n            name = 'SERVER_' + name\n            r.server = cls(name)\n            r.server.name = name\n            if regexp.startswith(('(@', '^(@')):\n                r.server.re = regexp.split(' ', 2)[2]\n                r.server.re = r'(@(?P<tags>\\S+) )?' + r.server.re\n            else:\n                r.server.re = regexp.split(' ', 1)[1]\n        return r\n\n\nCONNECTED = raw.new('CONNECTED',\n                    r'^:(?P<srv>\\S+) (376|422) (?P<me>\\S+) :(?P<data>.*)')\n\nPING = raw.new('PING', r'^PING :?(?P<data>.*)')\nPONG = raw.new(\n    'PONG',\n    r'^(@(?P<tags>\\S+) )?:(?P<server>\\S+) PONG (?P=server) :?(?P<data>.*)')\n\nNEW_NICK = raw.new(\n    'NEW_NICK',\n    regexp=r'^(@(?P<tags>\\S+) )?:(?P<nick>\\S+) NICK :?(?P<new_nick>\\S+)',\n    regexp_out=r'^NICK :?(?P<new_nick>\\S+)',\n)\n\nJOIN = raw.new(\n    'JOIN',\n    regexp=r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) JOIN :?(?P<channel>\\S+)',\n    regexp_out=r'^JOIN :?(?P<channel>\\S+)',\n)\n\nPART = raw.new(\n    'PART',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) '\n        r'PART (?P<channel>\\S+)(\\s+:(?P<data>.*)|$)'),\n    regexp_out=r'PART (?P<channel>\\S+)(\\s+:(?P<data>.*)|$)',\n)\n\nQUIT = raw.new(\n    'QUIT',\n    regexp=r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) QUIT(\\s+:(?P<data>.*)|$)',\n    regexp_out=r'^QUIT(\\s+:(?P<data>.*)|$)',\n)\n\nJOIN_PART_QUIT = raw.new(\n    'JOIN_PART_QUIT',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) '\n        r'(?P<event>JOIN|PART|QUIT)\\s*:*(?P<channel>\\S*)(\\s+:(?P<data>.*)|$)'),\n    regexp_out=(\n        r'^(?P<event>JOIN|PART|QUIT)\\s*:*(?P<channel>\\S*)(\\s+:(?P<data>.*)|$)')\n)\n\nKICK = raw.new(\n    'KICK',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) '\n        r'(?P<event>KICK)\\s+(?P<channel>\\S+)\\s*(?P<target>\\S+)'\n        r'(\\s+:(?P<data>.*)|$)'),\n    regexp_out=(\n        r'^(?P<event>KICK)\\s+(?P<channel>\\S+)\\s*(?P<target>\\S+)'\n        r'(\\s+:(?P<data>.*)|$)'),\n)\n\nMODE = raw.new(\n    'MODE',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+) (?P<event>MODE)\\s+'\n        r'(?P<target>\\S+)\\s+(?P<modes>\\S+)(\\s+(?P<data>.*)|$)'),\n    regexp_out=(\n        r'^(?P<event>MODE)\\s+'\n        r'(?P<target>\\S+)\\s+(?P<modes>\\S+)(\\s+(?P<data>.*)|$)'),\n)\n\nMY_PRIVMSG = raw.new(\n    'MY_PRIVMSG',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) '\n        r'(?P<event>(PRIVMSG|NOTICE)) '\n        r'(?P<target>(#\\S+|{nick})) :{nick}[:,\\s]\\s*'\n        r'(?P<data>\\S+.*)$'),\n    regexp_out=(\n        r'^(?P<event>(PRIVMSG|NOTICE)) (?P<target>\\S+) :(?P<data>.*)$')\n)\n\nPRIVMSG = raw.new(\n    'PRIVMSG',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) '\n        r'(?P<event>(PRIVMSG|NOTICE)) '\n        r'(?P<target>\\S+) :(?P<data>.*)$'),\n)\nPRIVMSG.re_out = MY_PRIVMSG.re_out\n\nCTCP = raw.new(\n    'CTCP',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) '\n        '(?P<event>(PRIVMSG|NOTICE)) '\n        '{nick} :\\x01(?P<ctcp>.*)\\x01$'),\n    regexp_out=(\n        '^(?P<event>(PRIVMSG|NOTICE)) (?P<target>\\\\S+) :\\x01(?P<ctcp>.*)\\x01$'\n    ),\n)\n\nINVITE = raw.new(\n    'INVITE',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) '\n        r'INVITE {nick} :?(?P<channel>\\S+)$')\n)\n\nTOPIC = raw.new(\n    'TOPIC',\n    regexp=(\n        r'^(@(?P<tags>\\S+) )?:(?P<mask>\\S+!\\S+@\\S+) '\n        r'TOPIC (?P<channel>\\S+) :(?P<data>.*)$'),\n    regexp_out=(\n        r'^TOPIC (?P<channel>\\S+) :(?P<data>.*)$'),\n)\n\nERR_NICK = raw.new(\n    'ERR_NICK',\n    r\"^(@(?P<tags>\\S+) )?:(?P<srv>\\S+) (?P<retcode>(432|433|436)) (?P<me>\\S+) \"\n    r\"(?P<nick>\\S+) :(?P<data>.*)\")\n"
  },
  {
    "path": "irc3/rfc1459.txt",
    "content": "\n\n\n\n\n\nNetwork Working Group                                      J. Oikarinen\nRequest for Comments: 1459                                      D. Reed\n                                                               May 1993\n\n\n                      Internet Relay Chat Protocol\n\nStatus of This Memo\n\n   This memo defines an Experimental Protocol for the Internet\n   community.  Discussion and suggestions for improvement are requested.\n   Please refer to the current edition of the \"IAB Official Protocol\n   Standards\" for the standardization state and status of this protocol.\n   Distribution of this memo is unlimited.\n\nAbstract\n\n   The IRC protocol was developed over the last 4 years since it was\n   first implemented as a means for users on a BBS to chat amongst\n   themselves.  Now it supports a world-wide network of servers and\n   clients, and is stringing to cope with growth. Over the past 2 years,\n   the average number of users connected to the main IRC network has\n   grown by a factor of 10.\n\n   The IRC protocol is a text-based protocol, with the simplest client\n   being any socket program capable of connecting to the server.\n\nTable of Contents\n\n   1.  INTRODUCTION ...............................................    4\n      1.1  Servers ................................................    4\n      1.2  Clients ................................................    5\n         1.2.1 Operators ..........................................    5\n      1.3 Channels ................................................    5\n      1.3.1  Channel Operators ....................................    6\n   2. THE IRC SPECIFICATION .......................................    7\n      2.1 Overview ................................................    7\n      2.2 Character codes .........................................    7\n      2.3 Messages ................................................    7\n         2.3.1  Message format in 'pseudo' BNF ....................    8\n      2.4 Numeric replies .........................................   10\n   3. IRC Concepts ................................................   10\n      3.1 One-to-one communication ................................   10\n      3.2 One-to-many .............................................   11\n         3.2.1 To a list ..........................................   11\n         3.2.2 To a group (channel) ...............................   11\n         3.2.3 To a host/server mask ..............................   12\n      3.3 One to all ..............................................   12\n\n\n\nOikarinen & Reed                                                [Page 1]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n         3.3.1 Client to Client ...................................   12\n         3.3.2 Clients to Server ..................................   12\n         3.3.3 Server to Server ...................................   12\n   4. MESSAGE DETAILS .............................................   13\n      4.1 Connection Registration .................................   13\n         4.1.1 Password message ...................................   14\n         4.1.2 Nickname message ...................................   14\n         4.1.3 User message .......................................   15\n         4.1.4 Server message .....................................   16\n         4.1.5 Operator message ...................................   17\n         4.1.6 Quit message .......................................   17\n         4.1.7 Server Quit message ................................   18\n      4.2 Channel operations ......................................   19\n         4.2.1 Join message .......................................   19\n         4.2.2 Part message .......................................   20\n         4.2.3 Mode message .......................................   21\n            4.2.3.1 Channel modes .................................   21\n            4.2.3.2 User modes ....................................   22\n         4.2.4 Topic message ......................................   23\n         4.2.5 Names message ......................................   24\n         4.2.6 List message .......................................   24\n         4.2.7 Invite message .....................................   25\n         4.2.8 Kick message .......................................   25\n      4.3 Server queries and commands .............................   26\n         4.3.1 Version message ....................................   26\n         4.3.2 Stats message ......................................   27\n         4.3.3 Links message ......................................   28\n         4.3.4 Time message .......................................   29\n         4.3.5 Connect message ....................................   29\n         4.3.6 Trace message ......................................   30\n         4.3.7 Admin message ......................................   31\n         4.3.8 Info message .......................................   31\n      4.4 Sending messages ........................................   32\n         4.4.1 Private messages ...................................   32\n         4.4.2 Notice messages ....................................   33\n      4.5 User-based queries ......................................   33\n         4.5.1 Who query ..........................................   33\n         4.5.2 Whois query ........................................   34\n         4.5.3 Whowas message .....................................   35\n      4.6 Miscellaneous messages ..................................   35\n         4.6.1 Kill message .......................................   36\n         4.6.2 Ping message .......................................   37\n         4.6.3 Pong message .......................................   37\n         4.6.4 Error message ......................................   38\n   5. OPTIONAL MESSAGES ...........................................   38\n      5.1 Away message ............................................   38\n      5.2 Rehash command ..........................................   39\n      5.3 Restart command .........................................   39\n\n\n\nOikarinen & Reed                                                [Page 2]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n      5.4 Summon message ..........................................   40\n      5.5 Users message ...........................................   40\n      5.6 Operwall command ........................................   41\n      5.7 Userhost message ........................................   42\n      5.8 Ison message ............................................   42\n   6. REPLIES .....................................................   43\n      6.1 Error Replies ...........................................   43\n      6.2 Command responses .......................................   48\n      6.3 Reserved numerics .......................................   56\n   7. Client and server authentication ............................   56\n   8. Current Implementations Details .............................   56\n      8.1 Network protocol: TCP ...................................   57\n         8.1.1 Support of Unix sockets ............................   57\n      8.2 Command Parsing .........................................   57\n      8.3 Message delivery ........................................   57\n      8.4 Connection 'Liveness' ...................................   58\n      8.5 Establishing a server-client connection .................   58\n      8.6 Establishing a server-server connection .................   58\n         8.6.1 State information exchange when connecting .........   59\n      8.7 Terminating server-client connections ...................   59\n      8.8 Terminating server-server connections ...................   59\n      8.9 Tracking nickname changes ...............................   60\n      8.10 Flood control of clients ...............................   60\n      8.11 Non-blocking lookups ...................................   61\n         8.11.1 Hostname (DNS) lookups ............................   61\n         8.11.2 Username (Ident) lookups ..........................   61\n      8.12 Configuration file .....................................   61\n         8.12.1 Allowing clients to connect .......................   62\n         8.12.2 Operators .........................................   62\n         8.12.3 Allowing servers to connect .......................   62\n         8.12.4 Administrivia .....................................   63\n      8.13 Channel membership .....................................   63\n   9. Current problems ............................................   63\n      9.1 Scalability .............................................   63\n      9.2 Labels ..................................................   63\n         9.2.1 Nicknames ..........................................   63\n         9.2.2 Channels ...........................................   64\n         9.2.3 Servers ............................................   64\n      9.3 Algorithms ..............................................   64\n   10. Support and availability ...................................   64\n   11. Security Considerations ....................................   65\n   12. Authors' Addresses .........................................   65\n\n\n\n\n\n\n\n\n\nOikarinen & Reed                                                [Page 3]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n1.  INTRODUCTION\n\n   The IRC (Internet Relay Chat) protocol has been designed over a\n   number of years for use with text based conferencing.  This document\n   describes the current IRC protocol.\n\n   The IRC protocol has been developed on systems using the TCP/IP\n   network protocol, although there is no requirement that this remain\n   the only sphere in which it operates.\n\n   IRC itself is a teleconferencing system, which (through the use of\n   the client-server model) is well-suited to running on many machines\n   in a distributed fashion.  A typical setup involves a single process\n   (the server) forming a central point for clients (or other servers)\n   to connect to, performing the required message delivery/multiplexing\n   and other functions.\n\n1.1 Servers\n\n   The server forms the backbone of IRC, providing a point to which\n   clients may connect to to talk to each other, and a point for other\n   servers to connect to, forming an IRC network.  The only network\n   configuration allowed for IRC servers is that of a spanning tree [see\n   Fig. 1] where each server acts as a central node for the rest of the\n   net it sees.\n\n\n                           [ Server 15 ]  [ Server 13 ] [ Server 14]\n                                 /                \\         /\n                                /                  \\       /\n        [ Server 11 ] ------ [ Server 1 ]       [ Server 12]\n                              /        \\          /\n                             /          \\        /\n                  [ Server 2 ]          [ Server 3 ]\n                    /       \\                      \\\n                   /         \\                      \\\n           [ Server 4 ]    [ Server 5 ]         [ Server 6 ]\n            /    |    \\                           /\n           /     |     \\                         /\n          /      |      \\____                   /\n         /       |           \\                 /\n [ Server 7 ] [ Server 8 ] [ Server 9 ]   [ Server 10 ]\n\n                                  :\n                               [ etc. ]\n                                  :\n\n                 [ Fig. 1. Format of IRC server network ]\n\n\n\nOikarinen & Reed                                                [Page 4]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n1.2 Clients\n\n   A client is anything connecting to a server that is not another\n   server.  Each client is distinguished from other clients by a unique\n   nickname having a maximum length of nine (9) characters.  See the\n   protocol grammar rules for what may and may not be used in a\n   nickname.  In addition to the nickname, all servers must have the\n   following information about all clients: the real name of the host\n   that the client is running on, the username of the client on that\n   host, and the server to which the client is connected.\n\n1.2.1 Operators\n\n   To allow a reasonable amount of order to be kept within the IRC\n   network, a special class of clients (operators) is allowed to perform\n   general maintenance functions on the network.  Although the powers\n   granted to an operator can be considered as 'dangerous', they are\n   nonetheless required.  Operators should be able to perform basic\n   network tasks such as disconnecting and reconnecting servers as\n   needed to prevent long-term use of bad network routing.  In\n   recognition of this need, the protocol discussed herein provides for\n   operators only to be able to perform such functions.  See sections\n   4.1.7 (SQUIT) and 4.3.5 (CONNECT).\n\n   A more controversial power of operators is the ability  to  remove  a\n   user  from  the connected network by 'force', i.e. operators are able\n   to close the connection between any client and server.   The\n   justification for  this  is delicate since its abuse is both\n   destructive and annoying.  For further details on this type of\n   action, see section 4.6.1 (KILL).\n\n1.3 Channels\n\n   A channel is a named group of one or more clients which will all\n   receive messages addressed to that channel.  The channel is created\n   implicitly when the first client joins it, and the channel ceases to\n   exist when the last client leaves it.  While channel exists, any\n   client can reference the channel using the name of the channel.\n\n   Channels names are strings (beginning with a '&' or '#' character) of\n   length up to 200 characters.  Apart from the the requirement that the\n   first character being either '&' or '#'; the only restriction on a\n   channel name is that it may not contain any spaces (' '), a control G\n   (^G or ASCII 7), or a comma (',' which is used as a list item\n   separator by the protocol).\n\n   There are two types of channels allowed by this protocol.  One is a\n   distributed channel which is known to all the servers that are\n\n\n\nOikarinen & Reed                                                [Page 5]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   connected to the network. These channels are marked by the first\n   character being a only clients on the server where it exists may join\n   it.  These are distinguished by a leading '&' character.  On top of\n   these two types, there are the various channel modes available to\n   alter the characteristics of individual channels.  See section 4.2.3\n   (MODE command) for more details on this.\n\n   To create a new channel or become part of an existing channel, a user\n   is required to JOIN the channel.  If the channel doesn't exist prior\n   to joining, the channel is created and the creating user becomes a\n   channel operator.  If the channel already exists, whether or not your\n   request to JOIN that channel is honoured depends on the current modes\n   of the channel. For example, if the channel is invite-only, (+i),\n   then you may only join if invited.  As part of the protocol, a user\n   may be a part of several channels at once, but a limit of ten (10)\n   channels is recommended as being ample for both experienced and\n   novice users.  See section 8.13 for more information on this.\n\n   If the IRC network becomes disjoint because of a split between two\n   servers, the channel on each side is only composed of those clients\n   which are connected to servers on the respective sides of the split,\n   possibly ceasing to exist on one side of the split.  When the split\n   is healed, the connecting servers announce to each other who they\n   think is in each channel and the mode of that channel.  If the\n   channel exists on both sides, the JOINs and MODEs are interpreted in\n   an inclusive manner so that both sides of the new connection will\n   agree about which clients are in the channel and what modes the\n   channel has.\n\n1.3.1 Channel Operators\n\n   The channel operator (also referred to as a \"chop\" or \"chanop\") on a\n   given channel is considered to 'own' that channel.  In recognition of\n   this status, channel operators are endowed with certain powers which\n   enable them to keep control and some sort of sanity in their channel.\n   As an owner of a channel, a channel operator is not required to have\n   reasons for their actions, although if their actions are generally\n   antisocial or otherwise abusive, it might be reasonable to ask an IRC\n   operator to intervene, or for the usersjust leave and go elsewhere\n   and form their own channel.\n\n   The commands which may only be used by channel operators are:\n\n        KICK    - Eject a client from the channel\n        MODE    - Change the channel's mode\n        INVITE  - Invite a client to an invite-only channel (mode +i)\n        TOPIC   - Change the channel topic in a mode +t channel\n\n\n\n\nOikarinen & Reed                                                [Page 6]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   A channel operator is identified by the '@' symbol next to their\n   nickname whenever it is associated with a channel (ie replies to the\n   NAMES, WHO and WHOIS commands).\n\n2. The IRC Specification\n\n2.1 Overview\n\n   The protocol as described herein is for use both with server to\n   server and client to server connections.  There are, however, more\n   restrictions on client connections (which are considered to be\n   untrustworthy) than on server connections.\n\n2.2 Character codes\n\n   No specific character set is specified. The protocol is based on a a\n   set of codes which are composed of eight (8) bits, making up an\n   octet.  Each message may be composed of any number of these octets;\n   however, some octet values are used for control codes which act as\n   message delimiters.\n\n   Regardless of being an 8-bit protocol, the delimiters and keywords\n   are such that protocol is mostly usable from USASCII terminal and a\n   telnet connection.\n\n   Because of IRC's scandanavian origin, the characters {}| are\n   considered to be the lower case equivalents of the characters []\\,\n   respectively. This is a critical issue when determining the\n   equivalence of two nicknames.\n\n2.3 Messages\n\n   Servers and clients send eachother messages which may or may not\n   generate a reply.  If the message contains a valid command, as\n   described in later sections, the client should expect a reply as\n   specified but it is not advised to wait forever for the reply; client\n   to server and server to server communication is essentially\n   asynchronous in nature.\n\n   Each IRC message may consist of up to three main parts: the prefix\n   (optional), the command, and the command parameters (of which there\n   may be up to 15).  The prefix, command, and all parameters are\n   separated by one (or more) ASCII space character(s) (0x20).\n\n   The presence of a prefix is indicated with a single leading ASCII\n   colon character (':', 0x3b), which must be the first character of the\n   message itself.  There must be no gap (whitespace) between the colon\n   and the prefix.  The prefix is used by servers to indicate the true\n\n\n\nOikarinen & Reed                                                [Page 7]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   origin of the message.  If the prefix is missing from the message, it\n   is assumed to have originated from the connection from which it was\n   received.  Clients should not use prefix when sending a message from\n   themselves; if they use a prefix, the only valid prefix is the\n   registered nickname associated with the client.  If the source\n   identified by the prefix cannot be found from the server's internal\n   database, or if the source is registered from a different link than\n   from which the message arrived, the server must ignore the message\n   silently.\n\n   The command must either be a valid IRC command or a three (3) digit\n   number represented in ASCII text.\n\n   IRC messages are always lines of characters terminated with a CR-LF\n   (Carriage Return - Line Feed) pair, and these messages shall not\n   exceed 512 characters in length, counting all characters including\n   the trailing CR-LF. Thus, there are 510 characters maximum allowed\n   for the command and its parameters.  There is no provision for\n   continuation message lines.  See section 7 for more details about\n   current implementations.\n\n2.3.1 Message format in 'pseudo' BNF\n\n   The protocol messages must be extracted from the contiguous stream of\n   octets.  The current solution is to designate two characters, CR and\n   LF, as message separators.   Empty  messages  are  silently  ignored,\n   which permits  use  of  the  sequence  CR-LF  between  messages\n   without extra problems.\n\n   The extracted message is parsed into the components <prefix>,\n   <command> and list of parameters matched either by <middle> or\n   <trailing> components.\n\n   The BNF representation for this is:\n\n\n<message>  ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>\n<prefix>   ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]\n<command>  ::= <letter> { <letter> } | <number> <number> <number>\n<SPACE>    ::= ' ' { ' ' }\n<params>   ::= <SPACE> [ ':' <trailing> | <middle> <params> ]\n\n<middle>   ::= <Any *non-empty* sequence of octets not including SPACE\n               or NUL or CR or LF, the first of which may not be ':'>\n<trailing> ::= <Any, possibly *empty*, sequence of octets not including\n                 NUL or CR or LF>\n\n<crlf>     ::= CR LF\n\n\n\nOikarinen & Reed                                                [Page 8]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\nNOTES:\n\n  1)    <SPACE> is consists only of SPACE character(s) (0x20).\n        Specially notice that TABULATION, and all other control\n        characters are considered NON-WHITE-SPACE.\n\n  2)    After extracting the parameter list, all parameters are equal,\n        whether matched by <middle> or <trailing>. <Trailing> is just\n        a syntactic trick to allow SPACE within parameter.\n\n  3)    The fact that CR and LF cannot appear in parameter strings is\n        just artifact of the message framing. This might change later.\n\n  4)    The NUL character is not special in message framing, and\n        basically could end up inside a parameter, but as it would\n        cause extra complexities in normal C string handling. Therefore\n        NUL is not allowed within messages.\n\n  5)    The last parameter may be an empty string.\n\n  6)    Use of the extended prefix (['!' <user> ] ['@' <host> ]) must\n        not be used in server to server communications and is only\n        intended for server to client messages in order to provide\n        clients with more useful information about who a message is\n        from without the need for additional queries.\n\n   Most protocol messages specify additional semantics and syntax for\n   the extracted parameter strings dictated by their position in the\n   list.  For example, many server commands will assume that the first\n   parameter after the command is the list of targets, which can be\n   described with:\n\n   <target>     ::= <to> [ \",\" <target> ]\n   <to>         ::= <channel> | <user> '@' <servername> | <nick> | <mask>\n   <channel>    ::= ('#' | '&') <chstring>\n   <servername> ::= <host>\n   <host>       ::= see RFC 952 [DNS:4] for details on allowed hostnames\n   <nick>       ::= <letter> { <letter> | <number> | <special> }\n   <mask>       ::= ('#' | '$') <chstring>\n   <chstring>   ::= <any 8bit code except SPACE, BELL, NUL, CR, LF and\n                     comma (',')>\n\n   Other parameter syntaxes are:\n\n   <user>       ::= <nonwhite> { <nonwhite> }\n   <letter>     ::= 'a' ... 'z' | 'A' ... 'Z'\n   <number>     ::= '0' ... '9'\n   <special>    ::= '-' | '[' | ']' | '\\' | '`' | '^' | '{' | '}'\n\n\n\nOikarinen & Reed                                                [Page 9]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   <nonwhite>   ::= <any 8bit code except SPACE (0x20), NUL (0x0), CR\n                     (0xd), and LF (0xa)>\n\n2.4 Numeric replies\n\n   Most of the messages sent to the server generate a reply of some\n   sort.  The most common reply is the numeric reply, used for both\n   errors and normal replies.  The numeric reply must be sent as one\n   message consisting of the sender prefix, the three digit numeric, and\n   the target of the reply.  A numeric reply is not allowed to originate\n   from a client; any such messages received by a server are silently\n   dropped. In all other respects, a numeric reply is just like a normal\n   message, except that the keyword is made up of 3 numeric digits\n   rather than a string of letters.  A list of different replies is\n   supplied in section 6.\n\n3. IRC Concepts.\n\n   This section is devoted to describing the actual concepts behind  the\n   organization  of  the  IRC  protocol and how the current\n   implementations deliver different classes of messages.\n\n\n\n                          1--\\\n                              A        D---4\n                          2--/ \\      /\n                                B----C\n                               /      \\\n                              3        E\n\n   Servers: A, B, C, D, E         Clients: 1, 2, 3, 4\n\n                    [ Fig. 2. Sample small IRC network ]\n\n3.1 One-to-one communication\n\n   Communication on a one-to-one basis is usually only performed by\n   clients, since most server-server traffic is not a result of servers\n   talking only to each other.  To provide a secure means for clients to\n   talk to each other, it is required that all servers be able to send a\n   message in exactly one direction along the spanning tree in order to\n   reach any client.  The path of a message being delivered is the\n   shortest path between any two points on the spanning tree.\n\n   The following examples all refer to Figure 2 above.\n\n\n\n\n\nOikarinen & Reed                                               [Page 10]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\nExample 1:\n     A message between clients 1 and 2 is only seen by server A, which\n     sends it straight to client 2.\n\nExample 2:\n     A message between clients 1 and 3 is seen by servers A & B, and\n     client 3.  No other clients or servers are allowed see the message.\n\nExample 3:\n     A message between clients 2 and 4 is seen by servers A, B, C & D\n     and client 4 only.\n\n3.2 One-to-many\n\n   The main goal of IRC is to provide a  forum  which  allows  easy  and\n   efficient  conferencing (one to many conversations).  IRC offers\n   several means to achieve this, each serving its own purpose.\n\n3.2.1 To a list\n\n   The least efficient style of one-to-many conversation is through\n   clients talking to a 'list' of users.  How this is done is almost\n   self explanatory: the client gives a list of destinations to which\n   the message is to be delivered and the server breaks it up and\n   dispatches a separate copy of the message to each given destination.\n   This isn't as efficient as using a group since the destination list\n   is broken up and the dispatch sent without checking to make sure\n   duplicates aren't sent down each path.\n\n3.2.2 To a group (channel)\n\n   In IRC the channel has a role equivalent to that of the multicast\n   group; their existence is dynamic (coming and going as people join\n   and leave channels) and the actual conversation carried out on a\n   channel is only sent to servers which are supporting users on a given\n   channel.  If there are multiple users on a server in the same\n   channel, the message text is sent only once to that server and then\n   sent to each client on the channel.  This action is then repeated for\n   each client-server combination until the original message has fanned\n   out and reached each member of the channel.\n\n   The following examples all refer to Figure 2.\n\nExample 4:\n     Any channel with 1 client in it. Messages to the channel go to the\n     server and then nowhere else.\n\n\n\n\n\nOikarinen & Reed                                               [Page 11]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\nExample 5:\n     2 clients in a channel. All messages traverse a path as if they\n     were private messages between the two clients outside a channel.\n\nExample 6:\n     Clients 1, 2 and 3 in a channel.  All messages to the channel are\n     sent to all clients and only those servers which must be traversed\n     by the message if it were a private message to a single client.  If\n     client 1 sends a message, it goes back to client 2 and then via\n     server B to client 3.\n\n3.2.3 To a host/server mask\n\n   To provide IRC operators with some mechanism to send  messages  to  a\n   large body of related users, host and server mask messages are\n   provided.  These messages are sent to users whose host or server\n   information  match that  of  the mask.  The messages are only sent to\n   locations where users are, in a fashion similar to that of channels.\n\n3.3 One-to-all\n\n   The one-to-all type of message is better described as a broadcast\n   message, sent to all clients or servers or both.  On a large network\n   of users and servers, a single message can result in a lot of traffic\n   being sent over the network in an effort to reach all of the desired\n   destinations.\n\n   For some messages, there is no option but to broadcast it to all\n   servers so that the state information held by each server is\n   reasonably consistent between servers.\n\n3.3.1 Client-to-Client\n\n   There is no class of message which, from a single message, results in\n   a message being sent to every other client.\n\n3.3.2 Client-to-Server\n\n   Most of the commands which result in a change of state information\n   (such as channel membership, channel mode, user status, etc) must be\n   sent to all servers by default, and this distribution may not be\n   changed by the client.\n\n3.3.3 Server-to-Server.\n\n   While most messages between servers are distributed to all 'other'\n   servers, this is only required for any message that affects either a\n   user, channel or server.  Since these are the basic items found in\n\n\n\nOikarinen & Reed                                               [Page 12]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   IRC, nearly all messages originating from a server are broadcast to\n   all other connected servers.\n\n4. Message details\n\n   On the following pages are descriptions of each message recognized by\n   the IRC server and client.  All commands described in this section\n   must be implemented by any server for this protocol.\n\n   Where the reply ERR_NOSUCHSERVER is listed, it means that the\n   <server> parameter could not be found.  The server must not send any\n   other replies after this for that command.\n\n   The server to which a client is connected is required to parse the\n   complete message, returning any appropriate errors.  If the server\n   encounters a fatal error while parsing a message, an error must be\n   sent back to the client and the parsing terminated.  A fatal error\n   may be considered to be incorrect command, a destination which is\n   otherwise unknown to the server (server, nick or channel names fit\n   this category), not enough parameters or incorrect privileges.\n\n   If a full set of parameters is presented, then each must be checked\n   for validity and appropriate responses sent back to the client.  In\n   the case of messages which use parameter lists using the comma as an\n   item separator, a reply must be sent for each item.\n\n   In the examples below, some messages appear using the full format:\n\n   :Name COMMAND parameter list\n\n   Such examples represent a message from \"Name\" in transit between\n   servers, where it is essential to include the name of the original\n   sender of the message so remote servers may send back a reply along\n   the correct path.\n\n4.1 Connection Registration\n\n   The commands described here are used to register a connection with an\n   IRC server as either a user or a server as well as correctly\n   disconnect.\n\n   A \"PASS\" command is not required for either client or server\n   connection to be registered, but it must precede the server message\n   or the latter of the NICK/USER combination.  It is strongly\n   recommended that all server connections have a password in order to\n   give some level of security to the actual connections.  The\n   recommended order for a client to register is as follows:\n\n\n\n\nOikarinen & Reed                                               [Page 13]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n           1. Pass message\n           2. Nick message\n           3. User message\n\n4.1.1 Password message\n\n\n      Command: PASS\n   Parameters: <password>\n\n   The PASS command is used to set a 'connection password'.  The\n   password can and must be set before any attempt to register the\n   connection is made.  Currently this requires that clients send a PASS\n   command before sending the NICK/USER combination and servers *must*\n   send a PASS command before any SERVER command.  The password supplied\n   must match the one contained in the C/N lines (for servers) or I\n   lines (for clients).  It is possible to send multiple PASS commands\n   before registering but only the last one sent is used for\n   verification and it may not be changed once registered.  Numeric\n   Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_ALREADYREGISTRED\n\n   Example:\n\n           PASS secretpasswordhere\n\n4.1.2 Nick message\n\n      Command: NICK\n   Parameters: <nickname> [ <hopcount> ]\n\n   NICK message is used to give user a nickname or change the previous\n   one.  The <hopcount> parameter is only used by servers to indicate\n   how far away a nick is from its home server.  A local connection has\n   a hopcount of 0.  If supplied by a client, it must be ignored.\n\n   If a NICK message arrives at a server which already knows about an\n   identical nickname for another client, a nickname collision occurs.\n   As a result of a nickname collision, all instances of the nickname\n   are removed from the server's database, and a KILL command is issued\n   to remove the nickname from all other server's database. If the NICK\n   message causing the collision was a nickname change, then the\n   original (old) nick must be removed as well.\n\n   If the server recieves an identical NICK from a client which is\n   directly connected, it may issue an ERR_NICKCOLLISION to the local\n   client, drop the NICK command, and not generate any kills.\n\n\n\nOikarinen & Reed                                               [Page 14]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   Numeric Replies:\n\n           ERR_NONICKNAMEGIVEN             ERR_ERRONEUSNICKNAME\n           ERR_NICKNAMEINUSE               ERR_NICKCOLLISION\n\n   Example:\n\n   NICK Wiz                        ; Introducing new nick \"Wiz\".\n\n   :WiZ NICK Kilroy                ; WiZ changed his nickname to Kilroy.\n\n4.1.3 User message\n\n      Command: USER\n   Parameters: <username> <hostname> <servername> <realname>\n\n   The USER message is used at the beginning of connection to specify\n   the username, hostname, servername and realname of s new user.  It is\n   also used in communication between servers to indicate new user\n   arriving on IRC, since only after both USER and NICK have been\n   received from a client does a user become registered.\n\n   Between servers USER must to be prefixed with client's NICKname.\n   Note that hostname and servername are normally ignored by the IRC\n   server when the USER command comes from a directly connected client\n   (for security reasons), but they are used in server to server\n   communication.  This means that a NICK must always be sent to a\n   remote server when a new user is being introduced to the rest of the\n   network before the accompanying USER is sent.\n\n   It must be noted that realname parameter must be the last parameter,\n   because it may contain space characters and must be prefixed with a\n   colon (':') to make sure this is recognised as such.\n\n   Since it is easy for a client to lie about its username by relying\n   solely on the USER message, the use of an \"Identity Server\" is\n   recommended.  If the host which a user connects from has such a\n   server enabled the username is set to that as in the reply from the\n   \"Identity Server\".\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_ALREADYREGISTRED\n\n   Examples:\n\n\n   USER guest tolmoon tolsun :Ronnie Reagan\n\n\n\nOikarinen & Reed                                               [Page 15]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                                   ; User registering themselves with a\n                                   username of \"guest\" and real name\n                                   \"Ronnie Reagan\".\n\n\n   :testnick USER guest tolmoon tolsun :Ronnie Reagan\n                                   ; message between servers with the\n                                   nickname for which the USER command\n                                   belongs to\n\n4.1.4 Server message\n\n      Command: SERVER\n   Parameters: <servername> <hopcount> <info>\n\n   The server message is used to tell a server that the other end of a\n   new connection is a server. This message is also used to pass server\n   data over whole net.  When a new server is connected to net,\n   information about it be broadcast to the whole network.  <hopcount>\n   is used to give all servers some internal information on how far away\n   all servers are.  With a full server list, it would be possible to\n   construct a map of the entire server tree, but hostmasks prevent this\n   from being done.\n\n   The SERVER message must only be accepted from either (a) a connection\n   which is yet to be registered and is attempting to register as a\n   server, or (b) an existing connection to another server, in  which\n   case the SERVER message is introducing a new server behind that\n   server.\n\n   Most errors that occur with the receipt of a SERVER command result in\n   the connection being terminated by the destination host (target\n   SERVER).  Error replies are usually sent using the \"ERROR\" command\n   rather than the numeric since the ERROR command has several useful\n   properties which make it useful here.\n\n   If a SERVER message is parsed and attempts to introduce a server\n   which is already known to the receiving server, the connection from\n   which that message must be closed (following the correct procedures),\n   since a duplicate route to a server has formed and the acyclic nature\n   of the IRC tree broken.\n\n   Numeric Replies:\n\n           ERR_ALREADYREGISTRED\n\n   Example:\n\n\n\n\nOikarinen & Reed                                               [Page 16]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\nSERVER test.oulu.fi 1 :[tolsun.oulu.fi] Experimental server\n                                ; New server test.oulu.fi introducing\n                                itself and attempting to register.  The\n                                name in []'s is the hostname for the\n                                host running test.oulu.fi.\n\n\n:tolsun.oulu.fi SERVER csd.bu.edu 5 :BU Central Server\n                                ; Server tolsun.oulu.fi is our uplink\n                                for csd.bu.edu which is 5 hops away.\n\n4.1.5 Oper\n\n      Command: OPER\n   Parameters: <user> <password>\n\n   OPER message is used by a normal user to obtain operator privileges.\n   The combination of <user> and <password> are required to gain\n   Operator privileges.\n\n   If the client sending the OPER command supplies the correct password\n   for the given user, the server then informs the rest of the network\n   of the new operator by issuing a \"MODE +o\" for the clients nickname.\n\n   The OPER message is client-server only.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              RPL_YOUREOPER\n           ERR_NOOPERHOST                  ERR_PASSWDMISMATCH\n\n   Example:\n\n   OPER foo bar                    ; Attempt to register as an operator\n                                   using a username of \"foo\" and \"bar\" as\n                                   the password.\n\n4.1.6 Quit\n\n      Command: QUIT\n   Parameters: [<Quit message>]\n\n   A client session is ended with a quit message.  The server must close\n   the connection to a client which sends a QUIT message. If a \"Quit\n   Message\" is given, this will be sent instead of the default message,\n   the nickname.\n\n   When netsplits (disconnecting of two servers) occur, the quit message\n\n\n\nOikarinen & Reed                                               [Page 17]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   is composed of the names of two servers involved, separated by a\n   space.  The first name is that of the server which is still connected\n   and the second name is that of the server that has become\n   disconnected.\n\n   If, for some other reason, a client connection is closed without  the\n   client  issuing  a  QUIT  command  (e.g.  client  dies and EOF occurs\n   on socket), the server is required to fill in the quit  message  with\n   some sort  of  message  reflecting the nature of the event which\n   caused it to happen.\n\n   Numeric Replies:\n\n           None.\n\n   Examples:\n\n   QUIT :Gone to have lunch        ; Preferred message format.\n\n4.1.7 Server quit message\n\n      Command: SQUIT\n   Parameters: <server> <comment>\n\n   The SQUIT message is needed to tell about quitting or dead servers.\n   If a server wishes to break the connection to another server it must\n   send a SQUIT message to the other server, using the the name of the\n   other server as the server parameter, which then closes its\n   connection to the quitting server.\n\n   This command is also available operators to help keep a network of\n   IRC servers connected in an orderly fashion.  Operators may also\n   issue an SQUIT message for a remote server connection.  In this case,\n   the SQUIT must be parsed by each server inbetween the operator and\n   the remote server, updating the view of the network held by each\n   server as explained below.\n\n   The <comment> should be supplied by all operators who execute a SQUIT\n   for a remote server (that is not connected to the server they are\n   currently on) so that other operators are aware for the reason of\n   this action.  The <comment> is also filled in by servers which may\n   place an error or similar message here.\n\n   Both of the servers which are on either side of the connection being\n   closed are required to to send out a SQUIT message (to all its other\n   server connections) for all other servers which are considered to be\n   behind that link.\n\n\n\n\nOikarinen & Reed                                               [Page 18]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   Similarly, a QUIT message must be sent to the other connected servers\n   rest of the network on behalf of all clients behind that link.  In\n   addition to this, all channel members of a channel which lost a\n   member due to the split must be sent a QUIT message.\n\n   If a server connection is terminated prematurely (e.g. the server  on\n   the  other  end  of  the  link  died),  the  server  which  detects\n   this disconnection is required to inform the rest of  the  network\n   that  the connection  has  closed  and  fill  in  the comment field\n   with something appropriate.\n\n   Numeric replies:\n\n           ERR_NOPRIVILEGES                ERR_NOSUCHSERVER\n\n   Example:\n\n   SQUIT tolsun.oulu.fi :Bad Link ? ; the server link tolson.oulu.fi has\n                                   been terminated because of \"Bad Link\".\n\n   :Trillian SQUIT cm22.eng.umd.edu :Server out of control\n                                    ; message from Trillian to disconnect\n                                   \"cm22.eng.umd.edu\" from the net\n                                    because \"Server out of control\".\n\n4.2 Channel operations\n\n   This group of messages is concerned with manipulating channels, their\n   properties (channel modes), and their contents (typically clients).\n   In implementing these, a number of race conditions are inevitable\n   when clients at opposing ends of a network send commands which will\n   ultimately clash.  It is also required that servers keep a nickname\n   history to ensure that wherever a <nick> parameter is given, the\n   server check its history in case it has recently been changed.\n\n4.2.1 Join message\n\n      Command: JOIN\n   Parameters: <channel>{,<channel>} [<key>{,<key>}]\n\n   The JOIN command is used by client to start listening a specific\n   channel. Whether or not a client is allowed to join a channel is\n   checked only by the server the client is connected to; all other\n   servers automatically add the user to the channel when it is received\n   from other servers.  The conditions which affect this are as follows:\n\n           1.  the user must be invited if the channel is invite-only;\n\n\n\n\nOikarinen & Reed                                               [Page 19]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n           2.  the user's nick/username/hostname must not match any\n               active bans;\n\n           3.  the correct key (password) must be given if it is set.\n\n   These are discussed in more detail under the MODE command (see\n   section 4.2.3 for more details).\n\n   Once a user has joined a channel, they receive notice about all\n   commands their server receives which affect the channel.  This\n   includes MODE, KICK, PART, QUIT and of course PRIVMSG/NOTICE.  The\n   JOIN command needs to be broadcast to all servers so that each server\n   knows where to find the users who are on the channel.  This allows\n   optimal delivery of PRIVMSG/NOTICE messages to the channel.\n\n   If a JOIN is successful, the user is then sent the channel's topic\n   (using RPL_TOPIC) and the list of users who are on the channel (using\n   RPL_NAMREPLY), which must include the user joining.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_BANNEDFROMCHAN\n           ERR_INVITEONLYCHAN              ERR_BADCHANNELKEY\n           ERR_CHANNELISFULL               ERR_BADCHANMASK\n           ERR_NOSUCHCHANNEL               ERR_TOOMANYCHANNELS\n           RPL_TOPIC\n\n   Examples:\n\n   JOIN #foobar                    ; join channel #foobar.\n\n   JOIN &foo fubar                 ; join channel &foo using key \"fubar\".\n\n   JOIN #foo,&bar fubar            ; join channel #foo using key \"fubar\"\n                                   and &bar using no key.\n\n   JOIN #foo,#bar fubar,foobar     ; join channel #foo using key \"fubar\".\n                                   and channel #bar using key \"foobar\".\n\n   JOIN #foo,#bar                  ; join channels #foo and #bar.\n\n   :WiZ JOIN #Twilight_zone        ; JOIN message from WiZ\n\n4.2.2 Part message\n\n      Command: PART\n   Parameters: <channel>{,<channel>}\n\n\n\n\nOikarinen & Reed                                               [Page 20]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   The PART message causes the client sending the message to be removed\n   from the list of active users for all given channels listed in the\n   parameter string.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOSUCHCHANNEL\n           ERR_NOTONCHANNEL\n\n   Examples:\n\n   PART #twilight_zone             ; leave channel \"#twilight_zone\"\n\n   PART #oz-ops,&group5            ; leave both channels \"&group5\" and\n                                   \"#oz-ops\".\n\n4.2.3 Mode message\n\n      Command: MODE\n\n   The MODE command is a dual-purpose command in IRC.  It allows both\n   usernames and channels to have their mode changed.  The rationale for\n   this choice is that one day nicknames will be obsolete and the\n   equivalent property will be the channel.\n\n   When parsing MODE messages, it is recommended that the entire message\n   be parsed first and then the changes which resulted then passed on.\n\n4.2.3.1 Channel modes\n\n   Parameters: <channel> {[+|-]|o|p|s|i|t|n|b|v} [<limit>] [<user>]\n               [<ban mask>]\n\n   The MODE command is provided so that channel operators may change the\n   characteristics of `their' channel.  It is also required that servers\n   be able to change channel modes so that channel operators may be\n   created.\n\n   The various modes available for channels are as follows:\n\n           o - give/take channel operator privileges;\n           p - private channel flag;\n           s - secret channel flag;\n           i - invite-only channel flag;\n           t - topic settable by channel operator only flag;\n           n - no messages to channel from clients on the outside;\n           m - moderated channel;\n           l - set the user limit to channel;\n\n\n\nOikarinen & Reed                                               [Page 21]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n           b - set a ban mask to keep users out;\n           v - give/take the ability to speak on a moderated channel;\n           k - set a channel key (password).\n\n   When using the 'o' and 'b' options, a restriction on a total of three\n   per mode command has been imposed.  That is, any combination of 'o'\n   and\n\n4.2.3.2 User modes\n\n   Parameters: <nickname> {[+|-]|i|w|s|o}\n\n   The user MODEs are typically changes which affect either how the\n   client is seen by others or what 'extra' messages the client is sent.\n   A user MODE command may only be accepted if both the sender of the\n   message and the nickname given as a parameter are both the same.\n\n   The available modes are as follows:\n\n           i - marks a users as invisible;\n           s - marks a user for receipt of server notices;\n           w - user receives wallops;\n           o - operator flag.\n\n   Additional modes may be available later on.\n\n   If a user attempts to make themselves an operator using the \"+o\"\n   flag, the attempt should be ignored.  There is no restriction,\n   however, on anyone `deopping' themselves (using \"-o\").  Numeric\n   Replies:\n\n           ERR_NEEDMOREPARAMS              RPL_CHANNELMODEIS\n           ERR_CHANOPRIVSNEEDED            ERR_NOSUCHNICK\n           ERR_NOTONCHANNEL                ERR_KEYSET\n           RPL_BANLIST                     RPL_ENDOFBANLIST\n           ERR_UNKNOWNMODE                 ERR_NOSUCHCHANNEL\n\n           ERR_USERSDONTMATCH              RPL_UMODEIS\n           ERR_UMODEUNKNOWNFLAG\n\n   Examples:\n\n           Use of Channel Modes:\n\nMODE #Finnish +im               ; Makes #Finnish channel moderated and\n                                'invite-only'.\n\nMODE #Finnish +o Kilroy         ; Gives 'chanop' privileges to Kilroy on\n\n\n\nOikarinen & Reed                                               [Page 22]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                                channel #Finnish.\n\nMODE #Finnish +v Wiz            ; Allow WiZ to speak on #Finnish.\n\nMODE #Fins -s                   ; Removes 'secret' flag from channel\n                                #Fins.\n\nMODE #42 +k oulu                ; Set the channel key to \"oulu\".\n\nMODE #eu-opers +l 10            ; Set the limit for the number of users\n                                on channel to 10.\n\nMODE &oulu +b                   ; list ban masks set for channel.\n\nMODE &oulu +b *!*@*             ; prevent all users from joining.\n\nMODE &oulu +b *!*@*.edu         ; prevent any user from a hostname\n                                matching *.edu from joining.\n\n        Use of user Modes:\n\n:MODE WiZ -w                    ; turns reception of WALLOPS messages\n                                off for WiZ.\n\n:Angel MODE Angel +i            ; Message from Angel to make themselves\n                                invisible.\n\nMODE WiZ -o                     ; WiZ 'deopping' (removing operator\n                                status).  The plain reverse of this\n                                command (\"MODE WiZ +o\") must not be\n                                allowed from users since would bypass\n                                the OPER command.\n\n4.2.4 Topic message\n\n      Command: TOPIC\n   Parameters: <channel> [<topic>]\n\n   The TOPIC message is used to change or view the topic of a channel.\n   The topic for channel <channel> is returned if there is no <topic>\n   given.  If the <topic> parameter is present, the topic for that\n   channel will be changed, if the channel modes permit this action.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOTONCHANNEL\n           RPL_NOTOPIC                     RPL_TOPIC\n           ERR_CHANOPRIVSNEEDED\n\n\n\nOikarinen & Reed                                               [Page 23]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   Examples:\n\n   :Wiz TOPIC #test :New topic     ;User Wiz setting the topic.\n\n   TOPIC #test :another topic      ;set the topic on #test to \"another\n                                   topic\".\n\n   TOPIC #test                     ; check the topic for #test.\n\n4.2.5 Names message\n\n      Command: NAMES\n   Parameters: [<channel>{,<channel>}]\n\n   By using the NAMES command, a user can list all nicknames that are\n   visible to them on any channel that they can see.  Channel names\n   which they can see are those which aren't private (+p) or secret (+s)\n   or those which they are actually on.  The <channel> parameter\n   specifies which channel(s) to return information about if valid.\n   There is no error reply for bad channel names.\n\n   If no <channel> parameter is given, a list of all channels and their\n   occupants is returned.  At the end of this list, a list of users who\n   are visible but either not on any channel or not on a visible channel\n   are listed as being on `channel' \"*\".\n\n   Numerics:\n\n           RPL_NAMREPLY                    RPL_ENDOFNAMES\n\n   Examples:\n\n   NAMES #twilight_zone,#42        ; list visible users on #twilight_zone\n                                   and #42 if the channels are visible to\n                                   you.\n\n   NAMES                           ; list all visible channels and users\n\n4.2.6 List message\n\n      Command: LIST\n   Parameters: [<channel>{,<channel>} [<server>]]\n\n   The list message is used to list channels and their topics.  If  the\n   <channel>  parameter  is  used,  only  the  status  of  that  channel\n   is displayed.  Private  channels  are  listed  (without  their\n   topics)  as channel \"Prv\" unless the client generating the query is\n   actually on that channel.  Likewise, secret channels are not listed\n\n\n\nOikarinen & Reed                                               [Page 24]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   at  all  unless  the client is a member of the channel in question.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER                RPL_LISTSTART\n           RPL_LIST                        RPL_LISTEND\n\n   Examples:\n\n   LIST                            ; List all channels.\n\n   LIST #twilight_zone,#42         ; List channels #twilight_zone and #42\n\n4.2.7 Invite message\n\n      Command: INVITE\n   Parameters: <nickname> <channel>\n\n   The INVITE message is used to invite users to a channel.  The\n   parameter <nickname> is the nickname of the person to be invited to\n   the target channel <channel>.  There is no requirement that the\n   channel the target user is being invited to must exist or be a valid\n   channel.  To invite a user to a channel which is invite only (MODE\n   +i), the client sending the invite must be recognised as being a\n   channel operator on the given channel.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOSUCHNICK\n           ERR_NOTONCHANNEL                ERR_USERONCHANNEL\n           ERR_CHANOPRIVSNEEDED\n           RPL_INVITING                    RPL_AWAY\n\n   Examples:\n\n   :Angel INVITE Wiz #Dust         ; User Angel inviting WiZ to channel\n                                   #Dust\n\n   INVITE Wiz #Twilight_Zone       ; Command to invite WiZ to\n                                   #Twilight_zone\n\n4.2.8 Kick command\n\n      Command: KICK\n   Parameters: <channel> <user> [<comment>]\n\n   The KICK command can be  used  to  forcibly  remove  a  user  from  a\n   channel.   It  'kicks  them  out'  of the channel (forced PART).\n\n\n\nOikarinen & Reed                                               [Page 25]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   Only a channel operator may kick another user out of a  channel.\n   Each  server that  receives  a KICK message checks that it is valid\n   (ie the sender is actually a  channel  operator)  before  removing\n   the  victim  from  the channel.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOSUCHCHANNEL\n           ERR_BADCHANMASK                 ERR_CHANOPRIVSNEEDED\n           ERR_NOTONCHANNEL\n\n   Examples:\n\nKICK &Melbourne Matthew         ; Kick Matthew from &Melbourne\n\nKICK #Finnish John :Speaking English\n                                ; Kick John from #Finnish using\n                                \"Speaking English\" as the reason\n                                (comment).\n\n:WiZ KICK #Finnish John         ; KICK message from WiZ to remove John\n                                from channel #Finnish\n\nNOTE:\n     It is possible to extend the KICK command parameters to the\nfollowing:\n\n<channel>{,<channel>} <user>{,<user>} [<comment>]\n\n4.3 Server queries and commands\n\n   The server query group of commands has been designed to return\n   information about any server which is connected to the network.  All\n   servers connected must respond to these queries and respond\n   correctly.  Any invalid response (or lack thereof) must be considered\n   a sign of a broken server and it must be disconnected/disabled as\n   soon as possible until the situation is remedied.\n\n   In these queries, where a parameter appears as \"<server>\", it will\n   usually mean it can be a nickname or a server or a wildcard name of\n   some sort.  For each parameter, however, only one query and set of\n   replies is to be generated.\n\n4.3.1 Version message\n\n      Command: VERSION\n   Parameters: [<server>]\n\n\n\n\nOikarinen & Reed                                               [Page 26]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   The VERSION message is used  to  query  the  version  of  the  server\n   program.  An optional parameter <server> is used to query the version\n   of the server program which a client is not directly connected to.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER                RPL_VERSION\n\n   Examples:\n\n   :Wiz VERSION *.se               ; message from Wiz to check the version\n                                   of a server matching \"*.se\"\n\n   VERSION tolsun.oulu.fi          ; check the version of server\n                                   \"tolsun.oulu.fi\".\n\n4.3.2 Stats message\n\n      Command: STATS\n   Parameters: [<query> [<server>]]\n\n   The stats message is used to query statistics of certain server.  If\n   <server> parameter is omitted, only the end of stats reply is sent\n   back.  The implementation of this command is highly dependent on the\n   server which replies, although the server must be able to supply\n   information as described by the queries below (or similar).\n\n   A query may be given by any single letter which is only checked by\n   the destination server (if given as the <server> parameter) and is\n   otherwise passed on by intermediate servers, ignored and unaltered.\n   The following queries are those found in the current IRC\n   implementation and provide a large portion of the setup information\n   for that server.  Although these may not be supported in the same way\n   by other versions, all servers should be able to supply a valid reply\n   to a STATS query which is consistent with the reply formats currently\n   used and the purpose of the query.\n\n   The currently supported queries are:\n\n           c - returns a list of servers which the server may connect\n               to or allow connections from;\n           h - returns a list of servers which are either forced to be\n               treated as leaves or allowed to act as hubs;\n           i - returns a list of hosts which the server allows a client\n               to connect from;\n           k - returns a list of banned username/hostname combinations\n               for that server;\n           l - returns a list of the server's connections, showing how\n\n\n\nOikarinen & Reed                                               [Page 27]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n               long each connection has been established and the traffic\n               over that connection in bytes and messages for each\n               direction;\n           m - returns a list of commands supported by the server and\n               the usage count for each if the usage count is non zero;\n           o - returns a list of hosts from which normal clients may\n               become operators;\n           y - show Y (Class) lines from server's configuration file;\n           u - returns a string showing how long the server has been up.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_STATSCLINE                  RPL_STATSNLINE\n           RPL_STATSILINE                  RPL_STATSKLINE\n           RPL_STATSQLINE                  RPL_STATSLLINE\n           RPL_STATSLINKINFO               RPL_STATSUPTIME\n           RPL_STATSCOMMANDS               RPL_STATSOLINE\n           RPL_STATSHLINE                  RPL_ENDOFSTATS\n\n   Examples:\n\nSTATS m                         ; check the command usage for the server\n                                you are connected to\n\n:Wiz STATS c eff.org            ; request by WiZ for C/N line\n                                information from server eff.org\n\n4.3.3 Links message\n\n      Command: LINKS\n   Parameters: [[<remote server>] <server mask>]\n\n   With LINKS, a user can list all servers which are known by the server\n   answering the query.  The returned list of servers must match the\n   mask, or if no mask is given, the full list is returned.\n\n   If <remote server> is given in addition to <server mask>, the LINKS\n   command is forwarded to the first server found that matches that name\n   (if any), and that server is then required to answer the query.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_LINKS                       RPL_ENDOFLINKS\n\n   Examples:\n\n\n\n\nOikarinen & Reed                                               [Page 28]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\nLINKS *.au                      ; list all servers which have a name\n                                that matches *.au;\n\n:WiZ LINKS *.bu.edu *.edu       ; LINKS message from WiZ to the first\n                                server matching *.edu for a list of\n                                servers matching *.bu.edu.\n\n4.3.4 Time message\n\n      Command: TIME\n   Parameters: [<server>]\n\n   The time message is used to query local time from the specified\n   server. If the server parameter is not given, the server handling the\n   command must reply to the query.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER                RPL_TIME\n\n   Examples:\n\n   TIME tolsun.oulu.fi             ; check the time on the server\n                                   \"tolson.oulu.fi\"\n\n   Angel TIME *.au                 ; user angel checking the time on a\n                                   server matching \"*.au\"\n\n4.3.5 Connect message\n\n      Command: CONNECT\n   Parameters: <target server> [<port> [<remote server>]]\n\n   The CONNECT command can be used to force a server to try to establish\n   a new connection to another server immediately.  CONNECT is a\n   privileged command and is to be available only to IRC Operators.  If\n   a remote server is given then the CONNECT attempt is made by that\n   server to <target server> and <port>.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER                ERR_NOPRIVILEGES\n           ERR_NEEDMOREPARAMS\n\n   Examples:\n\nCONNECT tolsun.oulu.fi          ; Attempt to connect a server to\n                                tolsun.oulu.fi\n\n\n\nOikarinen & Reed                                               [Page 29]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n:WiZ CONNECT eff.org 6667 csd.bu.edu\n                                ; CONNECT attempt by WiZ to get servers\n                                eff.org and csd.bu.edu connected on port\n                                6667.\n\n4.3.6 Trace message\n\n      Command: TRACE\n   Parameters: [<server>]\n\n   TRACE command is used to find the route to specific server.  Each\n   server that processes this message must tell the sender about it by\n   sending a reply indicating it is a pass-through link, forming a chain\n   of replies similar to that gained from using \"traceroute\".  After\n   sending this reply back, it must then send the TRACE message to the\n   next server until given server is reached.  If the <server> parameter\n   is omitted, it is recommended that TRACE command send a message to\n   the sender telling which servers the current server has direct\n   connection to.\n\n   If the destination given by \"<server>\" is an actual server, then the\n   destination server is required to report all servers and users which\n   are connected to it, although only operators are permitted to see\n   users present.  If the destination given by <server> is a nickname,\n   they only a reply for that nickname is given.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n\n   If the TRACE message is destined for another server, all intermediate\n   servers must return a RPL_TRACELINK reply to indicate that the TRACE\n   passed through it and where its going next.\n\n           RPL_TRACELINK\n   A TRACE reply may be composed of any number of the following numeric\n   replies.\n\n           RPL_TRACECONNECTING             RPL_TRACEHANDSHAKE\n           RPL_TRACEUNKNOWN                RPL_TRACEOPERATOR\n           RPL_TRACEUSER                   RPL_TRACESERVER\n           RPL_TRACESERVICE                RPL_TRACENEWTYPE\n           RPL_TRACECLASS\n\n   Examples:\n\nTRACE *.oulu.fi                 ; TRACE to a server matching *.oulu.fi\n\n\n\n\nOikarinen & Reed                                               [Page 30]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n:WiZ TRACE AngelDust            ; TRACE issued by WiZ to nick AngelDust\n\n4.3.7 Admin command\n\n      Command: ADMIN\n   Parameters: [<server>]\n\n   The admin message is used to find the name of the administrator of\n   the given server, or current server if <server> parameter is omitted.\n   Each server must have the ability to forward ADMIN messages to other\n   servers.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_ADMINME                     RPL_ADMINLOC1\n           RPL_ADMINLOC2                   RPL_ADMINEMAIL\n\n   Examples:\n\n   ADMIN tolsun.oulu.fi            ; request an ADMIN reply from\n                                   tolsun.oulu.fi\n\n   :WiZ ADMIN *.edu                ; ADMIN request from WiZ for first\n                                   server found to match *.edu.\n\n4.3.8 Info command\n\n      Command: INFO\n   Parameters: [<server>]\n\n   The INFO command is required to return information which describes\n   the server: its version, when it was compiled, the patchlevel, when\n   it was started, and any other miscellaneous information which may be\n   considered to be relevant.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_INFO                        RPL_ENDOFINFO\n\n   Examples:\n\n   INFO csd.bu.edu                 ; request an INFO reply from\n   csd.bu.edu\n\n   :Avalon INFO *.fi               ; INFO request from Avalon for first\n                                   server found to match *.fi.\n\n\n\nOikarinen & Reed                                               [Page 31]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   INFO Angel                      ; request info from the server that\n                                   Angel is connected to.\n\n4.4 Sending messages\n\n   The main purpose of the IRC protocol is to provide a base for clients\n   to communicate with each other.  PRIVMSG and NOTICE are the only\n   messages available which actually perform delivery of a text message\n   from one client to another - the rest just make it possible and try\n   to ensure it happens in a reliable and structured manner.\n\n4.4.1 Private messages\n\n      Command: PRIVMSG\n   Parameters: <receiver>{,<receiver>} <text to be sent>\n\n   PRIVMSG is used to send private messages between users.  <receiver>\n   is the nickname of the receiver of the message.  <receiver> can also\n   be a list of names or channels separated with commas.\n\n   The <receiver> parameter may also me a host mask  (#mask)  or  server\n   mask  ($mask).   In  both cases the server will only send the PRIVMSG\n   to those who have a server or host matching the mask.  The mask  must\n   have at  least  1  (one)  \".\"  in it and no wildcards following the\n   last \".\".  This requirement exists to prevent people sending messages\n   to  \"#*\"  or \"$*\",  which  would  broadcast  to  all  users; from\n   experience, this is abused more than used responsibly and properly.\n   Wildcards are  the  '*' and  '?'   characters.   This  extension  to\n   the PRIVMSG command is only available to Operators.\n\n   Numeric Replies:\n\n           ERR_NORECIPIENT                 ERR_NOTEXTTOSEND\n           ERR_CANNOTSENDTOCHAN            ERR_NOTOPLEVEL\n           ERR_WILDTOPLEVEL                ERR_TOOMANYTARGETS\n           ERR_NOSUCHNICK\n           RPL_AWAY\n\n   Examples:\n\n:Angel PRIVMSG Wiz :Hello are you receiving this message ?\n                                ; Message from Angel to Wiz.\n\nPRIVMSG Angel :yes I'm receiving it !receiving it !'u>(768u+1n) .br ;\n                                Message to Angel.\n\nPRIVMSG jto@tolsun.oulu.fi :Hello !\n                                ; Message to a client on server\n\n\n\nOikarinen & Reed                                               [Page 32]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                                tolsun.oulu.fi with username of \"jto\".\n\nPRIVMSG $*.fi :Server tolsun.oulu.fi rebooting.\n                                ; Message to everyone on a server which\n                                has a name matching *.fi.\n\nPRIVMSG #*.edu :NSFNet is undergoing work, expect interruptions\n                                ; Message to all users who come from a\n                                host which has a name matching *.edu.\n\n4.4.2 Notice\n\n      Command: NOTICE\n   Parameters: <nickname> <text>\n\n   The NOTICE message is used similarly to PRIVMSG.  The difference\n   between NOTICE and PRIVMSG is that automatic replies must never be\n   sent in response to a NOTICE message.  This rule applies to servers\n   too - they must not send any error reply back to the client on\n   receipt of a notice.  The object of this rule is to avoid loops\n   between a client automatically sending something in response to\n   something it received.  This is typically used by automatons (clients\n   with either an AI or other interactive program controlling their\n   actions) which are always seen to be replying lest they end up in a\n   loop with another automaton.\n\n   See PRIVMSG for more details on replies and examples.\n\n4.5 User based queries\n\n   User queries are a group of commands which are primarily concerned\n   with finding details on a particular user or group users.  When using\n   wildcards with any of these commands, if they match, they will only\n   return information on users who are 'visible' to you.  The visibility\n   of a user is determined as a combination of the user's mode and the\n   common set of channels you are both on.\n\n4.5.1 Who query\n\n      Command: WHO\n   Parameters: [<name> [<o>]]\n\n   The WHO message is used by a client to generate a query which returns\n   a list of information which 'matches' the <name> parameter given by\n   the client.  In the absence of the <name> parameter, all visible\n   (users who aren't invisible (user mode +i) and who don't have a\n   common channel with the requesting client) are listed.  The same\n   result can be achieved by using a <name> of \"0\" or any wildcard which\n\n\n\nOikarinen & Reed                                               [Page 33]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   will end up matching every entry possible.\n\n   The <name> passed to WHO is matched against users' host, server, real\n   name and nickname if the channel <name> cannot be found.\n\n   If the \"o\" parameter is passed only operators are returned according\n   to the name mask supplied.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_WHOREPLY                    RPL_ENDOFWHO\n\n   Examples:\n\n   WHO *.fi                        ; List all users who match against\n                                   \"*.fi\".\n\n   WHO jto* o                      ; List all users with a match against\n                                   \"jto*\" if they are an operator.\n\n4.5.2 Whois query\n\n      Command: WHOIS\n   Parameters: [<server>] <nickmask>[,<nickmask>[,...]]\n\n   This message is used to query information about particular user.  The\n   server will answer this message with several numeric messages\n   indicating different statuses of each user which matches the nickmask\n   (if you are entitled to see them).  If no wildcard is present in the\n   <nickmask>, any information about that nick which you are allowed to\n   see is presented.  A comma (',') separated list of nicknames may be\n   given.\n\n   The latter version sends the query to a specific server.  It is\n   useful if you want to know how long the user in question has been\n   idle as only local server (ie. the server the user is directly\n   connected to) knows that information, while everything else is\n   globally known.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER                ERR_NONICKNAMEGIVEN\n           RPL_WHOISUSER                   RPL_WHOISCHANNELS\n           RPL_WHOISCHANNELS               RPL_WHOISSERVER\n           RPL_AWAY                        RPL_WHOISOPERATOR\n           RPL_WHOISIDLE                   ERR_NOSUCHNICK\n           RPL_ENDOFWHOIS\n\n\n\nOikarinen & Reed                                               [Page 34]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   Examples:\n\n   WHOIS wiz                       ; return available user information\n                                   about nick WiZ\n\n   WHOIS eff.org trillian          ; ask server eff.org for user\n                                   information about trillian\n\n4.5.3 Whowas\n\n      Command: WHOWAS\n   Parameters: <nickname> [<count> [<server>]]\n\n   Whowas asks for information about a nickname which no longer exists.\n   This may either be due to a nickname change or the user leaving IRC.\n   In response to this query, the server searches through its nickname\n   history, looking for any nicks which are lexically the same (no wild\n   card matching here).  The history is searched backward, returning the\n   most recent entry first.  If there are multiple entries, up to\n   <count> replies will be returned (or all of them if no <count>\n   parameter is given).  If a non-positive number is passed as being\n   <count>, then a full search is done.\n\n   Numeric Replies:\n\n           ERR_NONICKNAMEGIVEN             ERR_WASNOSUCHNICK\n           RPL_WHOWASUSER                  RPL_WHOISSERVER\n           RPL_ENDOFWHOWAS\n\n   Examples:\n\n   WHOWAS Wiz                      ; return all information in the nick\n                                   history about nick \"WiZ\";\n\n   WHOWAS Mermaid 9                ; return at most, the 9 most recent\n                                   entries in the nick history for\n                                   \"Mermaid\";\n\n   WHOWAS Trillian 1 *.edu         ; return the most recent history for\n                                   \"Trillian\" from the first server found\n                                   to match \"*.edu\".\n\n4.6 Miscellaneous messages\n\n   Messages in this category do not fit into any of the above categories\n   but are nonetheless still a part of and required by the protocol.\n\n\n\n\n\nOikarinen & Reed                                               [Page 35]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n4.6.1 Kill message\n\n      Command: KILL\n   Parameters: <nickname> <comment>\n\n   The KILL message is used to cause a client-server connection to be\n   closed by the server which has the actual connection.  KILL is used\n   by servers when they encounter a duplicate entry in the list of valid\n   nicknames and is used to remove both entries.  It is also available\n   to operators.\n\n   Clients which have automatic reconnect algorithms effectively make\n   this command useless since the disconnection is only brief.  It does\n   however break the flow of data and can be used to stop large amounts\n   of being abused, any user may elect to receive KILL messages\n   generated for others to keep an 'eye' on would be trouble spots.\n\n   In an arena where nicknames are required to be globally unique at all\n   times, KILL messages are sent whenever 'duplicates' are detected\n   (that is an attempt to register two users with the same nickname) in\n   the hope that both of them will disappear and only 1 reappear.\n\n   The comment given must reflect the actual reason for the KILL.  For\n   server-generated KILLs it usually is made up of details concerning\n   the origins of the two conflicting nicknames.  For users it is left\n   up to them to provide an adequate reason to satisfy others who see\n   it.  To prevent/discourage fake KILLs from being generated to hide\n   the identify of the KILLer, the comment also shows a 'kill-path'\n   which is updated by each server it passes through, each prepending\n   its name to the path.\n\n   Numeric Replies:\n\n           ERR_NOPRIVILEGES                ERR_NEEDMOREPARAMS\n           ERR_NOSUCHNICK                  ERR_CANTKILLSERVER\n\n\n   KILL David (csd.bu.edu <- tolsun.oulu.fi)\n                                   ; Nickname collision between csd.bu.edu\n                                   and tolson.oulu.fi\n\n\n   NOTE:\n   It is recommended that only Operators be allowed to kill other users\n   with KILL message.  In an ideal world not even operators would need\n   to do this and it would be left to servers to deal with.\n\n\n\n\n\nOikarinen & Reed                                               [Page 36]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n4.6.2 Ping message\n\n      Command: PING\n   Parameters: <server1> [<server2>]\n\n   The PING message is used to test the presence of an active client at\n   the other end of the connection.  A PING message is sent at regular\n   intervals if no other activity detected coming from a connection.  If\n   a connection fails to respond to a PING command within a set amount\n   of time, that connection is closed.\n\n   Any client which receives a PING message must respond to <server1>\n   (server which sent the PING message out) as quickly as possible with\n   an appropriate PONG message to indicate it is still there and alive.\n   Servers should not respond to PING commands but rely on PINGs from\n   the other end of the connection to indicate the connection is alive.\n   If the <server2> parameter is specified, the PING message gets\n   forwarded there.\n\n   Numeric Replies:\n\n           ERR_NOORIGIN                    ERR_NOSUCHSERVER\n\n   Examples:\n\n   PING tolsun.oulu.fi             ; server sending a PING message to\n                                   another server to indicate it is still\n                                   alive.\n\n   PING WiZ                        ; PING message being sent to nick WiZ\n\n4.6.3 Pong message\n\n      Command: PONG\n   Parameters: <daemon> [<daemon2>]\n\n   PONG message is a reply to ping message.  If parameter <daemon2> is\n   given this message must be forwarded to given daemon.  The <daemon>\n   parameter is the name of the daemon who has responded to PING message\n   and generated this message.\n\n   Numeric Replies:\n\n           ERR_NOORIGIN                    ERR_NOSUCHSERVER\n\n   Examples:\n\n   PONG csd.bu.edu tolsun.oulu.fi  ; PONG message from csd.bu.edu to\n\n\n\nOikarinen & Reed                                               [Page 37]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                                   tolsun.oulu.fi\n\n4.6.4 Error\n\n      Command: ERROR\n   Parameters: <error message>\n\n   The ERROR command is for use by servers when reporting a serious or\n   fatal error to its operators.  It may also be sent from one server to\n   another but must not be accepted from any normal unknown clients.\n\n   An ERROR message is for use for reporting errors which occur with a\n   server-to-server link only.  An ERROR message is sent to the server\n   at the other end (which sends it to all of its connected operators)\n   and to all operators currently connected.  It is not to be passed\n   onto any other servers by a server if it is received from a server.\n\n   When a server sends a received ERROR message to its operators, the\n   message should be encapsulated inside a NOTICE message, indicating\n   that the client was not responsible for the error.\n\n   Numerics:\n\n           None.\n\n   Examples:\n\n   ERROR :Server *.fi already exists; ERROR message to the other server\n                                   which caused this error.\n\n   NOTICE WiZ :ERROR from csd.bu.edu -- Server *.fi already exists\n                                   ; Same ERROR message as above but sent\n                                   to user WiZ on the other server.\n\n5. OPTIONALS\n\n   This section describes OPTIONAL messages.  They are not required in a\n   working server implementation of the protocol described herein.  In\n   the absence of the option, an error reply message must be generated\n   or an unknown command error.  If the message is destined for another\n   server to answer then it must be passed on (elementary parsing\n   required) The allocated numerics for this are listed with the\n   messages below.\n\n5.1 Away\n\n      Command: AWAY\n   Parameters: [message]\n\n\n\nOikarinen & Reed                                               [Page 38]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   With the AWAY message, clients can set an automatic reply string for\n   any PRIVMSG commands directed at them (not to a channel they are on).\n   The automatic reply is sent by the server to client sending the\n   PRIVMSG command.  The only replying server is the one to which the\n   sending client is connected to.\n\n   The AWAY message is used either with one parameter (to set an AWAY\n   message) or with no parameters (to remove the AWAY message).\n\n   Numeric Replies:\n\n           RPL_UNAWAY                      RPL_NOWAWAY\n\n   Examples:\n\n   AWAY :Gone to lunch.  Back in 5 ; set away message to \"Gone to lunch.\n                                   Back in 5\".\n\n   :WiZ AWAY                       ; unmark WiZ as being away.\n\n\n5.2 Rehash message\n\n      Command: REHASH\n   Parameters: None\n\n   The rehash message can be used by the operator to force the server to\n   re-read and process its configuration file.\n\n   Numeric Replies:\n\n        RPL_REHASHING                   ERR_NOPRIVILEGES\n\nExamples:\n\nREHASH                          ; message from client with operator\n                                status to server asking it to reread its\n                                configuration file.\n\n5.3 Restart message\n\n      Command: RESTART\n   Parameters: None\n\n   The restart message can only be used by an operator to force a server\n   restart itself.  This message is optional since it may be viewed as a\n   risk to allow arbitrary people to connect to a server as an operator\n   and execute this command, causing (at least) a disruption to service.\n\n\n\nOikarinen & Reed                                               [Page 39]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   The RESTART command must always be fully processed by the server to\n   which the sending client is connected and not be passed onto other\n   connected servers.\n\n   Numeric Replies:\n\n           ERR_NOPRIVILEGES\n\n   Examples:\n\n   RESTART                         ; no parameters required.\n\n5.4 Summon message\n\n      Command: SUMMON\n   Parameters: <user> [<server>]\n\n   The SUMMON command can be used to give users who are on a host\n   running an IRC server a message asking them to please join IRC.  This\n   message is only sent if the target server (a) has SUMMON enabled, (b)\n   the user is logged in and (c) the server process can write to the\n   user's tty (or similar).\n\n   If no <server> parameter is given it tries to summon <user> from the\n   server the client is connected to is assumed as the target.\n\n   If summon is not enabled in a server, it must return the\n   ERR_SUMMONDISABLED numeric and pass the summon message onwards.\n\n   Numeric Replies:\n\n           ERR_NORECIPIENT                 ERR_FILEERROR\n           ERR_NOLOGIN                     ERR_NOSUCHSERVER\n           RPL_SUMMONING\n\n   Examples:\n\n   SUMMON jto                      ; summon user jto on the server's host\n\n   SUMMON jto tolsun.oulu.fi       ; summon user jto on the host which a\n                                   server named \"tolsun.oulu.fi\" is\n                                   running.\n\n\n5.5 Users\n\n      Command: USERS\n   Parameters: [<server>]\n\n\n\nOikarinen & Reed                                               [Page 40]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   The USERS command returns a list of users logged into the server in a\n   similar  format  to  who(1),  rusers(1)  and finger(1).  Some people\n   may disable this command on their server for security related\n   reasons.   If disabled, the correct numeric must be returned to\n   indicate this.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER                ERR_FILEERROR\n           RPL_USERSSTART                  RPL_USERS\n           RPL_NOUSERS                     RPL_ENDOFUSERS\n           ERR_USERSDISABLED\n\n   Disabled Reply:\n\n           ERR_USERSDISABLED\n\n   Examples:\n\nUSERS eff.org                   ; request a list of users logged in on\n                                server eff.org\n\n:John USERS tolsun.oulu.fi      ; request from John for a list of users\n                                logged in on server tolsun.oulu.fi\n\n5.6 Operwall message\n\n      Command: WALLOPS\n   Parameters: Text to be sent to all operators currently online\n\n   Sends  a  message  to  all   operators   currently   online.    After\n   implementing  WALLOPS  as  a user command it was found that it was\n   often and commonly abused as a means of sending a message to a lot\n   of  people (much  similar to WALL).  Due to this it is recommended\n   that the current implementation of  WALLOPS  be  used  as  an\n   example  by  allowing  and recognising only servers as the senders of\n   WALLOPS.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS\n\n   Examples:\n\n   :csd.bu.edu WALLOPS :Connect '*.uiuc.edu 6667' from Joshua; WALLOPS\n                                   message from csd.bu.edu announcing a\n                                   CONNECT message it received and acted\n                                   upon from Joshua.\n\n\n\nOikarinen & Reed                                               [Page 41]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n5.7 Userhost message\n\n      Command: USERHOST\n   Parameters: <nickname>{<space><nickname>}\n\n   The USERHOST command takes a list of up to 5 nicknames, each\n   separated by a space character and returns a list of information\n   about each nickname that it found.  The returned list has each reply\n   separated by a space.\n\n   Numeric Replies:\n\n           RPL_USERHOST                    ERR_NEEDMOREPARAMS\n\n   Examples:\n\n   USERHOST Wiz Michael Marty p    ;USERHOST request for information on\n                                   nicks \"Wiz\", \"Michael\", \"Marty\" and \"p\"\n\n5.8 Ison message\n\n      Command: ISON\n   Parameters: <nickname>{<space><nickname>}\n\n   The ISON command was implemented to provide  a  quick  and  efficient\n   means  to get a response about whether a given nickname was currently\n   on IRC. ISON only takes one (1) parameter: a space-separated list of\n   nicks.  For  each  nickname in the list that is present, the server\n   adds that to its reply string.  Thus the reply string may return\n   empty (none  of  the given  nicks are present), an exact copy of the\n   parameter string (all of them present) or as any other subset of the\n   set of nicks  given  in  the parameter.  The only limit on the number\n   of nicks that may be checked is that the combined length must not be\n   too large as to cause the server to chop it off so it fits in 512\n   characters.\n\n   ISON is only be processed by the server local to the client sending\n   the command and thus not passed onto other servers for further\n   processing.\n\n   Numeric Replies:\n\n           RPL_ISON                ERR_NEEDMOREPARAMS\n\n   Examples:\n\n   ISON phone trillian WiZ jarlek Avalon Angel Monstah\n                                   ; Sample ISON request for 7 nicks.\n\n\n\nOikarinen & Reed                                               [Page 42]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n6. REPLIES\n\n   The following is a list of numeric replies which are generated in\n   response to the commands given above.  Each numeric is given with its\n   number, name and reply string.\n\n6.1 Error Replies.\n\n        401     ERR_NOSUCHNICK\n                        \"<nickname> :No such nick/channel\"\n\n                - Used to indicate the nickname parameter supplied to a\n                  command is currently unused.\n\n        402     ERR_NOSUCHSERVER\n                        \"<server name> :No such server\"\n\n                - Used to indicate the server name given currently\n                  doesn't exist.\n\n        403     ERR_NOSUCHCHANNEL\n                        \"<channel name> :No such channel\"\n\n                - Used to indicate the given channel name is invalid.\n\n        404     ERR_CANNOTSENDTOCHAN\n                        \"<channel name> :Cannot send to channel\"\n\n                - Sent to a user who is either (a) not on a channel\n                  which is mode +n or (b) not a chanop (or mode +v) on\n                  a channel which has mode +m set and is trying to send\n                  a PRIVMSG message to that channel.\n\n        405     ERR_TOOMANYCHANNELS\n                        \"<channel name> :You have joined too many \\\n                         channels\"\n                - Sent to a user when they have joined the maximum\n                  number of allowed channels and they try to join\n                  another channel.\n\n        406     ERR_WASNOSUCHNICK\n                        \"<nickname> :There was no such nickname\"\n\n                - Returned by WHOWAS to indicate there is no history\n                  information for that nickname.\n\n        407     ERR_TOOMANYTARGETS\n                        \"<target> :Duplicate recipients. No message \\\n\n\n\nOikarinen & Reed                                               [Page 43]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                         delivered\"\n\n                - Returned to a client which is attempting to send a\n                  PRIVMSG/NOTICE using the user@host destination format\n                  and for a user@host which has several occurrences.\n\n        409     ERR_NOORIGIN\n                        \":No origin specified\"\n\n                - PING or PONG message missing the originator parameter\n                  which is required since these commands must work\n                  without valid prefixes.\n\n        411     ERR_NORECIPIENT\n                        \":No recipient given (<command>)\"\n        412     ERR_NOTEXTTOSEND\n                        \":No text to send\"\n        413     ERR_NOTOPLEVEL\n                        \"<mask> :No toplevel domain specified\"\n        414     ERR_WILDTOPLEVEL\n                        \"<mask> :Wildcard in toplevel domain\"\n\n                - 412 - 414 are returned by PRIVMSG to indicate that\n                  the message wasn't delivered for some reason.\n                  ERR_NOTOPLEVEL and ERR_WILDTOPLEVEL are errors that\n                  are returned when an invalid use of\n                  \"PRIVMSG $<server>\" or \"PRIVMSG #<host>\" is attempted.\n\n        421     ERR_UNKNOWNCOMMAND\n                        \"<command> :Unknown command\"\n\n                - Returned to a registered client to indicate that the\n                  command sent is unknown by the server.\n\n        422     ERR_NOMOTD\n                        \":MOTD File is missing\"\n\n                - Server's MOTD file could not be opened by the server.\n\n        423     ERR_NOADMININFO\n                        \"<server> :No administrative info available\"\n\n                - Returned by a server in response to an ADMIN message\n                  when there is an error in finding the appropriate\n                  information.\n\n        424     ERR_FILEERROR\n                \":File error doing <file op> on <file>\"\n\n\n\nOikarinen & Reed                                               [Page 44]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                - Generic error message used to report a failed file\n                  operation during the processing of a message.\n\n        431     ERR_NONICKNAMEGIVEN\n                        \":No nickname given\"\n\n                - Returned when a nickname parameter expected for a\n                  command and isn't found.\n\n        432     ERR_ERRONEUSNICKNAME\n                        \"<nick> :Erroneus nickname\"\n\n                - Returned after receiving a NICK message which contains\n                  characters which do not fall in the defined set.  See\n                  section x.x.x for details on valid nicknames.\n\n        433     ERR_NICKNAMEINUSE\n                        \"<nick> :Nickname is already in use\"\n\n                - Returned when a NICK message is processed that results\n                  in an attempt to change to a currently existing\n                  nickname.\n\n        436     ERR_NICKCOLLISION\n                        \"<nick> :Nickname collision KILL\"\n\n                - Returned by a server to a client when it detects a\n                  nickname collision (registered of a NICK that\n                  already exists by another server).\n\n        441     ERR_USERNOTINCHANNEL\n                        \"<nick> <channel> :They aren't on that channel\"\n\n                - Returned by the server to indicate that the target\n                  user of the command is not on the given channel.\n\n        442     ERR_NOTONCHANNEL\n                        \"<channel> :You're not on that channel\"\n\n                - Returned by the server whenever a client tries to\n                  perform a channel effecting command for which the\n                  client isn't a member.\n\n        443     ERR_USERONCHANNEL\n                        \"<user> <channel> :is already on channel\"\n\n                - Returned when a client tries to invite a user to a\n                  channel they are already on.\n\n\n\nOikarinen & Reed                                               [Page 45]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n        444     ERR_NOLOGIN\n                        \"<user> :User not logged in\"\n\n                - Returned by the summon after a SUMMON command for a\n                  user was unable to be performed since they were not\n                  logged in.\n\n        445     ERR_SUMMONDISABLED\n                        \":SUMMON has been disabled\"\n\n                - Returned as a response to the SUMMON command.  Must be\n                  returned by any server which does not implement it.\n\n        446     ERR_USERSDISABLED\n                        \":USERS has been disabled\"\n\n                - Returned as a response to the USERS command.  Must be\n                  returned by any server which does not implement it.\n\n        451     ERR_NOTREGISTERED\n                        \":You have not registered\"\n\n                - Returned by the server to indicate that the client\n                  must be registered before the server will allow it\n                  to be parsed in detail.\n\n        461     ERR_NEEDMOREPARAMS\n                        \"<command> :Not enough parameters\"\n\n                - Returned by the server by numerous commands to\n                  indicate to the client that it didn't supply enough\n                  parameters.\n\n        462     ERR_ALREADYREGISTRED\n                        \":You may not reregister\"\n\n                - Returned by the server to any link which tries to\n                  change part of the registered details (such as\n                  password or user details from second USER message).\n\n\n        463     ERR_NOPERMFORHOST\n                        \":Your host isn't among the privileged\"\n\n                - Returned to a client which attempts to register with\n                  a server which does not been setup to allow\n                  connections from the host the attempted connection\n                  is tried.\n\n\n\nOikarinen & Reed                                               [Page 46]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n        464     ERR_PASSWDMISMATCH\n                        \":Password incorrect\"\n\n                - Returned to indicate a failed attempt at registering\n                  a connection for which a password was required and\n                  was either not given or incorrect.\n\n        465     ERR_YOUREBANNEDCREEP\n                        \":You are banned from this server\"\n\n                - Returned after an attempt to connect and register\n                  yourself with a server which has been setup to\n                  explicitly deny connections to you.\n\n        467     ERR_KEYSET\n                        \"<channel> :Channel key already set\"\n        471     ERR_CHANNELISFULL\n                        \"<channel> :Cannot join channel (+l)\"\n        472     ERR_UNKNOWNMODE\n                        \"<char> :is unknown mode char to me\"\n        473     ERR_INVITEONLYCHAN\n                        \"<channel> :Cannot join channel (+i)\"\n        474     ERR_BANNEDFROMCHAN\n                        \"<channel> :Cannot join channel (+b)\"\n        475     ERR_BADCHANNELKEY\n                        \"<channel> :Cannot join channel (+k)\"\n        481     ERR_NOPRIVILEGES\n                        \":Permission Denied- You're not an IRC operator\"\n\n                - Any command requiring operator privileges to operate\n                  must return this error to indicate the attempt was\n                  unsuccessful.\n\n        482     ERR_CHANOPRIVSNEEDED\n                        \"<channel> :You're not channel operator\"\n\n                - Any command requiring 'chanop' privileges (such as\n                  MODE messages) must return this error if the client\n                  making the attempt is not a chanop on the specified\n                  channel.\n\n        483     ERR_CANTKILLSERVER\n                        \":You cant kill a server!\"\n\n                - Any attempts to use the KILL command on a server\n                  are to be refused and this error returned directly\n                  to the client.\n\n\n\n\nOikarinen & Reed                                               [Page 47]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n        491     ERR_NOOPERHOST\n                        \":No O-lines for your host\"\n\n                - If a client sends an OPER message and the server has\n                  not been configured to allow connections from the\n                  client's host as an operator, this error must be\n                  returned.\n\n        501     ERR_UMODEUNKNOWNFLAG\n                        \":Unknown MODE flag\"\n\n                - Returned by the server to indicate that a MODE\n                  message was sent with a nickname parameter and that\n                  the a mode flag sent was not recognized.\n\n        502     ERR_USERSDONTMATCH\n                        \":Cant change mode for other users\"\n\n                - Error sent to any user trying to view or change the\n                  user mode for a user other than themselves.\n\n6.2 Command responses.\n\n        300     RPL_NONE\n                        Dummy reply number. Not used.\n\n        302     RPL_USERHOST\n                        \":[<reply>{<space><reply>}]\"\n\n                - Reply format used by USERHOST to list replies to\n                  the query list.  The reply string is composed as\n                  follows:\n\n                  <reply> ::= <nick>['*'] '=' <'+'|'-'><hostname>\n\n                  The '*' indicates whether the client has registered\n                  as an Operator.  The '-' or '+' characters represent\n                  whether the client has set an AWAY message or not\n                  respectively.\n\n        303     RPL_ISON\n                        \":[<nick> {<space><nick>}]\"\n\n                - Reply format used by ISON to list replies to the\n                  query list.\n\n        301     RPL_AWAY\n                        \"<nick> :<away message>\"\n\n\n\nOikarinen & Reed                                               [Page 48]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n        305     RPL_UNAWAY\n                        \":You are no longer marked as being away\"\n        306     RPL_NOWAWAY\n                        \":You have been marked as being away\"\n\n                - These replies are used with the AWAY command (if\n                  allowed).  RPL_AWAY is sent to any client sending a\n                  PRIVMSG to a client which is away.  RPL_AWAY is only\n                  sent by the server to which the client is connected.\n                  Replies RPL_UNAWAY and RPL_NOWAWAY are sent when the\n                  client removes and sets an AWAY message.\n\n        311     RPL_WHOISUSER\n                        \"<nick> <user> <host> * :<real name>\"\n        312     RPL_WHOISSERVER\n                        \"<nick> <server> :<server info>\"\n        313     RPL_WHOISOPERATOR\n                        \"<nick> :is an IRC operator\"\n        317     RPL_WHOISIDLE\n                        \"<nick> <integer> :seconds idle\"\n        318     RPL_ENDOFWHOIS\n                        \"<nick> :End of /WHOIS list\"\n        319     RPL_WHOISCHANNELS\n                        \"<nick> :{[@|+]<channel><space>}\"\n\n                - Replies 311 - 313, 317 - 319 are all replies\n                  generated in response to a WHOIS message.  Given that\n                  there are enough parameters present, the answering\n                  server must either formulate a reply out of the above\n                  numerics (if the query nick is found) or return an\n                  error reply.  The '*' in RPL_WHOISUSER is there as\n                  the literal character and not as a wild card.  For\n                  each reply set, only RPL_WHOISCHANNELS may appear\n                  more than once (for long lists of channel names).\n                  The '@' and '+' characters next to the channel name\n                  indicate whether a client is a channel operator or\n                  has been granted permission to speak on a moderated\n                  channel.  The RPL_ENDOFWHOIS reply is used to mark\n                  the end of processing a WHOIS message.\n\n        314     RPL_WHOWASUSER\n                        \"<nick> <user> <host> * :<real name>\"\n        369     RPL_ENDOFWHOWAS\n                        \"<nick> :End of WHOWAS\"\n\n                - When replying to a WHOWAS message, a server must use\n                  the replies RPL_WHOWASUSER, RPL_WHOISSERVER or\n                  ERR_WASNOSUCHNICK for each nickname in the presented\n\n\n\nOikarinen & Reed                                               [Page 49]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                  list.  At the end of all reply batches, there must\n                  be RPL_ENDOFWHOWAS (even if there was only one reply\n                  and it was an error).\n\n        321     RPL_LISTSTART\n                        \"Channel :Users  Name\"\n        322     RPL_LIST\n                        \"<channel> <# visible> :<topic>\"\n        323     RPL_LISTEND\n                        \":End of /LIST\"\n\n                - Replies RPL_LISTSTART, RPL_LIST, RPL_LISTEND mark\n                  the start, actual replies with data and end of the\n                  server's response to a LIST command.  If there are\n                  no channels available to return, only the start\n                  and end reply must be sent.\n\n        324     RPL_CHANNELMODEIS\n                        \"<channel> <mode> <mode params>\"\n\n        331     RPL_NOTOPIC\n                        \"<channel> :No topic is set\"\n        332     RPL_TOPIC\n                        \"<channel> :<topic>\"\n\n                - When sending a TOPIC message to determine the\n                  channel topic, one of two replies is sent.  If\n                  the topic is set, RPL_TOPIC is sent back else\n                  RPL_NOTOPIC.\n\n        341     RPL_INVITING\n                        \"<channel> <nick>\"\n\n                - Returned by the server to indicate that the\n                  attempted INVITE message was successful and is\n                  being passed onto the end client.\n\n        342     RPL_SUMMONING\n                        \"<user> :Summoning user to IRC\"\n\n                - Returned by a server answering a SUMMON message to\n                  indicate that it is summoning that user.\n\n        351     RPL_VERSION\n                        \"<version>.<debuglevel> <server> :<comments>\"\n\n                - Reply by the server showing its version details.\n                  The <version> is the version of the software being\n\n\n\nOikarinen & Reed                                               [Page 50]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                  used (including any patchlevel revisions) and the\n                  <debuglevel> is used to indicate if the server is\n                  running in \"debug mode\".\n\n                  The \"comments\" field may contain any comments about\n                  the version or further version details.\n\n        352     RPL_WHOREPLY\n                        \"<channel> <user> <host> <server> <nick> \\\n                         <H|G>[*][@|+] :<hopcount> <real name>\"\n        315     RPL_ENDOFWHO\n                        \"<name> :End of /WHO list\"\n\n                - The RPL_WHOREPLY and RPL_ENDOFWHO pair are used\n                  to answer a WHO message.  The RPL_WHOREPLY is only\n                  sent if there is an appropriate match to the WHO\n                  query.  If there is a list of parameters supplied\n                  with a WHO message, a RPL_ENDOFWHO must be sent\n                  after processing each list item with <name> being\n                  the item.\n\n        353     RPL_NAMREPLY\n                        \"<channel> :[[@|+]<nick> [[@|+]<nick> [...]]]\"\n        366     RPL_ENDOFNAMES\n                        \"<channel> :End of /NAMES list\"\n\n                - To reply to a NAMES message, a reply pair consisting\n                  of RPL_NAMREPLY and RPL_ENDOFNAMES is sent by the\n                  server back to the client.  If there is no channel\n                  found as in the query, then only RPL_ENDOFNAMES is\n                  returned.  The exception to this is when a NAMES\n                  message is sent with no parameters and all visible\n                  channels and contents are sent back in a series of\n                  RPL_NAMEREPLY messages with a RPL_ENDOFNAMES to mark\n                  the end.\n\n        364     RPL_LINKS\n                        \"<mask> <server> :<hopcount> <server info>\"\n        365     RPL_ENDOFLINKS\n                        \"<mask> :End of /LINKS list\"\n\n                - In replying to the LINKS message, a server must send\n                  replies back using the RPL_LINKS numeric and mark the\n                  end of the list using an RPL_ENDOFLINKS reply.\n\n        367     RPL_BANLIST\n                        \"<channel> <banid>\"\n        368     RPL_ENDOFBANLIST\n\n\n\nOikarinen & Reed                                               [Page 51]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                        \"<channel> :End of channel ban list\"\n\n                - When listing the active 'bans' for a given channel,\n                  a server is required to send the list back using the\n                  RPL_BANLIST and RPL_ENDOFBANLIST messages.  A separate\n                  RPL_BANLIST is sent for each active banid.  After the\n                  banids have been listed (or if none present) a\n                  RPL_ENDOFBANLIST must be sent.\n\n        371     RPL_INFO\n                        \":<string>\"\n        374     RPL_ENDOFINFO\n                        \":End of /INFO list\"\n\n                - A server responding to an INFO message is required to\n                  send all its 'info' in a series of RPL_INFO messages\n                  with a RPL_ENDOFINFO reply to indicate the end of the\n                  replies.\n\n        375     RPL_MOTDSTART\n                        \":- <server> Message of the day - \"\n        372     RPL_MOTD\n                        \":- <text>\"\n        376     RPL_ENDOFMOTD\n                        \":End of /MOTD command\"\n\n                - When responding to the MOTD message and the MOTD file\n                  is found, the file is displayed line by line, with\n                  each line no longer than 80 characters, using\n                  RPL_MOTD format replies.  These should be surrounded\n                  by a RPL_MOTDSTART (before the RPL_MOTDs) and an\n                  RPL_ENDOFMOTD (after).\n\n        381     RPL_YOUREOPER\n                        \":You are now an IRC operator\"\n\n                - RPL_YOUREOPER is sent back to a client which has\n                  just successfully issued an OPER message and gained\n                  operator status.\n\n        382     RPL_REHASHING\n                        \"<config file> :Rehashing\"\n\n                - If the REHASH option is used and an operator sends\n                  a REHASH message, an RPL_REHASHING is sent back to\n                  the operator.\n\n        391     RPL_TIME\n\n\n\nOikarinen & Reed                                               [Page 52]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                        \"<server> :<string showing server's local time>\"\n\n                - When replying to the TIME message, a server must send\n                  the reply using the RPL_TIME format above.  The string\n                  showing the time need only contain the correct day and\n                  time there.  There is no further requirement for the\n                  time string.\n\n        392     RPL_USERSSTART\n                        \":UserID   Terminal  Host\"\n        393     RPL_USERS\n                        \":%-8s %-9s %-8s\"\n        394     RPL_ENDOFUSERS\n                        \":End of users\"\n        395     RPL_NOUSERS\n                        \":Nobody logged in\"\n\n                - If the USERS message is handled by a server, the\n                  replies RPL_USERSTART, RPL_USERS, RPL_ENDOFUSERS and\n                  RPL_NOUSERS are used.  RPL_USERSSTART must be sent\n                  first, following by either a sequence of RPL_USERS\n                  or a single RPL_NOUSER.  Following this is\n                  RPL_ENDOFUSERS.\n\n        200     RPL_TRACELINK\n                        \"Link <version & debug level> <destination> \\\n                         <next server>\"\n        201     RPL_TRACECONNECTING\n                        \"Try. <class> <server>\"\n        202     RPL_TRACEHANDSHAKE\n                        \"H.S. <class> <server>\"\n        203     RPL_TRACEUNKNOWN\n                        \"???? <class> [<client IP address in dot form>]\"\n        204     RPL_TRACEOPERATOR\n                        \"Oper <class> <nick>\"\n        205     RPL_TRACEUSER\n                        \"User <class> <nick>\"\n        206     RPL_TRACESERVER\n                        \"Serv <class> <int>S <int>C <server> \\\n                         <nick!user|*!*>@<host|server>\"\n        208     RPL_TRACENEWTYPE\n                        \"<newtype> 0 <client name>\"\n        261     RPL_TRACELOG\n                        \"File <logfile> <debug level>\"\n\n                - The RPL_TRACE* are all returned by the server in\n                  response to the TRACE message.  How many are\n                  returned is dependent on the the TRACE message and\n\n\n\nOikarinen & Reed                                               [Page 53]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                  whether it was sent by an operator or not.  There\n                  is no predefined order for which occurs first.\n                  Replies RPL_TRACEUNKNOWN, RPL_TRACECONNECTING and\n                  RPL_TRACEHANDSHAKE are all used for connections\n                  which have not been fully established and are either\n                  unknown, still attempting to connect or in the\n                  process of completing the 'server handshake'.\n                  RPL_TRACELINK is sent by any server which handles\n                  a TRACE message and has to pass it on to another\n                  server.  The list of RPL_TRACELINKs sent in\n                  response to a TRACE command traversing the IRC\n                  network should reflect the actual connectivity of\n                  the servers themselves along that path.\n                  RPL_TRACENEWTYPE is to be used for any connection\n                  which does not fit in the other categories but is\n                  being displayed anyway.\n\n        211     RPL_STATSLINKINFO\n                        \"<linkname> <sendq> <sent messages> \\\n                         <sent bytes> <received messages> \\\n                         <received bytes> <time open>\"\n        212     RPL_STATSCOMMANDS\n                        \"<command> <count>\"\n        213     RPL_STATSCLINE\n                        \"C <host> * <name> <port> <class>\"\n        214     RPL_STATSNLINE\n                        \"N <host> * <name> <port> <class>\"\n        215     RPL_STATSILINE\n                        \"I <host> * <host> <port> <class>\"\n        216     RPL_STATSKLINE\n                        \"K <host> * <username> <port> <class>\"\n        218     RPL_STATSYLINE\n                        \"Y <class> <ping frequency> <connect \\\n                         frequency> <max sendq>\"\n        219     RPL_ENDOFSTATS\n                        \"<stats letter> :End of /STATS report\"\n        241     RPL_STATSLLINE\n                        \"L <hostmask> * <servername> <maxdepth>\"\n        242     RPL_STATSUPTIME\n                        \":Server Up %d days %d:%02d:%02d\"\n        243     RPL_STATSOLINE\n                        \"O <hostmask> * <name>\"\n        244     RPL_STATSHLINE\n                        \"H <hostmask> * <servername>\"\n\n        221     RPL_UMODEIS\n                        \"<user mode string>\"\n\n\n\n\nOikarinen & Reed                                               [Page 54]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n                        - To answer a query about a client's own mode,\n                          RPL_UMODEIS is sent back.\n\n        251     RPL_LUSERCLIENT\n                        \":There are <integer> users and <integer> \\\n                         invisible on <integer> servers\"\n        252     RPL_LUSEROP\n                        \"<integer> :operator(s) online\"\n        253     RPL_LUSERUNKNOWN\n                        \"<integer> :unknown connection(s)\"\n        254     RPL_LUSERCHANNELS\n                        \"<integer> :channels formed\"\n        255     RPL_LUSERME\n                        \":I have <integer> clients and <integer> \\\n                          servers\"\n\n                        - In processing an LUSERS message, the server\n                          sends a set of replies from RPL_LUSERCLIENT,\n                          RPL_LUSEROP, RPL_USERUNKNOWN,\n                          RPL_LUSERCHANNELS and RPL_LUSERME.  When\n                          replying, a server must send back\n                          RPL_LUSERCLIENT and RPL_LUSERME.  The other\n                          replies are only sent back if a non-zero count\n                          is found for them.\n\n        256     RPL_ADMINME\n                        \"<server> :Administrative info\"\n        257     RPL_ADMINLOC1\n                        \":<admin info>\"\n        258     RPL_ADMINLOC2\n                        \":<admin info>\"\n        259     RPL_ADMINEMAIL\n                        \":<admin info>\"\n\n                        - When replying to an ADMIN message, a server\n                          is expected to use replies RLP_ADMINME\n                          through to RPL_ADMINEMAIL and provide a text\n                          message with each.  For RPL_ADMINLOC1 a\n                          description of what city, state and country\n                          the server is in is expected, followed by\n                          details of the university and department\n                          (RPL_ADMINLOC2) and finally the administrative\n                          contact for the server (an email address here\n                          is required) in RPL_ADMINEMAIL.\n\n\n\n\n\n\n\nOikarinen & Reed                                               [Page 55]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n6.3 Reserved numerics.\n\n   These numerics are not described above since they fall into one of\n   the following categories:\n\n        1. no longer in use;\n\n        2. reserved for future planned use;\n\n        3. in current use but are part of a non-generic 'feature' of\n           the current IRC server.\n\n        209     RPL_TRACECLASS          217     RPL_STATSQLINE\n        231     RPL_SERVICEINFO         232     RPL_ENDOFSERVICES\n        233     RPL_SERVICE             234     RPL_SERVLIST\n        235     RPL_SERVLISTEND\n        316     RPL_WHOISCHANOP         361     RPL_KILLDONE\n        362     RPL_CLOSING             363     RPL_CLOSEEND\n        373     RPL_INFOSTART           384     RPL_MYPORTIS\n        466     ERR_YOUWILLBEBANNED     476     ERR_BADCHANMASK\n        492     ERR_NOSERVICEHOST\n\n7. Client and server authentication\n\n   Clients and servers are both subject to the same level of\n   authentication.  For both, an IP number to hostname lookup (and\n   reverse check on this) is performed for all connections made to the\n   server.  Both connections are then subject to a password check (if\n   there is a password set for that connection).  These checks are\n   possible on all connections although the password check is only\n   commonly used with servers.\n\n   An additional check that is becoming of more and more common is that\n   of the username responsible for making the connection.  Finding the\n   username of the other end of the connection typically involves\n   connecting to an authentication server such as IDENT as described in\n   RFC 1413.\n\n   Given that without passwords it is not easy to reliably determine who\n   is on the other end of a network connection, use of passwords is\n   strongly recommended on inter-server connections in addition to any\n   other measures such as using an ident server.\n\n8. Current implementations\n\n   The only current implementation of this protocol is the IRC server,\n   version 2.8. Earlier versions may implement some or all of the\n   commands described by this document with NOTICE messages replacing\n\n\n\nOikarinen & Reed                                               [Page 56]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   many of the numeric replies.  Unfortunately, due to backward\n   compatibility requirements, the implementation of some parts of this\n   document varies with what is laid out.  On notable difference is:\n\n        * recognition that any LF or CR anywhere in a message marks the\n          end of that message (instead of requiring CR-LF);\n\n   The rest of this section deals with issues that are mostly of\n   importance to those who wish to implement a server but some parts\n   also apply directly to clients as well.\n\n8.1 Network protocol: TCP - why it is best used here.\n\n   IRC has been implemented on top of TCP since TCP supplies a reliable\n   network protocol which is well suited to this scale of conferencing.\n   The use of multicast IP is an alternative, but it is not widely\n   available or supported at the present time.\n\n8.1.1 Support of Unix sockets\n\n   Given that Unix domain sockets allow listen/connect operations, the\n   current implementation can be configured to listen and accept both\n   client and server connections on a Unix domain socket.  These are\n   recognized as sockets where the hostname starts with a '/'.\n\n   When providing any information about the connections on a Unix domain\n   socket, the server is required to supplant the actual hostname in\n   place of the pathname unless the actual socket name is being asked\n   for.\n\n8.2 Command Parsing\n\n   To provide useful 'non-buffered' network IO for clients and servers,\n   each connection is given its own private 'input buffer' in which the\n   results of the most recent read and parsing are kept.  A buffer size\n   of 512 bytes is used so as to hold 1 full message, although, this\n   will usually hold several commands.  The private buffer is parsed\n   after every read operation for valid messages.  When dealing with\n   multiple messages from one client in the buffer, care should be taken\n   in case one happens to cause the client to be 'removed'.\n\n8.3 Message delivery\n\n   It is common to find network links saturated or hosts to which you\n   are sending data unable to send data.  Although Unix typically\n   handles this through the TCP window and internal buffers, the server\n   often has large amounts of data to send (especially when a new\n   server-server link forms) and the small buffers provided in the\n\n\n\nOikarinen & Reed                                               [Page 57]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   kernel are not enough for the outgoing queue.  To alleviate this\n   problem, a \"send queue\" is used as a FIFO queue for data to be sent.\n   A typical \"send queue\" may grow to 200 Kbytes on a large IRC network\n   with a slow network connection when a new server connects.\n\n   When polling its connections, a server will first read and parse all\n   incoming data, queuing any data to be sent out. When all available\n   input is processed, the queued data is sent. This reduces the number\n   of write() system calls and helps TCP make bigger packets.\n\n8.4 Connection 'Liveness'\n\n   To detect when a connection has died or become unresponsive, the\n   server must ping each of its connections that it doesn't get a\n   response from in a given amount of time.\n\n   If a connection doesn't respond in time, its connection is closed\n   using the appropriate procedures.  A connection is also dropped if\n   its sendq grows beyond the maximum allowed, because it is better to\n   close a slow connection than have a server process block.\n\n8.5 Establishing a server to client connection\n\n   Upon connecting to an IRC server, a client is sent the MOTD (if\n   present) as well as the current user/server count (as per the LUSER\n   command).  The server is also required to give an unambiguous message\n   to the client which states its name and version as well as any other\n   introductory messages which may be deemed appropriate.\n\n   After dealing with this, the server must then send out the new user's\n   nickname and other information as supplied by itself (USER command)\n   and as the server could discover (from DNS/authentication servers).\n   The server must send this information out with NICK first followed by\n   USER.\n\n8.6 Establishing a server-server connection.\n\n   The process of establishing of a server-to-server connection is\n   fraught with danger since there are many possible areas where\n   problems can occur - the least of which are race conditions.\n\n   After a server has received a connection following by a PASS/SERVER\n   pair which were recognised as being valid, the server should then\n   reply with its own PASS/SERVER information for that connection as\n   well as all of the other state information it knows about as\n   described below.\n\n   When the initiating server receives a PASS/SERVER pair, it too then\n\n\n\nOikarinen & Reed                                               [Page 58]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   checks that the server responding is authenticated properly before\n   accepting the connection to be that server.\n\n8.6.1 Server exchange of state information when connecting\n\n   The order of state information being exchanged between servers is\n   essential.  The required order is as follows:\n\n        * all known other servers;\n\n        * all known user information;\n\n        * all known channel information.\n\n   Information regarding servers is sent via extra SERVER messages, user\n   information with NICK/USER/MODE/JOIN messages and channels with MODE\n   messages.\n\n   NOTE: channel topics are *NOT* exchanged here because the TOPIC\n   command overwrites any old topic information, so at best, the two\n   sides of the connection would exchange topics.\n\n   By passing the state information about servers first, any collisions\n   with servers that already exist occur before nickname collisions due\n   to a second server introducing a particular nickname.  Due to the IRC\n   network only being able to exist as an acyclic graph, it may be\n   possible that the network has already reconnected in another\n   location, the place where the collision occurs indicating where the\n   net needs to split.\n\n8.7 Terminating server-client connections\n\n   When a client connection closes, a QUIT message is generated on\n   behalf of the client by the server to which the client connected.  No\n   other message is to be generated or used.\n\n8.8 Terminating server-server connections\n\n   If a server-server connection is closed, either via a remotely\n   generated SQUIT or 'natural' causes, the rest of the connected IRC\n   network must have its information updated with by the server which\n   detected the closure.  The server then sends a list of SQUITs (one\n   for each server behind that connection) and a list of QUITs (again,\n   one for each client behind that connection).\n\n\n\n\n\n\n\nOikarinen & Reed                                               [Page 59]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n8.9 Tracking nickname changes\n\n   All IRC servers are required to keep a history of recent nickname\n   changes.  This is required to allow the server to have a chance of\n   keeping in touch of things when nick-change race conditions occur\n   with commands which manipulate them.  Commands which must trace nick\n   changes are:\n\n        * KILL (the nick being killed)\n\n        * MODE (+/- o,v)\n\n        * KICK (the nick being kicked)\n\n   No other commands are to have nick changes checked for.\n\n   In the above cases, the server is required to first check for the\n   existence of the nickname, then check its history to see who that\n   nick currently belongs to (if anyone!).  This reduces the chances of\n   race conditions but they can still occur with the server ending up\n   affecting the wrong client.  When performing a change trace for an\n   above command it is recommended that a time range be given and\n   entries which are too old ignored.\n\n   For a reasonable history, a server should be able to keep previous\n   nickname for every client it knows about if they all decided to\n   change.  This size is limited by other factors (such as memory, etc).\n\n8.10 Flood control of clients\n\n   With a large network of interconnected IRC servers, it is quite easy\n   for any single client attached to the network to supply a continuous\n   stream of messages that result in not only flooding the network, but\n   also degrading the level of service provided to others.  Rather than\n   require every 'victim' to be provide their own protection, flood\n   protection was written into the server and is applied to all clients\n   except services.  The current algorithm is as follows:\n\n        * check to see if client's `message timer' is less than\n          current time (set to be equal if it is);\n\n        * read any data present from the client;\n\n        * while the timer is less than ten seconds ahead of the current\n          time, parse any present messages and penalize the client by\n          2 seconds for each message;\n\n   which in essence means that the client may send 1 message every 2\n\n\n\nOikarinen & Reed                                               [Page 60]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   seconds without being adversely affected.\n\n8.11 Non-blocking lookups\n\n   In a real-time environment, it is essential that a server process do\n   as little waiting as possible so that all the clients are serviced\n   fairly.  Obviously this requires non-blocking IO on all network\n   read/write operations.  For normal server connections, this was not\n   difficult, but there are other support operations that may cause the\n   server to block (such as disk reads).  Where possible, such activity\n   should be performed with a short timeout.\n\n8.11.1 Hostname (DNS) lookups\n\n   Using the standard resolver libraries from Berkeley and others has\n   meant large delays in some cases where replies have timed out.  To\n   avoid this, a separate set of DNS routines were written which were\n   setup for non-blocking IO operations and then polled from within the\n   main server IO loop.\n\n8.11.2 Username (Ident) lookups\n\n   Although there are numerous ident libraries for use and inclusion\n   into other programs, these caused problems since they operated in a\n   synchronous manner and resulted in frequent delays.  Again the\n   solution was to write a set of routines which would cooperate with\n   the rest of the server and work using non-blocking IO.\n\n8.12 Configuration File\n\n   To provide a flexible way of setting up and running the server, it is\n   recommended that a configuration file be used which contains\n   instructions to the server on the following:\n\n        * which hosts to accept client connections from;\n\n        * which hosts to allow to connect as servers;\n\n        * which hosts to connect to (both actively and\n          passively);\n\n        * information about where the server is (university,\n          city/state, company are examples of this);\n\n        * who is responsible for the server and an email address\n          at which they can be contacted;\n\n        * hostnames and passwords for clients which wish to be given\n\n\n\nOikarinen & Reed                                               [Page 61]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n          access to restricted operator commands.\n\n   In specifying hostnames, both domain names and use of the 'dot'\n   notation (127.0.0.1) should both be accepted.  It must be possible to\n   specify the password to be used/accepted for all outgoing and\n   incoming connections (although the only outgoing connections are\n   those to other servers).\n\n   The above list is the minimum requirement for any server which wishes\n   to make a connection with another server.  Other items which may be\n   of use are:\n\n        * specifying which servers other server may introduce;\n\n        * how deep a server branch is allowed to become;\n\n        * hours during which clients may connect.\n\n8.12.1 Allowing clients to connect\n\n   A server should use some sort of 'access control list' (either in the\n   configuration file or elsewhere) that is read at startup and used to\n   decide what hosts clients may use to connect to it.\n\n   Both 'deny' and 'allow' should be implemented to provide the required\n   flexibility for host access control.\n\n8.12.2 Operators\n\n   The granting of operator privileges to a disruptive person can have\n   dire consequences for the well-being of the IRC net in general due to\n   the powers given to them.  Thus, the acquisition of such powers\n   should not be very easy.  The current setup requires two 'passwords'\n   to be used although one of them is usually easy guessed.  Storage of\n   oper passwords in configuration files is preferable to hard coding\n   them in and should be stored in a crypted format (ie using crypt(3)\n   from Unix) to prevent easy theft.\n\n8.12.3 Allowing servers to connect\n\n   The interconnection of server is not a trivial matter: a bad\n   connection can have a large impact on the usefulness of IRC.  Thus,\n   each server should have a list of servers to which it may connect and\n   which servers may connect to it.  Under no circumstances should a\n   server allow an arbitrary host to connect as a server.  In addition\n   to which servers may and may not connect, the configuration file\n   should also store the password and other characteristics of that\n   link.\n\n\n\nOikarinen & Reed                                               [Page 62]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n8.12.4 Administrivia\n\n   To provide accurate and valid replies to the ADMIN command (see\n   section 4.3.7), the server should find the relevant details in the\n   configuration.\n\n8.13 Channel membership\n\n   The current server allows any registered local user to join upto 10\n   different channels.  There is no limit imposed on non-local users so\n   that the server remains (reasonably) consistant with all others on a\n   channel membership basis\n\n9. Current problems\n\n   There are a number of recognized problems with this protocol, all  of\n   which  hope to be solved sometime in the near future during its\n   rewrite.  Currently, work is underway to find working solutions to\n   these problems.\n\n9.1 Scalability\n\n   It is widely recognized that this protocol does not scale\n   sufficiently well when used in a large arena.  The main problem comes\n   from the requirement that all servers know about all other servers\n   and users and that information regarding them be updated as soon as\n   it changes.  It is also desirable to keep the number of servers low\n   so that the path length between any two points is kept minimal and\n   the spanning tree as strongly branched as possible.\n\n9.2 Labels\n\n   The current IRC protocol has 3 types of labels: the nickname, the\n   channel name and the server name.  Each of the three types has its\n   own domain and no duplicates are allowed inside that domain.\n   Currently, it is possible for users to pick the label for any of the\n   three, resulting in collisions.  It is widely recognized that this\n   needs reworking, with a plan for unique names for channels and nicks\n   that don't collide being desirable as well as a solution allowing a\n   cyclic tree.\n\n9.2.1 Nicknames\n\n   The idea of the nickname on IRC is very convenient for users to use\n   when talking to each other outside of a channel, but there is only a\n   finite nickname space and being what they are, its not uncommon for\n   several people to want to use the same nick.  If a nickname is chosen\n   by two people using this protocol, either one will not succeed or\n\n\n\nOikarinen & Reed                                               [Page 63]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\n   both will removed by use of KILL (4.6.1).\n\n9.2.2 Channels\n\n   The current channel layout requires that all servers know about all\n   channels, their inhabitants and properties.  Besides not scaling\n   well, the issue of privacy is also a concern.  A collision of\n   channels is treated as an inclusive event (both people who create the\n   new channel are considered to be members of it) rather than an\n   exclusive one such as used to solve nickname collisions.\n\n9.2.3 Servers\n\n   Although the number of servers is usually small relative to the\n   number of users and channels, they two currently required to be known\n   globally, either each one separately or hidden behind a mask.\n\n9.3 Algorithms\n\n   In some places within the server code, it has not  been  possible  to\n   avoid  N^2  algorithms  such  as  checking  the channel list of a set\n   of clients.\n\n   In current server versions, there are no database consistency checks,\n   each server assumes that a neighbouring server is correct.  This\n   opens the door to large problems if a connecting server is buggy or\n   otherwise tries to introduce contradictions to the existing net.\n\n   Currently, because of the lack of unique internal and global labels,\n   there are a multitude of race conditions that exist.  These race\n   conditions generally arise from the problem of it taking time for\n   messages to traverse and effect the IRC network.  Even by changing to\n   unique labels, there are problems with channel-related commands being\n   disrupted.\n\n10. Current support and availability\n\n           Mailing lists for IRC related discussion:\n                Future protocol: ircd-three-request@eff.org\n                General discussion: operlist-request@eff.org\n\n           Software implemenations\n                cs.bu.edu:/irc\n                nic.funet.fi:/pub/irc\n                coombs.anu.edu.au:/pub/irc\n\n           Newsgroup: alt.irc\n\n\n\n\nOikarinen & Reed                                               [Page 64]\n\f\nRFC 1459              Internet Relay Chat Protocol              May 1993\n\n\nSecurity Considerations\n\n   Security issues are discussed in sections 4.1, 4.1.1, 4.1.3, 5.5, and\n   7.\n\n12. Authors' Addresses\n\n   Jarkko Oikarinen\n   Tuirantie 17 as 9\n   90500 OULU\n   FINLAND\n\n   Email: jto@tolsun.oulu.fi\n\n\n   Darren Reed\n   4 Pateman Street\n   Watsonia, Victoria 3087\n   Australia\n\n   Email: avalon@coombs.anu.edu.au\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nOikarinen & Reed                                               [Page 65]\n\f"
  },
  {
    "path": "irc3/rfc2812.txt",
    "content": "\n\n\n\n\n\nNetwork Working Group                                            C. Kalt\nRequest for Comments: 2812                                    April 2000\nUpdates: 1459\nCategory: Informational\n\n\n                  Internet Relay Chat: Client Protocol\n\nStatus of this Memo\n\n   This memo provides information for the Internet community.  It does\n   not specify an Internet standard of any kind.  Distribution of this\n   memo is unlimited.\n\nCopyright Notice\n\n   Copyright (C) The Internet Society (2000).  All Rights Reserved.\n\nIESG NOTE:\n\n   The IRC protocol itself enables several possibilities of transferring\n   data between clients, and just like with other transfer mechanisms\n   like email, the receiver of the data has to be careful about how the\n   data is handled. For more information on security issues with the IRC\n   protocol, see for example http://www.irchelp.org/irchelp/security/.\n\nAbstract\n\n   The IRC (Internet Relay Chat) protocol is for use with text based\n   conferencing; the simplest client being any socket program capable of\n   connecting to the server.\n\n   This document defines the Client Protocol, and assumes that the\n   reader is familiar with the IRC Architecture [IRC-ARCH].\n\nTable of Contents\n\n   1.  Labels .....................................................   3\n      1.1  Servers ................................................   3\n      1.2  Clients ................................................   3\n         1.2.1  Users .............................................   4\n            1.2.1.1  Operators ....................................   4\n         1.2.2  Services ..........................................   4\n      1.3  Channels ...............................................   4\n   2.  The IRC Client Specification ...............................   5\n      2.1  Overview ...............................................   5\n      2.2  Character codes ........................................   5\n      2.3  Messages ...............................................   5\n\n\n\nKalt                         Informational                      [Page 1]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n         2.3.1  Message format in Augmented BNF ...................   6\n      2.4  Numeric replies ........................................   8\n      2.5  Wildcard expressions ...................................   9\n   3.  Message Details ............................................   9\n      3.1  Connection Registration ................................  10\n         3.1.1  Password message ..................................  10\n         3.1.2  Nick message ......................................  10\n         3.1.3  User message ......................................  11\n         3.1.4  Oper message ......................................  12\n         3.1.5  User mode message .................................  12\n         3.1.6  Service message ...................................  13\n         3.1.7  Quit ..............................................  14\n         3.1.8  Squit .............................................  15\n      3.2  Channel operations .....................................  15\n         3.2.1  Join message ......................................  16\n         3.2.2  Part message ......................................  17\n         3.2.3  Channel mode message ..............................  18\n         3.2.4  Topic message .....................................  19\n         3.2.5  Names message .....................................  20\n         3.2.6  List message ......................................  21\n         3.2.7  Invite message ....................................  21\n         3.2.8  Kick command ......................................  22\n      3.3  Sending messages .......................................  23\n         3.3.1  Private messages ..................................  23\n         3.3.2  Notice ............................................  24\n      3.4  Server queries and commands ............................  25\n         3.4.1  Motd message ......................................  25\n         3.4.2  Lusers message ....................................  25\n         3.4.3  Version message ...................................  26\n         3.4.4  Stats message .....................................  26\n         3.4.5  Links message .....................................  27\n         3.4.6  Time message ......................................  28\n         3.4.7  Connect message ...................................  28\n         3.4.8  Trace message .....................................  29\n         3.4.9  Admin command .....................................  30\n         3.4.10 Info command ......................................  31\n      3.5  Service Query and Commands .............................  31\n         3.5.1  Servlist message ..................................  31\n         3.5.2  Squery ............................................  32\n      3.6  User based queries .....................................  32\n         3.6.1  Who query .........................................  32\n         3.6.2  Whois query .......................................  33\n         3.6.3  Whowas ............................................  34\n      3.7  Miscellaneous messages .................................  34\n         3.7.1  Kill message ......................................  35\n         3.7.2  Ping message ......................................  36\n         3.7.3  Pong message ......................................  37\n         3.7.4  Error .............................................  37\n\n\n\nKalt                         Informational                      [Page 2]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   4.  Optional features ..........................................  38\n      4.1  Away ...................................................  38\n      4.2  Rehash message .........................................  39\n      4.3  Die message ............................................  39\n      4.4  Restart message ........................................  40\n      4.5  Summon message .........................................  40\n      4.6  Users ..................................................  41\n      4.7  Operwall message .......................................  41\n      4.8  Userhost message .......................................  42\n      4.9  Ison message ...........................................  42\n   5.  Replies ....................................................  43\n      5.1  Command responses ......................................  43\n      5.2  Error Replies ..........................................  53\n      5.3  Reserved numerics ......................................  59\n   6.  Current implementations ....................................  60\n   7.  Current problems ...........................................  60\n      7.1  Nicknames ..............................................  60\n      7.2  Limitation of wildcards ................................  61\n      7.3  Security considerations ................................  61\n   8.  Current support and availability ...........................  61\n   9.  Acknowledgements ...........................................  61\n   10.  References ................................................  62\n   11.  Author's Address ..........................................  62\n   12.  Full Copyright Statement ..................................  63\n\n1. Labels\n\n   This section defines the identifiers used for the various components\n   of the IRC protocol.\n\n1.1 Servers\n\n   Servers are uniquely identified by their name, which has a maximum\n   length of sixty three (63) characters.  See the protocol grammar\n   rules (section 2.3.1) for what may and may not be used in a server\n   name.\n\n1.2 Clients\n\n   For each client all servers MUST have the following information: a\n   netwide unique identifier (whose format depends on the type of\n   client) and the server which introduced the client.\n\n\n\n\n\n\n\n\n\nKalt                         Informational                      [Page 3]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n1.2.1 Users\n\n   Each user is distinguished from other users by a unique nickname\n   having a maximum length of nine (9) characters.  See the protocol\n   grammar rules (section 2.3.1) for what may and may not be used in a\n   nickname.\n\n   While the maximum length is limited to nine characters, clients\n   SHOULD accept longer strings as they may become used in future\n   evolutions of the protocol.\n\n1.2.1.1 Operators\n\n   To allow a reasonable amount of order to be kept within the IRC\n   network, a special class of users (operators) is allowed to perform\n   general maintenance functions on the network.  Although the powers\n   granted to an operator can be considered as 'dangerous', they are\n   nonetheless often necessary.  Operators SHOULD be able to perform\n   basic network tasks such as disconnecting and reconnecting servers as\n   needed.  In recognition of this need, the protocol discussed herein\n   provides for operators only to be able to perform such functions.\n   See sections 3.1.8 (SQUIT) and 3.4.7 (CONNECT).\n\n   A more controversial power of operators is the ability to remove a\n   user from the connected network by 'force', i.e., operators are able\n   to close the connection between any client and server.  The\n   justification for this is very delicate since its abuse is both\n   destructive and annoying, and its benefits close to inexistent.  For\n   further details on this type of action, see section 3.7.1 (KILL).\n\n1.2.2 Services\n\n   Each service is distinguished from other services by a service name\n   composed of a nickname and a server name.  As for users, the nickname\n   has a maximum length of nine (9) characters.  See the protocol\n   grammar rules (section 2.3.1) for what may and may not be used in a\n   nickname.\n\n1.3 Channels\n\n   Channels names are strings (beginning with a '&', '#', '+' or '!'\n   character) of length up to fifty (50) characters.  Apart from the\n   requirement that the first character is either '&', '#', '+' or '!',\n   the only restriction on a channel name is that it SHALL NOT contain\n   any spaces (' '), a control G (^G or ASCII 7), a comma (',').  Space\n   is used as parameter separator and command is used as a list item\n   separator by the protocol).  A colon (':') can also be used as a\n   delimiter for the channel mask.  Channel names are case insensitive.\n\n\n\nKalt                         Informational                      [Page 4]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   See the protocol grammar rules (section 2.3.1) for the exact syntax\n   of a channel name.\n\n   Each prefix characterizes a different channel type.  The definition\n   of the channel types is not relevant to the client-server protocol\n   and thus it is beyond the scope of this document.  More details can\n   be found in \"Internet Relay Chat: Channel Management\" [IRC-CHAN].\n\n2. The IRC Client Specification\n\n2.1 Overview\n\n   The protocol as described herein is for use only with client to\n   server connections when the client registers as a user.\n\n2.2 Character codes\n\n   No specific character set is specified. The protocol is based on a\n   set of codes which are composed of eight (8) bits, making up an\n   octet.  Each message may be composed of any number of these octets;\n   however, some octet values are used for control codes, which act as\n   message delimiters.\n\n   Regardless of being an 8-bit protocol, the delimiters and keywords\n   are such that protocol is mostly usable from US-ASCII terminal and a\n   telnet connection.\n\n   Because of IRC's Scandinavian origin, the characters {}|^ are\n   considered to be the lower case equivalents of the characters []\\~,\n   respectively. This is a critical issue when determining the\n   equivalence of two nicknames or channel names.\n\n2.3 Messages\n\n   Servers and clients send each other messages, which may or may not\n   generate a reply.  If the message contains a valid command, as\n   described in later sections, the client should expect a reply as\n   specified but it is not advised to wait forever for the reply; client\n   to server and server to server communication is essentially\n   asynchronous by nature.\n\n   Each IRC message may consist of up to three main parts: the prefix\n   (OPTIONAL), the command, and the command parameters (maximum of\n   fifteen (15)).  The prefix, command, and all parameters are separated\n   by one ASCII space character (0x20) each.\n\n\n\n\n\n\nKalt                         Informational                      [Page 5]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   The presence of a prefix is indicated with a single leading ASCII\n   colon character (':', 0x3b), which MUST be the first character of the\n   message itself.  There MUST be NO gap (whitespace) between the colon\n   and the prefix.  The prefix is used by servers to indicate the true\n   origin of the message.  If the prefix is missing from the message, it\n   is assumed to have originated from the connection from which it was\n   received from.  Clients SHOULD NOT use a prefix when sending a\n   message; if they use one, the only valid prefix is the registered\n   nickname associated with the client.\n\n   The command MUST either be a valid IRC command or a three (3) digit\n   number represented in ASCII text.\n\n   IRC messages are always lines of characters terminated with a CR-LF\n   (Carriage Return - Line Feed) pair, and these messages SHALL NOT\n   exceed 512 characters in length, counting all characters including\n   the trailing CR-LF. Thus, there are 510 characters maximum allowed\n   for the command and its parameters.  There is no provision for\n   continuation of message lines.  See section 6 for more details about\n   current implementations.\n\n2.3.1 Message format in Augmented BNF\n\n   The protocol messages must be extracted from the contiguous stream of\n   octets.  The current solution is to designate two characters, CR and\n   LF, as message separators.  Empty messages are silently ignored,\n   which permits use of the sequence CR-LF between messages without\n   extra problems.\n\n   The extracted message is parsed into the components <prefix>,\n   <command> and list of parameters (<params>).\n\n    The Augmented BNF representation for this is:\n\n    message    =  [ \":\" prefix SPACE ] command [ params ] crlf\n    prefix     =  servername / ( nickname [ [ \"!\" user ] \"@\" host ] )\n    command    =  1*letter / 3digit\n    params     =  *14( SPACE middle ) [ SPACE \":\" trailing ]\n               =/ 14( SPACE middle ) [ SPACE [ \":\" ] trailing ]\n\n    nospcrlfcl =  %x01-09 / %x0B-0C / %x0E-1F / %x21-39 / %x3B-FF\n                    ; any octet except NUL, CR, LF, \" \" and \":\"\n    middle     =  nospcrlfcl *( \":\" / nospcrlfcl )\n    trailing   =  *( \":\" / \" \" / nospcrlfcl )\n\n    SPACE      =  %x20        ; space character\n    crlf       =  %x0D %x0A   ; \"carriage return\" \"linefeed\"\n\n\n\n\nKalt                         Informational                      [Page 6]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   NOTES:\n      1) After extracting the parameter list, all parameters are equal\n         whether matched by <middle> or <trailing>. <trailing> is just a\n         syntactic trick to allow SPACE within the parameter.\n\n      2) The NUL (%x00) character is not special in message framing, and\n         basically could end up inside a parameter, but it would cause\n         extra complexities in normal C string handling. Therefore, NUL\n         is not allowed within messages.\n\n   Most protocol messages specify additional semantics and syntax for\n   the extracted parameter strings dictated by their position in the\n   list.  For example, many server commands will assume that the first\n   parameter after the command is the list of targets, which can be\n   described with:\n\n  target     =  nickname / server\n  msgtarget  =  msgto *( \",\" msgto )\n  msgto      =  channel / ( user [ \"%\" host ] \"@\" servername )\n  msgto      =/ ( user \"%\" host ) / targetmask\n  msgto      =/ nickname / ( nickname \"!\" user \"@\" host )\n  channel    =  ( \"#\" / \"+\" / ( \"!\" channelid ) / \"&\" ) chanstring\n                [ \":\" chanstring ]\n  servername =  hostname\n  host       =  hostname / hostaddr\n  hostname   =  shortname *( \".\" shortname )\n  shortname  =  ( letter / digit ) *( letter / digit / \"-\" )\n                *( letter / digit )\n                  ; as specified in RFC 1123 [HNAME]\n  hostaddr   =  ip4addr / ip6addr\n  ip4addr    =  1*3digit \".\" 1*3digit \".\" 1*3digit \".\" 1*3digit\n  ip6addr    =  1*hexdigit 7( \":\" 1*hexdigit )\n  ip6addr    =/ \"0:0:0:0:0:\" ( \"0\" / \"FFFF\" ) \":\" ip4addr\n  nickname   =  ( letter / special ) *8( letter / digit / special / \"-\" )\n  targetmask =  ( \"$\" / \"#\" ) mask\n                  ; see details on allowed masks in section 3.3.1\n  chanstring =  %x01-07 / %x08-09 / %x0B-0C / %x0E-1F / %x21-2B\n  chanstring =/ %x2D-39 / %x3B-FF\n                  ; any octet except NUL, BELL, CR, LF, \" \", \",\" and \":\"\n  channelid  = 5( %x41-5A / digit )   ; 5( A-Z / 0-9 )\n\n\n\n\n\n\n\n\n\n\n\nKalt                         Informational                      [Page 7]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n  Other parameter syntaxes are:\n\n  user       =  1*( %x01-09 / %x0B-0C / %x0E-1F / %x21-3F / %x41-FF )\n                  ; any octet except NUL, CR, LF, \" \" and \"@\"\n  key        =  1*23( %x01-05 / %x07-08 / %x0C / %x0E-1F / %x21-7F )\n                  ; any 7-bit US_ASCII character,\n                  ; except NUL, CR, LF, FF, h/v TABs, and \" \"\n  letter     =  %x41-5A / %x61-7A       ; A-Z / a-z\n  digit      =  %x30-39                 ; 0-9\n  hexdigit   =  digit / \"A\" / \"B\" / \"C\" / \"D\" / \"E\" / \"F\"\n  special    =  %x5B-60 / %x7B-7D\n                   ; \"[\", \"]\", \"\\\", \"`\", \"_\", \"^\", \"{\", \"|\", \"}\"\n\n  NOTES:\n      1) The <hostaddr> syntax is given here for the sole purpose of\n         indicating the format to follow for IP addresses.  This\n         reflects the fact that the only available implementations of\n         this protocol uses TCP/IP as underlying network protocol but is\n         not meant to prevent other protocols to be used.\n\n      2) <hostname> has a maximum length of 63 characters.  This is a\n         limitation of the protocol as internet hostnames (in\n         particular) can be longer.  Such restriction is necessary\n         because IRC messages are limited to 512 characters in length.\n         Clients connecting from a host which name is longer than 63\n         characters are registered using the host (numeric) address\n         instead of the host name.\n\n      3) Some parameters used in the following sections of this\n         documents are not defined here as there is nothing specific\n         about them besides the name that is used for convenience.\n         These parameters follow the general syntax defined for\n         <params>.\n\n2.4 Numeric replies\n\n   Most of the messages sent to the server generate a reply of some\n   sort.  The most common reply is the numeric reply, used for both\n   errors and normal replies.  The numeric reply MUST be sent as one\n   message consisting of the sender prefix, the three-digit numeric, and\n   the target of the reply.  A numeric reply is not allowed to originate\n   from a client. In all other respects, a numeric reply is just like a\n   normal message, except that the keyword is made up of 3 numeric\n   digits rather than a string of letters.  A list of different replies\n   is supplied in section 5 (Replies).\n\n\n\n\n\n\nKalt                         Informational                      [Page 8]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n2.5 Wildcard expressions\n\n   When wildcards are allowed in a string, it is referred as a \"mask\".\n\n   For string matching purposes, the protocol allows the use of two\n   special characters: '?' (%x3F) to match one and only one character,\n   and '*' (%x2A) to match any number of any characters.  These two\n   characters can be escaped using the character '\\' (%x5C).\n\n   The Augmented BNF syntax for this is:\n\n    mask       =  *( nowild / noesc wildone / noesc wildmany )\n    wildone    =  %x3F\n    wildmany   =  %x2A\n    nowild     =  %x01-29 / %x2B-3E / %x40-FF\n                    ; any octet except NUL, \"*\", \"?\"\n    noesc      =  %x01-5B / %x5D-FF\n                    ; any octet except NUL and \"\\\"\n    matchone   =  %x01-FF\n                    ; matches wildone\n    matchmany  =  *matchone\n                    ; matches wildmany\n\n   Examples:\n\n   a?c         ; Matches any string of 3 characters in length starting\n               with \"a\" and ending with \"c\"\n\n   a*c         ; Matches any string of at least 2 characters in length\n               starting with \"a\" and ending with \"c\"\n\n3. Message Details\n\n   On the following pages there are descriptions of each message\n   recognized by the IRC server and client.  All commands described in\n   this section MUST be implemented by any server for this protocol.\n\n   Where the reply ERR_NOSUCHSERVER is returned, it means that the\n   target of the message could not be found.  The server MUST NOT send\n   any other replies after this error for that command.\n\n   The server to which a client is connected is required to parse the\n   complete message, and return any appropriate errors.\n\n   If multiple parameters is presented, then each MUST be checked for\n   validity and appropriate responses MUST be sent back to the client.\n   In the case of incorrect messages which use parameter lists with\n   comma as an item separator, a reply MUST be sent for each item.\n\n\n\nKalt                         Informational                      [Page 9]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.1 Connection Registration\n\n   The commands described here are used to register a connection with an\n   IRC server as a user as well as to correctly disconnect.\n\n   A \"PASS\" command is not required for a client connection to be\n   registered, but it MUST precede the latter of the NICK/USER\n   combination (for a user connection) or the SERVICE command (for a\n   service connection). The RECOMMENDED order for a client to register\n   is as follows:\n\n                           1. Pass message\n           2. Nick message                 2. Service message\n           3. User message\n\n   Upon success, the client will receive an RPL_WELCOME (for users) or\n   RPL_YOURESERVICE (for services) message indicating that the\n   connection is now registered and known the to the entire IRC network.\n   The reply message MUST contain the full client identifier upon which\n   it was registered.\n\n3.1.1 Password message\n\n      Command: PASS\n   Parameters: <password>\n\n   The PASS command is used to set a 'connection password'.  The\n   optional password can and MUST be set before any attempt to register\n   the connection is made.  Currently this requires that user send a\n   PASS command before sending the NICK/USER combination.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_ALREADYREGISTRED\n\n   Example:\n\n           PASS secretpasswordhere\n\n3.1.2 Nick message\n\n\n      Command: NICK\n   Parameters: <nickname>\n\n   NICK command is used to give user a nickname or change the existing\n   one.\n\n\n\n\nKalt                         Informational                     [Page 10]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Numeric Replies:\n\n           ERR_NONICKNAMEGIVEN             ERR_ERRONEUSNICKNAME\n           ERR_NICKNAMEINUSE               ERR_NICKCOLLISION\n           ERR_UNAVAILRESOURCE             ERR_RESTRICTED\n\n   Examples:\n\n   NICK Wiz                ; Introducing new nick \"Wiz\" if session is\n                           still unregistered, or user changing his\n                           nickname to \"Wiz\"\n\n   :WiZ!jto@tolsun.oulu.fi NICK Kilroy\n                           ; Server telling that WiZ changed his\n                           nickname to Kilroy.\n\n3.1.3 User message\n\n      Command: USER\n   Parameters: <user> <mode> <unused> <realname>\n\n   The USER command is used at the beginning of connection to specify\n   the username, hostname and realname of a new user.\n\n   The <mode> parameter should be a numeric, and can be used to\n   automatically set user modes when registering with the server.  This\n   parameter is a bitmask, with only 2 bits having any signification: if\n   the bit 2 is set, the user mode 'w' will be set and if the bit 3 is\n   set, the user mode 'i' will be set.  (See Section 3.1.5 \"User\n   Modes\").\n\n   The <realname> may contain space characters.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_ALREADYREGISTRED\n\n   Example:\n\n   USER guest 0 * :Ronnie Reagan   ; User registering themselves with a\n                                   username of \"guest\" and real name\n                                   \"Ronnie Reagan\".\n\n   USER guest 8 * :Ronnie Reagan   ; User registering themselves with a\n                                   username of \"guest\" and real name\n                                   \"Ronnie Reagan\", and asking to be set\n                                   invisible.\n\n\n\n\nKalt                         Informational                     [Page 11]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.1.4 Oper message\n\n      Command: OPER\n   Parameters: <name> <password>\n\n   A normal user uses the OPER command to obtain operator privileges.\n   The combination of <name> and <password> are REQUIRED to gain\n   Operator privileges.  Upon success, the user will receive a MODE\n   message (see section 3.1.5) indicating the new user modes.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              RPL_YOUREOPER\n           ERR_NOOPERHOST                  ERR_PASSWDMISMATCH\n\n   Example:\n\n   OPER foo bar                    ; Attempt to register as an operator\n                                   using a username of \"foo\" and \"bar\"\n                                   as the password.\n\n3.1.5 User mode message\n\n      Command: MODE\n   Parameters: <nickname>\n               *( ( \"+\" / \"-\" ) *( \"i\" / \"w\" / \"o\" / \"O\" / \"r\" ) )\n\n   The user MODE's are typically changes which affect either how the\n   client is seen by others or what 'extra' messages the client is sent.\n\n   A user MODE command MUST only be accepted if both the sender of the\n   message and the nickname given as a parameter are both the same.  If\n   no other parameter is given, then the server will return the current\n   settings for the nick.\n\n      The available modes are as follows:\n\n           a - user is flagged as away;\n           i - marks a users as invisible;\n           w - user receives wallops;\n           r - restricted user connection;\n           o - operator flag;\n           O - local operator flag;\n           s - marks a user for receipt of server notices.\n\n   Additional modes may be available later on.\n\n\n\n\n\nKalt                         Informational                     [Page 12]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   The flag 'a' SHALL NOT be toggled by the user using the MODE command,\n   instead use of the AWAY command is REQUIRED.\n\n   If a user attempts to make themselves an operator using the \"+o\" or\n   \"+O\" flag, the attempt SHOULD be ignored as users could bypass the\n   authentication mechanisms of the OPER command.  There is no\n   restriction, however, on anyone `deopping' themselves (using \"-o\" or\n   \"-O\").\n\n   On the other hand, if a user attempts to make themselves unrestricted\n   using the \"-r\" flag, the attempt SHOULD be ignored.  There is no\n   restriction, however, on anyone `deopping' themselves (using \"+r\").\n   This flag is typically set by the server upon connection for\n   administrative reasons.  While the restrictions imposed are left up\n   to the implementation, it is typical that a restricted user not be\n   allowed to change nicknames, nor make use of the channel operator\n   status on channels.\n\n   The flag 's' is obsolete but MAY still be used.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_USERSDONTMATCH\n           ERR_UMODEUNKNOWNFLAG            RPL_UMODEIS\n\n   Examples:\n\n   MODE WiZ -w                     ; Command by WiZ to turn off\n                                   reception of WALLOPS messages.\n\n   MODE Angel +i                   ; Command from Angel to make herself\n                                   invisible.\n\n   MODE WiZ -o                     ; WiZ 'deopping' (removing operator\n                                   status).\n\n3.1.6 Service message\n\n      Command: SERVICE\n   Parameters: <nickname> <reserved> <distribution> <type>\n               <reserved> <info>\n\n   The SERVICE command to register a new service.  Command parameters\n   specify the service nickname, distribution, type and info of a new\n   service.\n\n\n\n\n\n\nKalt                         Informational                     [Page 13]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   The <distribution> parameter is used to specify the visibility of a\n   service.  The service may only be known to servers which have a name\n   matching the distribution.  For a matching server to have knowledge\n   of the service, the network path between that server and the server\n   on which the service is connected MUST be composed of servers which\n   names all match the mask.\n\n   The <type> parameter is currently reserved for future usage.\n\n   Numeric Replies:\n\n           ERR_ALREADYREGISTRED            ERR_NEEDMOREPARAMS\n           ERR_ERRONEUSNICKNAME\n           RPL_YOURESERVICE                RPL_YOURHOST\n           RPL_MYINFO\n\n   Example:\n\n   SERVICE dict * *.fr 0 0 :French Dictionary ; Service registering\n                                   itself with a name of \"dict\".  This\n                                   service will only be available on\n                                   servers which name matches \"*.fr\".\n\n3.1.7 Quit\n\n      Command: QUIT\n   Parameters: [ <Quit Message> ]\n\n   A client session is terminated with a quit message.  The server\n   acknowledges this by sending an ERROR message to the client.\n\n   Numeric Replies:\n\n           None.\n\n   Example:\n\n   QUIT :Gone to have lunch        ; Preferred message format.\n\n   :syrk!kalt@millennium.stealth.net QUIT :Gone to have lunch ; User\n                                   syrk has quit IRC to have lunch.\n\n\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 14]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.1.8 Squit\n\n      Command: SQUIT\n   Parameters: <server> <comment>\n\n   The SQUIT command is available only to operators.  It is used to\n   disconnect server links.  Also servers can generate SQUIT messages on\n   error conditions.  A SQUIT message may also target a remote server\n   connection.  In this case, the SQUIT message will simply be sent to\n   the remote server without affecting the servers in between the\n   operator and the remote server.\n\n   The <comment> SHOULD be supplied by all operators who execute a SQUIT\n   for a remote server.  The server ordered to disconnect its peer\n   generates a WALLOPS message with <comment> included, so that other\n   users may be aware of the reason of this action.\n\n   Numeric replies:\n\n           ERR_NOPRIVILEGES                ERR_NOSUCHSERVER\n           ERR_NEEDMOREPARAMS\n\n   Examples:\n\n   SQUIT tolsun.oulu.fi :Bad Link ?  ; Command to uplink of the server\n                                   tolson.oulu.fi to terminate its\n                                   connection with comment \"Bad Link\".\n\n   :Trillian SQUIT cm22.eng.umd.edu :Server out of control ; Command\n                                   from Trillian from to disconnect\n                                   \"cm22.eng.umd.edu\" from the net with\n                                   comment \"Server out of control\".\n\n3.2 Channel operations\n\n   This group of messages is concerned with manipulating channels, their\n   properties (channel modes), and their contents (typically users).\n   For this reason, these messages SHALL NOT be made available to\n   services.\n\n   All of these messages are requests which will or will not be granted\n   by the server.  The server MUST send a reply informing the user\n   whether the request was granted, denied or generated an error.  When\n   the server grants the request, the message is typically sent back\n   (eventually reformatted) to the user with the prefix set to the user\n   itself.\n\n\n\n\n\nKalt                         Informational                     [Page 15]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   The rules governing how channels are managed are enforced by the\n   servers.  These rules are beyond the scope of this document.  More\n   details are found in \"Internet Relay Chat: Channel Management\" [IRC-\n   CHAN].\n\n3.2.1 Join message\n\n      Command: JOIN\n   Parameters: ( <channel> *( \",\" <channel> ) [ <key> *( \",\" <key> ) ] )\n               / \"0\"\n\n   The JOIN command is used by a user to request to start listening to\n   the specific channel.  Servers MUST be able to parse arguments in the\n   form of a list of target, but SHOULD NOT use lists when sending JOIN\n   messages to clients.\n\n   Once a user has joined a channel, he receives information about\n   all commands his server receives affecting the channel.  This\n   includes JOIN, MODE, KICK, PART, QUIT and of course PRIVMSG/NOTICE.\n   This allows channel members to keep track of the other channel\n   members, as well as channel modes.\n\n   If a JOIN is successful, the user receives a JOIN message as\n   confirmation and is then sent the channel's topic (using RPL_TOPIC) and\n   the list of users who are on the channel (using RPL_NAMREPLY), which\n   MUST include the user joining.\n\n   Note that this message accepts a special argument (\"0\"), which is\n   a special request to leave all channels the user is currently a member\n   of.  The server will process this message as if the user had sent\n   a PART command (See Section 3.2.2) for each channel he is a member\n   of.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_BANNEDFROMCHAN\n           ERR_INVITEONLYCHAN              ERR_BADCHANNELKEY\n           ERR_CHANNELISFULL               ERR_BADCHANMASK\n           ERR_NOSUCHCHANNEL               ERR_TOOMANYCHANNELS\n           ERR_TOOMANYTARGETS              ERR_UNAVAILRESOURCE\n           RPL_TOPIC\n\n   Examples:\n\n   JOIN #foobar                    ; Command to join channel #foobar.\n\n   JOIN &foo fubar                 ; Command to join channel &foo using\n                                   key \"fubar\".\n\n\n\nKalt                         Informational                     [Page 16]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   JOIN #foo,&bar fubar            ; Command to join channel #foo using\n                                   key \"fubar\" and &bar using no key.\n\n   JOIN #foo,#bar fubar,foobar     ; Command to join channel #foo using\n                                   key \"fubar\", and channel #bar using\n                                   key \"foobar\".\n\n   JOIN #foo,#bar                  ; Command to join channels #foo and\n                                   #bar.\n\n   JOIN 0                          ; Leave all currently joined\n                                   channels.\n\n   :WiZ!jto@tolsun.oulu.fi JOIN #Twilight_zone ; JOIN message from WiZ\n                                   on channel #Twilight_zone\n\n3.2.2 Part message\n\n      Command: PART\n   Parameters: <channel> *( \",\" <channel> ) [ <Part Message> ]\n\n   The PART command causes the user sending the message to be removed\n   from the list of active members for all given channels listed in the\n   parameter string.  If a \"Part Message\" is given, this will be sent\n   instead of the default message, the nickname.  This request is always\n   granted by the server.\n\n   Servers MUST be able to parse arguments in the form of a list of\n   target, but SHOULD NOT use lists when sending PART messages to\n   clients.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOSUCHCHANNEL\n           ERR_NOTONCHANNEL\n\n   Examples:\n\n   PART #twilight_zone             ; Command to leave channel\n                                   \"#twilight_zone\"\n\n   PART #oz-ops,&group5            ; Command to leave both channels\n                                   \"&group5\" and \"#oz-ops\".\n\n   :WiZ!jto@tolsun.oulu.fi PART #playzone :I lost\n                                   ; User WiZ leaving channel\n                                   \"#playzone\" with the message \"I\n                                   lost\".\n\n\n\nKalt                         Informational                     [Page 17]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.2.3 Channel mode message\n\n      Command: MODE\n   Parameters: <channel> *( ( \"-\" / \"+\" ) *<modes> *<modeparams> )\n\n   The MODE command is provided so that users may query and change the\n   characteristics of a channel.  For more details on available modes\n   and their uses, see \"Internet Relay Chat: Channel Management\" [IRC-\n   CHAN].  Note that there is a maximum limit of three (3) changes per\n   command for modes that take a parameter.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_KEYSET\n           ERR_NOCHANMODES                 ERR_CHANOPRIVSNEEDED\n           ERR_USERNOTINCHANNEL            ERR_UNKNOWNMODE\n           RPL_CHANNELMODEIS\n           RPL_BANLIST                     RPL_ENDOFBANLIST\n           RPL_EXCEPTLIST                  RPL_ENDOFEXCEPTLIST\n           RPL_INVITELIST                  RPL_ENDOFINVITELIST\n           RPL_UNIQOPIS\n\n   The following examples are given to help understanding the syntax of\n   the MODE command, but refer to modes defined in \"Internet Relay Chat:\n   Channel Management\" [IRC-CHAN].\n\n   Examples:\n\n   MODE #Finnish +imI *!*@*.fi     ; Command to make #Finnish channel\n                                   moderated and 'invite-only' with user\n                                   with a hostname matching *.fi\n                                   automatically invited.\n\n   MODE #Finnish +o Kilroy         ; Command to give 'chanop' privileges\n                                   to Kilroy on channel #Finnish.\n\n   MODE #Finnish +v Wiz            ; Command to allow WiZ to speak on\n                                   #Finnish.\n\n   MODE #Fins -s                   ; Command to remove 'secret' flag\n                                   from channel #Fins.\n\n   MODE #42 +k oulu                ; Command to set the channel key to\n                                   \"oulu\".\n\n   MODE #42 -k oulu                ; Command to remove the \"oulu\"\n                                   channel key on channel \"#42\".\n\n\n\n\nKalt                         Informational                     [Page 18]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   MODE #eu-opers +l 10            ; Command to set the limit for the\n                                   number of users on channel\n                                   \"#eu-opers\" to 10.\n\n   :WiZ!jto@tolsun.oulu.fi MODE #eu-opers -l\n                                   ; User \"WiZ\" removing the limit for\n                                   the number of users on channel \"#eu-\n                                   opers\".\n\n   MODE &oulu +b                   ; Command to list ban masks set for\n                                   the channel \"&oulu\".\n\n   MODE &oulu +b *!*@*             ; Command to prevent all users from\n                                   joining.\n\n   MODE &oulu +b *!*@*.edu +e *!*@*.bu.edu\n                                   ; Command to prevent any user from a\n                                   hostname matching *.edu from joining,\n                                   except if matching *.bu.edu\n\n   MODE #bu +be *!*@*.edu *!*@*.bu.edu\n                                   ; Comment to prevent any user from a\n                                   hostname matching *.edu from joining,\n                                   except if matching *.bu.edu\n\n   MODE #meditation e              ; Command to list exception masks set\n                                   for the channel \"#meditation\".\n\n   MODE #meditation I              ; Command to list invitations masks\n                                   set for the channel \"#meditation\".\n\n   MODE !12345ircd O               ; Command to ask who the channel\n                                   creator for \"!12345ircd\" is\n\n3.2.4 Topic message\n\n      Command: TOPIC\n   Parameters: <channel> [ <topic> ]\n\n   The TOPIC command is used to change or view the topic of a channel.\n   The topic for channel <channel> is returned if there is no <topic>\n   given.  If the <topic> parameter is present, the topic for that\n   channel will be changed, if this action is allowed for the user\n   requesting it.  If the <topic> parameter is an empty string, the\n   topic for that channel will be removed.\n\n\n\n\n\n\nKalt                         Informational                     [Page 19]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOTONCHANNEL\n           RPL_NOTOPIC                     RPL_TOPIC\n           ERR_CHANOPRIVSNEEDED            ERR_NOCHANMODES\n\n   Examples:\n\n   :WiZ!jto@tolsun.oulu.fi TOPIC #test :New topic ; User Wiz setting the\n                                   topic.\n\n   TOPIC #test :another topic      ; Command to set the topic on #test\n                                   to \"another topic\".\n\n   TOPIC #test :                   ; Command to clear the topic on\n                                   #test.\n\n   TOPIC #test                     ; Command to check the topic for\n                                   #test.\n\n3.2.5 Names message\n\n      Command: NAMES\n   Parameters: [ <channel> *( \",\" <channel> ) [ <target> ] ]\n\n   By using the NAMES command, a user can list all nicknames that are\n   visible to him. For more details on what is visible and what is not,\n   see \"Internet Relay Chat: Channel Management\" [IRC-CHAN].  The\n   <channel> parameter specifies which channel(s) to return information\n   about.  There is no error reply for bad channel names.\n\n   If no <channel> parameter is given, a list of all channels and their\n   occupants is returned.  At the end of this list, a list of users who\n   are visible but either not on any channel or not on a visible channel\n   are listed as being on `channel' \"*\".\n\n   If the <target> parameter is specified, the request is forwarded to\n   that server which will generate the reply.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numerics:\n\n           ERR_TOOMANYMATCHES              ERR_NOSUCHSERVER\n           RPL_NAMREPLY                    RPL_ENDOFNAMES\n\n\n\n\n\n\nKalt                         Informational                     [Page 20]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   NAMES #twilight_zone,#42        ; Command to list visible users on\n                                   #twilight_zone and #42\n\n   NAMES                           ; Command to list all visible\n                                   channels and users\n\n3.2.6 List message\n\n      Command: LIST\n   Parameters: [ <channel> *( \",\" <channel> ) [ <target> ] ]\n\n   The list command is used to list channels and their topics.  If the\n   <channel> parameter is used, only the status of that channel is\n   displayed.\n\n   If the <target> parameter is specified, the request is forwarded to\n   that server which will generate the reply.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_TOOMANYMATCHES              ERR_NOSUCHSERVER\n           RPL_LIST                        RPL_LISTEND\n\n   Examples:\n\n   LIST                            ; Command to list all channels.\n\n   LIST #twilight_zone,#42         ; Command to list channels\n                                   #twilight_zone and #42\n\n3.2.7 Invite message\n\n      Command: INVITE\n   Parameters: <nickname> <channel>\n\n   The INVITE command is used to invite a user to a channel.  The\n   parameter <nickname> is the nickname of the person to be invited to\n   the target channel <channel>.  There is no requirement that the\n   channel the target user is being invited to must exist or be a valid\n   channel.  However, if the channel exists, only members of the channel\n   are allowed to invite other users.  When the channel has invite-only\n   flag set, only channel operators may issue INVITE command.\n\n\n\n\n\nKalt                         Informational                     [Page 21]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Only the user inviting and the user being invited will receive\n   notification of the invitation.  Other channel members are not\n   notified.  (This is unlike the MODE changes, and is occasionally the\n   source of trouble for users.)\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOSUCHNICK\n           ERR_NOTONCHANNEL                ERR_USERONCHANNEL\n           ERR_CHANOPRIVSNEEDED\n           RPL_INVITING                    RPL_AWAY\n\n   Examples:\n\n   :Angel!wings@irc.org INVITE Wiz #Dust\n\n                                   ; Message to WiZ when he has been\n                                   invited by user Angel to channel\n                                   #Dust\n\n   INVITE Wiz #Twilight_Zone       ; Command to invite WiZ to\n                                   #Twilight_zone\n\n3.2.8 Kick command\n\n      Command: KICK\n   Parameters: <channel> *( \",\" <channel> ) <user> *( \",\" <user> )\n               [<comment>]\n\n   The KICK command can be used to request the forced removal of a user\n   from a channel.  It causes the <user> to PART from the <channel> by\n   force.  For the message to be syntactically correct, there MUST be\n   either one channel parameter and multiple user parameter, or as many\n   channel parameters as there are user parameters.  If a \"comment\" is\n   given, this will be sent instead of the default message, the nickname\n   of the user issuing the KICK.\n\n   The server MUST NOT send KICK messages with multiple channels or\n   users to clients.  This is necessarily to maintain backward\n   compatibility with old client software.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS              ERR_NOSUCHCHANNEL\n           ERR_BADCHANMASK                 ERR_CHANOPRIVSNEEDED\n           ERR_USERNOTINCHANNEL            ERR_NOTONCHANNEL\n\n\n\n\n\nKalt                         Informational                     [Page 22]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   KICK &Melbourne Matthew         ; Command to kick Matthew from\n                                   &Melbourne\n\n   KICK #Finnish John :Speaking English\n                                   ; Command to kick John from #Finnish\n                                   using \"Speaking English\" as the\n                                   reason (comment).\n\n   :WiZ!jto@tolsun.oulu.fi KICK #Finnish John\n                                   ; KICK message on channel #Finnish\n                                   from WiZ to remove John from channel\n\n3.3 Sending messages\n\n   The main purpose of the IRC protocol is to provide a base for clients\n   to communicate with each other.  PRIVMSG, NOTICE and SQUERY\n   (described in Section 3.5 on Service Query and Commands) are the only\n   messages available which actually perform delivery of a text message\n   from one client to another - the rest just make it possible and try\n   to ensure it happens in a reliable and structured manner.\n\n3.3.1 Private messages\n\n      Command: PRIVMSG\n   Parameters: <msgtarget> <text to be sent>\n\n   PRIVMSG is used to send private messages between users, as well as to\n   send messages to channels.  <msgtarget> is usually the nickname of\n   the recipient of the message, or a channel name.\n\n   The <msgtarget> parameter may also be a host mask (#<mask>) or server\n   mask ($<mask>).  In both cases the server will only send the PRIVMSG\n   to those who have a server or host matching the mask.  The mask MUST\n   have at least 1 (one) \".\" in it and no wildcards following the last\n   \".\".  This requirement exists to prevent people sending messages to\n   \"#*\" or \"$*\", which would broadcast to all users.  Wildcards are the\n   '*' and '?'  characters.  This extension to the PRIVMSG command is\n   only available to operators.\n\n   Numeric Replies:\n\n           ERR_NORECIPIENT                 ERR_NOTEXTTOSEND\n           ERR_CANNOTSENDTOCHAN            ERR_NOTOPLEVEL\n           ERR_WILDTOPLEVEL                ERR_TOOMANYTARGETS\n           ERR_NOSUCHNICK\n           RPL_AWAY\n\n\n\nKalt                         Informational                     [Page 23]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   :Angel!wings@irc.org PRIVMSG Wiz :Are you receiving this message ?\n                                   ; Message from Angel to Wiz.\n\n   PRIVMSG Angel :yes I'm receiving it !\n                                   ; Command to send a message to Angel.\n\n   PRIVMSG jto@tolsun.oulu.fi :Hello !\n                                   ; Command to send a message to a user\n                                   on server tolsun.oulu.fi with\n                                   username of \"jto\".\n\n   PRIVMSG kalt%millennium.stealth.net@irc.stealth.net :Are you a frog?\n                                   ; Message to a user on server\n                                   irc.stealth.net with username of\n                                   \"kalt\", and connected from the host\n                                   millennium.stealth.net.\n\n   PRIVMSG kalt%millennium.stealth.net :Do you like cheese?\n                                   ; Message to a user on the local\n                                   server with username of \"kalt\", and\n                                   connected from the host\n                                   millennium.stealth.net.\n\n   PRIVMSG Wiz!jto@tolsun.oulu.fi :Hello !\n                                   ; Message to the user with nickname\n                                   Wiz who is connected from the host\n                                   tolsun.oulu.fi and has the username\n                                   \"jto\".\n\n   PRIVMSG $*.fi :Server tolsun.oulu.fi rebooting.\n                                   ; Message to everyone on a server\n                                   which has a name matching *.fi.\n\n   PRIVMSG #*.edu :NSFNet is undergoing work, expect interruptions\n                                   ; Message to all users who come from\n                                   a host which has a name matching\n                                   *.edu.\n\n3.3.2 Notice\n\n      Command: NOTICE\n   Parameters: <msgtarget> <text>\n\n   The NOTICE command is used similarly to PRIVMSG.  The difference\n   between NOTICE and PRIVMSG is that automatic replies MUST NEVER be\n   sent in response to a NOTICE message.  This rule applies to servers\n\n\n\nKalt                         Informational                     [Page 24]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   too - they MUST NOT send any error reply back to the client on\n   receipt of a notice.  The object of this rule is to avoid loops\n   between clients automatically sending something in response to\n   something it received.\n\n   This command is available to services as well as users.\n\n   This is typically used by services, and automatons (clients with\n   either an AI or other interactive program controlling their actions).\n\n   See PRIVMSG for more details on replies and examples.\n\n3.4 Server queries and commands\n\n   The server query group of commands has been designed to return\n   information about any server which is connected to the network.\n\n   In these queries, where a parameter appears as <target>, wildcard\n   masks are usually valid.  For each parameter, however, only one query\n   and set of replies is to be generated.  In most cases, if a nickname\n   is given, it will mean the server to which the user is connected.\n\n   These messages typically have little value for services, it is\n   therefore RECOMMENDED to forbid services from using them.\n\n3.4.1 Motd message\n\n      Command: MOTD\n   Parameters: [ <target> ]\n\n   The MOTD command is used to get the \"Message Of The Day\" of the given\n   server, or current server if <target> is omitted.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n           RPL_MOTDSTART                   RPL_MOTD\n           RPL_ENDOFMOTD                   ERR_NOMOTD\n\n3.4.2 Lusers message\n\n      Command: LUSERS\n   Parameters: [ <mask> [ <target> ] ]\n\n   The LUSERS command is used to get statistics about the size of the\n   IRC network.  If no parameter is given, the reply will be about the\n   whole net.  If a <mask> is specified, then the reply will only\n\n\n\n\nKalt                         Informational                     [Page 25]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   concern the part of the network formed by the servers matching the\n   mask.  Finally, if the <target> parameter is specified, the request\n   is forwarded to that server which will generate the reply.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           RPL_LUSERCLIENT                 RPL_LUSEROP\n           RPL_LUSERUNKOWN                 RPL_LUSERCHANNELS\n           RPL_LUSERME                     ERR_NOSUCHSERVER\n\n3.4.3 Version message\n\n      Command: VERSION\n   Parameters: [ <target> ]\n\n   The VERSION command is used to query the version of the server\n   program.  An optional parameter <target> is used to query the version\n   of the server program which a client is not directly connected to.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER                RPL_VERSION\n\n   Examples:\n\n   VERSION tolsun.oulu.fi          ; Command to check the version of\n                                   server \"tolsun.oulu.fi\".\n\n3.4.4 Stats message\n\n      Command: STATS\n   Parameters: [ <query> [ <target> ] ]\n\n   The stats command is used to query statistics of certain server.  If\n   <query> parameter is omitted, only the end of stats reply is sent\n   back.\n\n   A query may be given for any single letter which is only checked by\n   the destination server and is otherwise passed on by intermediate\n   servers, ignored and unaltered.\n\n   Wildcards are allowed in the <target> parameter.\n\n\n\n\n\nKalt                         Informational                     [Page 26]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Except for the ones below, the list of valid queries is\n   implementation dependent.  The standard queries below SHOULD be\n   supported by the server:\n\n            l - returns a list of the server's connections, showing how\n                long each connection has been established and the\n                traffic over that connection in Kbytes and messages for\n                each direction;\n            m - returns the usage count for each of commands supported\n                by the server; commands for which the usage count is\n                zero MAY be omitted;\n            o - returns a list of configured privileged users,\n                operators;\n            u - returns a string showing how long the server has been\n                up.\n\n   It is also RECOMMENDED that client and server access configuration be\n   published this way.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_STATSLINKINFO                RPL_STATSUPTIME\n           RPL_STATSCOMMANDS                RPL_STATSOLINE\n           RPL_ENDOFSTATS\n\n   Examples:\n\n   STATS m                         ; Command to check the command usage\n                                   for the server you are connected to\n\n3.4.5 Links message\n\n      Command: LINKS\n   Parameters: [ [ <remote server> ] <server mask> ]\n\n   With LINKS, a user can list all servernames, which are known by the\n   server answering the query.  The returned list of servers MUST match\n   the mask, or if no mask is given, the full list is returned.\n\n   If <remote server> is given in addition to <server mask>, the LINKS\n   command is forwarded to the first server found that matches that name\n   (if any), and that server is then required to answer the query.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_LINKS                        RPL_ENDOFLINKS\n\n\n\nKalt                         Informational                     [Page 27]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   LINKS *.au                      ; Command to list all servers which\n                                   have a name that matches *.au;\n\n   LINKS *.edu *.bu.edu            ; Command to list servers matching\n                                   *.bu.edu as seen by the first server\n                                   matching *.edu.\n\n3.4.6 Time message\n\n      Command: TIME\n   Parameters: [ <target> ]\n\n   The time command is used to query local time from the specified\n   server. If the <target> parameter is not given, the server receiving\n   the command must reply to the query.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER              RPL_TIME\n\n   Examples:\n   TIME tolsun.oulu.fi             ; check the time on the server\n                                   \"tolson.oulu.fi\"\n\n3.4.7 Connect message\n\n      Command: CONNECT\n   Parameters: <target server> <port> [ <remote server> ]\n\n   The CONNECT command can be used to request a server to try to\n   establish a new connection to another server immediately.  CONNECT is\n   a privileged command and SHOULD be available only to IRC Operators.\n   If a <remote server> is given and its mask doesn't match name of the\n   parsing server, the CONNECT attempt is sent to the first match of\n   remote server. Otherwise the CONNECT attempt is made by the server\n   processing the request.\n\n   The server receiving a remote CONNECT command SHOULD generate a\n   WALLOPS message describing the source and target of the request.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER              ERR_NOPRIVILEGES\n           ERR_NEEDMOREPARAMS\n\n\n\nKalt                         Informational                     [Page 28]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   CONNECT tolsun.oulu.fi 6667     ; Command to attempt to connect local\n                                   server to tolsun.oulu.fi on port 6667\n\n3.4.8 Trace message\n\n      Command: TRACE\n   Parameters: [ <target> ]\n\n   TRACE command is used to find the route to specific server and\n   information about its peers.  Each server that processes this command\n   MUST report to the sender about it.  The replies from pass-through\n   links form a chain, which shows route to destination.  After sending\n   this reply back, the query MUST be sent to the next server until\n   given <target> server is reached.\n\n   TRACE command is used to find the route to specific server.  Each\n   server that processes this message MUST tell the sender about it by\n   sending a reply indicating it is a pass-through link, forming a chain\n   of replies.  After sending this reply back, it MUST then send the\n   TRACE message to the next server until given server is reached.  If\n   the <target> parameter is omitted, it is RECOMMENDED that TRACE\n   command sends a message to the sender telling which servers the local\n   server has direct connection to.\n\n   If the destination given by <target> is an actual server, the\n   destination server is REQUIRED to report all servers, services and\n   operators which are connected to it; if the command was issued by an\n   operator, the server MAY also report all users which are connected to\n   it.  If the destination given by <target> is a nickname, then only a\n   reply for that nickname is given.  If the <target> parameter is\n   omitted, it is RECOMMENDED that the TRACE command is parsed as\n   targeted to the processing server.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n\n      If the TRACE message is destined for another server, all\n      intermediate servers must return a RPL_TRACELINK reply to indicate\n      that the TRACE passed through it and where it is going next.\n\n           RPL_TRACELINK\n\n\n\n\n\nKalt                         Informational                     [Page 29]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n      A TRACE reply may be composed of any number of the following\n      numeric replies.\n\n           RPL_TRACECONNECTING           RPL_TRACEHANDSHAKE\n           RPL_TRACEUNKNOWN              RPL_TRACEOPERATOR\n           RPL_TRACEUSER                 RPL_TRACESERVER\n           RPL_TRACESERVICE              RPL_TRACENEWTYPE\n           RPL_TRACECLASS                RPL_TRACELOG\n           RPL_TRACEEND\n\n   Examples:\n\n   TRACE *.oulu.fi                 ; TRACE to a server matching\n                                   *.oulu.fi\n\n3.4.9 Admin command\n\n      Command: ADMIN\n   Parameters: [ <target> ]\n\n   The admin command is used to find information about the administrator\n   of the given server, or current server if <target> parameter is\n   omitted.  Each server MUST have the ability to forward ADMIN messages\n   to other servers.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_ADMINME                   RPL_ADMINLOC1\n           RPL_ADMINLOC2                 RPL_ADMINEMAIL\n\n   Examples:\n\n   ADMIN tolsun.oulu.fi            ; request an ADMIN reply from\n                                   tolsun.oulu.fi\n\n   ADMIN syrk                      ; ADMIN request for the server to\n                                   which the user syrk is connected\n\n\n\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 30]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.4.10 Info command\n\n      Command: INFO\n   Parameters: [ <target> ]\n\n   The INFO command is REQUIRED to return information describing the\n   server: its version, when it was compiled, the patchlevel, when it\n   was started, and any other miscellaneous information which may be\n   considered to be relevant.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_INFO                      RPL_ENDOFINFO\n\n   Examples:\n\n   INFO csd.bu.edu                 ; request an INFO reply from\n                                   csd.bu.edu\n\n   INFO Angel                      ; request info from the server that\n                                   Angel is connected to.\n\n3.5 Service Query and Commands\n\n   The service query group of commands has been designed to return\n   information about any service which is connected to the network.\n\n3.5.1 Servlist message\n\n      Command: SERVLIST\n   Parameters: [ <mask> [ <type> ] ]\n\n   The SERVLIST command is used to list services currently connected to\n   the network and visible to the user issuing the command.  The\n   optional parameters may be used to restrict the result of the query\n   (to matching services names, and services type).\n\n   Numeric Replies:\n\n           RPL_SERVLIST                  RPL_SERVLISTEND\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 31]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.5.2 Squery\n\n      Command: SQUERY\n   Parameters: <servicename> <text>\n\n   The SQUERY command is used similarly to PRIVMSG.  The only difference\n   is that the recipient MUST be a service.  This is the only way for a\n   text message to be delivered to a service.\n\n   See PRIVMSG for more details on replies and example.\n\n   Examples:\n\n   SQUERY irchelp :HELP privmsg\n                                   ; Message to the service with\n                                   nickname irchelp.\n\n   SQUERY dict@irc.fr :fr2en blaireau\n                                   ; Message to the service with name\n                                   dict@irc.fr.\n\n3.6 User based queries\n\n   User queries are a group of commands which are primarily concerned\n   with finding details on a particular user or group users.  When using\n   wildcards with any of these commands, if they match, they will only\n   return information on users who are 'visible' to you.  The visibility\n   of a user is determined as a combination of the user's mode and the\n   common set of channels you are both on.\n\n   Although services SHOULD NOT be using this class of message, they are\n   allowed to.\n\n3.6.1 Who query\n\n      Command: WHO\n   Parameters: [ <mask> [ \"o\" ] ]\n\n   The WHO command is used by a client to generate a query which returns\n   a list of information which 'matches' the <mask> parameter given by\n   the client.  In the absence of the <mask> parameter, all visible\n   (users who aren't invisible (user mode +i) and who don't have a\n   common channel with the requesting client) are listed.  The same\n   result can be achieved by using a <mask> of \"0\" or any wildcard which\n   will end up matching every visible user.\n\n   The <mask> passed to WHO is matched against users' host, server, real\n   name and nickname if the channel <mask> cannot be found.\n\n\n\nKalt                         Informational                     [Page 32]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   If the \"o\" parameter is passed only operators are returned according\n   to the <mask> supplied.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER\n           RPL_WHOREPLY                  RPL_ENDOFWHO\n\n   Examples:\n\n   WHO *.fi                        ; Command to list all users who match\n                                   against \"*.fi\".\n\n   WHO jto* o                      ; Command to list all users with a\n                                   match against \"jto*\" if they are an\n                                   operator.\n\n3.6.2 Whois query\n\n      Command: WHOIS\n   Parameters: [ <target> ] <mask> *( \",\" <mask> )\n\n   This command is used to query information about particular user.\n   The server will answer this command with several numeric messages\n   indicating different statuses of each user which matches the mask (if\n   you are entitled to see them).  If no wildcard is present in the\n   <mask>, any information about that nick which you are allowed to see\n   is presented.\n\n   If the <target> parameter is specified, it sends the query to a\n   specific server.  It is useful if you want to know how long the user\n   in question has been idle as only local server (i.e., the server the\n   user is directly connected to) knows that information, while\n   everything else is globally known.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER              ERR_NONICKNAMEGIVEN\n           RPL_WHOISUSER                 RPL_WHOISCHANNELS\n           RPL_WHOISCHANNELS             RPL_WHOISSERVER\n           RPL_AWAY                      RPL_WHOISOPERATOR\n           RPL_WHOISIDLE                 ERR_NOSUCHNICK\n           RPL_ENDOFWHOIS\n\n\n\n\n\n\nKalt                         Informational                     [Page 33]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   WHOIS wiz                       ; return available user information\n                                   about nick WiZ\n\n   WHOIS eff.org trillian          ; ask server eff.org for user\n                                   information  about trillian\n\n3.6.3 Whowas\n\n      Command: WHOWAS\n   Parameters: <nickname> *( \",\" <nickname> ) [ <count> [ <target> ] ]\n\n   Whowas asks for information about a nickname which no longer exists.\n   This may either be due to a nickname change or the user leaving IRC.\n   In response to this query, the server searches through its nickname\n   history, looking for any nicks which are lexically the same (no wild\n   card matching here).  The history is searched backward, returning the\n   most recent entry first.  If there are multiple entries, up to\n   <count> replies will be returned (or all of them if no <count>\n   parameter is given).  If a non-positive number is passed as being\n   <count>, then a full search is done.\n\n   Wildcards are allowed in the <target> parameter.\n\n   Numeric Replies:\n\n           ERR_NONICKNAMEGIVEN           ERR_WASNOSUCHNICK\n           RPL_WHOWASUSER                RPL_WHOISSERVER\n           RPL_ENDOFWHOWAS\n\n   Examples:\n\n   WHOWAS Wiz                      ; return all information in the nick\n                                   history about nick \"WiZ\";\n\n   WHOWAS Mermaid 9                ; return at most, the 9 most recent\n                                   entries in the nick history for\n                                   \"Mermaid\";\n\n   WHOWAS Trillian 1 *.edu         ; return the most recent history for\n                                   \"Trillian\" from the first server\n                                   found to match \"*.edu\".\n\n3.7 Miscellaneous messages\n\n   Messages in this category do not fit into any of the above categories\n   but are nonetheless still a part of and REQUIRED by the protocol.\n\n\n\nKalt                         Informational                     [Page 34]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.7.1 Kill message\n\n      Command: KILL\n   Parameters: <nickname> <comment>\n\n   The KILL command is used to cause a client-server connection to be\n   closed by the server which has the actual connection.  Servers\n   generate KILL messages on nickname collisions.  It MAY also be\n   available available to users who have the operator status.\n\n   Clients which have automatic reconnect algorithms effectively make\n   this command useless since the disconnection is only brief.  It does\n   however break the flow of data and can be used to stop large amounts\n   of 'flooding' from abusive users or accidents.  Abusive users usually\n   don't care as they will reconnect promptly and resume their abusive\n   behaviour.  To prevent this command from being abused, any user may\n   elect to receive KILL messages generated for others to keep an 'eye'\n   on would be trouble spots.\n\n   In an arena where nicknames are REQUIRED to be globally unique at all\n   times, KILL messages are sent whenever 'duplicates' are detected\n   (that is an attempt to register two users with the same nickname) in\n   the hope that both of them will disappear and only 1 reappear.\n\n   When a client is removed as the result of a KILL message, the server\n   SHOULD add the nickname to the list of unavailable nicknames in an\n   attempt to avoid clients to reuse this name immediately which is\n   usually the pattern of abusive behaviour often leading to useless\n   \"KILL loops\".  See the \"IRC Server Protocol\" document [IRC-SERVER]\n   for more information on this procedure.\n\n   The comment given MUST reflect the actual reason for the KILL.  For\n   server-generated KILLs it usually is made up of details concerning\n   the origins of the two conflicting nicknames.  For users it is left\n   up to them to provide an adequate reason to satisfy others who see\n   it.  To prevent/discourage fake KILLs from being generated to hide\n   the identify of the KILLer, the comment also shows a 'kill-path'\n   which is updated by each server it passes through, each prepending\n   its name to the path.\n\n   Numeric Replies:\n\n           ERR_NOPRIVILEGES              ERR_NEEDMOREPARAMS\n           ERR_NOSUCHNICK                ERR_CANTKILLSERVER\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 35]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   NOTE:\n   It is RECOMMENDED that only Operators be allowed to kill other users\n   with KILL command.  This command has been the subject of many\n   controversies over the years, and along with the above\n   recommendation, it is also widely recognized that not even operators\n   should be allowed to kill users on remote servers.\n\n3.7.2 Ping message\n\n      Command: PING\n   Parameters: <server1> [ <server2> ]\n\n   The PING command is used to test the presence of an active client or\n   server at the other end of the connection.  Servers send a PING\n   message at regular intervals if no other activity detected coming\n   from a connection.  If a connection fails to respond to a PING\n   message within a set amount of time, that connection is closed.  A\n   PING message MAY be sent even if the connection is active.\n\n   When a PING message is received, the appropriate PONG message MUST be\n   sent as reply to <server1> (server which sent the PING message out)\n   as soon as possible.  If the <server2> parameter is specified, it\n   represents the target of the ping, and the message gets forwarded\n   there.\n\n   Numeric Replies:\n\n           ERR_NOORIGIN                  ERR_NOSUCHSERVER\n\n   Examples:\n\n   PING tolsun.oulu.fi             ; Command to send a PING message to\n                                   server\n\n   PING WiZ tolsun.oulu.fi         ; Command from WiZ to send a PING\n                                   message to server \"tolsun.oulu.fi\"\n\n   PING :irc.funet.fi              ; Ping message sent by server\n                                   \"irc.funet.fi\"\n\n\n\n\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 36]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n3.7.3 Pong message\n\n      Command: PONG\n   Parameters: <server> [ <server2> ]\n\n   PONG message is a reply to ping message.  If parameter <server2> is\n   given, this message MUST be forwarded to given target.  The <server>\n   parameter is the name of the entity who has responded to PING message\n   and generated this message.\n\n   Numeric Replies:\n\n           ERR_NOORIGIN                  ERR_NOSUCHSERVER\n\n   Example:\n\n   PONG csd.bu.edu tolsun.oulu.fi  ; PONG message from csd.bu.edu to\n                                   tolsun.oulu.fi\n\n3.7.4 Error\n\n      Command: ERROR\n   Parameters: <error message>\n\n   The ERROR command is for use by servers when reporting a serious or\n   fatal error to its peers.  It may also be sent from one server to\n   another but MUST NOT be accepted from any normal unknown clients.\n\n   Only an ERROR message SHOULD be used for reporting errors which occur\n   with a server-to-server link.  An ERROR message is sent to the server\n   at the other end (which reports it to appropriate local users and\n   logs) and to appropriate local users and logs.  It is not to be\n   passed onto any other servers by a server if it is received from a\n   server.\n\n   The ERROR message is also used before terminating a client\n   connection.\n\n   When a server sends a received ERROR message to its operators, the\n   message SHOULD be encapsulated inside a NOTICE message, indicating\n   that the client was not responsible for the error.\n\n   Numerics:\n\n           None.\n\n\n\n\n\n\nKalt                         Informational                     [Page 37]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   ERROR :Server *.fi already exists ; ERROR message to the other server\n                                   which caused this error.\n\n   NOTICE WiZ :ERROR from csd.bu.edu -- Server *.fi already exists\n                                   ; Same ERROR message as above but\n                                   sent to user WiZ on the other server.\n\n4. Optional features\n\n   This section describes OPTIONAL messages.  They are not required in a\n   working server implementation of the protocol described herein.  In\n   the absence of the feature, an error reply message MUST be generated\n   or an unknown command error.  If the message is destined for another\n   server to answer then it MUST be passed on (elementary parsing\n   REQUIRED) The allocated numerics for this are listed with the\n   messages below.\n\n   From this section, only the USERHOST and ISON messages are available\n   to services.\n\n4.1 Away\n\n      Command: AWAY\n   Parameters: [ <text> ]\n\n   With the AWAY command, clients can set an automatic reply string for\n   any PRIVMSG commands directed at them (not to a channel they are on).\n   The server sends an automatic reply to the client sending the PRIVMSG\n   command.  The only replying server is the one to which the sending\n   client is connected to.\n\n   The AWAY command is used either with one parameter, to set an AWAY\n   message, or with no parameters, to remove the AWAY message.\n\n   Because of its high cost (memory and bandwidth wise), the AWAY\n   message SHOULD only be used for client-server communication.  A\n   server MAY choose to silently ignore AWAY messages received from\n   other servers.  To update the away status of a client across servers,\n   the user mode 'a' SHOULD be used instead.  (See Section 3.1.5)\n\n   Numeric Replies:\n\n           RPL_UNAWAY                    RPL_NOWAWAY\n\n\n\n\n\n\nKalt                         Informational                     [Page 38]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Example:\n\n   AWAY :Gone to lunch.  Back in 5 ; Command to set away message to\n                                   \"Gone to lunch.  Back in 5\".\n\n4.2 Rehash message\n\n      Command: REHASH\n   Parameters: None\n\n   The rehash command is an administrative command which can be used by\n   an operator to force the server to re-read and process its\n   configuration file.\n\n   Numeric Replies:\n\n           RPL_REHASHING                 ERR_NOPRIVILEGES\n\n\n   Example:\n\n   REHASH                          ; message from user with operator\n                                   status to server asking it to reread\n                                   its configuration file.\n\n4.3 Die message\n\n      Command: DIE\n   Parameters: None\n\n   An operator can use the DIE command to shutdown the server.  This\n   message is optional since it may be viewed as a risk to allow\n   arbitrary people to connect to a server as an operator and execute\n   this command.\n\n   The DIE command MUST always be fully processed by the server to which\n   the sending client is connected and MUST NOT be passed onto other\n   connected servers.\n\n   Numeric Replies:\n\n           ERR_NOPRIVILEGES\n\n   Example:\n\n   DIE                             ; no parameters required.\n\n\n\n\n\nKalt                         Informational                     [Page 39]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n4.4 Restart message\n\n      Command: RESTART\n   Parameters: None\n\n   An operator can use the restart command to force the server to\n   restart itself.  This message is optional since it may be viewed as a\n   risk to allow arbitrary people to connect to a server as an operator\n   and execute this command, causing (at least) a disruption to service.\n\n   The RESTART command MUST always be fully processed by the server to\n   which the sending client is connected and MUST NOT be passed onto\n   other connected servers.\n\n   Numeric Replies:\n\n           ERR_NOPRIVILEGES\n\n   Example:\n\n   RESTART                         ; no parameters required.\n\n4.5 Summon message\n\n      Command: SUMMON\n   Parameters: <user> [ <target> [ <channel> ] ]\n\n   The SUMMON command can be used to give users who are on a host\n   running an IRC server a message asking them to please join IRC.  This\n   message is only sent if the target server (a) has SUMMON enabled, (b)\n   the user is logged in and (c) the server process can write to the\n   user's tty (or similar).\n\n   If no <server> parameter is given it tries to summon <user> from the\n   server the client is connected to is assumed as the target.\n\n   If summon is not enabled in a server, it MUST return the\n   ERR_SUMMONDISABLED numeric.\n\n   Numeric Replies:\n\n           ERR_NORECIPIENT               ERR_FILEERROR\n           ERR_NOLOGIN                   ERR_NOSUCHSERVER\n           ERR_SUMMONDISABLED            RPL_SUMMONING\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 40]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   Examples:\n\n   SUMMON jto                      ; summon user jto on the server's\n                                   host\n\n   SUMMON jto tolsun.oulu.fi       ; summon user jto on the host which a\n                                   server named \"tolsun.oulu.fi\" is\n                                   running.\n\n4.6 Users\n\n      Command: USERS\n   Parameters: [ <target> ]\n\n   The USERS command returns a list of users logged into the server in a\n   format similar to the UNIX commands who(1), rusers(1) and finger(1).\n   If disabled, the correct numeric MUST be returned to indicate this.\n\n   Because of the security implications of such a command, it SHOULD be\n   disabled by default in server implementations.  Enabling it SHOULD\n   require recompiling the server or some equivalent change rather than\n   simply toggling an option and restarting the server.  The procedure\n   to enable this command SHOULD also include suitable large comments.\n\n   Numeric Replies:\n\n           ERR_NOSUCHSERVER              ERR_FILEERROR\n           RPL_USERSSTART                RPL_USERS\n           RPL_NOUSERS                   RPL_ENDOFUSERS\n           ERR_USERSDISABLED\n\n   Disabled Reply:\n\n           ERR_USERSDISABLED\n\n   Example:\n\n   USERS eff.org                   ; request a list of users logged in\n                                   on server eff.org\n\n4.7 Operwall message\n\n      Command: WALLOPS\n   Parameters: <Text to be sent>\n\n   The WALLOPS command is used to send a message to all currently\n   connected users who have set the 'w' user mode for themselves.  (See\n   Section 3.1.5 \"User modes\").\n\n\n\nKalt                         Informational                     [Page 41]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   After implementing WALLOPS as a user command it was found that it was\n   often and commonly abused as a means of sending a message to a lot of\n   people.  Due to this, it is RECOMMENDED that the implementation of\n   WALLOPS allows and recognizes only servers as the originators of\n   WALLOPS.\n\n   Numeric Replies:\n\n           ERR_NEEDMOREPARAMS\n\n   Example:\n\n   :csd.bu.edu WALLOPS :Connect '*.uiuc.edu 6667' from Joshua ; WALLOPS\n                                   message from csd.bu.edu announcing a\n                                   CONNECT message it received from\n                                   Joshua and acted upon.\n\n4.8 Userhost message\n\n      Command: USERHOST\n   Parameters: <nickname> *( SPACE <nickname> )\n\n   The USERHOST command takes a list of up to 5 nicknames, each\n   separated by a space character and returns a list of information\n   about each nickname that it found.  The returned list has each reply\n   separated by a space.\n\n   Numeric Replies:\n\n           RPL_USERHOST                  ERR_NEEDMOREPARAMS\n\n   Example:\n\n   USERHOST Wiz Michael syrk       ; USERHOST request for information on\n                                   nicks \"Wiz\", \"Michael\", and \"syrk\"\n\n   :ircd.stealth.net 302 yournick :syrk=+syrk@millennium.stealth.net\n                                   ; Reply for user syrk\n\n4.9 Ison message\n\n      Command: ISON\n   Parameters: <nickname> *( SPACE <nickname> )\n\n   The ISON command was implemented to provide a quick and efficient\n   means to get a response about whether a given nickname was currently\n   on IRC. ISON only takes one (1) type of parameter: a space-separated\n   list of nicks.  For each nickname in the list that is present, the\n\n\n\nKalt                         Informational                     [Page 42]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   server adds that to its reply string.  Thus the reply string may\n   return empty (none of the given nicks are present), an exact copy of\n   the parameter string (all of them present) or any other subset of the\n   set of nicks given in the parameter.  The only limit on the number of\n   nicks that may be checked is that the combined length MUST NOT be too\n   large as to cause the server to chop it off so it fits in 512\n   characters.\n\n   ISON is only processed by the server local to the client sending the\n   command and thus not passed onto other servers for further\n   processing.\n\n   Numeric Replies:\n\n           RPL_ISON                      ERR_NEEDMOREPARAMS\n\n   Example:\n\n   ISON phone trillian WiZ jarlek Avalon Angel Monstah syrk\n                                   ; Sample ISON request for 7 nicks.\n\n5. Replies\n\n   The following is a list of numeric replies which are generated in\n   response to the commands given above.  Each numeric is given with its\n   number, name and reply string.\n\n5.1 Command responses\n\n   Numerics in the range from 001 to 099 are used for client-server\n   connections only and should never travel between servers.  Replies\n   generated in the response to commands are found in the range from 200\n   to 399.\n\n       001    RPL_WELCOME\n              \"Welcome to the Internet Relay Network\n               <nick>!<user>@<host>\"\n       002    RPL_YOURHOST\n              \"Your host is <servername>, running version <ver>\"\n       003    RPL_CREATED\n              \"This server was created <date>\"\n       004    RPL_MYINFO\n              \"<servername> <version> <available user modes>\n               <available channel modes>\"\n\n         - The server sends Replies 001 to 004 to a user upon\n           successful registration.\n\n\n\n\nKalt                         Informational                     [Page 43]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       005    RPL_BOUNCE\n              \"Try server <server name>, port <port number>\"\n\n         - Sent by the server to a user to suggest an alternative\n           server.  This is often used when the connection is\n           refused because the server is already full.\n\n       302    RPL_USERHOST\n              \":*1<reply> *( \" \" <reply> )\"\n\n         - Reply format used by USERHOST to list replies to\n           the query list.  The reply string is composed as\n           follows:\n\n           reply = nickname [ \"*\" ] \"=\" ( \"+\" / \"-\" ) hostname\n\n           The '*' indicates whether the client has registered\n           as an Operator.  The '-' or '+' characters represent\n           whether the client has set an AWAY message or not\n           respectively.\n\n       303    RPL_ISON\n              \":*1<nick> *( \" \" <nick> )\"\n\n         - Reply format used by ISON to list replies to the\n           query list.\n\n       301    RPL_AWAY\n              \"<nick> :<away message>\"\n       305    RPL_UNAWAY\n              \":You are no longer marked as being away\"\n       306    RPL_NOWAWAY\n              \":You have been marked as being away\"\n\n         - These replies are used with the AWAY command (if\n           allowed).  RPL_AWAY is sent to any client sending a\n           PRIVMSG to a client which is away.  RPL_AWAY is only\n           sent by the server to which the client is connected.\n           Replies RPL_UNAWAY and RPL_NOWAWAY are sent when the\n           client removes and sets an AWAY message.\n\n       311    RPL_WHOISUSER\n              \"<nick> <user> <host> * :<real name>\"\n       312    RPL_WHOISSERVER\n              \"<nick> <server> :<server info>\"\n       313    RPL_WHOISOPERATOR\n              \"<nick> :is an IRC operator\"\n\n\n\n\nKalt                         Informational                     [Page 44]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       317    RPL_WHOISIDLE\n              \"<nick> <integer> :seconds idle\"\n       318    RPL_ENDOFWHOIS\n              \"<nick> :End of WHOIS list\"\n       319    RPL_WHOISCHANNELS\n              \"<nick> :*( ( \"@\" / \"+\" ) <channel> \" \" )\"\n\n         - Replies 311 - 313, 317 - 319 are all replies\n           generated in response to a WHOIS message.  Given that\n           there are enough parameters present, the answering\n           server MUST either formulate a reply out of the above\n           numerics (if the query nick is found) or return an\n           error reply.  The '*' in RPL_WHOISUSER is there as\n           the literal character and not as a wild card.  For\n           each reply set, only RPL_WHOISCHANNELS may appear\n           more than once (for long lists of channel names).\n           The '@' and '+' characters next to the channel name\n           indicate whether a client is a channel operator or\n           has been granted permission to speak on a moderated\n           channel.  The RPL_ENDOFWHOIS reply is used to mark\n           the end of processing a WHOIS message.\n\n       314    RPL_WHOWASUSER\n              \"<nick> <user> <host> * :<real name>\"\n       369    RPL_ENDOFWHOWAS\n              \"<nick> :End of WHOWAS\"\n\n         - When replying to a WHOWAS message, a server MUST use\n           the replies RPL_WHOWASUSER, RPL_WHOISSERVER or\n           ERR_WASNOSUCHNICK for each nickname in the presented\n           list.  At the end of all reply batches, there MUST\n           be RPL_ENDOFWHOWAS (even if there was only one reply\n           and it was an error).\n\n       321    RPL_LISTSTART\n              Obsolete. Not used.\n\n       322    RPL_LIST\n              \"<channel> <# visible> :<topic>\"\n       323    RPL_LISTEND\n              \":End of LIST\"\n\n         - Replies RPL_LIST, RPL_LISTEND mark the actual replies\n           with data and end of the server's response to a LIST\n           command.  If there are no channels available to return,\n           only the end reply MUST be sent.\n\n\n\n\n\nKalt                         Informational                     [Page 45]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       325    RPL_UNIQOPIS\n              \"<channel> <nickname>\"\n\n       324    RPL_CHANNELMODEIS\n              \"<channel> <mode> <mode params>\"\n\n       331    RPL_NOTOPIC\n              \"<channel> :No topic is set\"\n       332    RPL_TOPIC\n              \"<channel> :<topic>\"\n\n         - When sending a TOPIC message to determine the\n           channel topic, one of two replies is sent.  If\n           the topic is set, RPL_TOPIC is sent back else\n           RPL_NOTOPIC.\n\n       341    RPL_INVITING\n              \"<channel> <nick>\"\n\n         - Returned by the server to indicate that the\n           attempted INVITE message was successful and is\n           being passed onto the end client.\n\n       342    RPL_SUMMONING\n              \"<user> :Summoning user to IRC\"\n\n         - Returned by a server answering a SUMMON message to\n           indicate that it is summoning that user.\n\n       346    RPL_INVITELIST\n              \"<channel> <invitemask>\"\n       347    RPL_ENDOFINVITELIST\n              \"<channel> :End of channel invite list\"\n\n         - When listing the 'invitations masks' for a given channel,\n           a server is required to send the list back using the\n           RPL_INVITELIST and RPL_ENDOFINVITELIST messages.  A\n           separate RPL_INVITELIST is sent for each active mask.\n           After the masks have been listed (or if none present) a\n           RPL_ENDOFINVITELIST MUST be sent.\n\n       348    RPL_EXCEPTLIST\n              \"<channel> <exceptionmask>\"\n       349    RPL_ENDOFEXCEPTLIST\n              \"<channel> :End of channel exception list\"\n\n\n\n\n\n\nKalt                         Informational                     [Page 46]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n         - When listing the 'exception masks' for a given channel,\n           a server is required to send the list back using the\n           RPL_EXCEPTLIST and RPL_ENDOFEXCEPTLIST messages.  A\n           separate RPL_EXCEPTLIST is sent for each active mask.\n           After the masks have been listed (or if none present)\n           a RPL_ENDOFEXCEPTLIST MUST be sent.\n\n       351    RPL_VERSION\n              \"<version>.<debuglevel> <server> :<comments>\"\n\n         - Reply by the server showing its version details.\n           The <version> is the version of the software being\n           used (including any patchlevel revisions) and the\n           <debuglevel> is used to indicate if the server is\n           running in \"debug mode\".\n\n           The \"comments\" field may contain any comments about\n           the version or further version details.\n\n       352    RPL_WHOREPLY\n              \"<channel> <user> <host> <server> <nick>\n              ( \"H\" / \"G\" > [\"*\"] [ ( \"@\" / \"+\" ) ]\n              :<hopcount> <real name>\"\n\n       315    RPL_ENDOFWHO\n              \"<name> :End of WHO list\"\n\n         - The RPL_WHOREPLY and RPL_ENDOFWHO pair are used\n           to answer a WHO message.  The RPL_WHOREPLY is only\n           sent if there is an appropriate match to the WHO\n           query.  If there is a list of parameters supplied\n           with a WHO message, a RPL_ENDOFWHO MUST be sent\n           after processing each list item with <name> being\n           the item.\n\n       353    RPL_NAMREPLY\n              \"( \"=\" / \"*\" / \"@\" ) <channel>\n               :[ \"@\" / \"+\" ] <nick> *( \" \" [ \"@\" / \"+\" ] <nick> )\n         - \"@\" is used for secret channels, \"*\" for private\n           channels, and \"=\" for others (public channels).\n\n       366    RPL_ENDOFNAMES\n              \"<channel> :End of NAMES list\"\n\n         - To reply to a NAMES message, a reply pair consisting\n           of RPL_NAMREPLY and RPL_ENDOFNAMES is sent by the\n           server back to the client.  If there is no channel\n           found as in the query, then only RPL_ENDOFNAMES is\n\n\n\nKalt                         Informational                     [Page 47]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n           returned.  The exception to this is when a NAMES\n           message is sent with no parameters and all visible\n           channels and contents are sent back in a series of\n           RPL_NAMEREPLY messages with a RPL_ENDOFNAMES to mark\n           the end.\n\n       364    RPL_LINKS\n              \"<mask> <server> :<hopcount> <server info>\"\n       365    RPL_ENDOFLINKS\n              \"<mask> :End of LINKS list\"\n\n         - In replying to the LINKS message, a server MUST send\n           replies back using the RPL_LINKS numeric and mark the\n           end of the list using an RPL_ENDOFLINKS reply.\n\n       367    RPL_BANLIST\n              \"<channel> <banmask>\"\n       368    RPL_ENDOFBANLIST\n              \"<channel> :End of channel ban list\"\n\n         - When listing the active 'bans' for a given channel,\n           a server is required to send the list back using the\n           RPL_BANLIST and RPL_ENDOFBANLIST messages.  A separate\n           RPL_BANLIST is sent for each active banmask.  After the\n           banmasks have been listed (or if none present) a\n           RPL_ENDOFBANLIST MUST be sent.\n\n       371    RPL_INFO\n              \":<string>\"\n       374    RPL_ENDOFINFO\n              \":End of INFO list\"\n\n         - A server responding to an INFO message is required to\n           send all its 'info' in a series of RPL_INFO messages\n           with a RPL_ENDOFINFO reply to indicate the end of the\n           replies.\n\n       375    RPL_MOTDSTART\n              \":- <server> Message of the day - \"\n       372    RPL_MOTD\n              \":- <text>\"\n       376    RPL_ENDOFMOTD\n              \":End of MOTD command\"\n\n         - When responding to the MOTD message and the MOTD file\n           is found, the file is displayed line by line, with\n           each line no longer than 80 characters, using\n\n\n\n\nKalt                         Informational                     [Page 48]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n           RPL_MOTD format replies.  These MUST be surrounded\n           by a RPL_MOTDSTART (before the RPL_MOTDs) and an\n           RPL_ENDOFMOTD (after).\n\n       381    RPL_YOUREOPER\n              \":You are now an IRC operator\"\n\n         - RPL_YOUREOPER is sent back to a client which has\n           just successfully issued an OPER message and gained\n           operator status.\n\n       382    RPL_REHASHING\n              \"<config file> :Rehashing\"\n\n         - If the REHASH option is used and an operator sends\n           a REHASH message, an RPL_REHASHING is sent back to\n           the operator.\n\n       383    RPL_YOURESERVICE\n              \"You are service <servicename>\"\n\n         - Sent by the server to a service upon successful\n           registration.\n\n       391    RPL_TIME\n              \"<server> :<string showing server's local time>\"\n\n         - When replying to the TIME message, a server MUST send\n           the reply using the RPL_TIME format above.  The string\n           showing the time need only contain the correct day and\n           time there.  There is no further requirement for the\n           time string.\n\n       392    RPL_USERSSTART\n              \":UserID   Terminal  Host\"\n       393    RPL_USERS\n              \":<username> <ttyline> <hostname>\"\n       394    RPL_ENDOFUSERS\n              \":End of users\"\n       395    RPL_NOUSERS\n              \":Nobody logged in\"\n\n         - If the USERS message is handled by a server, the\n           replies RPL_USERSTART, RPL_USERS, RPL_ENDOFUSERS and\n           RPL_NOUSERS are used.  RPL_USERSSTART MUST be sent\n           first, following by either a sequence of RPL_USERS\n           or a single RPL_NOUSER.  Following this is\n           RPL_ENDOFUSERS.\n\n\n\nKalt                         Informational                     [Page 49]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       200    RPL_TRACELINK\n              \"Link <version & debug level> <destination>\n               <next server> V<protocol version>\n               <link uptime in seconds> <backstream sendq>\n               <upstream sendq>\"\n       201    RPL_TRACECONNECTING\n              \"Try. <class> <server>\"\n       202    RPL_TRACEHANDSHAKE\n              \"H.S. <class> <server>\"\n       203    RPL_TRACEUNKNOWN\n              \"???? <class> [<client IP address in dot form>]\"\n       204    RPL_TRACEOPERATOR\n              \"Oper <class> <nick>\"\n       205    RPL_TRACEUSER\n              \"User <class> <nick>\"\n       206    RPL_TRACESERVER\n              \"Serv <class> <int>S <int>C <server>\n               <nick!user|*!*>@<host|server> V<protocol version>\"\n       207    RPL_TRACESERVICE\n              \"Service <class> <name> <type> <active type>\"\n       208    RPL_TRACENEWTYPE\n              \"<newtype> 0 <client name>\"\n       209    RPL_TRACECLASS\n              \"Class <class> <count>\"\n       210    RPL_TRACERECONNECT\n              Unused.\n       261    RPL_TRACELOG\n              \"File <logfile> <debug level>\"\n       262    RPL_TRACEEND\n              \"<server name> <version & debug level> :End of TRACE\"\n\n         - The RPL_TRACE* are all returned by the server in\n           response to the TRACE message.  How many are\n           returned is dependent on the TRACE message and\n           whether it was sent by an operator or not.  There\n           is no predefined order for which occurs first.\n           Replies RPL_TRACEUNKNOWN, RPL_TRACECONNECTING and\n           RPL_TRACEHANDSHAKE are all used for connections\n           which have not been fully established and are either\n           unknown, still attempting to connect or in the\n           process of completing the 'server handshake'.\n           RPL_TRACELINK is sent by any server which handles\n           a TRACE message and has to pass it on to another\n           server.  The list of RPL_TRACELINKs sent in\n           response to a TRACE command traversing the IRC\n           network should reflect the actual connectivity of\n           the servers themselves along that path.\n\n\n\n\nKalt                         Informational                     [Page 50]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n           RPL_TRACENEWTYPE is to be used for any connection\n           which does not fit in the other categories but is\n           being displayed anyway.\n           RPL_TRACEEND is sent to indicate the end of the list.\n\n       211    RPL_STATSLINKINFO\n              \"<linkname> <sendq> <sent messages>\n               <sent Kbytes> <received messages>\n               <received Kbytes> <time open>\"\n\n         - reports statistics on a connection.  <linkname>\n           identifies the particular connection, <sendq> is\n           the amount of data that is queued and waiting to be\n           sent <sent messages> the number of messages sent,\n           and <sent Kbytes> the amount of data sent, in\n           Kbytes. <received messages> and <received Kbytes>\n           are the equivalent of <sent messages> and <sent\n           Kbytes> for received data, respectively.  <time\n           open> indicates how long ago the connection was\n           opened, in seconds.\n\n       212    RPL_STATSCOMMANDS\n              \"<command> <count> <byte count> <remote count>\"\n\n         - reports statistics on commands usage.\n\n       219    RPL_ENDOFSTATS\n              \"<stats letter> :End of STATS report\"\n\n       242    RPL_STATSUPTIME\n              \":Server Up %d days %d:%02d:%02d\"\n\n         - reports the server uptime.\n\n       243    RPL_STATSOLINE\n              \"O <hostmask> * <name>\"\n\n         - reports the allowed hosts from where user may become IRC\n           operators.\n\n       221    RPL_UMODEIS\n              \"<user mode string>\"\n\n         - To answer a query about a client's own mode,\n           RPL_UMODEIS is sent back.\n\n       234    RPL_SERVLIST\n              \"<name> <server> <mask> <type> <hopcount> <info>\"\n\n\n\nKalt                         Informational                     [Page 51]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       235    RPL_SERVLISTEND\n              \"<mask> <type> :End of service listing\"\n\n         - When listing services in reply to a SERVLIST message,\n           a server is required to send the list back using the\n           RPL_SERVLIST and RPL_SERVLISTEND messages.  A separate\n           RPL_SERVLIST is sent for each service.  After the\n           services have been listed (or if none present) a\n           RPL_SERVLISTEND MUST be sent.\n\n       251    RPL_LUSERCLIENT\n              \":There are <integer> users and <integer>\n               services on <integer> servers\"\n       252    RPL_LUSEROP\n              \"<integer> :operator(s) online\"\n       253    RPL_LUSERUNKNOWN\n              \"<integer> :unknown connection(s)\"\n       254    RPL_LUSERCHANNELS\n              \"<integer> :channels formed\"\n       255    RPL_LUSERME\n              \":I have <integer> clients and <integer>\n                servers\"\n\n         - In processing an LUSERS message, the server\n           sends a set of replies from RPL_LUSERCLIENT,\n           RPL_LUSEROP, RPL_USERUNKNOWN,\n           RPL_LUSERCHANNELS and RPL_LUSERME.  When\n           replying, a server MUST send back\n           RPL_LUSERCLIENT and RPL_LUSERME.  The other\n           replies are only sent back if a non-zero count\n           is found for them.\n\n       256    RPL_ADMINME\n              \"<server> :Administrative info\"\n       257    RPL_ADMINLOC1\n              \":<admin info>\"\n       258    RPL_ADMINLOC2\n              \":<admin info>\"\n       259    RPL_ADMINEMAIL\n              \":<admin info>\"\n\n         - When replying to an ADMIN message, a server\n           is expected to use replies RPL_ADMINME\n           through to RPL_ADMINEMAIL and provide a text\n           message with each.  For RPL_ADMINLOC1 a\n           description of what city, state and country\n           the server is in is expected, followed by\n           details of the institution (RPL_ADMINLOC2)\n\n\n\nKalt                         Informational                     [Page 52]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n           and finally the administrative contact for the\n           server (an email address here is REQUIRED)\n           in RPL_ADMINEMAIL.\n\n       263    RPL_TRYAGAIN\n              \"<command> :Please wait a while and try again.\"\n\n         - When a server drops a command without processing it,\n           it MUST use the reply RPL_TRYAGAIN to inform the\n           originating client.\n\n5.2 Error Replies\n\n       Error replies are found in the range from 400 to 599.\n\n       401    ERR_NOSUCHNICK\n              \"<nickname> :No such nick/channel\"\n\n          - Used to indicate the nickname parameter supplied to a\n            command is currently unused.\n\n       402    ERR_NOSUCHSERVER\n              \"<server name> :No such server\"\n\n         - Used to indicate the server name given currently\n           does not exist.\n\n       403    ERR_NOSUCHCHANNEL\n              \"<channel name> :No such channel\"\n\n         - Used to indicate the given channel name is invalid.\n\n       404    ERR_CANNOTSENDTOCHAN\n              \"<channel name> :Cannot send to channel\"\n\n         - Sent to a user who is either (a) not on a channel\n           which is mode +n or (b) not a chanop (or mode +v) on\n           a channel which has mode +m set or where the user is\n           banned and is trying to send a PRIVMSG message to\n           that channel.\n\n       405    ERR_TOOMANYCHANNELS\n              \"<channel name> :You have joined too many channels\"\n\n         - Sent to a user when they have joined the maximum\n           number of allowed channels and they try to join\n           another channel.\n\n\n\n\nKalt                         Informational                     [Page 53]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       406    ERR_WASNOSUCHNICK\n              \"<nickname> :There was no such nickname\"\n\n         - Returned by WHOWAS to indicate there is no history\n           information for that nickname.\n\n       407    ERR_TOOMANYTARGETS\n              \"<target> :<error code> recipients. <abort message>\"\n\n         - Returned to a client which is attempting to send a\n           PRIVMSG/NOTICE using the user@host destination format\n           and for a user@host which has several occurrences.\n\n         - Returned to a client which trying to send a\n           PRIVMSG/NOTICE to too many recipients.\n\n         - Returned to a client which is attempting to JOIN a safe\n           channel using the shortname when there are more than one\n           such channel.\n\n       408    ERR_NOSUCHSERVICE\n              \"<service name> :No such service\"\n\n         - Returned to a client which is attempting to send a SQUERY\n           to a service which does not exist.\n\n       409    ERR_NOORIGIN\n              \":No origin specified\"\n\n         - PING or PONG message missing the originator parameter.\n\n       411    ERR_NORECIPIENT\n              \":No recipient given (<command>)\"\n       412    ERR_NOTEXTTOSEND\n              \":No text to send\"\n       413    ERR_NOTOPLEVEL\n              \"<mask> :No toplevel domain specified\"\n       414    ERR_WILDTOPLEVEL\n              \"<mask> :Wildcard in toplevel domain\"\n       415    ERR_BADMASK\n              \"<mask> :Bad Server/host mask\"\n\n         - 412 - 415 are returned by PRIVMSG to indicate that\n           the message wasn't delivered for some reason.\n           ERR_NOTOPLEVEL and ERR_WILDTOPLEVEL are errors that\n           are returned when an invalid use of\n           \"PRIVMSG $<server>\" or \"PRIVMSG #<host>\" is attempted.\n\n\n\n\nKalt                         Informational                     [Page 54]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       421    ERR_UNKNOWNCOMMAND\n              \"<command> :Unknown command\"\n\n         - Returned to a registered client to indicate that the\n           command sent is unknown by the server.\n\n       422    ERR_NOMOTD\n              \":MOTD File is missing\"\n\n         - Server's MOTD file could not be opened by the server.\n\n       423    ERR_NOADMININFO\n              \"<server> :No administrative info available\"\n\n         - Returned by a server in response to an ADMIN message\n           when there is an error in finding the appropriate\n           information.\n\n       424    ERR_FILEERROR\n              \":File error doing <file op> on <file>\"\n\n         - Generic error message used to report a failed file\n           operation during the processing of a message.\n\n       431    ERR_NONICKNAMEGIVEN\n              \":No nickname given\"\n\n         - Returned when a nickname parameter expected for a\n           command and isn't found.\n\n       432    ERR_ERRONEUSNICKNAME\n              \"<nick> :Erroneous nickname\"\n\n         - Returned after receiving a NICK message which contains\n           characters which do not fall in the defined set.  See\n           section 2.3.1 for details on valid nicknames.\n\n       433    ERR_NICKNAMEINUSE\n              \"<nick> :Nickname is already in use\"\n\n         - Returned when a NICK message is processed that results\n           in an attempt to change to a currently existing\n           nickname.\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 55]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       436    ERR_NICKCOLLISION\n              \"<nick> :Nickname collision KILL from <user>@<host>\"\n\n         - Returned by a server to a client when it detects a\n           nickname collision (registered of a NICK that\n           already exists by another server).\n\n       437    ERR_UNAVAILRESOURCE\n              \"<nick/channel> :Nick/channel is temporarily unavailable\"\n\n         - Returned by a server to a user trying to join a channel\n           currently blocked by the channel delay mechanism.\n\n         - Returned by a server to a user trying to change nickname\n           when the desired nickname is blocked by the nick delay\n           mechanism.\n\n       441    ERR_USERNOTINCHANNEL\n              \"<nick> <channel> :They aren't on that channel\"\n\n         - Returned by the server to indicate that the target\n           user of the command is not on the given channel.\n\n       442    ERR_NOTONCHANNEL\n              \"<channel> :You're not on that channel\"\n\n         - Returned by the server whenever a client tries to\n           perform a channel affecting command for which the\n           client isn't a member.\n\n       443    ERR_USERONCHANNEL\n              \"<user> <channel> :is already on channel\"\n\n         - Returned when a client tries to invite a user to a\n           channel they are already on.\n\n       444    ERR_NOLOGIN\n              \"<user> :User not logged in\"\n\n         - Returned by the summon after a SUMMON command for a\n           user was unable to be performed since they were not\n           logged in.\n\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 56]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       445    ERR_SUMMONDISABLED\n              \":SUMMON has been disabled\"\n\n         - Returned as a response to the SUMMON command.  MUST be\n           returned by any server which doesn't implement it.\n\n       446    ERR_USERSDISABLED\n              \":USERS has been disabled\"\n\n         - Returned as a response to the USERS command.  MUST be\n           returned by any server which does not implement it.\n\n       451    ERR_NOTREGISTERED\n              \":You have not registered\"\n\n         - Returned by the server to indicate that the client\n           MUST be registered before the server will allow it\n           to be parsed in detail.\n\n       461    ERR_NEEDMOREPARAMS\n              \"<command> :Not enough parameters\"\n\n         - Returned by the server by numerous commands to\n           indicate to the client that it didn't supply enough\n           parameters.\n\n       462    ERR_ALREADYREGISTRED\n              \":Unauthorized command (already registered)\"\n\n         - Returned by the server to any link which tries to\n           change part of the registered details (such as\n           password or user details from second USER message).\n\n       463    ERR_NOPERMFORHOST\n              \":Your host isn't among the privileged\"\n\n         - Returned to a client which attempts to register with\n           a server which does not been setup to allow\n           connections from the host the attempted connection\n           is tried.\n\n       464    ERR_PASSWDMISMATCH\n              \":Password incorrect\"\n\n         - Returned to indicate a failed attempt at registering\n           a connection for which a password was required and\n           was either not given or incorrect.\n\n\n\n\nKalt                         Informational                     [Page 57]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       465    ERR_YOUREBANNEDCREEP\n              \":You are banned from this server\"\n\n         - Returned after an attempt to connect and register\n           yourself with a server which has been setup to\n           explicitly deny connections to you.\n\n       466    ERR_YOUWILLBEBANNED\n\n         - Sent by a server to a user to inform that access to the\n           server will soon be denied.\n\n       467    ERR_KEYSET\n              \"<channel> :Channel key already set\"\n       471    ERR_CHANNELISFULL\n              \"<channel> :Cannot join channel (+l)\"\n       472    ERR_UNKNOWNMODE\n              \"<char> :is unknown mode char to me for <channel>\"\n       473    ERR_INVITEONLYCHAN\n              \"<channel> :Cannot join channel (+i)\"\n       474    ERR_BANNEDFROMCHAN\n              \"<channel> :Cannot join channel (+b)\"\n       475    ERR_BADCHANNELKEY\n              \"<channel> :Cannot join channel (+k)\"\n       476    ERR_BADCHANMASK\n              \"<channel> :Bad Channel Mask\"\n       477    ERR_NOCHANMODES\n              \"<channel> :Channel doesn't support modes\"\n       478    ERR_BANLISTFULL\n              \"<channel> <char> :Channel list is full\"\n\n       481    ERR_NOPRIVILEGES\n              \":Permission Denied- You're not an IRC operator\"\n\n         - Any command requiring operator privileges to operate\n           MUST return this error to indicate the attempt was\n           unsuccessful.\n\n       482    ERR_CHANOPRIVSNEEDED\n              \"<channel> :You're not channel operator\"\n\n         - Any command requiring 'chanop' privileges (such as\n           MODE messages) MUST return this error if the client\n           making the attempt is not a chanop on the specified\n           channel.\n\n\n\n\n\n\nKalt                         Informational                     [Page 58]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n       483    ERR_CANTKILLSERVER\n              \":You can't kill a server!\"\n\n         - Any attempts to use the KILL command on a server\n           are to be refused and this error returned directly\n           to the client.\n\n       484    ERR_RESTRICTED\n              \":Your connection is restricted!\"\n\n         - Sent by the server to a user upon connection to indicate\n           the restricted nature of the connection (user mode \"+r\").\n\n       485    ERR_UNIQOPPRIVSNEEDED\n              \":You're not the original channel operator\"\n\n         - Any MODE requiring \"channel creator\" privileges MUST\n           return this error if the client making the attempt is not\n           a chanop on the specified channel.\n\n       491    ERR_NOOPERHOST\n              \":No O-lines for your host\"\n\n         - If a client sends an OPER message and the server has\n           not been configured to allow connections from the\n           client's host as an operator, this error MUST be\n           returned.\n\n       501    ERR_UMODEUNKNOWNFLAG\n              \":Unknown MODE flag\"\n\n         - Returned by the server to indicate that a MODE\n           message was sent with a nickname parameter and that\n           the a mode flag sent was not recognized.\n\n       502    ERR_USERSDONTMATCH\n              \":Cannot change mode for other users\"\n\n         - Error sent to any user trying to view or change the\n           user mode for a user other than themselves.\n\n5.3 Reserved numerics\n\n   These numerics are not described above since they fall into one of\n   the following categories:\n\n   1. no longer in use;\n\n\n\n\nKalt                         Informational                     [Page 59]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n   2. reserved for future planned use;\n\n   3. in current use but are part of a non-generic 'feature' of\n      the current IRC server.\n\n            231    RPL_SERVICEINFO     232  RPL_ENDOFSERVICES\n            233    RPL_SERVICE\n            300    RPL_NONE            316  RPL_WHOISCHANOP\n            361    RPL_KILLDONE        362  RPL_CLOSING\n            363    RPL_CLOSEEND        373  RPL_INFOSTART\n            384    RPL_MYPORTIS\n\n            213    RPL_STATSCLINE      214  RPL_STATSNLINE\n            215    RPL_STATSILINE      216  RPL_STATSKLINE\n            217    RPL_STATSQLINE      218  RPL_STATSYLINE\n            240    RPL_STATSVLINE      241  RPL_STATSLLINE\n            244    RPL_STATSHLINE      244  RPL_STATSSLINE\n            246    RPL_STATSPING       247  RPL_STATSBLINE\n            250    RPL_STATSDLINE\n\n            492    ERR_NOSERVICEHOST\n\n6. Current implementations\n\n   The IRC software, version 2.10 is the only complete implementation of\n   the IRC protocol (client and server).  Because of the small amount of\n   changes in the client protocol since the publication of RFC 1459\n   [IRC], implementations that follow it are likely to be compliant with\n   this protocol or to require a small amount of changes to reach\n   compliance.\n\n7. Current problems\n\n   There are a number of recognized problems with the IRC Client\n   Protocol, and more generally with the IRC Server Protocol.  In order\n   to preserve backward compatibility with old clients, this protocol\n   has almost not evolved since the publication of RFC 1459 [IRC].\n\n7.1 Nicknames\n\n   The idea of the nickname on IRC is very convenient for users to use\n   when talking to each other outside of a channel, but there is only a\n   finite nickname space and being what they are, it's not uncommon for\n   several people to want to use the same nick.  If a nickname is chosen\n   by two people using this protocol, either one will not succeed or\n   both will removed by use of a server KILL (See Section 3.7.1).\n\n\n\n\n\nKalt                         Informational                     [Page 60]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n7.2 Limitation of wildcards\n\n   There is no way to escape the escape character \"\\\" (%x5C).  While\n   this isn't usually a problem, it makes it impossible to form a mask\n   with a backslash character (\"\\\") preceding a wildcard.\n\n7.3 Security considerations\n\n   Security issues related to this protocol are discussed in the \"IRC\n   Server Protocol\" [IRC-SERVER] as they are mostly an issue for the\n   server side of the connection.\n\n8. Current support and availability\n\n        Mailing lists for IRC related discussion:\n          General discussion: ircd-users@irc.org\n          Protocol development: ircd-dev@irc.org\n\n        Software implementations:\n          ftp://ftp.irc.org/irc/server\n          ftp://ftp.funet.fi/pub/unix/irc\n          ftp://ftp.irc.org/irc/clients\n\n        Newsgroup: alt.irc\n\n9. Acknowledgements\n\n   Parts of this document were copied from the RFC 1459 [IRC] which\n   first formally documented the IRC Protocol.  It has also benefited\n   from many rounds of review and comments.  In particular, the\n   following people have made significant contributions to this\n   document:\n\n   Matthew Green, Michael Neumayer, Volker Paulsen, Kurt Roeckx, Vesa\n   Ruokonen, Magnus Tjernstrom, Stefan Zehl.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 61]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n10. References\n\n   [KEYWORDS]   Bradner, S., \"Key words for use in RFCs to Indicate\n                Requirement Levels\", BCP 14, RFC 2119, March 1997.\n\n   [ABNF]       Crocker, D. and P. Overell, \"Augmented BNF for Syntax\n                Specifications: ABNF\", RFC 2234, November 1997.\n\n   [HNAME]      Braden, R., \"Requirements for Internet Hosts --\n                Application and Support\", STD 3, RFC 1123, October 1989.\n\n   [IRC]        Oikarinen, J. & D. Reed, \"Internet Relay Chat Protocol\",\n                RFC 1459, May 1993.\n\n   [IRC-ARCH]   Kalt, C., \"Internet Relay Chat: Architecture\", RFC 2810,\n                April 2000.\n\n   [IRC-CHAN]   Kalt, C., \"Internet Relay Chat: Channel Management\", RFC\n                2811, April 2000.\n\n   [IRC-SERVER] Kalt, C., \"Internet Relay Chat: Server Protocol\", RFC\n                2813, April 2000.\n\n11. Author's Address\n\n   Christophe Kalt\n   99 Teaneck Rd, Apt #117\n   Ridgefield Park, NJ 07660\n   USA\n\n   EMail: kalt@stealth.net\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 62]\n\f\nRFC 2812          Internet Relay Chat: Client Protocol        April 2000\n\n\n12.  Full Copyright Statement\n\n   Copyright (C) The Internet Society (2000).  All Rights Reserved.\n\n   This document and translations of it may be copied and furnished to\n   others, and derivative works that comment on or otherwise explain it\n   or assist in its implementation may be prepared, copied, published\n   and distributed, in whole or in part, without restriction of any\n   kind, provided that the above copyright notice and this paragraph are\n   included on all such copies and derivative works.  However, this\n   document itself may not be modified in any way, such as by removing\n   the copyright notice or references to the Internet Society or other\n   Internet organizations, except as needed for the purpose of\n   developing Internet standards in which case the procedures for\n   copyrights defined in the Internet Standards process must be\n   followed, or as required to translate it into languages other than\n   English.\n\n   The limited permissions granted above are perpetual and will not be\n   revoked by the Internet Society or its successors or assigns.\n\n   This document and the information contained herein is provided on an\n   \"AS IS\" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING\n   TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING\n   BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION\n   HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF\n   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n\nAcknowledgement\n\n   Funding for the RFC Editor function is currently provided by the\n   Internet Society.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nKalt                         Informational                     [Page 63]\n\f\n"
  },
  {
    "path": "irc3/tags.py",
    "content": "# -*- coding: utf-8 -*-\n'''\nModule offering 2 functions, encode() and decode(), to transcode between\nIRCv3.2 tags and python dictionaries.\n'''\nimport re\nimport random\nimport string\n\n\n_escapes = (\n    (\"\\\\\", \"\\\\\\\\\"),\n    (\";\", r\"\\:\"),\n    (\" \", r\"\\s\"),\n    (\"\\r\", r\"\\r\"),\n    (\"\\n\", r\"\\n\"),\n)\n\n# make the possibility of the substitute actually appearing in the text\n# negligible. Even for targeted attacks\n_substitute = (\";TEMP:%s;\" %\n               ''.join(random.choice(string.ascii_letters) for i in range(20)))\n_unescapes = (\n    (\"\\\\\\\\\", _substitute),\n    (r\"\\:\", \";\"),\n    (r\"\\s\", \" \"),\n    (r\"\\r\", \"\\r\"),\n    (r\"\\n\", \"\\n\"),\n    (_substitute, \"\\\\\"),\n)\n\n# valid tag-keys must contain of alphanumerics and hyphens only.\n# for vendor-tagnames: TLD with slash appended\n_valid_key = re.compile(r\"^([\\w.-]+/)?[\\w-]+$\")\n\n# valid escaped tag-values must not contain\n# NUL, CR, LF, semicolons or spaces\n_valid_escaped_value = re.compile(\"^[^ ;\\n\\r\\0]*$\")\n\n\ndef _unescape(string):\n    for a, b in _unescapes:\n        string = string.replace(a, b)\n    return string\n\n\ndef _escape(string):\n    for a, b in _escapes:\n        string = string.replace(a, b)\n    return string\n\n\ndef encode(tags):\n    r'''Encodes a dictionary of tags to fit into an IRC-message.\n    See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html\n\n    >>> from collections import OrderedDict\n    >>> encode({'key': 'value'})\n    'key=value'\n\n    >>> d = {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'}\n    >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n    >>> encode(d_ordered)\n    'aaa=bbb;ccc;example.com/ddd=eee'\n\n    >>> d = {'key': 'value;with special\\\\characters', 'key2': 'with=equals'}\n    >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n    >>> print(encode(d_ordered))\n    key=value\\:with\\sspecial\\\\characters;key2=with=equals\n\n    >>> print(encode({'key': r'\\something'}))\n    key=\\\\something\n\n    '''\n    tagstrings = []\n    for key, value in tags.items():\n        if not _valid_key.match(key):\n            raise ValueError(\"dictionary key is invalid as tag key: \" + key)\n        # if no value, just append the key\n        if value:\n            tagstrings.append(key + \"=\" + _escape(value))\n        else:\n            tagstrings.append(key)\n    return \";\".join(tagstrings)\n\n\ndef decode(tagstring):\n    '''Decodes a tag-string from an IRC-message into a python dictionary.\n    See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html\n\n    >>> from pprint import pprint\n    >>> pprint(decode('key=value'))\n    {'key': 'value'}\n\n    >>> pprint(decode('aaa=bbb;ccc;example.com/ddd=eee'))\n    {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'}\n\n    >>> s = r'key=value\\\\:with\\\\sspecial\\\\\\\\characters;key2=with=equals'\n    >>> pprint(decode(s))\n    {'key': 'value;with special\\\\\\\\characters', 'key2': 'with=equals'}\n    >>> print(decode(s)['key'])\n    value;with special\\\\characters\n\n    >>> print(decode(r'key=\\\\\\\\something')['key'])\n    \\\\something\n\n    '''\n    if not tagstring:\n        # None/empty = no tags\n        return {}\n\n    tags = {}\n\n    for tag in tagstring.split(\";\"):\n        # value is either everything after \"=\", or None\n        key, value = (tag.split(\"=\", 1) + [None])[:2]\n        if not _valid_key.match(key):\n            raise ValueError(\"invalid tag key: \" + key)\n        if value:\n            if not _valid_escaped_value.match(value):\n                raise ValueError(\"invalid escaped tag value: \" + value)\n            value = _unescape(value)\n        tags[key] = value\n\n    return tags\n"
  },
  {
    "path": "irc3/template/__init__.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport sys\n__doc__ = \"\"\"\nUsage: python -m irc3.template <nickname>\n\"\"\"\n\ndirname = os.path.dirname(__file__)\n\n\ndef get_template(filename, **kwargs):\n    with open(os.path.join(dirname, filename)) as fd:\n        data = fd.read()\n        data = data.format(**kwargs)\n    return data\n\n\ndef main(nick=None, user=None, dest=None):\n    if nick is None:  # pragma: no cover\n        try:\n            nick = sys.argv[1]\n        except IndexError:\n            print(__doc__)\n            sys.exit(-1)\n    dest = dest or os.getcwd()\n    user = user or os.environ.get('USER', 'mynick')\n    config = dict(nick=nick, user=user, hash='${#}')\n    data = get_template('config.ini', **config)\n    with open(os.path.join(dest, 'config.ini'), 'w') as fd:\n        fd.write(data)\n\n    data = get_template('plugin.py', **config)\n    filename = os.path.join(dest, '{nick}_plugin.py'.format(**config))\n    with open(filename, 'w') as fd:\n        fd.write(data)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "irc3/template/__main__.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.template import main\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "irc3/template/config.ini",
    "content": "[bot]\nnick = {nick}\nusername = {nick}\n\nhost = localhost\nport = 6667\n\n# uncomment this if you want ssl support\n# ssl = true\n# uncomment this if you don't want to check the certificate\n# ssl_verify = CERT_NONE\n\n# uncomment this if you want to use sasl authentication\n# sasl_username = {nick}\n# sasl_password = yourpassword\n\nincludes =\n    irc3.plugins.command\n#    irc3.plugins.uptime\n#    irc3.plugins.ctcp\n    {nick}_plugin\n\n# the bot will join #{nick}_channel\n# {hash} is replaced by the # char\nautojoins =\n    {hash}{nick}_channel\n\n# Autojoin delay, disabled by default\n# float or int value\n# autojoin_delay = 3.1\n\n# The maximum amount of lines irc3 sends at once.\n# Default to 4, set to 0 to disable\n# flood_burst = 10\n\n# The number of lines per $flood_rate_delay seconds irc3 sends after reaching\n# the $flood_burst limit.\n# Default to 1\n# flood_rate = 2\n\n# The bot will send $flood_rate messages per $flood_rate_delay seconds\n# Default to 1\n# flood_rate_delay = 5\n\n[irc3.plugins.command]\n# command plugin configuration\n\n# set command char\ncmd = !\n\n# set guard policy\nguard = irc3.plugins.command.mask_based_policy\n\n[irc3.plugins.command.masks]\n# this section is used by the guard to secure the bot's command\n# change your nickname and uncomment the line below\n# {user}!*@* = all_permissions\n* = view\n"
  },
  {
    "path": "irc3/template/plugin.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins.command import command\nimport irc3\n\n\n@irc3.plugin\nclass Plugin:\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @irc3.event(irc3.rfc.JOIN)\n    def say_hi(self, mask, channel, **kw):\n        \"\"\"Say hi when someone join a channel\"\"\"\n        if mask.nick != self.bot.nick:\n            self.bot.privmsg(channel, 'Hi %s!' % mask.nick)\n        else:\n            self.bot.privmsg(channel, 'Hi!')\n\n    @command(permission='view')\n    def echo(self, mask, target, args):\n        \"\"\"Echo\n\n            %%echo <message>...\n        \"\"\"\n        yield ' '.join(args['<message>'])\n"
  },
  {
    "path": "irc3/testing.py",
    "content": "# -*- coding: utf-8 -*-\nfrom unittest import TestCase\nimport irc3\nimport irc3d\nfrom irc3.compat import asyncio\nimport tempfile\nimport time\nimport os\n\ntry:\n    from unittest import mock\nexcept ImportError:  # pragma: no cover\n    import mock\n\nMagicMock = mock.MagicMock\npatch = mock.patch\ncall = mock.call\nPROJECT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\npasswd_ini = \"\"\"\n[irc.freenode.net]\nirc3=password\n\n[twitter]\nkey=key\nsecret=secret\ntoken=token\ntoken_secret=token_secret\n\"\"\"\n\n\ndef ini2config(data, type='bot', env=None):\n    if env is None:\n        env = {}\n    data = data.encode('utf8')\n    with tempfile.NamedTemporaryFile(prefix='irc3-') as fd:\n        fd.write(data)\n        fd.flush()\n        data = irc3.utils.parse_config(type, fd.name, env=env)\n    return data\n\n\ndef call_later(i, func, *args):\n    if func.__name__ in dir(IrcBot):\n        func(*args)\n    return asyncio.Handle(func, args, asyncio.get_event_loop())\n\n\ndef call_soon(func, *args):\n    func(*args)\n    return asyncio.Handle(func, args, asyncio.get_event_loop())\n\n\nclass IrcBot(irc3.IrcBot):\n\n    def __init__(self, **config):\n        self.check_required()\n        if 'loop' not in config:\n            loop = asyncio.new_event_loop()\n            loop = mock.create_autospec(loop, spec_set=True)\n            loop.call_later = call_later\n            loop.call_soon = call_soon\n            loop.time.return_value = 10\n            config.update(testing=True, asynchronous=False, level=1000,\n                          loop=loop)\n        else:\n            config.update(testing=True, level=1000)\n        super(IrcBot, self).__init__(**config)\n        self.protocol = irc3.IrcConnection()\n        self.protocol.closed = False\n        self.protocol.factory = self\n        self.protocol.transport = MagicMock()\n        self.protocol.write = MagicMock()\n\n    def check_required(self):  # pragma: no cover\n        dirname = os.path.expanduser('~/.irc3')\n        if not os.path.isdir(dirname):\n            os.makedirs(dirname)\n        filename = os.path.expanduser('~/.irc3/passwd.ini')\n        if not os.path.isfile(filename):\n            with open(filename, 'w') as fd:\n                fd.write(passwd_ini)\n\n    def test(self, data, show=True):\n        self.dispatch(data)\n        if show:\n            for line in self.sent:  # pragma: no cover\n                print(line)\n\n    @property\n    def sent(self):\n        values = [tuple(c)[0][0] for c in self.protocol.write.call_args_list]\n        self.protocol.write.reset_mock()\n        return values\n\n\nclass IrcTestCase(TestCase):\n\n    project_path = PROJECT_PATH\n\n    def patch_requests(self, **kwargs):\n        self.patcher = patch('requests.Session.request')\n        self.addCleanup(self.patcher.stop)\n        request = self.patcher.start()\n\n        filename = kwargs.pop('filename', None)\n        if filename:\n            filename = os.path.join(self.project_path, filename)\n            with open(filename, 'rb') as feed:\n                content = feed.read()\n            for k, v in kwargs.items():\n                content = content.replace(k.encode('ascii'), v.encode('ascii'))\n            kwargs['content'] = content\n            kwargs['text'] = content.decode('utf8')\n        kwargs.setdefault('status_code', 200)\n        resp = MagicMock(**kwargs)\n        for k, v in kwargs.items():\n            if k in ('json',):\n                setattr(resp, k, MagicMock(return_value=v))\n        request.return_value = resp\n        return request\n\n    def patch_asyncio(self):\n        patcher = patch('irc3.compat.asyncio.Task')\n        self.Task = patcher.start()\n        self.addCleanup(patcher.stop)\n        patcher = patch('irc3.compat.asyncio.get_event_loop')\n        patcher.start()\n        self.addCleanup(patcher.stop)\n\n\nclass BotTestCase(IrcTestCase):\n\n    config = {'nick': 'nono'}\n\n    def callFTU(self, **config):\n        config = dict(self.config, **config)\n        bot = IrcBot(**config)\n        self.bot = bot\n        return bot\n\n    def assertSent(self, lines):\n        if not lines:\n            self.assertNothingSent()\n            return\n        if not self.bot.loop.called:\n            self.bot.protocol.write.assert_has_calls(\n                [call(line) for line in lines])\n        else:  # pragma: no cover\n            self.bot.loop.call_later.assert_has_calls(\n                [call(line) for line in lines])\n        self.reset_mock()\n\n    def assertNothingSent(self):\n        self.assertFalse(self.bot.protocol.write.called)\n        self.assertFalse(self.bot.loop.called)\n        self.reset_mock()\n\n    def reset_mock(self):\n        self.bot.protocol.write.reset_mock()\n        self.bot.loop.reset_mock()\n\n\nclass IrcClient(irc3d.IrcClient):\n\n    def __init__(self):\n        self.sent = []\n\n    def dispatch(self, data):\n        self.data['data_received'] = time.time()\n        return self.factory.dispatch(data, client=self)\n\n    def write(self, data):\n        super(IrcClient, self).write(data)\n        self.sent.extend(data.split('\\r\\n'))\n\n    def reset(self, data=False):\n        self.sent = []\n        if data:  # pragma: no cover\n            self.data = []\n\n\nclass IrcServer(irc3d.IrcServer):\n\n    def __init__(self, **config):\n        loop = MagicMock()\n        loop.call_later = call_later\n        loop.call_soon = call_soon\n        loop.time = MagicMock()\n        loop.time.return_value = 10\n        config.update(testing=True, asynchronous=False, level=1000,\n                      loop=loop)\n        super(IrcServer, self).__init__(**config)\n        print(self.clients)\n\n    def add_clients(self, amount=2):\n        for i in range(1, amount + 1):\n            client = IrcClient()\n            client.factory = self\n            transport = MagicMock()\n            transport.get_extra_info.return_value = ('127.0.0.1', i)\n            client.connection_made(transport)\n            nick = 'client%s' % i\n            client.data.update(nick=nick)\n            client.dispatch(\n                \"USER u{0} 127.0.0.1 127.0.0.1 :I'm {0}\".format(nick))\n            setattr(self, nick, client)\n\n\nclass ServerTestCase(IrcTestCase):\n\n    config = {'servername': 'irc.com',\n              'includes': ['irc3d.plugins.core']}\n\n    def callFTU(self, clients=2, **config):\n        config = dict(self.config, **config)\n        server = IrcServer(**config)\n        server.add_clients(amount=clients)\n        self.server = server\n        return server\n\n    def assertSent(self, client, data, origin=None):\n        if origin:\n            data = data.format(**origin.data)\n        self.assertIn(data, client.sent)\n\n    def assertNotSent(self, client, data, origin=None):\n        if origin:\n            data = data.format(**origin.data)\n        self.assertNotIn(data, client.sent)\n"
  },
  {
    "path": "irc3/utils.py",
    "content": "# -*- coding: utf-8 -*-\nfrom unicodedata import normalize\nfrom .compat import asyncio\nfrom . import tags\nimport configparser\nimport importlib\nimport functools\nimport logging\nimport os\nimport re\n\n\ndef slugify(value):\n    if not isinstance(value, str):  # pragma: no cover\n        value = value.decode('utf8', 'ignore')\n    value = normalize('NFKD', value)\n    value = value.encode('ascii', 'ignore').decode('ascii')\n    value = re.sub(r'[^\\w\\s\\.-]', '', value).strip().lower()\n    value = re.sub(r'[-\\s]+', '-', value)\n    value = re.sub(r'-*\\.+-*', '.', value)\n    return value\n\n\nclass IrcString(str):\n    \"\"\"Argument wrapper\"\"\"\n\n    @property\n    def nick(self):\n        \"\"\"return nick name:\n\n        .. code-block:: py\n\n            >>> print(IrcString('foo').nick)\n            foo\n            >>> print(IrcString('foo!user@host').nick)\n            foo\n            >>> IrcString('#foo').nick is None\n            True\n            >>> IrcString('irc.freenode.net').nick is None\n            True\n        \"\"\"\n        if '!' in self:\n            return self.split('!', 1)[0]\n        if not self.is_channel and not self.is_server:\n            return self\n\n    @property\n    def lnick(self):\n        \"\"\"return nick name in lowercase:\n\n        .. code-block:: py\n\n            >>> print(IrcString('Foo').lnick)\n            foo\n        \"\"\"\n        nick = self.nick\n        if nick:\n            return nick.lower()\n\n    @property\n    def host(self):\n        if '!' in self:\n            return self.split('!', 1)[1]\n\n    @property\n    def username(self):\n        \"\"\"return user name:\n\n        .. code-block:: py\n\n            >>> print(IrcString('foo!user@host').username)\n            user\n            >>> IrcString('#foo').username is None\n            True\n            >>> IrcString('irc.freenode.net').username is None\n            True\n        \"\"\"\n        if self.host and '@' in self.host:\n            return self.host.split('@', 1)[0]\n\n    @property\n    def hostname(self):\n        \"\"\"return host name:\n\n        .. code-block:: py\n\n            >>> print(IrcString('foo!user@host').hostname)\n            host\n            >>> IrcString('#foo').hostname is None\n            True\n            >>> IrcString('irc.freenode.net').hostname is None\n            True\n        \"\"\"\n        if self.host and '@' in self.host:\n            return self.host.split('@', 1)[1]\n\n    @property\n    def is_user(self):\n        return '!' in self\n\n    @property\n    def is_channel(self):\n        \"\"\"return True if the string is a channel:\n\n        .. code-block:: py\n\n            >>> IrcString('#channel').is_channel\n            True\n            >>> IrcString('&channel').is_channel\n            True\n        \"\"\"\n        return self.startswith(('#', '&'))\n\n    @property\n    def is_server(self):\n        \"\"\"return True if the string is a server:\n\n        .. code-block:: py\n\n            >>> IrcString('irc.freenode.net').is_server\n            True\n        \"\"\"\n        if self == '*':\n            return True\n        return '!' not in self and '.' in self\n\n    @property\n    def is_nick(self):\n        \"\"\"return True if the string is a nickname:\n\n        .. code-block:: py\n\n            >>> IrcString('foo').is_nick\n            True\n        \"\"\"\n        return not (self.is_server or self.is_channel)\n\n    @property\n    def tagdict(self):\n        \"\"\"return a dict converted from this string interpreted as a tag-string\n\n        .. code-block:: py\n\n            >>> from pprint import pprint\n            >>> dict_ = IrcString('aaa=bbb;ccc;example.com/ddd=eee').tagdict\n            >>> pprint({str(k): str(v) for k, v in dict_.items()})\n            {'aaa': 'bbb', 'ccc': 'None', 'example.com/ddd': 'eee'}\n        \"\"\"\n        tagdict = getattr(self, '_tagdict', None)\n        if tagdict is None:\n            try:\n                self._tagdict = tags.decode(self)\n            except ValueError:\n                self._tagdict = {}\n        return self._tagdict\n\n\nSPACE = ' '\n\n\ndef split_message(message, max_bytes, encoding, prefix=''):\n    \"\"\"Split long messages based on byte length, ensuring chunks\n    do not exceed max_bytes when encoded. Break up words when necessary.\n    \"\"\"\n    if max_bytes <= 0:\n        raise ValueError(\"max_bytes must be positive\")\n\n    prefix_bytes = len(prefix.encode(encoding))\n    max_bytes -= prefix_bytes\n    if max_bytes <= 0:\n        raise ValueError(f\"{max_bytes=} too small for prefix\")\n\n    byte_message = message.encode(encoding)\n    message_bytes = len(byte_message)\n\n    start = 0\n\n    while start < message_bytes:\n        end = min(start + max_bytes, message_bytes)\n        chunk = byte_message[start:end]\n\n        while True:\n            valid = True\n\n            # Ensure the chunk doesn't end mid-character.\n            try:\n                chunk_str = chunk.decode(encoding, errors='strict')\n            except UnicodeDecodeError:\n                valid = False\n\n            valid = valid and (\n                end == message_bytes or chunk_str[-1] == SPACE or SPACE\n                not in chunk_str\n            )\n\n            if valid:\n                break\n\n            chunk = chunk[:-1]\n            end -= 1\n\n            if end == start:\n                raise ValueError(f\"cannot fit chunk in {max_bytes=}\")\n\n        if start == 0:\n            # Keep leading spaces.\n            clean = chunk_str.rstrip(SPACE)\n        else:\n            clean = chunk_str.strip(SPACE)\n        if clean:\n            yield clean\n\n        start = end\n\n\nclass Config(dict):\n    \"\"\"Simple dict wrapper:\n\n    .. code-block:: python\n\n        >>> c = Config(dict(a=True))\n        >>> c.a\n        True\n    \"\"\"\n\n    def __getattr__(self, attr):\n        return self[attr]\n\n\ndef parse_config_env(env=None):\n    \"\"\"return config set in env vars.\n    `IRC3_BOT_PASSWORD=value` becomes `[bot] password=value`.\n    `IRC3__BOT__SASL_PASSWORD=value` becomes `[bot] sasl_password=value`.\n    \"\"\"\n    value = {}\n    if env is None:\n        env = os.environ\n\n    for k, v in env.items():\n        prefix = 'IRC3__'\n        if k.startswith(prefix):\n            # This prefix allows setting keys with underscores.\n            # Double underscores '__' are replaced with periods.\n            splitted = k.removeprefix(prefix).lower().split('__')\n            key = splitted.pop()\n            section = '.'.join(splitted)\n            section = value.setdefault(section, {})\n            section[key] = v\n        elif k.startswith('IRC3_'):\n            # This prefix replaces single underscores with periods.\n            # Keys with underscores cannot be set.\n            splitted = k.lower().split('_')\n            key = splitted.pop()\n            section = '.'.join(splitted[1:])\n            section = value.setdefault(section, {})\n            section[key] = v\n\n    return value\n\n\ndef parse_config(main_section, *filenames, **kwargs):\n    \"\"\"parse config files\"\"\"\n    filename = filenames[-1]\n    filename = os.path.abspath(filename)\n    here = os.path.dirname(filename)\n    defaults = dict(here=here, hash='#')\n    defaults['#'] = '#'\n    defaults['##'] = '##'\n\n    config = configparser.ConfigParser(\n        defaults, allow_no_value=False,\n        interpolation=configparser.ExtendedInterpolation(),\n    )\n    config.optionxform = str\n    config.read([os.path.expanduser('~/.irc3/passwd.ini')] + list(filenames))\n\n    config_env = parse_config_env(env=kwargs.get('env'))\n\n    value = {}\n    for s in config.sections():\n        items = {}\n        config_items = dict(config.items(s))\n        config_items.update(config_env.get(s, {}))\n        for k, v in config_items.items():\n            if '\\n' in v:\n                v = as_list(v)\n            elif s == main_section and k in ('autojoins',):\n                v = as_list(v)\n            elif v.isdigit():\n                v = int(v)\n            elif v.replace('.', '').isdigit() and v.count('.') == 1:\n                v = float(v)\n            elif v in ('true', 'false'):\n                v = v == 'true' and True or False\n            items[k] = v\n        if s == main_section:\n            value.update(items)\n        else:\n            for k in ('here', 'config'):\n                items.pop(k, '')\n            value[s] = items\n    value.update(defaults)\n    value['configfiles'] = filenames\n    return value\n\n\ndef extract_config(config, prefix):\n    \"\"\"return all keys with the same prefix without the prefix\"\"\"\n    prefix = prefix.strip('.') + '.'\n    plen = len(prefix)\n    value = {}\n    for k, v in config.items():\n        if k.startswith(prefix):\n            value[k[plen:]] = v\n    return value\n\n\ndef as_list(value):\n    \"\"\"clever string spliting:\n\n    .. code-block:: python\n\n        >>> print(as_list('value'))\n        ['value']\n        >>> print(as_list('v1 v2'))\n        ['v1', 'v2']\n        >>> print(as_list(None))\n        []\n        >>> print(as_list(['v1']))\n        ['v1']\n    \"\"\"\n    if isinstance(value, (list, tuple)):\n        return value\n    if not value:\n        return []\n    for c in '\\n ':\n        if c in value:\n            value = value.split(c)\n            return [v.strip() for v in value if v.strip()]\n    return [value]\n\n\ndef as_channel(value):\n    \"\"\"Always return a channel name:\n\n    .. code-block:: python\n\n        >>> print(as_channel('chan'))\n        #chan\n        >>> print(as_channel('#chan'))\n        #chan\n        >>> print(as_channel('&chan'))\n        &chan\n    \"\"\"\n    if not value.startswith(('#', '&')):\n        return '#' + value\n    return value\n\n\ndef parse_modes(modes, targets=None, noargs=''):\n    \"\"\"Parse channel modes:\n\n    .. code-block:: python\n\n        >>> parse_modes('+c-n', noargs='cn')\n        [('+', 'c', None), ('-', 'n', None)]\n        >>> parse_modes('+c-v', ['gawel'], noargs='c')\n        [('+', 'c', None), ('-', 'v', 'gawel')]\n    \"\"\"\n    if not targets:\n        targets = []\n    cleaned = []\n    for mode in modes:\n        if mode in '-+':\n            char = mode\n            continue\n        target = targets.pop(0) if mode not in noargs else None\n        cleaned.append((char, mode, target))\n    return cleaned\n\n\ndef wraps_with_context(func, context):\n    \"\"\"Return a wrapped partial(func, context)\"\"\"\n    if asyncio.iscoroutinefunction(func):\n        async def wrapped(*args, **kwargs):\n            return await func(context, *args, **kwargs)\n    else:\n        wrapped = functools.partial(func, context)\n    wrapped = functools.wraps(func)(wrapped)\n    return wrapped\n\n\ndef maybedotted(name):\n    \"\"\"Resolve dotted names:\n\n    .. code-block:: python\n\n        >>> maybedotted('irc3.config')\n        <module 'irc3.config' from '...'>\n        >>> maybedotted('irc3.utils.IrcString')\n        <class 'irc3.utils.IrcString'>\n\n    ..\n    \"\"\"\n    if not name:\n        raise LookupError(\n            'Not able to resolve %s' % name)\n    if not hasattr(name, '__name__'):\n        try:\n            mod = importlib.import_module(name)\n        except ImportError:\n            attr = None\n            if '.' in name:\n                names = name.split('.')\n                attr = names.pop(-1)\n                try:\n                    mod = maybedotted('.'.join(names))\n                except LookupError:\n                    attr = None\n                else:\n                    attr = getattr(mod, attr, None)\n            if attr is not None:\n                return attr\n            raise LookupError(\n                'Not able to resolve %s' % name)\n        else:\n            return mod\n    return name\n\n\nclass Handler(logging.Handler):\n\n    def __init__(self, bot, *targets):\n        super(Handler, self).__init__()\n        self.bot = bot\n        self.targets = targets\n\n    def yield_records(self, record):\n        for record in self.format(record).split('\\n'):\n            for t in self.targets:\n                yield t, record\n\n    def emit(self, record):\n        self.bot.call_many('privmsg', self.yield_records(record))\n\n\nclass Logger(logging.getLoggerClass()):\n    \"\"\"Replace the default logger to add a set_irc_targets() method\"\"\"\n\n    def set_irc_targets(self, bot, *targets):\n        \"\"\"Add a irc Handler using bot and log to targets (can be nicks or\n        channels:\n\n        ..\n            >>> bot = None\n\n        .. code-block:: python\n\n            >>> log = logging.getLogger('irc.mymodule')\n            >>> log.set_irc_targets(bot, '#chan', 'admin')\n        \"\"\"\n        # get formatter initialized by config (usualy on a NullHandler)\n        ll = logging.getLogger('irc')\n        formatter = ll.handlers[0].formatter\n        # add a handler for the sub logger\n        handler = Handler(bot, *targets)\n        handler.setFormatter(formatter)\n        self.addHandler(handler)\n\n\nlogging.setLoggerClass(Logger)\n"
  },
  {
    "path": "irc3d/__init__.py",
    "content": "# -*- coding: utf-8 -*-\nimport time\nimport venusian\nfrom os import path\nfrom irc3 import base\nfrom irc3 import utils\nfrom irc3 import config\nfrom irc3.compat import asyncio\nfrom irc3.compat import Queue\nfrom collections import defaultdict\nfrom .plugins.command import command\nfrom .dec import plugin\nfrom .dec import extend\nfrom .dec import event\n\n\nclass IrcClient(asyncio.Protocol):\n    \"\"\"asyncio protocol to handle an irc connection\"\"\"\n\n    def connection_made(self, transport):\n        self.closed = False\n        self.transport = transport\n        self.queue = Queue()\n        self.uuid = self.transport.get_extra_info('peername')\n        self.factory.clients[self.uuid] = self\n        self.encoding = self.factory.encoding\n        self.data = {}\n        self.modes = set()\n        self.channels = set()\n        t = time.time()\n        self.data.update(\n            uuid=self.uuid, host=self.uuid[0],\n            connection_made=t, data_received=t,\n            srv=self.factory.config.servername,\n            version=self.factory.config.version)\n\n    def __getattr__(self, attr):\n        return self.data[attr]\n\n    def get_nick(self):\n        return self.data.get('nick')\n\n    def set_nick(self, nick):\n        self.data['nick'] = nick\n        self.data['mask'] = utils.IrcString(\n            '{nick}!{username}@{uuid[0]}'.format(**self.data))\n\n    nick = property(get_nick, set_nick)\n\n    @property\n    def registered(self):\n        return bool('nick' in self.data and 'username' in self.data)\n\n    def decode(self, data):  # pragma: no cover\n        \"\"\"Decode data with bot's encoding\"\"\"\n        encoding = getattr(self, 'encoding', 'ascii')\n        return data.decode(encoding, 'ignore')\n\n    def data_received(self, data):  # pragma: no cover\n        self.data['data_received'] = time.time()\n        data = self.decode(data)\n        if not self.queue.empty():\n            data = self.queue.get_nowait() + data\n        lines = data.split('\\r\\n')\n        self.queue.put_nowait(lines.pop(-1))\n        for line in lines:\n            self.factory.dispatch(line, client=self)\n\n    def fwrite(self, messages, **kwargs):\n        kwargs['c'] = self\n        if not isinstance(messages, (list, tuple)):\n            fmt = getattr(messages, 'tpl', messages)\n        else:\n            fmt = '\\r\\n'.join([getattr(m, 'tpl', m) for m in messages])\n        self.write(fmt.format(**kwargs))\n\n    def write(self, data):\n        if data is not None:\n            self.factory.dispatch(data, client=self, iotype='out')\n            data = data.encode(self.encoding)\n            if not data.endswith(b'\\r\\n'):\n                data = data + b'\\r\\n'\n            self.transport.write(data)\n\n    def connection_lost(self, exc):\n        self.factory.log.critical('connection lost (%s): %r',\n                                  id(self.transport),\n                                  exc)\n        self.factory.notify('connection_lost', client=self)\n        del self.factory.clients[self.uuid]\n        if not self.closed:\n            self.closed = True\n            self.close()\n\n    def close(self):  # pragma: no cover\n        if not self.closed:\n            self.factory.log.critical('closing old transport (%r)',\n                                      id(self.transport))\n            try:\n                self.transport.close()\n            finally:\n                self.closed = True\n\n    def __str__(self):\n        if 'nick' in self.data:\n            return '{nick}'.format(**self.data)\n        else:\n            return 'unknown'\n\n    __repr__ = __str__\n\n\nclass IrcServer(base.IrcObject):\n    \"\"\"An irc server\"\"\"\n\n    nick = None\n    server = True\n    plugin_category = '__irc3_plugin__'\n\n    _pep8 = [config, extend, plugin, event, command]\n    venusian = venusian\n    venusian_categories = [\n        'irc3d',\n        'irc3d.extend',\n        'irc3d.rfc1459',\n        'irc3d.plugins.command',\n    ]\n\n    server_config = {\n        'NETWORK': 'freenode', 'MODES': '1', 'DEAF': 'D', 'SAFELIST': True,\n        'CHANTYPES': '#', 'TARGMAX':\n        'NAMES:1,LIST:1,KICK:1,WHOIS:1,PRIVMSG:1,NOTICE:1,ACCEPT:,MONITOR:',\n        'CNOTICE': True, 'TOPICLEN': '390', 'EXTBAN': '$,ajrxz',\n        'CALLERID': 'g', 'ETRACE': True, 'CHANLIMIT': '#:120', 'CHARSET':\n        'ascii', 'PREFIX': '(ov)@+', 'INVEX': True, 'NICKLEN': '16',\n        'CLIENTVER': '3.0', 'CPRIVMSG': True, 'CHANMODES':\n        '', 'MAXLIST': 'bqeI:100', 'KNOCK':\n        True, 'EXCEPTS': True, 'CHANNELLEN': '50', 'CASEMAPPING':\n        'rfc1459', 'FNC': True, 'STATUSMSG': '@+', 'ELIST': 'CTU', 'WHOX':\n        True, 'MONITOR': '100'}\n\n    defaults = dict(\n        base.IrcObject.defaults,\n        motd=path.join(path.dirname(__file__), 'motd.txt'),\n        cmd='',\n        host='0.0.0.0',\n        port=6667,\n        connection=IrcClient,\n        server_config=server_config,\n        servername='localhost',\n    )\n\n    def __init__(self, *args, **kwargs):\n        self.clients = defaultdict(dict)\n        super(IrcServer, self).__init__(*args, **kwargs)\n\n    def connection_made(self, f):  # pragma: no cover\n        if getattr(self, 'protocol', None):\n            self.protocol.close()\n        try:\n            f.result()\n        except Exception as e:\n            self.log.exception(e)\n            self.loop.call_later(3, self.create_connection)\n        else:\n            self.log.info('Started')\n\n    def notice(self, client, message):\n        \"\"\"send a notice to client\"\"\"\n        if client and message:\n            messages = utils.split_message(\n                message,\n                self.config.max_length,\n                self.encoding,\n            )\n            for msg in messages:\n                client.fwrite(':{c.srv} NOTICE {c.nick} :{msg}', msg=msg)\n\n    privmsg = notice\n\n    def SIGHUP(self, *args):  # pragma: no cover\n        self.loop.stop()\n\n    def SIGINT(self, *args):  # pragma: no cover\n        self.loop.stop()\n\n\ndef run(argv=None):\n    return IrcServer.from_argv(argv)\n"
  },
  {
    "path": "irc3d/__main__.py",
    "content": "import sys\nimport getpass\nfrom irc3d import IrcServer\n\n\ndef main():  # pragma: no cover\n    args = sys.argv[1:]\n    host = '127.0.0.1'\n    port = 6667\n    if args:\n        hp = args.pop(0)\n        if ':' in hp:\n            host, port = hp.split(':')\n        else:\n            port = hp\n    user = getpass.getuser()\n    config = dict(\n        servername='test_server',\n        host=host,\n        port=int(port),\n        raw=True,\n        opers={user: user},\n        includes=['irc3d.plugins.core'],\n    )\n    print((\n        'Starting irc3d test server on {0}:{1} with {2}/{2} as IrcOp'\n    ).format(host, port, user))\n    server = IrcServer.from_config(config)\n    try:\n        server.run()\n    except KeyboardInterrupt:\n        pass\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "irc3d/dec.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import dec\nimport venusian\nimport functools\n\n\ndef plugin(wrapped):\n    \"\"\"register a class as server plugin\"\"\"\n    setattr(wrapped, '__irc3_plugin__', False)\n    setattr(wrapped, '__irc3d_plugin__', True)\n    return wrapped\n\n\nclass event(dec.event):\n    \"\"\"same as :class:`~irc3.dec.event` but for servers\"\"\"\n\n    def __init__(self, regexp, *args, **kwargs):\n        kwargs.setdefault('venusian_category', 'irc3d.rfc1459')\n        regexp = getattr(regexp, 'server', None) or regexp\n        super(event, self).__init__(regexp, *args, **kwargs)\n\n\ndef extend(func):\n    \"\"\"same as :func:`~irc3.dec.extend` but for servers\"\"\"\n    def callback(context, name, ob):\n        obj = context.context\n        if info.scope == 'class':\n            @functools.wraps(func)\n            def f(self, *args, **kwargs):\n                plugin = obj.get_plugin(ob)\n                return getattr(plugin, func.__name__)(*args, **kwargs)\n            setattr(obj, func.__name__, f.__get__(obj, obj.__class__))\n        else:\n            setattr(obj, func.__name__, func.__get__(obj, obj.__class__))\n    info = venusian.attach(func, callback, category='irc3d.extend')\n    return func\n"
  },
  {
    "path": "irc3d/motd.txt",
    "content": "               ___          _____     _   ____\n              |_ _|_ __ ___|___ /  __| | / ___|  ___ _ ____   _____ _ __\n               | || '__/ __| |_ \\ / _` | \\___ \\ / _ \\ '__\\ \\ / / _ \\ '__|\n               | || | | (__ ___) | (_| |  ___) |  __/ |   \\ V /  __/ |\n              |___|_|  \\___|____/ \\__,_| |____/ \\___|_|    \\_/ \\___|_|\n\n                                    v{version}\n"
  },
  {
    "path": "irc3d/plugins/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "irc3d/plugins/command.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import rfc\nfrom irc3d.dec import event\nfrom irc3d.dec import plugin\nfrom irc3.plugins.command import Commands\nfrom irc3.plugins.command import attach_command\n__doc__ = '''\n==============================================\n:mod:`irc3d.plugins.command` Server commands\n==============================================\n\nSame as :mod:`~irc3.plugins.command` but for servers\n'''\n\n\nclass server_policy:\n    \"\"\"Default server policy\"\"\"\n    def __init__(self, context):\n        self.context = context\n        self.opers = context.config.get('opers', {})\n\n    def check_oper_credentials(self, user, password):\n        \"\"\"return True if credential matches\"\"\"\n        return self.opers.get(user, None) == password\n\n    def __call__(self, predicates, meth, client, target, args, **kwargs):\n        perm = predicates.get('permission', 'registered')\n        if perm is not None and not client.registered:\n            client.fwrite(rfc.ERR_NOTREGISTERED)\n        elif str(perm).lower() == 'oper' and 'o' not in client.modes:\n            client.fwrite(rfc.ERR_NOPRIVILEGES)\n        else:\n            return meth(client, args)\n\n\ndef command(*func, **predicates):\n    predicates.setdefault('commands', __name__ + '.ServerCommands')\n    predicates.setdefault('venusian_category', __name__)\n    predicates['use_shlex'] = False\n    if func:\n        func = func[0]\n        attach_command(func, **predicates)\n        return func\n    else:\n        def wrapper(func):\n            attach_command(func, **predicates)\n            return func\n        return wrapper\n\n\n@plugin\nclass ServerCommands(Commands):\n\n    requires = ['irc3d.plugins.userlist']\n    default_policy = server_policy\n    case_sensitive = True\n\n    @event(r'^(?P<cmd>\\w+)(\\s(?P<data>\\S.*)|$)')\n    def on_command(self, cmd, mask=None, target=None, client=None, **kw):\n        cmd = cmd.upper()\n        predicates, meth = self.get(cmd, (None, None))\n        if meth is not None:\n            self.do_command(predicates, meth, client, client, **kw)\n        elif cmd not in ('MODE', 'USER', 'PRIVMSG', 'NOTICE'):\n            client.fwrite(rfc.ERR_UNKNOWNCOMMAND, cmd=cmd)\n\n    @command\n    def OPER(self, client=None, args=None, **kwargs):\n        \"\"\" The OPER command requires two arguments to be given. The first\n        argument is the name of the operator as specified in the configuration\n        file. The second argument is the password for the operator matching the\n        name and host.\n\n        The operator privileges are shown on a successful OPER.\n\n            %%OPER <user> <password>\n        \"\"\"\n        user = args['<user>']\n        passwd = args['<password>']\n        if self.guard.check_oper_credentials(user, passwd):\n            self.context.log.warn('%r is now oper (%s)', client, user)\n            client.modes.add('o')\n            client.fwrite(rfc.RPL_YOUREOPER)\n        else:\n            self.context.log.warn('%r tried to be oper (%s)', client, user)\n            client.fwrite(rfc.ERR_PASSWDMISMATCH)\n\n    @command\n    def HELP(self, client=None, args=None, **kwargs):\n        \"\"\"HELP displays the contents of the help file for topic requested.\n        If no topic is requested, it will perform the equivalent to HELP index.\n\n            %%HELP [<cmd>]\n        \"\"\"\n        msgs = []\n        cmd = (args['<cmd>'] or '').upper()\n        if cmd and cmd != 'INDEX':\n            predicates, meth = self.get(cmd, (None, None))\n            if meth is not None:\n                cmd = cmd.lower()\n                index = '{c.srv} 705 {c.nick} ' + cmd + ' :'\n                doc = meth.__doc__ or ''\n                doc = [\n                    line.strip() for line in doc.split('\\n')\n                    if line.strip()\n                ]\n                for line in doc:\n                    if '%%' in line:\n                        line = line.strip('%')\n                        msgs.insert(\n                            0, '{c.srv} 704 {c.nick} ' + cmd + ' :' + line)\n                    else:\n                        msgs.append(index + line)\n                msgs.append('{c.srv} 706 {c.nick} ' + cmd + ' :End of /HELP')\n        else:\n            index = '{c.srv} 705 {c.nick} index :'\n            msgs.append(\n                '{c.srv} 704 {c.nick} index :Help topics available to users:')\n            cmds = []\n            for cmd in sorted(self.keys()):\n                cmds.append('{0:<16}'.format(cmd))\n                if len(cmds) == 3:\n                    msgs.append(index + ''.join(cmds).strip())\n                    cmds = []\n            if cmds:\n                msgs.append(index + ''.join(cmds).strip())\n            msgs.append('{c.srv} 706 {c.nick} index :End of /HELP')\n        client.fwrite(msgs)\n"
  },
  {
    "path": "irc3d/plugins/core.py",
    "content": "# -*- coding: utf-8 -*-\nimport os\nimport time\nfrom irc3 import rfc\nfrom .command import command\nimport irc3d\n__doc__ = '''\n==============================================\n:mod:`irc3d.plugins.core` Server core plugin\n==============================================\n\nProvide basic server functionality.\n\nUse :mod:`~irc3.plugins.userlist` to maintain a list of channels/users\n\nAPI\n===\n\n.. autoclass:: Core\n   :members:\n\n    .. autoattribute:: requires\n'''\n\n\n@irc3d.plugin\nclass Core:\n\n    requires = [\n        'irc3d.plugins.userlist',\n        'irc3d.plugins.command',\n    ]\n\n    def __init__(self, context):\n        self.context = context\n\n    @command(permission=None)\n    def USER(self, client, args=None):\n        \"\"\"USER\n\n            %%USER <username> <hostname> <servername> <:realname>...\n        \"\"\"\n        if client.registered:\n            client.fwrite(rfc.ERR_ALREADYREGISTRED)\n        else:\n            self.register(client,\n                          username=args['<username>'],\n                          realname=' '.join(args['<:realname>']).lstrip(':'))\n\n    @irc3d.extend\n    def register(self, client, **kwargs):\n        data = client.data\n        data.update(kwargs)\n        if client.registered:\n            if 'signon' not in data:\n                data['signon'] = int(time.time())\n                client.nick = data['nick']\n                self.context.notify('connection_made', client=client)\n                client.fwrite(':{c.srv} 001 {c.nick} :Welcome')\n                self.VERSION(client)\n                self.MOTD(client)\n\n    @command\n    def VERSION(self, client, args=None):\n        \"\"\"VERSION\n\n            %%VERSION\n        \"\"\"\n        client.fwrite(':{c.srv} 004 {c.nick} :irc3d {c.version}')\n\n    @command\n    def MOTD(self, client, args=None):\n        \"\"\"MOTD\n\n            %%MOTD\n        \"\"\"\n        config = self.context.config\n        if 'motd_fmt' not in config:\n            config['motd_fmt'] = rfc.ERR_NOMOTD\n            if not config.testing and os.path.isfile(config.motd):\n                with open(config.motd) as fd:\n                    lines = [line.rstrip() for line in fd.readlines()]\n                    data = [rfc.RPL_MOTDSTART] + [\n                        ':{c.srv} 372 {c.nick} :' + line for line in lines\n                    ] + [rfc.RPL_ENDOFMOTD]\n                    config['motd_fmt'] = data\n\n        client.fwrite(config.motd_fmt,\n                      server=client.srv, version=client.version)\n\n    @command\n    def PING(self, client, args):\n        \"\"\"PING\n\n            %%PING <data>\n        \"\"\"\n        client.fwrite(':{c.srv} PONG {c.srv} :{<data>}', **args)\n\n    @command(permission='oper')\n    def DIE(self, client=None, args=None, **kwargs):\n        \"\"\"DIE\n\n            %%DIE\n        \"\"\"\n        self.context.log.warn('%r killed me', client)\n        self.context.SIGINT()\n\n    @command(permission='oper')\n    def WALLOPS(self, client=None, args=None, **kwargs):\n        \"\"\"WALLOPS\n\n            %%WALLOPS <message>...\n        \"\"\"\n        kw = dict(mask=client.mask, message=' '.join(args['<message>']))\n        for c in self.context.nicks.values():\n            if client is not c and 'w' in c.modes:\n                c.fwrite(':{mask} NOTICE {c.nick} :{message}', **kw)\n\n    @command\n    def AWAY(self, client, args):\n        \"\"\"AWAY\n\n            %%AWAY [<:reason>...]\n        \"\"\"\n        reason = ' '.join(args['<:reason>']).lstrip(':')\n        if not reason:\n            client.data.pop('away', None)\n            client.data.pop('away_message', None)\n            client.fwrite(rfc.RPL_UNAWAY)\n        elif reason:\n            client.data['away'] = self.context.loop.time()\n            client.data['away_message'] = reason\n            client.fwrite(rfc.RPL_NOWAWAY)\n"
  },
  {
    "path": "irc3d/plugins/userlist.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.plugins import userlist\nfrom irc3 import utils\nfrom irc3 import rfc\nimport irc3d\nimport string\n__doc__ = '''\n============================================================\n:mod:`irc3d.plugins.userlist` Nick and channel related stuff\n============================================================\n\nUse :mod:`~irc3.plugins.userlist` to maintain a list of channels/users\n\nAPI\n===\n\n.. autoclass:: ServerUserlist\n   :members:\n\n'''\n\n\n@irc3d.plugin\nclass ServerUserlist(userlist.Userlist):\n\n    def connection_made(self, client=None):\n        self.nicks[client.data['nick']] = client\n\n    def connection_lost(self, client=None):\n        if client is None:\n            super(ServerUserlist, self).connection_lost()\n        else:\n            if self.nicks.get(client.nick):\n                self.QUIT(client,\n                          {'<:reason>': [':Connection reset by peer']})\n\n    def get_client(self, nick_or_client):\n        if isinstance(nick_or_client, irc3d.IrcClient):\n            return nick_or_client\n        return self.nicks.get(nick_or_client)\n\n    @irc3d.extend\n    def broadcast(self, client=None, clients=None, **kwargs):\n        if clients is None:\n            clients = self.context.clients.values()\n        else:\n            clients = [self.get_client(c) for c in clients]\n        for c in clients:\n            c.write(kwargs['broadcast'])\n\n    @irc3d.command\n    def ISON(self, client, args=None, **kwargs):\n        \"\"\"ISON will return a list of users who are present on the network from\n        the list that was passed in.\n        This command is rarely used directly.\n\n            %%ISON <nicks>...\n        \"\"\"\n        nicks = [n for n in args['<nicks>'] or [] if n in self.nicks]\n        client.fwrite(rfc.RPL_ISON, nicknames=' '.join(nicks))\n\n    @irc3d.command\n    def JOIN(self, client, args=None, **kwargs):\n        \"\"\" The JOIN command allows you to enter a public chat area known as a\n        channel. Network wide channels are proceeded by a '#', while a local\n        server channel is proceeded by an '&'. More than one channel may be\n        specified, separated with commas (no spaces).\n\n        If the channel has a key set, the 2nd argument must be given to enter.\n        This allows channels to be password protected.\n\n            %%JOIN <channel>\n        \"\"\"\n        for channel in args['<channel>'].split(','):\n            if channel in client.channels:\n                continue\n            message = ':{mask} JOIN {<channel>}'\n            kwargs.update(\n                broadcast=message.format(\n                    mask=client.mask, **dict(args, **{'<channel>': channel})\n                ),\n                channel=channel)\n            self.join(client.nick, client.mask, client=client, **kwargs)\n            client.channels.add(channel)\n            self.NAMES(client=client, **kwargs)\n\n    @irc3d.command\n    def PART(self, client, args=None, **kwargs):\n        \"\"\" PART requires at least a channel argument to be given. It will exit\n        the client from the specified channel. More than one channel may be\n        specified, separated with commas (no spaces).\n\n        An optional part message may be given to be displayed to the channel.\n\n            %%PART <channel> [<:reason>...]\n        \"\"\"\n        if args['<channel>'] not in client.channels:\n            return\n        message = ':{mask} PART {<channel>}'\n        if args.get('<:reason>'):\n            args['data'] = ' '.join(args['<:reason>'])\n            message += ' {data}'\n        kwargs.update(\n            broadcast=message.format(mask=client.mask, **args),\n            channel=args.get('<channel>'),\n        )\n        self.part(client.nick, client.mask, client=client, **kwargs)\n        client.channels.remove(args['<channel>'])\n\n    @irc3d.command\n    def QUIT(self, client, args=None, **kwargs):\n        \"\"\"QUIT sends a message to the IRC server letting it know you would\n        like to disconnect.  The quit message will be displayed to the users in\n        the channels you were in when you are disconnected.\n\n            %%QUIT [<:reason>...]\n        \"\"\"\n        message = ':{mask} QUIT'\n        if args.get('<:reason>'):\n            args['data'] = ' '.join(args['<:reason>'])\n            message += ' {data}'\n        kwargs.update(\n            broadcast=message.format(mask=client.mask, **args),\n        )\n        self.quit(client.nick, client.mask, client=client, **kwargs)\n        client.close()\n\n    @irc3d.command\n    def KICK(self, client, args=None, **kwargs):\n        \"\"\"The KICK command will remove the specified user from the specified\n        channel, using the optional kick message.  You must be a channel\n        operator to use this command.\n\n            %%KICK <channel> <target> [<:reason>...]\n        \"\"\"\n        target = args['<target>']\n        channel = args['<channel>']\n        target_client = self.get_client(target)\n        if channel not in target_client.channels:\n            return\n        target_client.channels.remove(channel)\n        message = ':{mask} KICK {<channel>} {<target>}'\n        if args.get('<:reason>'):\n            args['data'] = ' '.join(args['<:reason>'])\n            message += ' {data}'\n        kwargs.update(\n            broadcast=message.format(mask=client.mask, **args),\n            channel=channel,\n        )\n        self.part(target, client.mask, client=client, **kwargs)\n\n    @irc3d.command(permission=None)\n    def NICK(self, client, args=None, **kwargs):\n        \"\"\"When first connected to the IRC server, NICK is required to set the\n        client's nickname.\n\n        NICK will also change the client's nickname once a connection has been\n        established.\n\n            %%NICK <nick>\n        \"\"\"\n        new_nick = args['<nick>']\n        if new_nick in self.nicks:\n            if self.nicks[new_nick] != client:\n                client.fwrite(rfc.ERR_NICKNAMEINUSE, nick=new_nick)\n            return\n\n        self.nicks[new_nick] = client\n        if client.registered:\n            nick = client.nick\n            kwargs['broadcast'] = ':{mask} NICK {new_nick}'.format(\n                new_nick=new_nick, **client.data)\n            client.nick = new_nick\n            super(ServerUserlist, self).new_nick(\n                nick, new_nick, client=client, **kwargs)\n        else:  # pragma: no cover\n            self.context.register(client, nick=new_nick)\n\n    @irc3d.command\n    def PRIVMSG(self, client=None, args=None, event='PRIVMSG', **kwargs):\n        \"\"\" PRIVMSG will send a standard message to the user or channel\n        specified.\n\n        PRIVMSG supports the following prefixes for sending messages to\n        specific clients in a channel:\n\n        @ - channel operators only\n        + - channel operators and voiced users\n\n        The nick can be extended to fit into the following syntax:\n\n        username@servername\n\n        This syntax is used to securely send a message to a service or a bot.\n\n            %%PRIVMSG <target> <:message>...\n        \"\"\"\n        dest = args['<target>']\n        target = self.nicks.get(dest, None)\n        if target is not None:\n            clients = [target]\n        else:\n            clients = self.channels.get(dest, set())\n            # do not send to sender\n            clients = clients.difference({client.nick})\n        if clients:\n            data = ' '.join(args['<:message>'])\n            if not data.startswith(':'):\n                data = ':' + data\n            self.broadcast(\n                client=client,\n                broadcast=':{c.mask} {event} {<target>} {data}'.format(\n                    c=client, target=target, event=event, data=data, **args),\n                clients=clients)\n        elif dest not in self.channels:\n            client.fwrite(rfc.ERR_NOSUCHNICK, nick=dest)\n\n    @irc3d.command\n    def NOTICE(self, client=None, args=None, event='PRIVMSG', **kwargs):\n        \"\"\"NOTICE will send a notice message to the user or channel specified.\n\n        NOTICE supports the following prefixes for sending messages to specific\n        clients in a channel:\n\n        @ - channel operators only\n        + - channel operators and voiced users\n\n        The nick can be extended to fit into the following syntax:\n\n        username@servername\n\n        This syntax is used to securely send a notice to a service or a bot.\n\n            %%NOTICE <target> <:message>...\n        \"\"\"\n        self.PRIVMSG(client, args, event='NOTICE', **kwargs)\n\n    @irc3d.event(rfc.MODE)\n    def mode(self, target=None, **kw):\n        \"\"\"MODE\n\n            %%MODE <channel> <modes> <nicks>...\n            %%MODE <modes> <nick>\n        \"\"\"\n        if target.is_channel:\n            super(ServerUserlist, self).mode(target=target, **kw)\n        elif kw['data'] is None:\n            client = kw['client']\n            modes = kw['modes']\n            if not modes.startswith(('+', '-')):\n                modes = '+' + modes\n            modes = utils.parse_modes(modes, noargs=string.ascii_letters)\n            for char, mode, tgt in modes:\n                meth = getattr(self.context, 'UMODE_' + mode, None)\n                if meth is not None:\n                    if meth(client, target, char, mode):\n                        if char == '+':\n                            client.modes.add(mode)\n                        elif mode in client.modes:\n                            client.modes.remove(mode)\n                else:\n                    client.fwrite(rfc.ERR_UMODEUNKNOWNFLAG)\n        else:\n            client.fwrite(rfc.ERR_NOSUCHCHANNEL, channel=target)\n\n    @irc3d.extend\n    def UMODE_i(self, client, target, char, mode):\n        return client.nick == target\n\n    @irc3d.extend\n    def UMODE_w(self, client, target, char, mode):\n        return client.nick == target\n\n    @irc3d.command\n    def NAMES(self, client=None, args=None, **kwargs):\n        \"\"\" With no channel argument, NAMES shows the names (nicks) of all\n        clients logged in to the network that do not have +i flag.\n\n        With the #channel argument, it displays the nicks on that channel, also\n        respecting the +i flag of each client. If the channel specified is a\n        channel that the issuing client is currently in, all nicks are listed\n        in similar fashion to when the user first joins a channel.\n\n            %%NAMES <channel>\n        \"\"\"\n        if args:\n            kwargs['channel'] = args['<channel>']\n        channel = self.context.channels[kwargs['channel']]\n        if self.context.config.testing:\n            # easyer to test\n            channel = sorted(channel)\n        # everything is a public channel\n        kwargs['m'] = '='\n        client.fwrite((rfc.RPL_NAMREPLY, rfc.RPL_ENDOFNAMES),\n                      nicknames=' '.join(channel), **kwargs)\n\n    @irc3d.command\n    def WHOIS(self, client=None, args=None, **kwargs):\n        \"\"\"WHOIS will display detailed user information for the specified nick.\n        If the first parameter is specified, WHOIS will display information\n        from the specified server, or the server that the user is on.  This is\n        how to remotely see idle time and away status.\n\n            %%WHOIS <nick>\n        \"\"\"\n        try:\n            target = self.nicks[args['<nick>']]\n            kwargs.update(target.data)\n        except Exception:\n            channels = None\n            kwargs['nick'] = args['<nick>']\n            rpl = [rfc.ERR_NOSUCHNICK]\n        else:\n            channels = ' '.join(target.channels)\n            rpl = [rfc.RPL_WHOISUSER]\n            if 'away_message' in target.data:\n                rpl.append(rfc.RPL_AWAY)\n            if channels:\n                rpl.append(rfc.RPL_WHOISCHANNELS)\n        rpl.append(rfc.RPL_ENDOFWHOIS)\n        kwargs['m'] = '*'\n        client.fwrite(rpl, channels=channels, **kwargs)\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"irc3\"\nversion = \"1.1.11.dev0\"\ndescription = \"plugable irc client library based on asyncio with DCC and SASL support\"\nreadme = \"README.rst\"\nrequires-python = \">=3.11\"\nlicense = { file = \"LICENSE\" }\nauthors = [{ name = \"Gael Pasgrimaud\", email = \"gael@gawel.org\" }]\nkeywords = [\"irc\", \"dcc\", \"asyncio\"]\nclassifiers = [\n  \"Intended Audience :: Developers\",\n  \"Programming Language :: Python :: 3\",\n  \"Topic :: Communications :: Chat :: Internet Relay Chat\",\n  \"Development Status :: 5 - Production/Stable\",\n]\ndependencies = [\"venusian>=3.0\", \"docopt\"]\n\n[project.optional-dependencies]\ntest = [\n  \"aiocron\",\n  \"aiohttp\",\n  \"aiohttp-wsgi\",\n  \"feedparser\",\n  \"irc3-plugins-test\",\n  \"pysocks\",\n  \"pytest\",\n  \"pytest-aiohttp\",\n  \"pytest-asyncio<1.0\",\n  \"redis\",\n  \"requests\",\n  \"twitter\",\n]\nweb = [\n  \"aiohttp\",\n  \"aiohttp-wsgi\",\n]\n\n[project.scripts]\nirc3 = \"irc3:run\"\nirc3d = \"irc3d:run\"\n\n[project.urls]\nHomepage = \"https://github.com/gawel/irc3/\"\n\n[tool.setuptools.packages.find]\nexclude = [\"docs\", \"tests\"]\n\n[tool.pytest.ini_options]\nasyncio_default_fixture_loop_scope = \"function\"\naddopts = [\n  \"-p no:warnings\",\n  \"-p no:unraisableexception\",\n  \"--doctest-modules\",\n  \"--doctest-glob='*.rst'\",\n]\nignore = [\n  \"CHANGES.rst\",\n  \"examples/*\",\n  \"docs/conf.py\",\n  \"irc3/_*.py\",\n  \"irc3/testing.py\",\n]\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/feed.atom",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xml:lang=\"en-US\">\n  <id>tag:github.com,2008:/gawel/irc3/commits/master</id>\n  <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commits/master\"/>\n  <link type=\"application/atom+xml\" rel=\"self\" href=\"https://github.com/gawel/irc3/commits/master.atom\"/>\n  <title>Recent Commits to irc3:master</title>\n  <updated>DATE</updated>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/ec82ae2c5f8b2954f0646a2177deb65ad9db712a</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/ec82ae2c5f8b2954f0646a2177deb65ad9db712a\"/>\n    <title>\n        coverage\n    </title>\n    <updated>DATE</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>coverage&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/27e5f3e1a06935b620936d7708cab8f3d14b1fbe</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/27e5f3e1a06935b620936d7708cab8f3d14b1fbe\"/>\n    <title>\n        Back to development: 0.4.2\n    </title>\n    <updated>2013-12-30T01:04:29-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>Back to development: 0.4.2&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/ffb7e86a953c61579f973110350b2fffd37c92eb</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/ffb7e86a953c61579f973110350b2fffd37c92eb\"/>\n    <title>\n        Preparing release 0.4.1\n    </title>\n    <updated>2013-12-30T01:04:08-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>Preparing release 0.4.1&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/9bd453e2960cb28513d3201266e104f934775f60</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/9bd453e2960cb28513d3201266e104f934775f60\"/>\n    <title>\n        changes\n    </title>\n    <updated>2013-12-30T00:51:03-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>changes&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/fa05ef7832f77bf2786440d4031b32f65a8b66a8</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/fa05ef7832f77bf2786440d4031b32f65a8b66a8\"/>\n    <title>\n        require at least venusian 1.0a8\n    </title>\n    <updated>2013-12-30T00:48:37-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>require at least venusian 1.0a8&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/b009d104772868f14fc77b1dad931af333dece54</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/b009d104772868f14fc77b1dad931af333dece54\"/>\n    <title>\n        install section\n    </title>\n    <updated>2013-12-24T09:39:31-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>install section&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/5ffc40f842f479c0d21a0b0c6d36f9be2ce5e455</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/5ffc40f842f479c0d21a0b0c6d36f9be2ce5e455\"/>\n    <title>\n        Back to development: 0.4\n    </title>\n    <updated>2013-12-24T09:30:05-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>Back to development: 0.4&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/e6b1861495665b0ac9c0ac7685810484112814ee</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/e6b1861495665b0ac9c0ac7685810484112814ee\"/>\n    <title>\n        Preparing release 0.3\n    </title>\n    <updated>2013-12-24T09:29:44-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>Preparing release 0.3&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/0e9256915e84919b6d73b6e3db57b730e91c9403</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/0e9256915e84919b6d73b6e3db57b730e91c9403\"/>\n    <title>\n        docs\n    </title>\n    <updated>2013-12-24T09:29:23-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>docs&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/8434a21cf523d3a20bdead83eaf5b6575b57dec6</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/8434a21cf523d3a20bdead83eaf5b6575b57dec6\"/>\n    <title>\n        moar coverage\n    </title>\n    <updated>2013-12-24T09:22:59-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>moar coverage&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/d7baddca466909d47d3a295a13ebbd5bd415b26d</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/d7baddca466909d47d3a295a13ebbd5bd415b26d\"/>\n    <title>\n        typo\n    </title>\n    <updated>2013-12-22T15:06:44-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>typo&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/a5d40375a47ea6daf0c6800c6d5b872ac3b2d46f</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/a5d40375a47ea6daf0c6800c6d5b872ac3b2d46f\"/>\n    <title>\n        web client\n    </title>\n    <updated>2013-12-22T15:06:07-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>web client&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/d34286bda2da58419d1d9d9bb3c64a0aeb0fb099</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/d34286bda2da58419d1d9d9bb3c64a0aeb0fb099\"/>\n    <title>\n        do not support 2.7\n    </title>\n    <updated>2013-12-22T15:02:26-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>do not support 2.7&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/034595c614897350098331570f748e4542c55e2b</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/034595c614897350098331570f748e4542c55e2b\"/>\n    <title>\n        Back to development: 0.3\n    </title>\n    <updated>2013-12-22T15:01:01-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>Back to development: 0.3&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/6a845dd9b901c95bf37cad705a816104f2e8a6b8</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/6a845dd9b901c95bf37cad705a816104f2e8a6b8\"/>\n    <title>\n        Preparing release 0.2\n    </title>\n    <updated>2013-12-22T15:00:39-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>Preparing release 0.2&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/ebd462deb70b64f394676ffbfa7cdf887dd2bd0a</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/ebd462deb70b64f394676ffbfa7cdf887dd2bd0a\"/>\n    <title>\n        changes\n    </title>\n    <updated>2013-12-22T15:00:22-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>changes&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/c846584214d054b65dd7199c932669d098440764</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/c846584214d054b65dd7199c932669d098440764\"/>\n    <title>\n        crate.io is dead\n    </title>\n    <updated>2013-12-22T14:59:12-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>crate.io is dead&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/16fa9067759bd3b4b4446d0dc9e27e3539ba5c8c</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/16fa9067759bd3b4b4446d0dc9e27e3539ba5c8c\"/>\n    <title>\n        must log to stderr\n    </title>\n    <updated>2013-12-22T14:57:37-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>must log to stderr&lt;/pre>\n    </content>\n  </entry>\n  <entry>\n    <id>tag:github.com,2008:Grit::Commit/bb925b7e655e51f4ded9fcee4cf1bc7490b43420</id>\n    <link type=\"text/html\" rel=\"alternate\" href=\"https://github.com/gawel/irc3/commit/bb925b7e655e51f4ded9fcee4cf1bc7490b43420\"/>\n    <title>\n        improve configuration / logging\n    </title>\n    <updated>2013-12-22T14:52:12-08:00</updated>\n    <media:thumbnail height=\"30\" width=\"30\" url=\"https://0.gravatar.com/avatar/88ce49f7443a9ef45abb3574d25c55f4?d=https%3A%2F%2Fidenticons.github.com%2Fb9d7714f958c6b3092c752e99e6e4b5d.png&amp;r=x&amp;s=30\"/>\n    <author>\n      <name>gawel</name>\n      <uri>https://github.com/gawel</uri>\n    </author>\n    <content type=\"html\">\n      &lt;pre style='white-space:pre-wrap;width:81ex'>improve configuration / logging&lt;/pre>\n    </content>\n  </entry>\n</feed>\n"
  },
  {
    "path": "tests/test.ini",
    "content": "[bot]\nnick = irc3\n\nhost = localhost\nport = 6667\nssl = false\n\nincludes =\n    irc3.plugins.core\n    irc3.plugins.ctcp\n    irc3.plugins.cron\n    irc3.plugins.autojoins\n    irc3.plugins.userlist\n    irc3.plugins.command\n    irc3.plugins.human\n    irc3.plugins.search\n    irc3.plugins.uptime\n    irc3.plugins.feeds\n    irc3.plugins.dcc\n    irc3.plugins.pager\n    irc3.plugins.web\n\n# channels to join\nautojoins =\n    ${#}irc3\n\n[server]\nincludes =\n    irc3d.plugins.core\n\n[opers]\ngawel=passwd\n"
  },
  {
    "path": "tests/test_async.py",
    "content": "# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.mark.asyncio\nasync def test_whois_fail(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.whois(nick='gawel')\n    assert len(bot.registry.events_re['in']) > 2\n    bot.dispatch(':localhost 401 me gawel :No such nick')\n    result = await task\n    assert result['success'] is False\n    assert len(bot.registry.events_re['in']) == 0\n\n\n@pytest.mark.asyncio\nasync def test_whois_success(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.whois(nick='Ga[W]el', timeout=0.1)\n    assert len(bot.registry.events_re['in']) > 2\n    bot.dispatch(':localhost 311 me ga[w]el username localhost * :realname')\n    bot.dispatch(':localhost 319 me ga[w]el :@#irc3')\n    bot.dispatch(':localhost 312 me ga[w]el localhost :Paris, FR')\n    bot.dispatch(':localhost 671 me ga[w]el :is using a secure connection')\n    bot.dispatch(':localhost 330 me ga[w]el gawel :is logged in as')\n    bot.dispatch(':localhost 318 me ga[w]el :End')\n    result = await task\n    assert len(bot.registry.events_re['in']) == 0\n    assert result['success']\n    assert result['timeout'] is False\n    assert result['username'] == 'username'\n    assert result['realname'] == 'realname'\n\n\n@pytest.mark.asyncio\nasync def test_whois_timeout(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.whois(nick='GaWel', timeout=.1)\n    assert len(bot.registry.events_re['in']) > 2\n    result = await task\n    assert result['timeout'] is True\n\n\n@pytest.mark.asyncio\nasync def test_who_channel(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.who('#irc3')\n    assert len(bot.registry.events_re['in']) == 2\n    bot.dispatch(\n        ':card.freenode.net 352 nick #irc3 ~irc3 host1 srv1 irc3 H :0 bot')\n    bot.dispatch(\n        ':card.freenode.net 352 nick #irc3 ~gael host2 srv2 gawel H@ :1 g')\n    bot.dispatch(':card.freenode.net 315 nick #irc3 :End of /WHO list.')\n    result = await task\n    assert result['timeout'] is False\n    assert len(result['users']) == 2\n\n\n@pytest.mark.asyncio\nasync def test_who_channel_flags(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.who('#irc3', 'ahinrsu')\n    assert len(bot.registry.events_re['in']) == 2\n    bot.dispatch(\n        ':card.freenode.net 354 nick ~irc3 1.1.1.1 host1 srv1 irc3 0 :0 bot')\n    bot.dispatch(\n        ':card.freenode.net 354 nick ~gael 2.2.2.2 host2 srv2 gawel g :1 g')\n    bot.dispatch(':card.freenode.net 315 nick #irc3 :End of /WHO list.')\n    result = await task\n    assert result['timeout'] is False\n    assert len(result['users']) == 2\n    # First user\n    assert result['users'][0]['account'] is None\n    assert result['users'][0]['host'] == 'host1'\n    assert result['users'][0]['ip'] == '1.1.1.1'\n    assert result['users'][0]['nick'] == 'irc3'\n    assert result['users'][0]['realname'] == '0 bot'\n    assert result['users'][0]['server'] == 'srv1'\n    assert result['users'][0]['user'] == '~irc3'\n    # Second user\n    assert result['users'][1]['account'] == 'g'\n    assert result['users'][1]['host'] == 'host2'\n    assert result['users'][1]['ip'] == '2.2.2.2'\n    assert result['users'][1]['nick'] == 'gawel'\n    assert result['users'][1]['realname'] == '1 g'\n    assert result['users'][1]['server'] == 'srv2'\n    assert result['users'][1]['user'] == '~gael'\n\n\n@pytest.mark.asyncio\nasync def test_who_nick(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.who('irc3')\n    assert len(bot.registry.events_re['in']) == 2\n    bot.dispatch(\n        ':card.freenode.net 352 nick * ~irc3 host1 serv1 irc3 H :0 bot')\n    bot.dispatch(':card.freenode.net 315 nick irc3 :End of /WHO list.')\n    result = await task\n    assert result['timeout'] is False\n    assert result['hopcount'] == '0'\n\n\n@pytest.mark.asyncio\nasync def test_topic(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.topic('#chan', topic='test', timeout=.1)\n    assert len(bot.registry.events_re['in']) > 0\n    bot.dispatch(':localhost TOPIC #chan :test')\n    result = await task\n    assert result['timeout'] is False\n    assert result['topic'] == 'test'\n\n\n@pytest.mark.asyncio\nasync def test_no_topic(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.topic('#chan', timeout=.1)\n    assert len(bot.registry.events_re['in']) > 0\n    bot.dispatch(':localhost 331 me #chan :Not topic')\n    result = await task\n    assert result['timeout'] is False\n    assert result['topic'] is None\n\n\n@pytest.mark.asyncio\nasync def test_ison(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.ison('GaWel', timeout=.1)\n    assert len(bot.registry.events_re['in']) > 0\n    bot.dispatch(':localhost 303 me :gawel')\n    result = await task\n    assert result['timeout'] is False\n    assert result['names'] == ['gawel']\n\n\n@pytest.mark.asyncio\nasync def test_names(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.names('#irc3')\n    assert len(bot.registry.events_re['in']) == 2\n    bot.dispatch(\n        ':card.freenode.net 353 nick @ #irc3 :irc3 @gawel')\n    bot.dispatch(\n        ':card.freenode.net 353 nick @ #irc3 :+panoramisk')\n    bot.dispatch(\n        ':card.freenode.net 366 nick #irc3 :End of /NAMES list.')\n    result = await task\n    assert result['timeout'] is False\n    assert len(result['names']) == 3\n\n\n@pytest.mark.asyncio\nasync def test_channel_bans(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.channel_bans('#irc3')\n    assert len(bot.registry.events_re['in']) == 2\n    bot.dispatch(':card.freenode.net 367 nick #irc3 *!*@host irc3 1494621383')\n    bot.dispatch(':card.freenode.net 368 nick #irc3 :End of Channel Ban List')\n    result = await task\n    assert result['timeout'] is False\n    assert len(result['bans']) == 1\n    assert result['bans'][0]['mask'] == '*!*@host'\n    assert result['bans'][0]['user'] == 'irc3'\n    assert result['bans'][0]['timestamp'] == 1494621383\n\n\n@pytest.mark.asyncio\nasync def test_ctcp(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.asynchronious'])\n    assert len(bot.registry.events_re['in']) == 0\n    task = bot.async_cmds.ctcp_async('irc3', 'VERSION')\n    assert len(bot.registry.events_re['in']) == 2\n    bot.dispatch(':irc3!irc3@host1 NOTICE nick :\\x01VERSION IRC3 Library\\x01')\n    result = await task\n    assert result['timeout'] is False\n    assert result['mask'] == 'irc3!irc3@host1'\n    assert result['ctcp'] == 'VERSION'\n    assert result['reply'] == 'IRC3 Library'\n"
  },
  {
    "path": "tests/test_autocommand.py",
    "content": "import asyncio\nfrom irc3.testing import BotTestCase, patch\nfrom irc3.plugins.autocommand import AutoCommand, SleepCommand\n\n\nasync def mock(*args, **kwargs):\n    pass\n\n\nclass TestAutoCommand(BotTestCase):\n\n    config = dict(includes=['irc3.plugins.autocommand'])\n\n    def test_autocommand(self):\n        loop = asyncio.get_event_loop()\n\n        # sleep typed in mixed case to test that work with different cases\n        bot = self.callFTU(autocommands=['AUTH user pass', '/slEep  3',\n                                         'MODE {nick} +x'])\n        with patch('irc3.plugins.autocommand.SleepCommand.execute', mock):\n            plugin = bot.get_plugin(AutoCommand)\n            loop.run_until_complete(plugin.execute_commands())\n            self.assertSent(['AUTH user pass', 'MODE irc3 +x'])\n\n            with self.assertRaises(ValueError):\n                # test bad arguments too\n                self.callFTU(autocommands=[\n                    None, '/sleep 3.4.5', '/sleep bad', 'TEST SENT'])\n\n    def test_autocommand_validation(self):\n        sleep = AutoCommand.parse_command(\"/sleeP 3\")\n        self.assertIsInstance(sleep, SleepCommand)\n        self.assertEqual(sleep.time, 3)\n        # test unknown command\n        with self.assertRaises(ValueError):\n            AutoCommand.parse_command(\"/sleepwhile\")\n\n        with self.assertRaises(ValueError):\n            AutoCommand.parse_command(\"/bad\")\n\n        # test error on multiple arguments\n        with self.assertRaises(ValueError):\n            AutoCommand.parse_command(\"/sleep 3.2 two 3\")\n\n        # test sleep without arguments\n        with self.assertRaises(ValueError):\n            AutoCommand.parse_command(\"/sleep\")\n\n        # test sleep with wrong aruments\n        with self.assertRaises(ValueError):\n            AutoCommand.parse_command(\"/sleep bad\")\n\n        with self.assertRaises(ValueError):\n            AutoCommand.parse_command(\"/sleep 3.4.5\")\n\n        with self.assertRaises(TypeError):\n            SleepCommand(\"bad\")\n"
  },
  {
    "path": "tests/test_autojoins.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase, MagicMock\nfrom irc3.plugins.autojoins import AutoJoins\n\n\nclass TestAutojoin(BotTestCase):\n\n    def test_autojoin_without_diese(self):\n        bot = self.callFTU(autojoins=['foo'])\n        bot.notify('connection_made')\n\n        bot.dispatch(':hobana.freenode.net 376 irc3 :End of /MOTD command.')\n        self.assertSent(['JOIN #foo'])\n\n        bot.dispatch(':hobana.freenode.net 376 irc3 :End of /MOTD command.')\n        self.assertSent([])\n\n    def test_nomotd_events_removed(self):\n        bot = self.callFTU(autojoins=['#foo'])\n        bot.notify('connection_made')\n\n        bot.dispatch(':hobana.freenode.net 422 irc3 :No MOTD.')\n        self.assertSent(['JOIN #foo'])\n\n        bot.dispatch(':hobana.freenode.net 422 irc3 :No MOTD.')\n        self.assertSent([])\n\n    def test_autojoin_nomotd(self):\n        bot = self.callFTU(autojoins=['#foo'])\n        bot.notify('connection_made')\n\n        bot.dispatch(':hobana.freenode.net 422 irc3 :No MOTD.')\n        self.assertSent(['JOIN #foo'])\n\n    def test_autojoin(self):\n        bot = self.callFTU(autojoins=['#foo'])\n        bot.notify('connection_made')\n\n        bot.dispatch(':hobana.freenode.net 376 irc3 :End of /MOTD command.')\n        self.assertSent(['JOIN #foo'])\n\n        bot.dispatch(':kicker!k@k KICK #foo irc3')\n        self.assertSent(['JOIN #foo'])\n\n        bot.dispatch(':kicker!k@k KICK #foo irc3 :bastard!')\n        self.assertSent(['JOIN #foo'])\n\n        plugin = bot.get_plugin(AutoJoins)\n        self.assertEqual(plugin.handles, {})\n        bot.dispatch(':server 473 irc3 #foo :You are banned')\n        self.assertSent(['JOIN #foo'])\n        self.assertIn('#foo', plugin.handles)\n        self.assertEqual(2, plugin.handles['#foo'][0])\n\n        # assume it doesn't break when a timeout is set\n        bot.dispatch(':server 473 irc3 #foo :You are banned')\n        self.assertSent(['JOIN #foo'])\n        self.assertEqual(8, plugin.handles['#foo'][0])\n\n        bot.dispatch(':kicker!k@k KICK #foo irc3 :bastard!')\n        self.assertSent(['JOIN #foo'])\n        self.assertNotIn('#foo', plugin.handles)\n\n        bot.notify('connection_lost')\n\n    def test_autojoin_delay(self):\n        bot = self.callFTU(autojoins=['#foo'], autojoin_delay=3)\n        bot.loop.call_later = MagicMock()\n        bot.notify('connection_made')\n        bot.dispatch(':hobana.freenode.net 422 irc3 :No MOTD.')\n        self.assertTrue(bot.loop.call_later.called)\n\n    def test_autojoin_reload(self):\n        bot = self.callFTU(autojoins=['#foo', '#bar'])\n        bot.notify('connection_made')\n        bot.dispatch(':hobana.freenode.net 422 irc3 :No MOTD.')\n        self.assertSent(['JOIN #foo', 'JOIN #bar'])\n        bot.config['autojoins'] = ['#foo', '#foo2']\n        bot.reload()\n        self.assertSent(['JOIN #foo2', 'PART #bar'])\n"
  },
  {
    "path": "tests/test_bot.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.testing import patch\nfrom irc3_plugins_test import test\nimport logging\n\n\nclass TestBot(BotTestCase):\n\n    def test_config(self):\n        bot = self.callFTU(verbose=True)\n        self.assertEqual(bot.config.verbose, True)\n\n    def test_include_twice(self):\n        bot = self.callFTU()\n        bot.include('irc3.plugins.log')\n        bot.include('irc3.plugins.log')\n\n    def test_plugin(self):\n        bot = self.callFTU()\n        bot.include('irc3.plugins.command')\n        plugin = bot.get_plugin('irc3.plugins.command.Commands')\n        self.assertTrue(plugin is not None)\n        plugin = bot.get_plugin('irc3.plugins.command.Commands')\n        self.assertTrue(plugin is not None)\n        self.assertRaises(LookupError, bot.get_plugin,\n                          'irc3.plugins.log.RawLog')\n\n    def test_join(self):\n        bot = self.callFTU(passwords=dict(foo='bar'))\n        bot.join('#foo')\n        self.assertSent(['JOIN #foo bar'])\n\n    def test_message(self):\n        bot = self.callFTU()\n        bot.privmsg('gawel', 'Youhou!')\n        self.assertSent(['PRIVMSG gawel :Youhou!'])\n        bot.notice('gawel', 'Youhou!')\n        self.assertSent(['NOTICE gawel :Youhou!'])\n        bot.action('gawel', 'does a cool action')\n        self.assertSent(['PRIVMSG gawel :\\x01ACTION does a cool action\\x01'])\n\n    def test_long_message(self):\n        bot = self.callFTU(max_length=23)\n        message = 'How you doing?'\n        bot.privmsg('gawel', message)\n        self.assertSent([\n            'PRIVMSG gawel :How you',\n            'PRIVMSG gawel :doing?'\n        ])\n\n    def test_log(self):\n        bot = self.callFTU(level='ERROR')\n        bot.include('irc3.plugins.log', venusian_categories=['irc3.debug'])\n        bot.dispatch('PING :youhou')\n        bot.dispatch(':gawel!user@host PRIVMSG #chan :youhou')\n\n    def test_logger(self):\n        bot = self.callFTU(level='ERROR')\n        log = logging.getLogger('irc.1')\n        log.set_irc_targets(bot, '#log')\n        log2 = logging.getLogger('irc.2')\n        log2.set_irc_targets(bot, '#log2')\n        log.info('foo')\n        log2.info('foo2')\n        self.assertSent([\n            'PRIVMSG #log :INFO foo',\n            'PRIVMSG #log2 :INFO foo2'\n        ])\n        self.assertNotEqual(\n            log.handlers[0].targets,\n            log2.handlers[0].targets\n        )\n\n    def test_quote(self):\n        bot = self.callFTU()\n        bot.include('irc3.plugins.command',\n                    venusian_categories=bot.venusian_categories + [\n                        'irc3.debug',\n                    ])\n        bot.dispatch(':gawel!user@host PRIVMSG nono :!quote who gawel')\n        self.assertSent(['who gawel'])\n\n    def test_ctcp(self):\n        bot = self.callFTU()\n        bot.ctcp('gawel', 'VERSION')\n        self.assertSent(['PRIVMSG gawel :\\x01VERSION\\x01'])\n\n    def test_server_config(self):\n        bot = self.callFTU()\n        bot.include('irc3.plugins.core')\n        bot.notify('connection_made')\n        bot.dispatch(':srv 005 foo STATUSMSG=+%@ ETRACE :are supported')\n        bot.dispatch(':srv 376 foo :End of MOTD')\n        self.assertEqual(bot.config['server_config']['STATUSMSG'], '+%@')\n        self.assertTrue(bot.config['server_config']['ETRACE'])\n\n    def test_ping(self):\n        bot = self.callFTU()\n        bot.include('irc3.plugins.core')\n        bot.dispatch('PING :youhou')\n        self.assertSent(['PONG :youhou'])\n\n    def test_nick(self):\n        bot = self.callFTU()\n        bot.include('irc3.plugins.core')\n        self.assertEqual(bot.nick, 'nono')\n        bot.dispatch(':nono!user@host NICK :withcolon')\n        self.assertEqual(bot.nick, 'withcolon')\n        bot.dispatch(':withcolon!user@host NICK bar')\n        self.assertEqual(bot.nick, 'bar')\n        bot.dispatch(':h.net 432 * bar :xx')\n        self.assertSent(['NICK bar_'])\n\n    def test_mode(self):\n        bot = self.callFTU()\n        bot.mode('#foo', '+v', 'bar')\n        self.assertSent(['MODE #foo +v bar'])\n\n    def test_kick(self):\n        bot = self.callFTU()\n        bot.kick('#foo', 'bar')\n        self.assertSent(['KICK #foo bar'])\n        bot.kick('#foo', 'bar', 'bye')\n        self.assertSent(['KICK #foo bar :bye'])\n\n    def test_part(self):\n        bot = self.callFTU()\n        bot.part('#foo')\n        self.assertSent(['PART #foo'])\n        bot.part('#foo', 'bye')\n        self.assertSent(['PART #foo :bye'])\n\n    def test_quit(self):\n        bot = self.callFTU()\n        bot.quit()\n        self.assertSent(['QUIT :bye'])\n        bot.quit('foo')\n        self.assertSent(['QUIT :foo'])\n\n    @patch('time.sleep')\n    def test_SIGINT(self, sleep):\n        bot = self.callFTU()\n        bot.SIGINT()\n        self.assertTrue(sleep.called)\n        self.assertTrue(bot.loop.stop.called)\n\n    def test_SIGHUP(self):\n        bot = self.callFTU()\n        bot.SIGHUP()\n\n    def test_pkg_resources_entry_points(self):\n        config = dict(includes=['irc3.plugins.test'])\n        bot = self.callFTU(**config)\n        plugin = bot.get_plugin(test.test)\n        self.assertEqual(plugin, 'success')\n\n    def test_pkg_resources_entry_points_exception(self):\n        config = dict(includes=['irc3.plugins.badtest'])\n        with self.assertRaises(LookupError):\n            self.callFTU(**config)\n"
  },
  {
    "path": "tests/test_casefold.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\n\n\nclass TestCasefold(BotTestCase):\n\n    config = dict(includes=['irc3.plugins.casefold'])\n\n    def test_ascii(self):\n        bot = self.callFTU(server_config={'CASEMAPPING': 'ascii'})\n\n        self.assertEqual(bot.casefold('#testchan\\\\123[]56'),\n                         '#testchan\\\\123[]56')\n        self.assertEqual(bot.casefold('#tESt[]chAn'), '#test[]chan')\n        self.assertEqual(bot.casefold('#TEsT\\\\CHaN'), '#test\\\\chan')\n\n        self.assertEqual(bot.casefold('#TEsT\\\\CHaN'), '#test\\\\chan')\n\n    def test_rfc1459(self):\n        bot = self.callFTU(server_config={'CASEMAPPING': 'rfc1459'})\n\n        self.assertEqual(bot.casefold('#testchan\\\\123[]56'),\n                         '#testchan|123{}56')\n        self.assertEqual(bot.casefold('#tESt[]chAn'), '#test{}chan')\n        self.assertEqual(bot.casefold('#TEsT\\\\CHaN'), '#test|chan')\n\n        self.assertEqual(bot.casefold('#TEsT\\\\CHaN'), '#test|chan')\n"
  },
  {
    "path": "tests/test_commands.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.plugins import command\nfrom irc3.plugins import dcc\nfrom irc3.compat import asyncio\nfrom irc3 import utils\nimport tempfile\nimport unittest\nimport shutil\nimport codecs\nimport os\n\n\n@command.command(permission='myperm',\n                 aliases=['cmd_alias'],\n                 show_in_help_list=False,\n                 use_shlex=False,\n                 options_first=True,\n                 quiet=True)\n@dcc.dcc_command(options_first=True)\ndef cmd(bot, *args):\n    \"\"\"Test command\n        %%cmd\n    \"\"\"\n    return 'Done'\n\n\n@command.command\ndef cmd_view(bot, *args):\n    \"\"\"test command\n        %%cmd_view\n    \"\"\"\n    return 'Done'\n\n\n@command.command(quiet=True)\ndef cmd_arg(bot, *args):\n    \"\"\"test command\n\n        %%cmd_arg <arg>\n    \"\"\"\n    return 'Done'\n\n\nclass TestCommands(BotTestCase):\n\n    name = 'irc3.plugins.command'\n    guard = 'irc3.plugins.command.mask_based_policy'\n    masks = 'irc3.plugins.command.masks'\n\n    config = dict(includes=[name])\n\n    def test_async_plugin(self):\n        bot = self.callFTU(nick='foo', loop=asyncio.new_event_loop())\n        bot.include('async_command')\n        plugin = bot.get_plugin(command.Commands)\n        mask = utils.IrcString('a@a.com')\n        res = plugin.on_command('get', mask, mask.nick, data='')\n        assert isinstance(res, asyncio.Task)\n        res2 = plugin.on_command('get', mask, mask.nick, data='')\n        assert res2 is None\n        plugin.on_command('put', mask, mask.nick, data='xx yy')\n        bot.loop.run_until_complete(res)\n        assert res.result() == ['xx', 'yy']\n\n    def test_help(self):\n        bot = self.callFTU(nick='foo')\n        plugin = bot.get_plugin(command.Commands)\n        self.assertEqual(len(plugin), 2, plugin)\n        bot.dispatch(':bar!user@host PRIVMSG foo :!help')\n        self.assertSent(\n            ['PRIVMSG bar :Available commands: !help'])\n\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!help')\n        self.assertSent(\n            ['PRIVMSG #chan :Available commands: !help'])\n\n    def test_help_hides(self):\n        bot = self.callFTU(nick='foo')\n        bot.include(__name__)\n        # For direct messages\n        bot.dispatch(':bar!user@host PRIVMSG foo :!help')\n        self.assertSent(['PRIVMSG bar :Available commands: '\n                        '!cmd_arg, !cmd_view, !help'])\n        # channel messages\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!help')\n        self.assertSent(['PRIVMSG #chan :Available commands: '\n                        '!cmd_arg, !cmd_view, !help'])\n\n    def test_help_with_url(self):\n        bot = self.callFTU(nick='foo', **{\n            'irc3.plugins.command': dict(url='http://localhost/')})\n        plugin = bot.get_plugin(command.Commands)\n        self.assertEqual(len(plugin), 2, plugin)\n        bot.dispatch(':bar!user@host PRIVMSG foo :!help')\n        self.assertSent([\n            'PRIVMSG bar :Available commands: !help',\n            'PRIVMSG bar :Full help is available at http://localhost/',\n        ])\n\n    def test_print_help(self):\n        bot = self.callFTU(nick='foo')\n        tmp = tempfile.mkdtemp()\n        self.addCleanup(shutil.rmtree, tmp)\n        path = os.path.join(tmp, 'help.rst')\n        with codecs.open(path, 'w', encoding='utf8') as fd:\n            bot.print_help_page(file=fd)\n        with codecs.open(path, encoding='utf8') as fd:\n            self.assertIn('Available Commands', fd.read())\n\n    def test_command_char(self):\n        bot = self.callFTU(**{'irc3.plugins.command': {'cmd': '$'}})\n        bot.dispatch(':bar!user@host PRIVMSG foo :$ping')\n        self.assertSent(['NOTICE bar :PONG bar!'])\n\n        bot = self.callFTU(**{'cmd': '$'})\n        bot.dispatch(':bar!user@host PRIVMSG foo :$ping')\n        self.assertSent(['NOTICE bar :PONG bar!'])\n\n    def test_command_alias(self):\n        bot = self.callFTU(nick='nono')\n        bot.include(__name__)\n        bot.dispatch(':adm!user@host PRIVMSG #chan :!cmd_alias')\n        self.assertSent(['PRIVMSG #chan :Done'])\n        bot.dispatch(':adm!user@host PRIVMSG #chan :!help cmd_alias')\n        self.assertSent([\n            'PRIVMSG #chan :Test command',\n            'PRIVMSG #chan :!cmd',\n            'PRIVMSG #chan :Aliases: cmd_alias'])\n\n    def test_weird_chars(self):\n        bot = self.callFTU(nick='foo', **{\n            'irc3.plugins.command': dict(cmd='|')})\n        plugin = bot.get_plugin(command.Commands)\n        self.assertEqual(len(plugin), 2, plugin)\n        bot.dispatch(':bar!user@host PRIVMSG foo :|help')\n        self.assertSent(\n            ['PRIVMSG bar :Available commands: |help'])\n\n    def test_command_trailing_space(self):\n        bot = self.callFTU(nick='foo')\n        bot.dispatch(':bar!user@host PRIVMSG foo :!ping')\n        bot.dispatch(':bar!user@host PRIVMSG foo :!ping ')\n        bot.dispatch(':bar!user@host PRIVMSG foo :!ping  ')\n        self.assertSent(['NOTICE bar :PONG bar!'] * 3)\n\n    def test_command_argument_space(self):\n        bot = self.callFTU(nick='foo')\n        bot.include(__name__)\n        bot.dispatch(':bar!user@host PRIVMSG foo :!cmd_arg test')\n        bot.dispatch(':bar!user@host PRIVMSG foo :!cmd_arg  test')\n        bot.dispatch(':bar!user@host PRIVMSG foo :!cmd_arg   test')\n        bot.dispatch(':bar!user@host PRIVMSG foo :!cmd_arg   test ')\n        self.assertSent(['PRIVMSG bar :Done'] * 4)\n\n    def test_command_argument_shlex(self):\n        bot = self.callFTU(nick='foo')\n        bot.include(__name__)\n        bot.dispatch(':bar!user@host PRIVMSG foo :!cmd_arg   \"test test\" ')\n        self.assertSent(['PRIVMSG bar :Done'])\n\n    def test_command_argument_quiet(self):\n        bot = self.callFTU(nick='nono')\n        bot.include(__name__)\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!cmd xx')\n        self.assertNothingSent()\n\n    def test_command_argument_quiet_shlex(self):\n        bot = self.callFTU(nick='nono')\n        bot.include(__name__)\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!cmd_arg \"test')\n        self.assertNothingSent()\n\n    def test_private_command(self):\n        bot = self.callFTU()\n        bot.dispatch(':bar!user@host PRIVMSG nono :!ping')\n        self.assertSent(['NOTICE bar :PONG bar!'])\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!ping')\n        self.assertSent([\n            \"PRIVMSG bar :You can only use the 'ping' command in private.\"])\n\n    def test_help_command(self):\n        bot = self.callFTU()\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!help ping')\n        self.assertSent(['PRIVMSG #chan :ping/pong', 'PRIVMSG #chan :!ping'])\n\n    def test_help_command_with_bang(self):\n        bot = self.callFTU()\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!help !ping')\n        self.assertSent(['PRIVMSG #chan :ping/pong', 'PRIVMSG #chan :!ping'])\n\n    def test_reconnect_command(self):\n        self.patch_asyncio()\n        bot = self.callFTU(includes=['irc3.plugins.core'])\n        bot.include('irc3.plugins.command',\n                    venusian_categories=bot.venusian_categories + [\n                        'irc3.debug',\n                    ])\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!reconnect')\n        self.assertSent(['PING :10'])\n\n    @unittest.skip('')\n    def test_antiflood(self):\n        bot = self.callFTU(asynchronous=True,\n                           **{self.name: dict(antiflood=True)})\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!help ping')\n        self.assertSent(['PRIVMSG #chan :ping/pong', 'PRIVMSG #chan :!ping'])\n\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!help ping')\n        self.assertSent([\"NOTICE bar :Please be patient and don't flood me\"])\n\n        plugin = bot.get_plugin(command.Commands)\n        plugin.handles[('help', '#chan')].set_result(True)\n        bot.dispatch(':bar!user@host PRIVMSG #chan :!help ping')\n        self.assertSent(['PRIVMSG #chan :ping/pong', 'PRIVMSG #chan :!ping'])\n\n    def test_unicode(self):\n        bot = self.callFTU(nick='nono')\n        bot.dispatch(':bar!user@host PRIVMSG nono :!ping eé')\n        self.assertSent(['PRIVMSG bar :Invalid arguments.'])\n\n    def test_invalid_arguments(self):\n        bot = self.callFTU(nick='nono')\n        bot.dispatch(':bar!user@host PRIVMSG nono :!ping xx')\n        self.assertSent(['PRIVMSG bar :Invalid arguments.'])\n\n    def test_invalid_arguments_shlex(self):\n        bot = self.callFTU(nick='nono')\n        bot.dispatch(':bar!user@host PRIVMSG nono :!ping \"xx')\n        self.assertSent(\n            ['PRIVMSG bar :Invalid arguments: No closing quotation.'])\n\n    def test_command_case_insensitive(self):\n        bot = self.callFTU(nick='nono')\n        bot.dispatch(':bar!user@host PRIVMSG nono :!PiNG')\n        self.assertSent(['NOTICE bar :PONG bar!'])\n\n    def test_command_case_sensitive(self):\n        bot = self.callFTU(**{self.name: {'casesensitive': True}})\n        bot.dispatch(':bar!user@host PRIVMSG nono :!PiNG')\n        self.assertNothingSent()\n\n    def test_permissions(self):\n        tmp = tempfile.mkdtemp()\n        self.addCleanup(shutil.rmtree, tmp)\n\n        bot = self.callFTU(**{\n            'storage': 'json://%s/storage.json' % tmp,\n            self.name: dict(guard=self.guard),\n            self.masks: {\n                'adm!*': 'all_permissions',\n                'local_adm!*': 'myperm view',\n                '*': 'view',\n            }\n        })\n        bot.include(__name__)\n        bot.dispatch(':adm!user@host PRIVMSG #chan :!cmd')\n        self.assertSent(['PRIVMSG #chan :Done'])\n\n        bot.dispatch(':local_adm!user@host PRIVMSG #chan :!cmd')\n        self.assertSent(['PRIVMSG #chan :Done'])\n\n        bot.dispatch(':nobody!user@host PRIVMSG #chan :!cmd')\n        self.assertSent([\n            \"PRIVMSG nobody :You are not allowed to use the 'cmd' command\"])\n\n        bot.dispatch(':nobody!user@host PRIVMSG #chan :!cmd_view')\n        self.assertSent(['PRIVMSG #chan :Done'])\n\n        bot.dispatch(':local_adm!user@host PRIVMSG #chan :!cmd_view')\n        self.assertSent(['PRIVMSG #chan :Done'])\n\n        bot.include('irc3.plugins.storage')\n        bot.db[self.name] = {\n            'nobody!*': 'myperm view'\n        }\n        bot.dispatch(':nobody!user@host PRIVMSG #chan :!cmd')\n        self.assertSent(['PRIVMSG #chan :Done'])\n"
  },
  {
    "path": "tests/test_cron.py",
    "content": "# -*- coding: utf-8 -*-\nimport pytest\nfrom irc3.testing import BotTestCase\nfrom irc3.testing import MagicMock\nfrom irc3.plugins import cron\nfrom irc3.compat import asyncio\n\n\nclass MyCron:\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @cron.cron('* * * * *')\n    def method(self):\n        return self.bot\n\n\n@cron.cron('* * * * *')\nasync def function(bot):\n    return bot\n\n\nclass TestCron(BotTestCase):\n\n    config = dict(includes=['irc3.plugins.cron'])\n\n    def test_add_remove_cron(self):\n        bot = self.callFTU()\n        plugin = bot.get_plugin(cron.Crons)\n        plugin.connection_made()\n        callback = MagicMock()\n        c = bot.add_cron('* * * * *', callback)\n        assert c.handle is not None\n        assert len(plugin) == 1\n        assert not callback.called\n        plugin.remove_cron(c)\n        assert len(plugin) == 0\n\n    def test_connection_made(self):\n        bot = self.callFTU()\n        bot.include(__name__)\n        plugin = bot.get_plugin(cron.Crons)\n        assert not plugin.started\n        plugin.connection_made()\n        assert plugin.started\n\n    def test_reload(self):\n        bot = self.callFTU()\n        bot.include(__name__)\n        plugin = bot.get_plugin(cron.Crons)\n        assert len(plugin) == 2\n        plugin.before_reload()\n        assert len(plugin) == 0\n        assert not plugin.started\n        plugin.after_reload()\n        assert plugin.started\n\n    def test_callable(self):\n        loop = asyncio.new_event_loop()\n        bot = self.callFTU(loop=loop)\n        bot.include(__name__)\n        plugin = bot.get_plugin(cron.Crons)\n\n        results = []\n\n        f = asyncio.Future(loop=loop)\n\n        def complete(future):\n            results.append(future.result())\n            if len(results) == 2:\n                f.set_result(results)\n\n        for c in plugin:\n            asyncio.ensure_future(\n                c.next(), loop=loop).add_done_callback(complete)\n\n        try:\n            loop.run_until_complete(asyncio.wait_for(f, timeout=61))\n        except asyncio.TimeoutError:\n            pytest.fail(\n                \"Test timed out waiting for cron jobs. \"\n                f\"Results: {results}\"\n            )\n        assert results == [bot, bot]\n"
  },
  {
    "path": "tests/test_ctcp.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.plugins.ctcp import CTCP\n\n\nclass TestCTCP(BotTestCase):\n\n    config = dict(includes=['irc3.plugins.ctcp'],\n                  ctcp_max_replies=3,\n                  ctcp=dict(foo='bar'))\n\n    def test_ctcp(self):\n        bot = self.callFTU(autojoins=['foo'])\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n        self.assertSent(['NOTICE gawel :\\x01FOO bar\\x01'])\n\n    def test_ctcp_flood(self):\n        bot = self.callFTU(autojoins=['foo'])\n        plugin = bot.get_plugin(CTCP)\n\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n        self.assertTrue(plugin.handle is not None, plugin.handle)\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n\n        # flood\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n        bot.dispatch(':gawel!user@host PRIVMSG irc3 :\\x01FOO\\x01')\n        self.assertSent(['NOTICE gawel :\\x01FOO bar\\x01'] * 3)\n"
  },
  {
    "path": "tests/test_dcc.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.compat import asyncio\nfrom irc3.dcc.client import DCCSend\nfrom irc3.plugins.dcc import dcc_command\nfrom irc3 import dcc_event\nfrom irc3 import utils\nimport tempfile\nimport pytest\nimport shutil\nimport os\n\n\nlog = {'in': [], 'out': []}\n\n\ndef get_extra_info(*args):\n    return ('127.0.0.1', 4567)\n\n\n@dcc_event('(?P<data>.*)')\ndef log_in(bot, client=None, data=None):\n    log['in'].append((client, data))\n\n\n@dcc_event('(?P<data>.*)', iotype='out')\ndef log_out(bot, client=None, data=None):\n    log['out'].append((client, data))\n\n\n@dcc_command\ndef syn(bot, mask, client, args):\n    \"\"\"Ok\n\n        %%syn\n    \"\"\"\n    client.send_line('ack')\n\n\ndef chat_ready(client):\n    client = client.result()\n    client.actions(client.mask)\n    client.send('\\x01ACTION syn\\x01')\n    client.send('\\x01ACTION help\\x01')\n    client.loop.call_later(.1, client.idle_timeout_reached)\n\n\n@pytest.mark.usefixtures('cls_event_loop')\nclass TestChat(BotTestCase):\n\n    config = dict(includes=['irc3.plugins.dcc'],\n                  dcc={'ip': '127.0.0.1'})\n    mask = utils.IrcString('gawel@gawel!bearstech.com')\n    dmask = utils.IrcString('gawel@gawel!127.0.0.1')\n\n    def callDCCFTU(self, *args, **kwargs):\n        self.bot = self.callFTU()\n        self.bot.protocol.transport.get_extra_info = get_extra_info\n        self.bot.dispatch(':%s PRIVMSG irc3 :!chat' % self.mask)\n        self.future = asyncio.Future(loop=self.loop)\n        self.loop.call_later(.1, self.created)\n\n    def created(self):\n        servers = self.bot.dcc.connections['chat']['masks'][self.mask]\n        self.server = list(servers.values())[0]\n        print(self.server)\n        self.client = self.bot.dcc.create(\n            'chat', self.dmask,\n            host='127.0.0.1', port=self.server.port)\n        self.client.ready.add_done_callback(chat_ready)\n        self.client.closed.add_done_callback(self.future.set_result)\n\n    def test_create(self):\n        self.callDCCFTU()\n        self.bot.include('irc3.plugins.dcc')\n        self.bot.include(__name__)\n        self.loop.run_until_complete(self.future)\n        proto = self.client\n        assert proto.transport is not None\n        info = self.bot.dcc.connections['chat']['masks']['gawel']\n        assert proto not in info.values()\n        assert proto.started.result() is proto\n        assert proto.closed.done()\n\n        # the timeout message is sent or not regarding python version.\n        # we tolerate both\n        assert len(log['in']) in (5, 6)\n        assert len(log['out']) == 6\n\n\n@pytest.mark.usefixtures('cls_event_loop')\nclass DCCTestCase(BotTestCase):\n\n    dmask = utils.IrcString('gawel@gawel!127.0.0.1')\n\n    def callDCCFTU(self, *args, **kwargs):\n        bot = self.callFTU()\n        self.future = asyncio.Future(loop=self.loop)\n        bot.protocol.transport.get_extra_info = get_extra_info\n        self.manager = manager = bot.dcc\n        self.server = manager.create(*args, **kwargs)\n        self.server.ready.add_done_callback(self.created)\n\n    def createFiles(self):\n        self.wd = tempfile.mkdtemp(prefix='irc3dcc')\n        self.addCleanup(shutil.rmtree, self.wd)\n        self.dst = os.path.join(self.wd, 'dst')\n        self.src = os.path.join(self.wd, 'src')\n        with open(self.src, 'wb') as fd:\n            fd.write(('start%ssend' % ('---' * (1024 * 1024))).encode('ascii'))\n\n    def assertFileSent(self):\n        getsize = os.path.getsize\n        assert getsize(self.dst), getsize(self.src)\n        assert getsize(self.dst), getsize(self.src)\n        with open(self.src, 'rb') as fd:\n            src = fd.read()\n        with open(self.dst, 'rb') as fd:\n            dest = fd.read()\n        assert src == dest\n\n\nclass TestSend(DCCTestCase):\n\n    send_class = DCCSend\n\n    def created(self, f):\n        self.client = self.manager.create(\n            'get', utils.IrcString('gawel!gawel@host'),\n            host='127.0.0.1', port=self.server.port,\n            idle_timeout=10, filepath=self.dst)\n        self.client.closed.add_done_callback(self.future.set_result)\n\n    def test_create(self):\n        self.createFiles()\n        self.callDCCFTU(self.send_class, self.dmask, filepath=self.src)\n        self.loop.run_until_complete(self.future)\n        proto = self.client\n        assert proto.transport is not None\n        info = self.manager.connections['get']['masks'][self.dmask]\n        assert proto not in info.values()\n        assert proto.started.result() is proto\n        assert proto.closed.done()\n        self.assertFileSent()\n\n\nclass TestResume(DCCTestCase):\n\n    send_class = DCCSend\n\n    def created(self, f):\n        with open(self.dst, 'wb') as fd:\n            with open(self.src, 'rb') as fdd:\n                fd.write(fdd.read(1345))\n        self.client = self.manager.create(\n            'get', self.dmask,\n            host='127.0.0.1', port=self.server.port,\n            idle_timeout=10, filepath=self.dst)\n        self.client.resume = True\n        self.manager.resume(self.dmask, self.server.filename_safe,\n                            self.server.port, self.client.offset)\n        self.client.closed.add_done_callback(self.future.set_result)\n\n    def test_create(self):\n        self.createFiles()\n        self.callDCCFTU(self.send_class, self.dmask, filepath=self.src)\n        self.loop.run_until_complete(self.future)\n        proto = self.client\n        assert proto.transport is not None\n        info = self.manager.connections['get']['masks'][self.dmask]\n        assert proto not in info.values()\n        assert proto.started.result() is proto\n        assert proto.closed.done()\n        self.assertFileSent()\n\n\nclass TestSendWithLimit(DCCTestCase):\n\n    send_class = DCCSend\n\n    def created(self, f):\n        self.client = self.manager.create(\n            'get', self.dmask,\n            host='127.0.0.1', port=self.server.port,\n            idle_timeout=10, filepath=self.dst)\n        self.client.closed.add_done_callback(self.future.set_result)\n\n    def test_create(self):\n        self.createFiles()\n        self.callDCCFTU(self.send_class, self.dmask,\n                        filepath=self.src, limit_rate=64)\n        self.loop.run_until_complete(self.future)\n        proto = self.client\n        assert proto.transport is not None\n        info = self.manager.connections['get']['masks'][self.dmask]\n        assert proto not in info.values()\n        assert proto.started.result() is proto\n        assert proto.closed.done()\n        self.assertFileSent()\n"
  },
  {
    "path": "tests/test_dec.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nimport irc3\n\n\n@irc3.plugin\nclass OldStyleClass:\n    def __init__(self, bot):\n        self.bot = bot\n\n\n@irc3.plugin\nclass NewStyleClass:\n    def __init__(self, bot):\n        self.bot = bot\n\n\nclass TestPlugin(BotTestCase):\n\n    def test_registration(self):\n        bot = self.callFTU(includes=[__name__])\n        plugin = bot.get_plugin(__name__ + '.OldStyleClass')\n        assert isinstance(plugin, OldStyleClass)\n        plugin = bot.get_plugin(__name__ + '.NewStyleClass')\n        assert isinstance(plugin, NewStyleClass)\n"
  },
  {
    "path": "tests/test_events.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.compat import asyncio\nimport irc3\n\n\n@irc3.event(irc3.rfc.PRIVMSG)\ndef msg1(bot, **kwargs):\n    bot.privmsg('#irc3', 'msg1')\n\n\n@irc3.event(irc3.rfc.PRIVMSG)\ndef msg2(bot, **kwargs):\n    bot.privmsg('#irc3', 'msg2')\n\n\n@irc3.event(irc3.rfc.PRIVMSG, iotype='out')\ndef msg3(bot, target=None, event=None, data=None):\n    if target != '#irc3':\n        bot.privmsg('#irc3', '<{0}> {1}: {2}'.format(bot.nick, target, data))\n\n\nclass TestEvents(BotTestCase):\n\n    def test_event(self):\n        bot = self.callFTU()\n        bot.include('irc3.plugins.core')\n        self.assertIn('<bound event ',\n                      repr(list(bot.registry.events['in'].values())[0]))\n\n    def test_bad_event(self):\n        self.assertRaises(Exception, irc3.event, '(.*')\n\n    def test_not_include_twice(self):\n        bot = self.callFTU()\n        bot.include(__name__)\n        bot.include(__name__)\n        bot.dispatch(':g!g@g PRIVMSG #irc3 :allo')\n        self.assertSent(['PRIVMSG #irc3 :msg1', 'PRIVMSG #irc3 :msg2'])\n\n    def test_out_event(self):\n        bot = self.callFTU()\n        bot.include(__name__)\n        bot.privmsg('foo', 'Hi!')\n        self.assertSent([\n            'PRIVMSG foo :Hi!',\n            'PRIVMSG #irc3 :<nono> foo: Hi!',\n        ])\n\n    def test_async_event(self):\n        loop = asyncio.new_event_loop()\n        future = asyncio.Future(loop=loop)\n\n        async def e(ctx, **kwargs):\n            ctx.privmsg('#irc3', 'async')\n            future.set_result(ctx)\n\n        bot = self.callFTU(loop=loop)\n\n        e = irc3.utils.wraps_with_context(e, bot)\n        bot.attach_events(irc3.event(irc3.rfc.PRIVMSG, e))\n\n        bot.dispatch(':g!g@g PRIVMSG #irc3 :async')\n\n        loop.run_until_complete(future)\n        assert future.result() is bot\n"
  },
  {
    "path": "tests/test_feeds.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.testing import MagicMock\nfrom irc3.testing import asyncio\nimport datetime\nimport tempfile\nimport shutil\nimport os\n\n\ndef hook(entries):\n    return []\n\n\nclass Hook:\n\n    def __init__(self, bot):\n        pass\n\n    def __call__(self, entries):\n        return []\n\n\nclass Dispatcher:\n\n    def __init__(self, bot):\n        self.loop = bot.loop\n        self.reset()\n\n    def reset(self):\n        self.future = asyncio.Future(loop=self.loop)\n        return self.future\n\n    def __call__(self, messages):\n        self.future.set_result(list(messages))\n\n\nclass TestFeeds(BotTestCase):\n\n    name = 'irc3.plugins.feeds'\n\n    def setUp(self):\n        wd = tempfile.mkdtemp()\n        self.addCleanup(shutil.rmtree, wd)\n        self.wd = os.path.join(wd, 'feeds')\n        dt = datetime.datetime.now().strftime('%Y-%m-%dT%M:%M:OO-08:00')\n        self.patch_requests(\n            filename='tests/feed.atom',\n            DATE=dt,\n        )\n\n    def callFTU(self, **kwargs):\n        loop = kwargs.pop('loop', None)\n        config = dict(\n            directory=self.wd,\n            irc3='http://xxx',\n            dispatcher='tests.test_feeds.Dispatcher',\n            channels='#irc3', **kwargs\n        )\n        config = {\n            'includes': [self.name],\n            self.name: config\n        }\n        if loop:\n            config.update(loop=loop)\n        return super(TestFeeds, self).callFTU(**config)\n\n    def test_connection_made(self):\n        bot = self.callFTU()\n        bot.loop.call_later = MagicMock()\n        bot.notify('connection_made')\n        self.assertTrue(bot.loop.call_later.called)\n\n    def test_feed(self):\n        bot = self.callFTU(loop=asyncio.new_event_loop())\n        future = bot.feeds.dispatcher.reset()\n        bot.feeds.update()\n        bot.loop.run_until_complete(future)\n        assert future.result() == [\n            ('#irc3', '[irc3] coverage https://github.com/gawel/irc3/commit/'\n                      'ec82ae2c5f8b2954f0646a2177deb65ad9db712a')]\n        bot = self.callFTU(loop=asyncio.new_event_loop())\n        future = bot.feeds.dispatcher.reset()\n        bot.feeds.update()\n        bot.loop.run_until_complete(future)\n        assert future.result() == []\n\n    def test_hooked_feed(self):\n        bot = self.callFTU(hook='tests.test_feeds.hook',\n                           loop=asyncio.new_event_loop())\n        future = bot.feeds.dispatcher.reset()\n        bot.feeds.update()\n        bot.loop.run_until_complete(future)\n        assert future.result() == []\n\n    def test_hooked_feed_with_class(self):\n        bot = self.callFTU(hook='tests.test_feeds.Hook',\n                           loop=asyncio.new_event_loop())\n        assert isinstance(bot.feeds.hook, Hook)\n        future = bot.feeds.dispatcher.reset()\n        bot.feeds.update()\n        bot.loop.run_until_complete(future)\n        assert future.result() == []\n"
  },
  {
    "path": "tests/test_fifo.py",
    "content": "from irc3.testing import BotTestCase, MagicMock\nfrom irc3.plugins.fifo import Fifo\nimport shutil\n\n\nclass TestFifo(BotTestCase):\n\n    config = {\n        \"includes\": ['irc3.plugins.fifo'],\n        \"irc3.plugins.fifo\": {\"runpath\": \"/tmp/run/irc3\"}\n    }\n\n    def test_fifo_fake_event_loop(self):\n        try:\n            shutil.rmtree('/tmp/run/irc3')\n        except Exception:\n            pass\n        bot = self.callFTU()\n        plugin = bot.get_plugin(Fifo)\n        plugin.loop = MagicMock()\n\n        with open(\"/tmp/run/irc3/channel\", \"wb\") as f:\n            f.write(b'-\\n')\n\n        bot.test(':irc3!user@host JOIN #channel')\n        channel_fd = plugin.fifos[\"#channel\"]\n\n        with open(\"/tmp/run/irc3/channel\", \"wb\", 0) as f:\n            f.write(b\"test1\\n\")\n            plugin.watch_fd(channel_fd, \"#chanel\")\n            self.assertSent(['PRIVMSG #chanel :test1'])\n\n            f.write(b\"test2\\r\\n\")\n            plugin.watch_fd(channel_fd, \"#chanel\")\n            self.assertSent(['PRIVMSG #chanel :test2'])\n\n            f.write(b\"test3\\r\\ntest4\\n\")\n            plugin.watch_fd(channel_fd, \"#chanel\")\n            self.assertSent(['PRIVMSG #chanel :test3',\n                             'PRIVMSG #chanel :test4'])\n\n            for char in b\"test5\\n\":\n                f.write(bytes([char]))\n                plugin.watch_fd(channel_fd, \"#chanel\")\n\n            self.assertSent(['PRIVMSG #chanel :test5'])\n"
  },
  {
    "path": "tests/test_irc3d.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import testing\nimport irc3d\n\n\n@irc3d.extend\ndef echo(self):\n    return self\n\n\nclass TestServer(testing.ServerTestCase):\n\n    def test_mock(self):\n        s = self.callFTU(clients=2)\n        print(s.clients)\n        self.assertEqual(len(s.clients), 2)\n\n    def test_connection_lost(self):\n        s = self.callFTU(clients=2)\n        s.client1.connection_lost(None)\n        self.assertEqual(len(s.nicks), 1)\n\n    def test_log(self):\n        s = self.callFTU(clients=2)\n        s.include('irc3.plugins.log', venusian_categories=['irc3d.debug'])\n        s.client1.dispatch('PING :yé')\n\n    def test_extend(self):\n        s = self.callFTU(clients=0)\n        s.include(__name__)\n        self.assertTrue(s.echo() is s)\n\n    def test_unknow_command(self):\n        s = self.callFTU(clients=1)\n        s.client1.dispatch('EHLO')\n        self.assertSent(\n            s.client1, ':irc.com 421 client1 EHLO :Unknown command')\n\n    def test_server_notice(self):\n        s = self.callFTU(clients=1)\n        s.notice(s.client1, 'test')\n        self.assertSent(s.client1, ':irc.com NOTICE client1 :test')\n\n    def test_broadcast(self):\n        s = self.callFTU(clients=1)\n        s.broadcast(s.client1, broadcast='Hi')\n\n    def test_privmsg(self):\n        s = self.callFTU(clients=3)\n        s.client1.dispatch('JOIN #irc3')\n        s.client2.dispatch('JOIN #irc3')\n\n        s.client1.dispatch('PRIVMSG client3 :Hello client3!')\n        self.assertSent(\n            s.client3, ':{mask} PRIVMSG client3 :Hello client3!', s.client1)\n\n        s.client1.dispatch('PRIVMSG #irc3 :Hello #irc3!')\n        self.assertSent(\n            s.client2, ':{mask} PRIVMSG #irc3 :Hello #irc3!', s.client1)\n        self.assertNotSent(\n            s.client1, ':{mask} PRIVMSG #irc3 :Hello #irc3!', s.client1)\n        self.assertNotSent(\n            s.client3, ':{mask} PRIVMSG #irc3 :Hello #irc3!', s.client1)\n\n        s.client1.dispatch('PRIVMSG #irc5 :Hello #irc5!')\n        self.assertSent(\n            s.client1, ':irc.com 401 client1 #irc5 :No such nick/channel')\n\n        # Test control codes integrity\n        for code in '\\x02\\x03\\x1D\\x1F\\x16\\x0F':\n            for pattern in ('X%sY', '%s'):\n                msg = pattern % (5 * code)\n                s.client1.reset()\n                s.client1.dispatch('PRIVMSG client1 :%s' % msg)\n                self.assertSent(\n                    s.client1,\n                    ':{mask} PRIVMSG client1 :%s' % msg,\n                    s.client1)\n\n    def test_motd(self):\n        s = self.callFTU(clients=1)\n        s.config['testing'] = False\n        del s.config['motd_fmt']\n        s.client1.reset()\n        s.client1.dispatch('MOTD')\n        self.assertSent(\n            s.client1, ':irc.com 375 client1 :- irc.com Message of the day -')\n\n    def test_ping(self):\n        s = self.callFTU(clients=1)\n        s.client1.dispatch('PING xx')\n        self.assertSent(s.client1, ':irc.com PONG irc.com :xx')\n\n    def test_away(self):\n        s = self.callFTU(clients=2)\n        s.client1.dispatch('AWAY :away from keyboard')\n        self.assertSent(\n            s.client1,\n            ':irc.com 306 client1 :You have been marked as being away')\n        self.assertIn('away_message', s.client1.data)\n        s.client2.dispatch('WHOIS client1')\n        self.assertSent(\n            s.client2, ':irc.com 301 client2 client1 :away from keyboard')\n\n    def test_no_away(self):\n        s = self.callFTU(clients=2)\n        s.client1.dispatch('AWAY')\n        self.assertSent(\n            s.client1,\n            ':irc.com 305 client1 :You are no longer marked as being away')\n\n    def test_die(self):\n        s = self.callFTU(clients=3, opers={'superman': 'passwd'})\n        s.client1.dispatch('OPER superman passwd')\n        s.client1.dispatch('DIE')\n"
  },
  {
    "path": "tests/test_irc3d_commands.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import testing\n\n\nclass TestCommands(testing.ServerTestCase):\n\n    def test_not_registered(self):\n        s = self.callFTU(clients=3, opers={'superman': 'passwd'})\n        del s.client1.data['nick']\n        s.client1.dispatch('OPER superman passwd')\n        self.assertSent(\n            s.client1, ':irc.com 451 None :You have not registered')\n\n    def test_help(self):\n        s = self.callFTU(clients=1)\n        p = s.get_plugin('irc3d.plugins.command.ServerCommands')\n        s.client1.dispatch('HELP')\n        self.assertSent(\n            s.client1,\n            'irc.com 704 client1 index :Help topics available to users:')\n        self.assertSent(\n            s.client1, 'irc.com 706 client1 index :End of /HELP')\n        sent = ''.join(s.client1.sent)\n        for cmd in p.keys():\n            self.assertIn(cmd, sent)\n\n    def test_help_cmd(self):\n        s = self.callFTU(clients=1)\n        s.client1.dispatch('HELP join')\n        self.assertSent(\n            s.client1, 'irc.com 704 client1 join :JOIN <channel>')\n        self.assertSent(\n            s.client1, 'irc.com 706 client1 join :End of /HELP')\n\n    def test_oper(self):\n        s = self.callFTU(clients=3, opers={'superman': 'passwd'})\n        s.client2.modes.add('w')\n        s.client1.dispatch('OPER c c')\n        self.assertSent(s.client1, ':irc.com 464 client1 :Password incorrect')\n\n        s.client1.dispatch('WALLOPS Hi!')\n        self.assertSent(\n            s.client1,\n            (':irc.com 481 client1 '\n             ':Permission Denied- You\\'re not an IRC operator'))\n\n        s.client1.dispatch('OPER superman passwd')\n        self.assertSent(\n            s.client1, ':irc.com 381 client1 :You are now an IRC operator')\n\n        s.client1.dispatch('WALLOPS Hi!')\n        self.assertSent(\n            s.client2, ':client1!uclient1@127.0.0.1 NOTICE client2 :Hi!')\n        self.assertNotSent(\n            s.client3, ':client1!uclient1@127.0.0.1 NOTICE client3 :Hi!')\n"
  },
  {
    "path": "tests/test_irc3d_userlist.py",
    "content": "\n# -*- coding: utf-8 -*-\nfrom irc3 import testing\n\n\nclass TestServerUserList(testing.ServerTestCase):\n\n    def test_ison(self):\n        s = self.callFTU(clients=2)\n        s.client1.dispatch('ISON client2 client4')\n        self.assertSent(\n            s.client1,\n            ':irc.com 303 client1 :client2'\n        )\n\n    def test_whois(self):\n        s = self.callFTU(clients=2)\n        s.client1.dispatch('WHOIS client2')\n        self.assertSent(\n            s.client1,\n            \":irc.com 311 client1 client2 uclient2 127.0.0.1 * :I'm client2\"\n        )\n\n    def test_whois_err(self):\n        s = self.callFTU(clients=1)\n        s.client1.dispatch('WHOIS client2')\n        self.assertSent(\n            s.client1, \":irc.com 401 client1 client2 :No such nick/channel\")\n\n    def test_user_modes(self):\n        s = self.callFTU(clients=1)\n\n        for mode in 'iw':\n            s.client1.dispatch('MODE client1 +' + mode)\n            self.assertIn(mode, s.client1.modes)\n            s.client1.dispatch('MODE client1 -' + mode)\n            self.assertNotIn(mode, s.client1.modes)\n\n        s.client1.dispatch('MODE client1 +s')\n        self.assertSent(s.client1, ':irc.com 501 client1 :Unknown MODE flag')\n\n    def test_userlist(self):\n        s = self.callFTU(clients=0)\n        self.assertEqual(len(s.nicks), 0)\n        s.add_clients(amount=3)\n        self.assertEqual(len(s.nicks), 3)\n        s.client1.dispatch('JOIN #irc')\n        s.client1.dispatch('JOIN #irc3')\n        self.assertEqual(len(s.channels['#irc3']), 1)\n        self.assertEqual(len(s.client1.channels), 2)\n        s.client2.dispatch('JOIN #irc3')\n        self.assertEqual(len(s.channels['#irc3']), 2)\n        self.assertSent(s.client1, ':{mask} JOIN #irc3', s.client2)\n        self.assertSent(s.client2, ':{mask} JOIN #irc3', s.client2)\n        self.assertNotSent(s.client3, ':{mask} JOIN #irc3', s.client2)\n\n        s.client1.dispatch('KICK #irc3 client2 :Lamer!')\n        self.assertEqual(len(s.channels['#irc3']), 1)\n        self.assertEqual(len(s.client1.channels), 2)\n        self.assertEqual(len(s.client2.channels), 0)\n        self.assertSent(\n            s.client1, ':{mask} KICK #irc3 client2 :Lamer!', s.client1)\n        self.assertSent(\n            s.client2, ':{mask} KICK #irc3 client2 :Lamer!', s.client1)\n        self.assertNotSent(\n            s.client3, ':{mask} KICK #irc3 client2 :Lamer!', s.client1)\n\n        s.client1.reset()\n        s.client2.reset()\n        s.client1.dispatch('KICK #irc3 client2 :Lamer!')\n        self.assertNotSent(\n            s.client1, ':{mask} KICK #irc3 client2 :Lamer!', s.client1)\n        self.assertNotSent(\n            s.client2, ':{mask} KICK #irc3 client2 :Lamer!', s.client1)\n\n        s.client2.dispatch('JOIN #irc3')\n        self.assertEqual(len(s.channels['#irc3']), 2)\n\n        s.client1.dispatch('MODE #irc3 +v client2')\n        self.assertSent(s.client1, ':{mask} MODE #irc3 +v client2', s.client1)\n        self.assertSent(s.client2, ':{mask} MODE #irc3 +v client2', s.client1)\n        self.assertNotSent(\n            s.client3, ':{mask} MODE #irc3 +v client2', s.client1)\n\n        s.client1.dispatch('NICK irc3')\n        self.assertSent(s.client1, ':client1!uclient1@127.0.0.1 NICK irc3')\n        self.assertSent(s.client2, ':client1!uclient1@127.0.0.1 NICK irc3')\n        self.assertNotSent(s.client3, ':client1!uclient1@127.0.0.1 NICK irc3')\n\n        s.client3.dispatch('JOIN #irc,#irc3')\n        s.client1.dispatch('NICK client1')\n        self.assertSent(s.client1, ':irc3!uclient1@127.0.0.1 NICK client1')\n        self.assertSent(s.client2, ':irc3!uclient1@127.0.0.1 NICK client1')\n        self.assertSent(s.client3, ':irc3!uclient1@127.0.0.1 NICK client1')\n\n        s.client2.dispatch('NICK client1')\n        self.assertSent(\n            s.client2,\n            ':irc.com 433 client2 client1 :Nickname is already in use')\n\n        s.client2.dispatch('NICK client2')\n        self.assertNotSent(\n            s.client2,\n            ':irc.com 433 client2 client2 :Nickname is already in use')\n\n        s.client1.reset()\n        s.client2.reset()\n        s.client1.dispatch('JOIN #irc3')  # JOIN when already on channel\n        self.assertNotSent(s.client1, ':{mask} JOIN #irc3', s.client1)\n        self.assertNotSent(s.client2, ':{mask} JOIN #irc3', s.client1)\n\n        s.client1.dispatch('NAMES #irc')\n        self.assertSent(s.client1,\n                        ':irc.com 353 client1 = #irc :client1 client3')\n        s.client1.dispatch('WHOIS client2')\n        self.assertSent(s.client1, ':irc.com 319 client1 :#irc3')\n\n        s.client3.dispatch('PART #irc :Bye')\n        s.client3.dispatch('PART #irc3 :Bye')\n        self.assertSent(s.client3, ':{mask} PART #irc :Bye', s.client3)\n        self.assertSent(s.client1, ':{mask} PART #irc :Bye', s.client3)\n        self.assertNotSent(s.client2, ':{mask} PART #irc :Bye', s.client3)\n        self.assertEqual(len(s.client3.channels), 0)\n        self.assertEqual(len(s.channels['#irc']), 1)\n\n        s.client1.reset()\n        s.client3.reset()\n        s.client3.dispatch('PART #irc :Bye')  # PART when not on channel\n        self.assertNotSent(s.client3, ':{mask} PART #irc :Bye', s.client3)\n        self.assertNotSent(s.client1, ':{mask} PART #irc :Bye', s.client3)\n\n        self.assertEqual(len(s.nicks), 3)\n"
  },
  {
    "path": "tests/test_logger.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nimport tempfile\nimport shutil\nimport glob\nimport os\n\n\nclass LoggerFileTestCase(BotTestCase):\n\n    config = dict(includes=[\n        'irc3.plugins.logger',\n        'irc3.plugins.userlist',\n    ])\n\n    def setUp(self):\n        super(LoggerFileTestCase, self).setUp()\n        self.logdir = tempfile.mkdtemp(prefix='irc3log')\n        self.addCleanup(shutil.rmtree, self.logdir)\n\n    def test_logger(self):\n        bot = self.callFTU(\n            **{'irc3.plugins.logger': dict(\n                handler='irc3.plugins.logger.file_handler',\n                filename=os.path.join(\n                    self.logdir,\n                    '{host}-{channel}-{date:%Y-%m-%d}.log')\n            )}\n        )\n        filenames = os.listdir(self.logdir)\n        self.assertEqual(len(filenames), 0, filenames)\n\n        bot.dispatch(':server 332 foo #foo :topîc')\n        filenames = glob.glob(os.path.join(self.logdir, '*.log'))\n        self.assertEqual(len(filenames), 1, filenames)\n\n        with open(filenames[0]) as fd:\n            self.assertIn('server has set topic to: topîc', fd.read())\n\n        bot.dispatch(':bar!user@host JOIN #foo')\n        with open(filenames[0]) as fd:\n            self.assertIn('bar joined #foo', fd.read())\n\n        bot.dispatch(':bar!user@host PRIVMSG #foo :!help')\n        with open(filenames[0]) as fd:\n            self.assertIn('<bar> !help', fd.read())\n\n        bot.dispatch(':bar!user@host QUIT')\n        with open(filenames[0]) as fd:\n            self.assertIn('bar has quit', fd.read())\n\n        bot.privmsg('#foo', 'youhou!')\n        with open(filenames[0]) as fd:\n            self.assertIn('<irc3> youhou!', fd.read())\n"
  },
  {
    "path": "tests/test_paginate.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.plugins import command\n\n\n@command.command\ndef to_page(bot, mask, *args):\n    \"\"\"test command\n        %%to_page\n    \"\"\"\n    def iterator():\n        for i in range(10):\n            yield str(i)\n    for m in bot.paginate(mask, iterator()):\n        yield m\n\n\nclass TestPager(BotTestCase):\n\n    name = 'irc3.plugins.pager'\n\n    config = dict(includes=[name, __name__])\n\n    def test_cmd(self):\n        bot = self.callFTU(nick='foo')\n        plugin = bot.get_plugin(command.Commands)\n        self.assertEqual(len(plugin), 4, plugin)\n        bot.dispatch(':bar!user@host PRIVMSG foo :!to_page')\n        self.assertSent(['PRIVMSG bar :%s' % i for i in range(4)])\n        bot.dispatch(':bar!user@host PRIVMSG foo :!more')\n        self.assertSent(['PRIVMSG bar :%s' % i for i in range(4, 10)])\n"
  },
  {
    "path": "tests/test_protocol.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import MagicMock\nimport pytest\nimport irc3\n\n\n@pytest.fixture(scope='function')\ndef irc_conn(request):\n    irc_conn = irc3.IrcConnection()\n    irc_conn.encoding = 'utf8'\n    irc_conn.factory = MagicMock()\n    irc_conn.connection_made(MagicMock())\n    return irc_conn\n\n\ndef test_buffer(irc_conn):\n    irc_conn.data_received(b'message')\n    assert irc_conn.queue.popleft() == 'message'\n\n\ndef test_no_buffer(irc_conn):\n    irc_conn.data_received(b'message\\r\\n')\n    irc_conn.factory.dispatch.assert_called_with('message')\n    assert irc_conn.queue.popleft() == ''\n\n\ndef test_with_buffer(irc_conn):\n    irc_conn.data_received(b'm1 ')\n    irc_conn.data_received(b'm2 ')\n    buf = irc_conn.queue.popleft()\n    assert buf == 'm1 m2 '\n    irc_conn.queue.append(buf)\n    irc_conn.data_received(b'm3\\r\\nm4')\n    irc_conn.factory.dispatch.assert_called_with('m1 m2 m3')\n    assert irc_conn.queue.popleft() == 'm4'\n\n\ndef test_write(irc_conn):\n    irc_conn.write('m1')\n    irc_conn.transport.write.assert_called_with(b'm1\\r\\n')\n    irc_conn.write('m2\\r\\n')\n    irc_conn.transport.write.assert_called_with(b'm2\\r\\n')\n"
  },
  {
    "path": "tests/test_quakenet.py",
    "content": "from irc3.testing import BotTestCase\nfrom irc3.plugins import quakenet\n\n\nclass TestQuakenet(BotTestCase):\n\n    config = dict(\n        includes=['irc3.plugins.quakenet'],\n        quakenet=dict(user=\"bot\", password=\"password\", hidehost=True,\n                      challenge_auth=False))\n\n    def test_challenge(self):\n        # Test vectors taken from:\n        # https://www.quakenet.org/development/challengeauth\n        user1 = (\"mooking\", \"0000000000\")\n        user2 = (\"fishking\", \"ZZZZZZZZZZ\")\n        challenge = \"12345678901234567890123456789012\"\n\n        def digest(user, algo):\n            return quakenet.challenge_auth(user[0], user[1], challenge,\n                                           str.lower, algo)\n\n        res1 = digest(user1, \"md5\")\n        self.assertEqual(res1, '2ed1a1f1d2cd5487d2e18f27213286b9')\n\n        res2 = digest(user2, \"md5\")\n        self.assertEqual(res2, '8990cb478218b6c0063daf08dd7e1a72')\n\n        res3 = digest(user1, \"sha1\")\n        self.assertEqual(res3, 'd0328d41426bd2ace183467ce0a6305445e3d497')\n\n        res4 = digest(user2, \"sha1\")\n        self.assertEqual(res4, '4de3f1c86dd0f59da44852d507e193c339c4b108')\n\n        res5 = digest(user1, \"sha256\")\n        self.assertEqual(res5, 'f6eced34321a69c270472d06c50e959c48e9fd323'\n                         'b2c5d3194f44b50a118a7ea')\n\n        res6 = digest(user2, \"sha256\")\n        self.assertEqual(res6, '504056d53b2fc4fd783dc4f086dabc59f845d201e650'\n                         'b96dfa95dacc8cac2892')\n\n    def test_simple_auth(self):\n        bot = self.callFTU()\n        bot.notify('connection_made')\n        bot.dispatch(':azubu.uk.quakenet.org 376 irc3 :End of /MOTD command.')\n        self.assertSent(['AUTH bot password', \"MODE irc3 +x\"])\n\n    def test_challenge_auth(self):\n        quakenet_config = dict(self.config[\"quakenet\"])\n        quakenet_config[\"challenge_auth\"] = True\n        bot = self.callFTU(quakenet=quakenet_config)\n        bot.notify('connection_made')\n        bot.dispatch(':azubu.uk.quakenet.org 376 irc3 :End of /MOTD command.')\n        self.assertSent(['PRIVMSG Q@CServe.quakenet.org :CHALLENGE'])\n        bot.dispatch(\":Q!TheQBot@CServe.quakenet.org NOTICE irc3 \"\n                     \":CHALLENGE 12345678901234567890123456789012 \"\n                     \"HMAC-MD5 HMAC-SHA-1 HMAC-SHA-256 LEGACY-MD5\")\n\n        self.assertSent([\"PRIVMSG Q@CServe.quakenet.org \"\n                         \":CHALLENGEAUTH bot 76abae4fbbcf56b7296c1477e7d378a\"\n                         \"2590a147cf92afa5a952b321491c51bc6 HMAC-SHA-256\"])\n"
  },
  {
    "path": "tests/test_reconn.py",
    "content": "# -*- coding: utf-8 -*-\nimport pytest\nimport irc3\nimport irc3d\nfrom irc3.compat import asyncio\n\n\n@irc3.plugin\nclass P:\n\n    connections_made = []\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    def connection_made(self, *args, **kwargs):\n        self.bot.log.info('P.connection_made')\n        self.ready.set_result(True)\n        self.connections_made.append(1)\n\n\n@pytest.mark.asyncio\nasync def test_reconn(irc3_bot_factory):\n    cfg = {'verbose': True, 'debug': True, 'port': 49137}\n    bot = irc3_bot_factory(includes=[__name__], **cfg)\n    cfg['loop'] = bot.loop\n    server = irc3d.IrcServer.from_config(cfg)\n\n    P.ready = asyncio.Future(loop=bot.loop)\n    assert len(P.connections_made) == 0\n\n    server.run(forever=False)\n    bot.run(forever=False)\n\n    await P.ready\n    P.ready = asyncio.Future(loop=bot.loop)\n\n    assert len(P.connections_made) == 1\n\n    for uid, client in server.clients.items():\n        client.transport.close()\n        print(uid, client)\n    await P.ready\n    P.ready = asyncio.Future(loop=bot.loop)\n\n    assert len(P.connections_made) == 2\n"
  },
  {
    "path": "tests/test_reload.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nimport tempfile\nimport shutil\nimport sys\nimport os\n\nplugin = '''\nfrom irc3.plugins.cron import cron\nfrom irc3.plugins.command import command\nimport irc3\n\nclass P:\n\n    requires = [\n        'irc3.plugins.cron',\n        'irc3.plugins.command',\n    ]\n\n    def __init__(self, context, old=None):\n        self.context = context\n        self.old = old\n\n    @cron('* * * * *')\n    def cron(self):\n        pass\n\n    @irc3.event(irc3.rfc.PRIVMSG)\n    def event(self, **kwargs):\n        pass\n\n    @irc3.extend\n    def extend(self, **kwargs):\n        return self.old\n\n    @command()\n    def cmd(self, *args, **kwargs):\n        \"\"\"\n        %%cmd\n        \"\"\"\n        yield str(id(self))\n\n    @classmethod\n    def reload(cls, old):\n        new = cls(old.context, old=old)\n        return new\n\n'''\n\n\nclass TestReload(BotTestCase):\n\n    def test_reload(self):\n        # add test plugin to pythonpath\n        tmp = tempfile.mkdtemp()\n        self.addCleanup(shutil.rmtree, tmp)\n        sys.path.append(tmp)\n        with open(os.path.join(tmp, 'p.py'), 'w') as fd:\n            fd.write(plugin)\n\n        bot = self.callFTU()\n        bot.include('p')\n        p = bot.get_plugin('p.P')\n        assert p.extend() is None\n        assert bot.extend() is None\n        crons = bot.get_plugin('irc3.plugins.cron.Crons')\n        assert len(crons) == 1\n        assert len(bot.registry.events['in']) == 6\n        bot.dispatch(':adm!user@host PRIVMSG #chan :!cmd')\n        self.assertSent(['PRIVMSG #chan :%s' % id(p)])\n\n        # modify test plugin\n        with open(os.path.join(tmp, 'p.py'), 'a') as fd:\n            fd.write('x = 1')\n        bot.reload()\n\n        # assume it's reloaded\n        np = bot.get_plugin('p.P')\n        assert np is not p\n        assert np.extend() is p\n        assert bot.extend() is p\n        assert crons == bot.get_plugin('irc3.plugins.cron.Crons')\n        assert len(crons) == 1\n        assert len(bot.registry.events['in']) == 6\n        bot.dispatch(':adm!user@host PRIVMSG #chan :!cmd')\n        self.assertSent(['PRIVMSG #chan :%s' % id(np)])\n"
  },
  {
    "path": "tests/test_run.py",
    "content": "# -*- coding: utf-8 -*-\nfrom docopt import DocoptExit\nfrom irc3 import testing\nimport tempfile\nimport shutil\nimport irc3d\nimport irc3\nimport os\n\n\nclass TestRun(testing.BotTestCase):\n\n    def setUp(self):\n        self.patch_asyncio()\n        self.addCleanup(setattr, irc3.IrcBot,\n                        'logging_config',\n                        irc3.config.LOGGING)\n        self.wd = tempfile.mkdtemp()\n        self.addCleanup(shutil.rmtree, self.wd)\n        self.wd = os.path.join(self.wd, 'logs')\n\n    def callFTU(self, *args):\n        return irc3.run(args)['bot']\n\n    def test_args_error(self):\n        self.assertRaises(DocoptExit, self.callFTU, '-x')\n\n    def test_logdir(self):\n        bot = self.callFTU('-dr', 'tests/test.ini', '--logdir=' + self.wd)\n        self.assertEqual(\n            bot.logging_config['handlers']['console']['formatter'], 'file')\n        self.assertTrue(self.Task.called)\n\n\nclass TestServerRun(testing.ServerTestCase):\n\n    def setUp(self):\n        self.patch_asyncio()\n        self.addCleanup(setattr, irc3d.IrcServer,\n                        'logging_config',\n                        irc3.config.LOGGING)\n        self.wd = tempfile.mkdtemp()\n        self.addCleanup(shutil.rmtree, self.wd)\n        self.wd = os.path.join(self.wd, 'logs')\n\n    def callFTU(self, *args):\n        return irc3d.run(args)\n\n    def test_args_error(self):\n        self.assertRaises(DocoptExit, self.callFTU, '-x')\n\n    def test_logdir(self):\n        bot = self.callFTU('-dr', 'tests/test.ini', '--logdir=' + self.wd)\n        self.assertEqual(\n            bot.logging_config['handlers']['console']['formatter'], 'file')\n        self.assertTrue(self.Task.called)\n"
  },
  {
    "path": "tests/test_sasl.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\n\n\nclass TestSasl(BotTestCase):\n\n    def test_sasl_plain(self):\n        bot = self.callFTU(sasl_username='foo', sasl_password='bar')\n        bot.notify('connection_ready')\n        bot.dispatch(':s CAP * LS :multi-prefix sasl')\n        self.assertSent(['CAP REQ :sasl'])\n        bot.dispatch(':s CAP foo ACK :sasl')\n        self.assertSent(['AUTHENTICATE PLAIN'])\n        bot.dispatch('AUTHENTICATE +')\n        self.assertSent(['AUTHENTICATE Zm9vAGZvbwBiYXI='])\n        bot.dispatch(':s 903 foo :SASL authentication successful')\n        self.assertSent(['CAP END'])\n\n    def test_no_sasl(self):\n        bot = self.callFTU(sasl_username='foo', sasl_password='bar')\n        bot.notify('connection_ready')\n        bot.dispatch(':s CAP * LS :multi-prefix')\n        self.assertSent(['CAP END'])\n"
  },
  {
    "path": "tests/test_search.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\n\n\nclass TestSearch(BotTestCase):\n\n    config = dict(includes=['irc3.plugins.search'])\n\n    def test_ddg(self):\n        self.patch_requests(\n            status_code=200,\n            headers={'content-type': 'application/json'},\n            json=dict(AbstractText='Yo', AbstractURL='http://'),\n        )\n        bot = self.callFTU()\n        bot.dispatch(':g!u@h PRIVMSG #chan :!ddg cuisine')\n        self.assertSent(['PRIVMSG #chan :Yo - http://'])\n\n    def test_ddg_redirect(self):\n        self.patch_requests(\n            status_code=303,\n            headers={'content-type': 'application/json',\n                     'location': 'http://google'},\n        )\n        bot = self.callFTU()\n        bot.dispatch(':g!u@h PRIVMSG #chan :!ddg cuisine')\n        self.assertSent(['PRIVMSG #chan :Redirect to: http://google'])\n"
  },
  {
    "path": "tests/test_slack.py",
    "content": "# -*- coding: utf-8 -*-\nimport pytest\nfrom irc3.plugins import slack\n\npytestmark = pytest.mark.asyncio\n\n\nasync def test_simple_matches(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.slack'])\n    plugin = bot.get_plugin(slack.Slack)\n    setattr(plugin, 'config', {'token': 'xoxp-faketoken'})\n    assert '' == await plugin.parse_text('\\n')\n    assert '' == await plugin.parse_text('\\r\\n')\n    assert '' == await plugin.parse_text('\\r')\n    assert '@channel' == await plugin.parse_text('<!channel>')\n    assert '@group' == await plugin.parse_text('<!group>')\n    assert '@everyone' == await plugin.parse_text('<!everyone>')\n    assert '<' == await plugin.parse_text('&lt')\n    assert '>' == await plugin.parse_text('&gt')\n    assert '&' == await plugin.parse_text('&amp')\n    assert 'daniel' == await plugin.parse_text('<WHATEVER|daniel>')\n\n\nasync def test_channel_matches(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.slack'])\n    plugin = bot.get_plugin(slack.Slack)\n    setattr(plugin, 'config', {'token': 'xoxp-faketoken'})\n\n    async def api_call(self, method, date=None):\n        return ({'channel': {'name': 'testchannel'}})\n\n    plugin.api_call = api_call\n    assert '#testchannel' == await plugin.parse_text('<#C12345>')\n    assert 'channel' == await plugin.parse_text('<#C12345|channel>')\n\n\nasync def test_user_matches(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.slack'])\n    plugin = bot.get_plugin(slack.Slack)\n    setattr(plugin, 'config', {'token': 'xoxp-faketoken'})\n\n    async def api_call(self, method, date=None):\n        return ({'user': {'name': 'daniel'}})\n\n    plugin.api_call = api_call\n    assert '@daniel' == await plugin.parse_text('<@U12345>')\n    assert 'user' == await plugin.parse_text('<@U12345|user>')\n\n\nasync def test_emoji_matches(irc3_bot_factory):\n    bot = irc3_bot_factory(includes=['irc3.plugins.slack'])\n    plugin = bot.get_plugin(slack.Slack)\n    setattr(plugin, 'config', {'token': 'xoxp-faketoken'})\n    assert ':-)' == await plugin.parse_text(':smiley:')\n    assert ':@' == await plugin.parse_text(':rage:')\n"
  },
  {
    "path": "tests/test_social.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.testing import patch\n\n\nclass TestSocial(BotTestCase):\n\n    config = dict(\n        includes=['irc3.plugins.social'],\n        twitter=dict(key='', secret='', token='', token_secret=''),\n    )\n\n    def test_get_conn(self):\n        bot = self.callFTU()\n        conn = bot.get_social_connection()\n        self.assertTrue(hasattr(conn, 'conn'))\n\n    def test_conns(self):\n        bot = self.callFTU()\n        plugin = bot.get_plugin('irc3.plugins.social.Social')\n        self.assertIn('twitter', plugin.conns)\n\n    @patch('twitter.api.TwitterCall.__call__', return_value=dict(id='yy'))\n    def test_tweet(self, c):\n        bot = self.callFTU()\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!tweet yé')\n        self.assertSent(['PRIVMSG bar :twitter success'])\n\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!tweet --id=twitter yo')\n        self.assertSent(['PRIVMSG bar :twitter success'])\n\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!tweet --id=tw yo')\n        self.assertSent(['PRIVMSG bar :tw is an invalid id. Use twitter'])\n\n    @patch('twitter.api.TwitterCall.__call__', return_value=dict(error='fail'))\n    def test_tweet_fail(self, c):\n        bot = self.callFTU()\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!tweet yo')\n        self.assertSent(['PRIVMSG bar :twitter fail'])\n\n    @patch('twitter.api.TwitterCall.__call__',\n           return_value=dict(id='yy', text='yo!',\n                             user=dict(screen_name='foo')))\n    def test_retweet(self, c):\n        bot = self.callFTU()\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!retweet 123')\n        self.assertSent(['PRIVMSG bar :@foo: yo!'])\n\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!retweet --id=twitter 123')\n        self.assertSent(['PRIVMSG bar :@foo: yo!'])\n\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!retweet --id=tw 123')\n        self.assertSent(['PRIVMSG bar :tw is an invalid id. Use twitter'])\n\n    @patch('twitter.api.TwitterCall.__call__', return_value='fail')\n    def test_retweet_fail(self, c):\n        bot = self.callFTU()\n        bot.dispatch(':bar!a@b PRIVMSG irc3 :!retweet 123')\n        self.assertSent(['PRIVMSG bar :twitter: fail'])\n\n    @patch('twitter.api.TwitterCall.__call__',\n           return_value=dict(statuses=['blah']))\n    def test_search(self, c):\n        bot = self.callFTU()\n        self.assertTrue(bot.search_tweets(q='foo'), ['blah'])\n\n    @patch('twitter.api.TwitterCall.__call__',\n           side_effect=KeyError())\n    def test_search_raise(self, c):\n        bot = self.callFTU()\n        self.assertEqual(bot.search_tweets(q='foo'), [])\n"
  },
  {
    "path": "tests/test_template.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\nfrom irc3.template import main\nfrom irc3 import utils\nfrom shutil import rmtree\nimport tempfile\nimport sys\nimport os\n\n\nclass Template(BotTestCase):\n\n    def setUp(self):\n        self.wd = tempfile.mkdtemp(prefix='irc3-template')\n        self.addCleanup(os.chdir, os.getcwd())\n        self.addCleanup(rmtree, self.wd)\n        self.addCleanup(sys.path.remove, self.wd)\n        sys.path.append(self.wd)\n        os.chdir(self.wd)\n\n    def test_template(self):\n        main(nick='mybot')\n        files = sorted(os.listdir(self.wd))\n        assert files == ['config.ini', 'mybot_plugin.py']\n        config = utils.parse_config('bot', 'config.ini')\n        bot = self.callFTU(**config)\n        bot.dispatch(':gawel!n@h JOIN #mybot')\n        self.assertSent(['PRIVMSG #mybot :Hi gawel!'])\n        bot.dispatch(':yournick!n@h PRIVMSG #mybot :!echo Hi!')\n        self.assertSent(['PRIVMSG #mybot :Hi!'])\n"
  },
  {
    "path": "tests/test_uptime.py",
    "content": "\n# -*- coding: utf-8 -*-\nfrom irc3.testing import BotTestCase\n\n\nclass TestUptime(BotTestCase):\n\n    def test_uptime(self):\n        bot = self.callFTU(includes=['irc3.plugins.uptime'])\n        bot.notify('connection_made')\n        bot.dispatch(':gawel!u@h PRIVMSG #chan :!uptime')\n        self.assertSent(\n            [('PRIVMSG #chan :Up since 0 days 0 hours 0 minutes. '\n              'Connected since 0 days 0 hours 0 minutes')])\n        bot.uptime.uptime -= 3600 * 54\n        bot.uptime.connection_uptime -= 3600 * 13\n\n        bot.dispatch(':gawel!u@h PRIVMSG foo :!uptime')\n        self.assertSent(\n            [('PRIVMSG foo :Up since 2 days 6 hours 0 minutes. '\n              'Connected since 0 days 13 hours 0 minutes')])\n"
  },
  {
    "path": "tests/test_userlist.py",
    "content": "# -*- coding: utf-8 -*-\nfrom irc3 import testing\n\n\nclass TestUserList(testing.BotTestCase):\n\n    def test_userlist(self):\n        bot = self.callFTU(nick='foo')\n        bot.include('irc3.plugins.core',\n                    'irc3.plugins.userlist')\n        plugin = bot.get_plugin('irc3.plugins.userlist.Userlist')\n\n        bot.dispatch(':bar!u@b JOIN #foo')\n        self.assertIn('bar', plugin.channels['#foo'])\n        self.assertNotIn('bar', plugin.channels['#bar'])\n        self.assertIn('bar', plugin.nicks)\n\n        bot.dispatch(':bar!u@b JOIN #bar')\n        self.assertIn('bar', plugin.channels['#bar'])\n        self.assertIn('bar', plugin.nicks)\n\n        bot.dispatch(':gawel!u@h MODE #foo +v-v+v bar bar bar')\n        self.assertIn('bar', plugin.channels['#foo'].modes['+'])\n\n        bot.dispatch(':foo!u@b KICK #foo bar :bastard!')\n        self.assertNotIn('bar', plugin.channels['#foo'])\n        self.assertNotIn('bar', plugin.channels['#foo'].modes['+'])\n\n        bot.dispatch(':gawel!u@h MODE #foo +c')  # coverage\n        bot.dispatch(':gawel!u@h MODE gawel')  # coverage\n\n        bot.dispatch(':gawel!u@h MODE #bar +v bar')\n        self.assertIn('bar', plugin.channels['#bar'].modes['+'])\n\n        bot.dispatch(':bar!u@b NICK babar')\n        self.assertIn('babar', plugin.nicks)\n        self.assertIn('babar', plugin.channels['#bar'])\n        self.assertIn('babar', plugin.channels['#bar'].modes['+'])\n        self.assertNotIn('bar', plugin.channels['#bar'].modes['+'])\n\n        bot.dispatch(':babar!u@b QUIT :lksdlds')\n        self.assertNotIn('babar', plugin.nicks)\n        self.assertNotIn('babar', plugin.channels['#bar'])\n\n        bot.dispatch(':serv 352 irc3 #chan ~user host serv bar H@ :Blah')\n        self.assertIn('bar', plugin.channels['#chan'])\n        self.assertIn('bar', plugin.nicks)\n\n        bot.dispatch(':serv 353 irc3 = #chan2 :bar @gawel')\n        self.assertIn('bar', plugin.channels['#chan2'])\n        self.assertIn('gawel', plugin.channels['#chan2'])\n        self.assertIn('gawel', plugin.channels['#chan2'].modes['@'])\n        self.assertIn('gawel', plugin.nicks)\n\n        bot.notify('connection_lost')\n        self.assertEqual(len(plugin.nicks), 0)\n        self.assertEqual(len(plugin.channels), 0)\n\n        bot.dispatch(':serv 353 irc3 = #chan2 :bar @gawel')\n        self.assertEqual(len(plugin.nicks), 2)\n        self.assertEqual(len(plugin.channels), 1)\n\n        bot.dispatch(':gawel!u@h MODE #chan2 +v bar')\n        self.assertIn('bar', plugin.channels['#chan2'].modes['+'])\n\n        bot.dispatch(':bar!u@h PART #chan2')\n        self.assertEqual(len(plugin.nicks), 1)\n        self.assertNotIn('bar', plugin.channels['#chan2'].modes['+'])\n\n        bot.dispatch(':foo!u@h PART #chan2')\n        self.assertNotIn('#chan2', plugin.channels)\n\n        bot.dispatch(':foo!u@h QUIT')\n        self.assertEqual(len(plugin.nicks), 0)\n"
  },
  {
    "path": "tests/test_utils.py",
    "content": "# -*- coding: utf-8 -*-\nfrom unittest import TestCase\nfrom irc3.utils import IrcString\nfrom irc3.utils import maybedotted\nfrom irc3.utils import split_message\nfrom irc3.utils import parse_config_env\nfrom irc3.utils import slugify\nfrom irc3.testing import ini2config\nimport irc3.plugins\n\n\ndef test_hash():\n    config = ini2config('''\n[bot]\nautojoins =\n    ${hash}irc3\n    ${hash}${hash}irc3\n    ${#}irc3\n    ${#}${#}irc3\n    ${##}irc3\n''')\n    assert config['autojoins'] == [\n        '#irc3',\n        '##irc3',\n        '#irc3',\n        '##irc3',\n        '##irc3',\n    ]\n\n\ndef test_config_env():\n    config = ini2config('''\n[bot]\nnickname = bot\n''', env={'IRC3_BOT_AUTOJOINS': '#irc3 ##irc3'})\n    assert config['autojoins'] == ['#irc3', '##irc3']\n\n\nclass TestUtils(TestCase):\n\n    def test_ircstring(self):\n        s = IrcString('nick')\n        self.assertTrue(s.is_nick)\n        self.assertEqual(s.nick, 'nick')\n        self.assertEqual(s.host, None)\n\n        s = IrcString('nick!user@host')\n        self.assertTrue(s.is_user)\n        self.assertTrue(s.is_nick)\n        self.assertEqual(s.nick, 'nick')\n        self.assertEqual(s.host, 'user@host')\n        self.assertEqual(s.username, 'user')\n        self.assertEqual(s.hostname, 'host')\n\n        s = IrcString('#chan')\n        self.assertTrue(s.is_channel)\n        s = IrcString('&chan')\n        self.assertTrue(s.is_channel)\n\n        s = IrcString('*')\n        self.assertTrue(s.is_server)\n\n    def test_maybedotted(self):\n        self.assertTrue(\n            maybedotted('irc3.plugins') is irc3.plugins)\n        self.assertTrue(\n            maybedotted('irc3.utils.IrcString') is IrcString)\n        self.assertTrue(\n            maybedotted(IrcString) is IrcString)\n        self.assertRaises(LookupError, maybedotted, 'irc3.none.none')\n        self.assertRaises(LookupError, maybedotted, 'irc3.none')\n        self.assertRaises(LookupError, maybedotted, None)\n        self.assertRaises(LookupError, maybedotted, '')\n\n    def test_slugify(self):\n        assert slugify('a test file .rst') == 'a-test-file.rst'\n        assert slugify('a test/../ file .rst') == 'a-test.file.rst'\n        assert slugify(r'C:\\\\a test\\../ file .rst') == 'ca-test.file.rst'\n\n\nclass TestConfig(TestCase):\n\n    def test_config_env(self):\n        value = parse_config_env({\n            'IRC3_BOT_NICKNAME': 'env_nickname',\n            'IRC3_BOT_PASSWORD': 'env_password',\n\n            'IRC3__BOT__SASL_PASSWORD': 'hunter2',\n            'IRC3__IRC3__PLUGINS__FOO__BAR_BAZ': 'qux',\n        })\n        self.assertEqual(value, {\n            'bot': {\n                'nickname': 'env_nickname',\n                'password': 'env_password',\n\n                'sasl_password': 'hunter2',\n            },\n            'irc3.plugins.foo': {\n                'bar_baz': 'qux',\n            },\n        })\n\n\nclass TestSplit(TestCase):\n\n    def test_split_message(self):\n        messages = [\n            'allo',\n            'allo\\t',\n            '   allo',\n            'alloallo',\n            'Qwerty uiop asdfghjkl zxcvbnm',\n            '\\x1d \\x1f',\n            # \"Hello world!\" in Belarusian, Greek, and Japanese.\n            'Прывітанне свет!',\n            'Γειά σου Κόσμε!',\n            'こんにちは 世界',\n        ]\n        expected = [\n            ['allo'],\n            ['allo\\t'],\n            ['   allo'],\n            ['alloallo'],\n            ['Qwerty', 'uiop', 'asdfghjkl', 'zxcvbnm'],\n            ['\\x1d \\x1f'],\n            ['Прыві', 'танне', 'свет!'],\n            ['Γειά', 'σου', 'Κόσμε', '!'],\n            ['こんに', 'ちは', '世界'],\n        ]\n\n        split = [\n            list(split_message(msg, 10, 'utf-8'))\n            for msg in messages\n        ]\n        self.assertEqual(split, expected)\n\n    def test_split_message_long(self):\n        message = (\n            'Harum qui commodi voluptas veritatis provident voluptatem '\n            'accusamus. Ut odio porro voluptas. Totam perspiciatis dolorem '\n            'maxime beatae sit. Consectetur ducimus qui ut quae. Dolor optio '\n            'minima cupiditate ut. Laborum officia ut voluptas est porro '\n            'nulla qui.'\n        )\n        expected = {\n            50: [\n                # 1\n                'Harum qui commodi voluptas veritatis provident',\n                # 2\n                'voluptatem accusamus. Ut odio porro voluptas.',\n                # 3\n                'Totam perspiciatis dolorem maxime beatae sit.',\n                # 4\n                'Consectetur ducimus qui ut quae. Dolor optio',\n                # 5\n                'minima cupiditate ut. Laborum officia ut voluptas',\n                # 6\n                'est porro nulla qui.',\n            ],\n            100: [\n                # 1\n                'Harum qui commodi voluptas veritatis provident voluptatem '\n                'accusamus. Ut odio porro voluptas. Totam',\n                # 2\n                'perspiciatis dolorem maxime beatae sit. Consectetur ducimus '\n                'qui ut quae. Dolor optio minima',\n                # 3\n                'cupiditate ut. Laborum officia ut voluptas est porro nulla '\n                'qui.',\n            ],\n            150: [\n                # 1\n                'Harum qui commodi voluptas veritatis provident voluptatem '\n                'accusamus. Ut odio porro voluptas. Totam perspiciatis '\n                'dolorem maxime beatae sit.',\n                # 2\n                'Consectetur ducimus qui ut quae. Dolor optio minima '\n                'cupiditate ut. Laborum officia ut voluptas est porro nulla '\n                'qui.',\n            ],\n            200: [\n                # 1\n                'Harum qui commodi voluptas veritatis provident voluptatem '\n                'accusamus. Ut odio porro voluptas. Totam perspiciatis '\n                'dolorem maxime beatae sit. Consectetur ducimus qui ut quae. '\n                'Dolor optio minima',\n                # 2\n                'cupiditate ut. Laborum officia ut voluptas est porro nulla '\n                'qui.',\n            ],\n            300: [message],\n        }\n\n        for max_bytes in expected.keys():\n            split = list(\n                split_message(message, max_bytes, 'utf-8')\n            )\n            self.assertEqual(split, expected[max_bytes])\n\n    def test_split_message_no_whitespace(self):\n        message_len = 100\n        message = 'A' * message_len\n\n        def split_lens(max_bytes):\n            split = list(\n                split_message(message, max_bytes, 'utf-8')\n            )\n            return len(''.join(split)), len(split)\n\n        result = [\n            (max_bytes, *split_lens(max_bytes))\n            for max_bytes in [*range(1, 10), *range(10, 110, 10)]\n        ]\n        expected = [\n            (1, 100, 100),\n            (2, 100, 50),\n            (3, 100, 34),\n            (4, 100, 25),\n            (5, 100, 20),\n            (6, 100, 17),\n            (7, 100, 15),\n            (8, 100, 13),\n            (9, 100, 12),\n            (10, 100, 10),\n            (20, 100, 5),\n            (30, 100, 4),\n            (40, 100, 3),\n            (50, 100, 2),\n            (60, 100, 2),\n            (70, 100, 2),\n            (80, 100, 2),\n            (90, 100, 2),\n            (100, 100, 1),\n        ]\n        self.assertEqual(result, expected)\n\n    def test_split_message_byte_max_bytes_too_small(self):\n        message = 'こんにちは'\n\n        for max_bytes in (1, 2):\n            with self.assertRaisesRegex(ValueError, f'{max_bytes=}'):\n                list(split_message(message, max_bytes, 'utf-8'))\n"
  },
  {
    "path": "tests/test_web.py",
    "content": "# -*- coding: utf-8 -*-\nimport pytest\nfrom irc3.plugins import web\nfrom aiohttp.test_utils import make_mocked_request\n\n\nclass Payload:\n\n    def __init__(self, data):\n        self.data = data\n\n    async def readany(self):\n        data = self.data\n        self.data = b''\n        return data\n\n\n@pytest.mark.asyncio\nasync def test_web_handler(\n    irc3_bot_factory, aiohttp_raw_server, aiohttp_client\n):\n    bot = irc3_bot_factory(includes=['irc3.plugins.web'])\n    plugin = bot.get_plugin(web.Web)\n    plugin.server_ready()\n\n    req = make_mocked_request('GET', '/')\n    resp = await plugin.handler(req)\n    assert resp.status == 200\n\n\n@pytest.mark.asyncio\nasync def test_web_handler_post(\n    irc3_bot_factory, aiohttp_raw_server, aiohttp_client\n):\n    bot = irc3_bot_factory(includes=['irc3.plugins.web'])\n    plugin = bot.get_plugin(web.Web)\n\n    plugin.channels['channel'] = '#channel'\n    handler = plugin.handler\n\n    req = make_mocked_request('POST', '/channels/channel',\n                              payload=Payload(b'hi'))\n    resp = await handler(req)\n    assert resp.status == 201\n\n\n@pytest.mark.asyncio\nasync def test_web_handler_post_auth(\n    irc3_bot_factory, aiohttp_raw_server, aiohttp_client\n):\n    bot = irc3_bot_factory(**{\n        'includes': ['irc3.plugins.web'],\n        'irc3.plugins.web': {'api_key': 'toomanysecrets'},\n    })\n    plugin = bot.get_plugin(web.Web)\n\n    plugin.channels['channel'] = '#channel'\n    handler = plugin.handler\n\n    req = make_mocked_request('POST', '/channels/channel',\n                              payload=Payload(b'hi'))\n    resp = await handler(req)\n    assert resp.status == 403\n\n    req = make_mocked_request('POST', '/channels/channel',\n                              headers={'X-Api-Key': 'toomanysecrets'},\n                              payload=Payload(b'hi'))\n    resp = await handler(req)\n    assert resp.status == 201\n\n\n@pytest.mark.asyncio\nasync def test_web_handler_404(\n    irc3_bot_factory, aiohttp_raw_server, aiohttp_client\n):\n    bot = irc3_bot_factory(includes=['irc3.plugins.web'])\n    plugin = bot.get_plugin(web.Web)\n\n    plugin.channels['channel'] = '#channel'\n    handler = plugin.handler\n\n    req = make_mocked_request('POST', '/channels/notfound')\n    resp = await handler(req)\n    assert resp.status == 404\n"
  },
  {
    "path": "tox.ini",
    "content": "[tox]\nenvlist = py311,py312,py313,flake8,docs\nisolated_build=true\n\n[testenv]\nskipsdist=true\nskip_install=true\nallowlist_externals =\n    rm\ncommands =\n    rm -f .coverage\n    coverage run {envbindir}/py.test -xv tests\n    coverage report -m\ndeps =\n    -e .[test,web]\n    coverage\n    pytest\n\n[testenv:flake8]\nskipsdist=true\nskip_install=true\nbasepython = python3.12\ncommands =\n    flake8\ndeps =\n    flake8\n\n[testenv:docs]\nskip_install=false\nskipsdist=true\nbasepython = python3.12\nchangedir = docs\ndeps =\n    sphinx\n    Pygments\ncommands =\n    rm -Rf {envtmpdir}/doctrees {envtmpdir}/html\n    sphinx-build -b html -d {envtmpdir}/doctrees . {envtmpdir}/html\n\n[testenv:build]\nskip_install=false\nskipsdist=true\nbasepython = python3.12\ncommands =\n    python -m irc3._parse_rfc\n    python -m irc3._gen_doc\ndeps =\n\n[flake8]\nexclude =\n    ./irc3/compat.py\n    ./.tox/*\n    ./src/*\n    ./docs*\n    ./.eggs/\n    ./.venv/\nignore = W605\n"
  }
]