Not Logged In

Gnotty 0.2.6

Gnotty ties the knot between the web and IRC. It is a web client and message archive for IRC.

======Gnotty======

Created by `Stephen McDonald <http: twitter.com="" stephen_mcd="">`_

Gnotty ties the knot between the web and IRC. It is designed to assistopen source projects that host an IRC channel for collaboration ontheir project.Gnotty is `BSD licensed <http: www.linfo.org="" bsdlicense.html="">`_.

Gnotty is comprised of several parts. Primarily Gnotty provides amodern web client and server for communicating with an IRC channel viaa web browser. The web server uses `gevent <http: www.gevent.org="">`_and `WebSockets <http: en.wikipedia.org="" wiki="" websockets="">`_, whichprovides the communication layer between the IRC channel and the webbrowser. Twitter's `Bootstrap <http: twitter.github.com="" bootstrap=""/>`_is used to style the web interface, providing a fully responsivelayout, suitable for use with mobile devices. Customisable templatesare also provided for skinning the web interface.

Check out the `Gnotty live demo <http: gnotty.jupo.org="">`_ to see theweb interface in action.

Secondly, Gnotty provides the ability to run a highly customisableIRC bot. Different classes of bots can be configured on startup, andbots can perform different services such as message logging andinteracting with users in the IRC channel. Bots also contain webhooks,which allows bots to receive and act on input over HTTP from externalservices.

Gnotty also provides an optional Django application that archives IRCmessages, for browsing and searching via a web interface. By defaultthe IRC bot uses Python's logging module to provide configurablelogging handlers for IRC messages. When the Django application isused, a logging handler is added that logs all IRC messages to theDjango project's database. The Django application then provides allthe necessary views and templates for messages to be searched bykeyword, or browsed by date using a calendar interface.

Note that the Django application is entirely optional. Gnotty canbe run without using Django at all, as a stand-alone gevent webserver that provides the web interface to an IRC channel, withconfigurable IRC bots.

Installation============

The easiest way to install Gnotty is directly from PyPi using`pip <http: www.pip-installer.org="">`_ by running the command below::

Gnotty is configured via a handful of settings. When integratedwith Django, these settings can be defined in your Django project's``settings.py`` module. When Gnotty is run as a stand-aloneclient, these same settings can be defined via the command-line, orin a separate Python configuration module. See the "Stand-Alone WebClient" section below for details.

To be clear: the IRC host and port are for specifying the IRC serverto connect to. The HTTP host and port are what will be used to hostthe gevent/WebSocket server.

Django Integration==================

With the above settings defined in your Django project's``settings.py`` module, a few more steps are required. As with mostDjango apps, add ``gnotty`` to your ``INSTALLED_APPS`` setting, and``gnotty.urls`` to your project's ``urls.py`` module::

As you can see we've mounted all of the urls Gnotty provides underthe prefix ``/irc/`` - feel free to use whatever suits you here. Withthis prefix, the URL on our Django development server`http://127.0.0.1:8000/irc/ <http: 127.0.0.1:8000="" irc=""/>`_ will loadthe chat interface to the IRC channel, along with a search form forsearching the message archive, and links to browsing the archive bydate.

The final step when integrated with Django is to run the Gnottyserver itself. The Gnotty server is backed by gevent, and will hostthe WebSocket bridge to the IRC channel. It will also start up theIRC bot that will connect to the channel, and log all of the messagesin the channel to the database archive.

Running the Gnotty server when integrated with Django is simply amatter of running the ``gnottify`` Django management command::

$ python manage.py gnottify [options]

Note that each of the configuration options can also be specified asarguments to the ``gnottify`` management command. The names andformats used in this context are the same as those described next forthe stand-alone web client. Any options provided as command-linearguments take precendence over those defined in your Django project's``settings.py`` module.

The ``gnottify_runserver`` command is also included, which will runboth the Gnotty server and Django's ``runserver`` command at once,which is useful during development.

Stand-Alone Web Client======================

As mentioned, Gnotty can also be run as a stand-alone web clientwithout using Django at all. In this mode, only the web interface tothe IRC channel is provided, along with whichever IRC bot class isconfigured. Message logging can be configured using standard handlersfor the ``logging`` module in Python's standard library.

Once installed, the command ``gnottify`` should be available on yoursystem, and all of the options described earlier can be provided asarguments to it::

Note the final argument in the list, ``--conf-file``. This can be usedto provide the path to a Python config module, that contains each ofthe settings described earlier. Any options provided via command-linearguments will take precedence over any options defined in the Pythonconfiguration module.

Daemon Mode===========

Gnotty can be configured to run as a background process when the``GNOTTY_DAEMON`` setting is set to ``True`` (the ``--daemon`` argwhen running stand-alone). When in daemon mode, Gnotty will write itsprocess ID to the absolute file path specfified by the``GNOTTY_PID_FILE`` setting (the ``--pid-file`` arg when runningstand-alone). If the PID file path is not configured, Gnotty will usea file name based on the HTTP host and port, in your operatingsystem's location for temporary files.

When run in daemon mode, Gnotty will check for an existing PID fileand if found, will attempt to shut down a previously started serverwith the same PID file.

IRC Bots========

When running, Gnotty hosts an IRC bot that will connect to theconfigured IRC channel. The ``gnotty.bots.BaseBot`` bot is run bydefault, which implements message logging and support for commandsissued within the IRC channel, and webhooks, which allow the IRCbot to receive data over HTTP.

You can implement your own IRC bot simply by subclassing``gnotty.bots.BaseBot`` and defining the Python dotted path to it onstartup, via the ``GNOTTY_BOT_CLASS`` setting (the ``--bot-class`` argwhen running stand-alone).

The ``gnotty.bots.BaseBot`` class is derived from the third-party``irclib`` package's ``irc.client.SimpleIRCClient`` class (andtranslated into a Python new-style class for sanity). The IRCbot will have all of the same methods and events available as the``SimpleIRCClient`` class.

These are the built-in IRC bot classes provided by the``gnotty.bots`` package:

* ``gnotty.bots.BaseBot`` - The default bot class that implements logging and handling for commands and webhooks. Your custom bot should subclass this. * ``gnotty.bots.ChatBot`` - A bot that demonstrates interacting with the IRC channel by greeting and responding to other users. Requires the ``nltk`` package to be installed. * ``gnotty.bots.commits.CommitMixin`` - A base bot mixin for receiving commit information for version control systems via bot webhooks, and relaying the commits to the IRC channel. Used as the base for the ``GitHubBot`` and ``BitBucketBot`` bots. * ``gnotty.bots.GitHubBot`` - ``CommitMixin`` subclass for `GitHub <http: github.com="">`_ * ``gnotty.bots.BitBucketBot`` - ``CommitMixin`` subclass for `Bitbucket <http: bitbucket.org="">`_ * ``gnotty.bots.CommandBot`` - A bot that implements a handful of basic commands that can be issued by users in the channel. * ``gnotty.bots.RSSBot`` - A bot that watches RSS feeds and posts new items from them to the IRC channel. * ``gnotty.bots.Voltron`` - All of the available bots, merged into one `super bot <http: www.youtube.com="" watch?v="tZZv5Z2Iz_s">`_.

Take a look at the source code for the ``gnotty.bots`` package. You'llsee that the different features from all of the available bots areimplemented as mixins, which you can mix and match together whenbuilding your own bot classes.

Bot Events==========

Gnotty's IRC bots make use of an event handling system. Event handlersare implemented as methods on any of the classes used to build a bot.Each event handler gets wrapped with the decorator``gnotty.bots.events.on``, which takes a single positional argument forthe event name and marks the method as being a handler for that event.The decorator may also accept optional keyword arguments depending onthe type of event. Several types of events are available:

* IRC channel events, as implemented by the ``irclib`` package's ``irc.client.SimpleIRCClient`` class. * IRC commands, which are custom commands that can be triggered by users in the IRC channel. Each of these take a ``command`` keyword argument, which defines the command name. * Timer events, which are handlers that are periodically run at a defined time interval. Each of these take a ``seconds`` keyword argument, which defines the time interval. * Webhooks, which are handlers that accept data over HTTP. Each of take a ``urlpattern`` keyword argument which defines a regular expression to match against the webhook's URL, similar to Django's ``urlpatterns``.

@events.on("command", command="!time") def my_time_command(self, connection, event): """Write the time to the channel when someone types !time""" from datetime import datetime return "The date and time is %s" % datetime.now()

As described above, each of the IRC channel events implemented by the``irclib`` package's ``irc.client.SimpleIRCClient`` class are availableas event handlers for an IRC bot. Consult the ``irclib`` docs or sourcecode for details about each of the IRC channel events that areimplemented, as documenting all of these is beyond the scope of thisdocument. Here are some of the common events to get you started:

- ``events.on("welcome")``: Bot has connected to the server but not yet joined the channel. - ``events.on("namreply")``: Bot receives the initial list of nicknames in the channel once joined. - ``events.on("join")``: Someone new joined the channel. - ``events.on("quit")``: Someone left the channel. - ``events.on("pubmsg")``: A message was sent to the channel.

Each of the channel events receive a ``connection`` and ``event``argument, which are objects for the connection to the IRC server, andinformation about the event that occurred.

Command Events==============

Event handlers for simple commands can be implemented using the``command`` event name for the ``gnotty.bots.events.on`` decorator.The decorator then takes a ``command`` keyword argument, which is thecommand name itself. Command events are then triggered by any publicmessages in the channel that contain the command name as the first wordin the message. Each subsequent word in the message after the commandis then passed as a separate argument to the event handler method forthe command. In each command event handler method, the bot can thenperform some task, and return a message back to the channel.

Timer Events============

These event handlers are defined using the ``timer`` event name for the``gnotty.bots.events.on`` decorator, and simply run repeatedly at agiven interval. A ``seconds`` keyword argument to the decorator definesthe interval in seconds as an integer. Note that the ``seconds``keyword argument is used to ``sleep`` after each time the event handleris run, in order to implement the interval, so an interval of 30seconds won't necessarily run precisely twice per minute, since theevent handler itself will take time to execute, particularly if itaccesses external resources over a network.

Webhook Events==============

IRC bots run by Gnotty contain the ability to receive data over HTTPvia webhooks. Webhooks are methods defined on the bot class with the``webhook`` event handler name specified for the``gnotty.bots.events.on`` decorator. The decorator also requires a``urlpattern`` keyword argument, which is a regular expression formatching the webhook URL.

The gevent web server will intercept any URLs prefixedwith the path ``/webhook/``, and pass the request onto the bot whichwill match the URL to any of the URL patterns defined by webhook eventhandlers on the running bot class. A webhook event handler receivesthe following arguments:

* ``environ`` - The raw environment dict supplied by the gevent web server that contains all information about the HTTP request. * ``url`` - The actual URL accessed. * ``params`` - A dictionary containing all of the POST and GET data.

Note that the ``url`` and ``params`` arguments are simply provided forextra convenience, as their values (and all other environmentinformation) are already available via the ``environ`` argument.

Message Logging===============

By default, each IRC message in the channel is logged by the IRC botrun by Gnotty. Logging occurs using `Python's logging module<http: docs.python.org="" library="" logging.html="">`_, to the logger named``irc.message``.

Each log record contains the following attributes, where ``record`` isthe log record instance:

* ``record.server`` - The IRC server the message occurred on. * ``record.channel`` - The IRC channel the message occurred on. * ``record.nickname`` - The nickname of the user who sent the message. * ``record.msg`` - The actual message string itself. * ``record.join_or_leave`` - ``True`` if the record was for a user joining or leaving the channel, otherwise ``False``.

Here's an example of adding an extra logging handler for IRC messages::

The web client that Gnotty provides includes all the necessaryJavaScript files for communicating with the WebSocket server, such asDouglas Crockford's ``json2.js``, and the ``socket.io.js`` libraryitself. Also provided is the file ``gnotty.js`` which implements acouple of public functions used by the web interface. The first is the``gnotty`` JavaScript function, which deals directly with the HTMLstructure of the chat template::

The second interface is the ``IRCClient`` function. This is ofparticular interest if you'd like to create your own chat interface,as it deals exclusively with communication between the web browser andthe WebSocket server. Here's an example client that simply writesevents out to the console::

// When the client first joins the IRC channel, // send a message to the channel to say hello. client.onJoin = function() { console.log('joined the channel'); client.message('Hello, is it me you\'re looking for?'); };

As you may have guessed, the server-side settings configured forGnotty are passed directly into the ``gnotty`` JavaScript function,which then creates its own ``IRCClient`` instance.

You'll also see the data sent to the ``onMessage`` and ``onNickname``events contain color values that the interface can use for colorizingnicknames. These are calculated on the server, so that both the chatinterface and message archive produce consistent colors every timea particular nickname is displayed.

Hosting Private Chat Rooms==========================

Creating a private login-protected chat room for your team membersto collaborate on is a breeze using Gnotty. By setting the``GNOTTY_LOGIN_REQUIRED`` setting to ``True``, Gnotty will requireeach user to have a Django user account which they can authenticatewith. The following steps should get you started:

* Create a Django project with Gnotty installed, using the steps described above under `Django Integration`. Take a look at the ``example_project`` directory within Gnotty, which contains a working Django project with Gnotty configured. * Install an IRC server such as `ngIRCd <http: ngircd.barton.de=""/>`_. ngIRCd can be installed on both Linux or OSX with a single command (this works great for local development on OSX). Be sure to configure ngIRCd to only allow local connections, so that only Gnotty can connect to it.

With the above setup, all that is then needed are the followingGnotty settings configured in your Django project's ``settings.py``module::