API Documentation

helga.comm.irc

Twisted protocol and communication implementations for IRC

class helga.comm.irc.Client(factory=None)

An implementation of twisted.words.protocols.irc.IRCClient with some overrides derived from helga settings (see Configuring Helga). Some methods are overridden to provide additional functionality.

action(user, channel, message)

Handler for an IRC message. This method handles logging channel messages (if it occurs on a public channel) as well as allowing the plugin manager to send the message to all registered plugins. Should the plugin manager yield a response, it will be sent back over IRC.

Parameters:
  • user – IRC user string of the form {nick}!~{user}@{host}
  • channel – the channel from which the message came
  • message – the message contents
alterCollidedNick(nickname)

Called when the bot has a nickname collision. This will generate a new nick containing the perferred nick and the current timestamp.

Parameters:nickname – the nickname that was already taken
connectionLost(reason)

Called when the connection is shut down.

Clear any circular references here, and any external references to this Protocol. The connection has been closed.

@type reason: L{twisted.python.failure.Failure}

connectionMade()

Called when a connection is made.

This may be considered the initializer of the protocol, because it is called when the connection is completed. For clients, this is called once the connection to the server has been established; for servers, this is called after an accept() call stops blocking and a socket has been received. If you need to send any greeting or initial message, do it here.

encoding = 'UTF-8'

The assumed encoding of IRC messages

erroneousNickFallback = None

A backup nick should the preferred nickname be taken. This defaults to a string in the form of the preferred nick plus the timestamp when the process was started (i.e. helga_12345)

get_channel_logger(channel)

Gets a channel logger, keeping track of previously requested ones. (see Channel Logging)

Parameters:channel – A channel name
Returns:a python logger suitable for channel logging
irc_unknown(prefix, command, params)

Handler for any unknown IRC commands. Currently handles /INVITE commands

Parameters:
  • prefix – any command prefix, such as the IRC user
  • command – the IRC command received
  • params – list of parameters for the given command
is_public_channel(channel)

Checks if a given channel is public or not. A channel is public if it starts with ‘#’ and is not the bot’s nickname (which occurs when a private message is received)

Parameters:channel – the channel name to check
join(channel, key=None)

Join a channel, optionally with a passphrase required to join.

Parameters:
  • channel – the name of the channel to join
  • key – an optional passphrase used to join the given channel
joined(channel)

Called when the client successfully joins a new channel. Adds the channel to the known channel list and sends the join signal (see Signals/Notifications of Helga Events)

Parameters:channel – the channel that has been joined
kickedFrom(channel, kicker, message)

Called when I am kicked from a channel.

leave(channel, reason=None)

Leave a channel, optionally with a reason for leaving

Parameters:
  • channel – the name of the channel to leave
  • reason – an optional reason for leaving
left(channel)

Called when the client successfully leaves a channel. Removes the channel from the known channel list and sends the left signal (see Signals/Notifications of Helga Events)

Parameters:channel – the channel that has been left
lineRate = None

An integer, in seconds, if IRC messages should be sent at a limit of once per this many seconds. None implies no limit. (setting RATE_LIMIT)

log_channel_message(channel, nick, message)

Logs one or more messages by a user on a channel using a channel logger. If channel logging is not enabled, nothing happens. (see Channel Logging)

Parameters:
  • channel – A channel name
  • nick – The nick of the user sending an IRC message
  • message – The IRC message
me(channel, message)

Equivalent to: /me message

Parameters:
  • channel – The IRC channel to send the message to. A channel not prefixed by a ‘#’ will be sent as a private message to a user with that nick.
  • message – The message to send
msg(channel, message)

Send a message over IRC to the specified channel

Parameters:
  • channel – The IRC channel to send the message to. A channel not prefixed by a ‘#’ will be sent as a private message to a user with that nick.
  • message – The message to send
nickname = None

The preferred IRC nick of the bot instance (setting NICK)

on_invite(inviter, invitee, channel)

Handler for /INVITE commands. If the invitee is the bot, it will join the requested channel.

Parameters:
  • inviter – IRC user string of the form {nick}!~{user}@{host}
  • invitee – the nick of the user receiving the invite
  • channel – the channel to which invitee has been invited
parse_nick(full_nick)

Parses a nick from a full IRC user string. For example from me!~myuser@localhost would return me.

Parameters:full_nick – the full IRC user string of the form {nick}!~{user}@{host}
Returns:The nick portion of the IRC user string
password = None

A password should the IRC server require authentication (setting SERVER)

privmsg(user, channel, message)

Handler for an IRC message. This method handles logging channel messages (if it occurs on a public channel) as well as allowing the plugin manager to send the message to all registered plugins. Should the plugin manager yield a response, it will be sent back over IRC.

Parameters:
  • user – IRC user string of the form {nick}!~{user}@{host}
  • channel – the channel from which the message came
  • message – the message contents
signedOn()

Called when the client has successfully signed on to IRC. Establishes automatically joining channels. Sends the signon signal (see Signals/Notifications of Helga Events)

sourceURL = 'http://github.com/shaunduncan/helga'

The URL where the source of the bot is found

userJoined(user, channel)

Called when a user joins a channel in which the bot resides. Responsible for sending the user_joined signal (see Signals/Notifications of Helga Events)

Parameters:
  • user – IRC user string of the form {nick}!~{user}@{host}
  • channel – the channel in which the event occurred
userLeft(user, channel)

Called when a user leaves a channel in which the bot resides. Responsible for sending the user_left signal (see Signals/Notifications of Helga Events)

Parameters:
  • user – IRC user string of the form {nick}!~{user}@{host}
  • channel – the channel in which the event occurred
userRenamed(oldname, newname)
Parameters:
  • oldname – the nick of the user before the rename
  • newname – the nick of the user after the rename
username = None

A username should the IRC server require authentication (setting SERVER)

class helga.comm.irc.Factory

The client factory for twisted. Ensures that a client is properly created and handles auto reconnect if helga is configured for it (see settings AUTO_RECONNECT and AUTO_RECONNECT_DELAY)

buildProtocol(address)

Build the helga protocol for twisted, or in other words, create the client object and return it.

Parameters:address – an implementation of twisted.internet.interfaces.IAddress
Returns:an instance of Client
clientConnectionFailed(connector, reason)

Handler for when the IRC connection fails. Handles auto reconnect if helga is configured for it (see settings AUTO_RECONNECT and AUTO_RECONNECT_DELAY)

clientConnectionLost(connector, reason)

Handler for when the IRC connection is lost. Handles auto reconnect if helga is configured for it (see settings AUTO_RECONNECT and AUTO_RECONNECT_DELAY)

helga.comm.xmpp

class helga.comm.xmpp.Client(factory)

The XMPP client that has predetermined behavior for certain events. This client assumes some default behavior for multi user chat (MUC) by setting the conference host as conference.HOST using HOST in SERVER. A specific MUC host can be specified using the key MUC_HOST in SERVER.

This client is also a bit opinionated when it comes to chat rooms and how room names and nicks are delivered to plugins. Since helga originally started as an IRC bot, channels are sent to plugins as the user portion of the room JID prefixed with ‘#’. For example, if a message is received from bots@conference.example.com/some_user, the channel will be #bots. In this instance, plugins would see the user nick as some_user. For private messages, a message received from some_user@example.com would result in an identical channel and nick some_user.

factory

An instance of Factory used to create this client instance.

jid

The Jabber ID used by the client. A copy of the factory jid attribute.

nickname

The current nickname of the bot. Generally this is the user portion of the jid attribute, and the resource portion of chat room JIDs, but the value is obtained via the setting NICK. For HipChat support, this should be set to the user account’s Full Name.

stream

The raw data stream. An instance of twisted.words.protocols.jabber.xmlstream.XmlStream

format_channel(channel)

Formats a channel as a valid JID string. This will operate with a fallback of channel@conference_host should any of the following conditions happen:

  • Parsing the channel as a JID fails with twisted.words.protocols.jabber.jid.InvalidFormat
  • Either the user or host portion of the parsed JID is empty

Any prefixed ‘#’ characters are removed. For example, assuming a conference host of ‘conf.example.com’:

  • #bots would return bots@conf.example.com
  • bots would return bots@conf.example.com
  • bots@rooms.example.com would return bots@rooms.example.com
  • bots@rooms.example.com/resource would return bots@rooms.example.com
Parameters:channel – The channel to format as a full JID. Can be a simple string, ‘#’ prefixed string, or full room JID.
Returns:The full user@host JID of the room
get_channel_logger(channel)

Gets a channel logger, keeping track of previously requested ones. (see Channel Logging)

Parameters:channel – A channel name
Returns:a python logger suitable for channel logging
is_public_channel(channel)

Checks if a given channel is public or not. A channel is public if it starts with ‘#’

Parameters:channel – the channel name to check
join(channel, password=None)

Join a channel, optionally with a passphrase required to join. Channels can either be a full, valid JID or a simple channel name like ‘#bots’, which will be expanded into something like bots@conference.example.com (see format_channel())

Parameters:
  • channel – the name of the channel to join
  • key – an optional passphrase used to join the given channel
joined(channel)

Called when the client successfully joins a new channel. Adds the channel to the known channel list and sends the join signal (see Signals/Notifications of Helga Events)

Parameters:channel – the channel that has been joined
leave(channel, reason=None)

Leave a channel, optionally with a reason for leaving

Parameters:
  • channel – the name of the channel to leave
  • reason – an optional reason for leaving
left(channel)

Called when the client successfully leaves a channel. Removes the channel from the known channel list and sends the left signal (see Signals/Notifications of Helga Events)

Parameters:channel – the channel that has been left
log_channel_message(channel, nick, message)

Logs one or more messages by a user on a channel using a channel logger. If channel logging is not enabled, nothing happens. (see Channel Logging)

Parameters:
  • channel – A channel name
  • nick – The nick of the user sending an IRC message
  • message – The IRC message
me(channel, message)

Equivalent to: /me message. This is more compatibility with existing IRC plugins that use this method. Channels prefixed with ‘#’ are assumed to be multi user chat rooms, otherwise, they are assumed to be individual users.

Parameters:
  • channel – The XMPP channel to send the message to. A channel not prefixed by a ‘#’ will be sent as a private message to a user with that nick.
  • message – The message to send, which will be prefixed with ‘/me’
msg(channel, message)

Send a message over XMPP to the specified channel. Channels prefixed with ‘#’ are assumed to be multi user chat rooms, otherwise, they are assumed to be individual users.

Parameters:
  • channel – The XMPP channel to send the message to. A channel not prefixed by a ‘#’ will be sent as a private message to a user with that nick.
  • message – The message to send
on_authenticated(stream)

Handler for successful authentication to the XMPP server. Establishes automatically joining channels. Sends the signon signal (see Signals/Notifications of Helga Events)

Parameters:stream – An instance of twisted.words.protocols.jabber.xmlstream.XmlStream
on_connect(stream)

Handler for a successful connection to the server. Sets the client xml stream and starts the heartbeat service.

Parameters:stream – An instance of twisted.words.protocols.jabber.xmlstream.XmlStream
on_disconnect(stream)

Handler for an unexpected disconnect. Logs the disconnect and stops the heartbeat service.

Parameters:stream – An instance of twisted.words.protocols.jabber.xmlstream.XmlStream
on_init_failed(failure)

Handler for when client initialization fails. This should end contact with the server by sending the xml footer.

Parameters:failure – The element of the failure
on_invite(element)

Handler that responds to channel invites from other users. This will acknowledge the request by joining the room indicated in the xml payload.

Parameters:element – A <message/> element, instance of twisted.words.xish.domish.Element
on_message(element)

Handler for an XMPP message. This method handles logging channel messages (if it occurs on a public channel) as well as allowing the plugin manager to send the message to all registered plugins. Should the plugin manager yield a response, it will be sent back.

Parameters:message – A <message/> element, instance of twisted.words.xish.domish.Element
on_nick_collision(element)

Handler called when the server responds of nick collision with the bot. This will generate a new nick containing the preferred nick and the current timestamp and attempt to rejoin the room it failed to join.

Parameters:element – A <presence/> element, instance of twisted.words.xish.domish.Element
on_ping(el)

Handler for server IQ pings. Automatically responds back with a PONG.

Parameters:el – A <iq/> PING message, instance of twisted.words.xish.domish.Element
on_subscribe(element)

Handler that responds to ‘buddy requests’ from other users. This will acknowledge the request by approving it.

Parameters:element – A <presence/> element, instance of twisted.words.xish.domish.Element
on_user_joined(element)

Handler called when a user enters a public room. Responsible for sending the user_joined signal (see Signals/Notifications of Helga Events)

Parameters:element – A <presence/> element, instance of twisted.words.xish.domish.Element
on_user_left(element)

Handler called when a user leaves a public room. Responsible for sending the user_left signal (see Signals/Notifications of Helga Events)

Parameters:element – A <presence/> element, instance of twisted.words.xish.domish.Element
parse_channel(element)

Parses a channel name from an element. This follows a few rules to determine the right channel to use. Assuming a ‘from’ jid of user@host/resource:

  • If the element tag is ‘presence’, the user portion of the jid is returned with ‘#’ prefix
  • If the element type is ‘groupchat’, the user portion of the jid is returned with a ‘#’ prefix
  • If the element type is ‘chat’, but the host is the conference host name, the resource portion of the jid is returned
  • Otherwise, the user portion of the jid is returned
Parameters:element – An instance of twisted.words.xish.domish.Element
Returns:The channel portion of the XMPP jid, prefixed with ‘#’ if it’s a chat room
parse_message(message)

Parses the message body from a <message/> element, ignoring any delayed messages. If a message is indeed a delayed message, an empty string is returned

Parameters:message – A <message/> element, instance of twisted.words.xish.domish.Element
Returns:The contents of the message, empty string if the message is delayed
parse_nick(message)

Parses a nick from a full XMPP jid. This will also take special care to parse a nick as a user jid or a resource from a room jid. For example from me@jabber.local would return me and bots@conference.jabber.local/me would return me.

Parameters:message – A <message/> element, instance of twisted.words.xish.domish.Element
Returns:The nick portion of the XMPP jid
ping()

Sends an IQ PING to the host server. Useful for establishing a heartbeat/keepalive

set_presence(presence)

Sends a <presence/> element to the connected server. Used to indicate online or available status

Parameters:presence – The presence status string to send to the server
class helga.comm.xmpp.Factory

XMPP client factory. following twisted.words.protocols.jabber.client.XMPPClientFactory. Ensures that a client is properly created and handles auto reconnect if helga is configured for it (see settings AUTO_RECONNECT and AUTO_RECONNECT_DELAY).

By default the Jabber ID is set using the form USERNAME@HOST from SERVER, but a specific value can be used with the JID key instead.

jid

The Jabber ID used by the client. Configured directly via JID in SERVER or indirectly as USERNAME@HOST from SERVER. An instance of twisted.words.protocols.jabber.jid.JID.

auth

An instance of twisted.words.protocols.jabber.client.XMPPAuthenticator used for password authentication of the server connection.

client

The client instance of Client

clientConnectionFailed(connector, reason)

Handler for when the XMPP connection fails. Handles auto reconnect if helga is configured for it (see settings AUTO_RECONNECT and AUTO_RECONNECT_DELAY)

Parameters:
  • connector – The twisted conntector
  • reason – A twisted Failure instance
Raises:

The given reason unless AUTO_RECONNECT is enabled

clientConnectionLost(connector, reason)

Handler for when the XMPP connection is lost. Handles auto reconnect if helga is configured for it (see settings AUTO_RECONNECT and AUTO_RECONNECT_DELAY)

Parameters:
  • connector – The twisted conntector
  • reason – A twisted Failure instance
Raises:

The given reason unless AUTO_RECONNECT is enabled

protocol

alias of twisted.words.protocols.jabber.xmlstream.XmlStream

helga.db

pymongo connection objects and utilities

helga.db.client

A pymongo.mongo_client.MongoClient instance, the connection client to MongoDB

helga.db.db

A pymongo.database.Database instance, the default MongoDB database to use

helga.db.connect()

Connect to a MongoDB instance, if helga is configured to do so (see setting DATABASE). This will return the MongoDB client as well as the default database as configured.

Returns:A two-tuple of (pymongo.MongoClient, pymongo.database.Database)

helga.log

Logging utilities for helga

class helga.log.ChannelLogFileHandler(basedir)

A rotating file handler implementation that will create UTC dated log files suitable for channel logging.

compute_next_rollover()

Based on UTC now, computes the next rollover date, which will be 00:00:00 of the following day. For example, if the current datetime is 2014-10-31 08:15:00, then the next rollover will be 2014-11-01 00:00:00.

current_filename()

Returns a UTC dated filename suitable as a log file. Example: 2014-12-15.txt

doRollover()

Perform log rollover. Closes any open stream, sets a new log filename, and computes the next rollover time.

shouldRollover(record)

Returns True if the current UTC datetime occurs on or after the next scheduled rollover datetime. False otherwise.

Parameters:record – a python log record
class helga.log.UTCTimeLogFilter(name='')

A log record filter that will add an attribute utcnow and utctime to a log record. The former is a utcnow datetime object, the latter is the formatted time of day for utcnow.

filter(record)

Filter the log record and add two attributes:

  • utcnow: the value of datetime.datetime.utcnow
  • utctime: the time formatted string of utcnow in the form HH:MM:SS
helga.log.getLogger(name)

Obtains a named logger and ensures that it is configured according to helga’s log settings (see Log Settings). Use of this is generally intended to mimic logging.getLogger with the exception that it takes care of formatters and handlers.

Parameters:name – The name of the logger to get
helga.log.get_channel_logger(channel)

Obtains a python logger configured to operate as a channel logger.

Parameters:channel – the channel name for the desired logger

helga.plugins

Helga’s core plugin library containing base implementations for creating plugins as well as utilities for managing plugins at runtime

helga.plugins.registry

A singleton instance of helga.plugins.Registry

helga.plugins.ACKS = ['roger', '10-4', 'no problem', 'will do', 'you got it', 'anything you say', 'sure thing', 'ok', 'right-o', 'consider it done']

A collection of pre-canned acknowledgement type responses

class helga.plugins.Command(command='', aliases=None, help='', priority=50, shlex=False)

A subclass of Plugin for command type plugins (see Plugin Types). Command plugins have a default priority of PRIORITY_NORMAL

aliases = []

A list of command aliases. If a command ‘search’ has an alias list [‘s’], then ‘helga search foo’ and ‘helga s foo’ will both run the command

command = ''

The command string, i.e. ‘search’ for a command ‘helga search foo’

help = ''

An optional help string for the command. This is used by the builtin help plugin

parse(botnick, message)

Parse the incoming message using the current nick of the bot, the defined command string of this object, plus any aliases. Will return the actual command parsed (which could be an alias), plus either whitespaced delimited list of strings that follow the parsed command, or shlex argument list if shlex is True.

Generally, this does not need to be implemented by subclasses

Parameters:
  • botnick – the current bot nickname
  • message – the incoming chat message
Returns:

two-tuple consisting of the string of parsed command, and an argument list of strings either whitespace delimited or shlex split.

process(client, channel, nick, message)

Parses the incoming message and determins if this command should run (i.e. if the primary command or one of the aliases match).

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
Returns:

None if the plugin should not run, otherwise the return value of the run method

run(client, channel, nick, message, command, args)

Executes this plugin with a given message to generate a response. This should run without regard to whether it should or should not for a given message. Note, that this is where the actual work for the plugin should occur. Subclasses should implement this method.

A return value of None, an empty string, or empty list implies that no response should be sent via chat. A non-empty string, list of strings, or raised ResponseNotReady implies a response to be sent.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
  • cmd – The parsed command string which could be the registered command or one of the command aliases
  • args – The parsed command arguments as a list, i.e. any content following the command. For example: helga foo bar baz would be ['bar', 'baz']
Returns:

String or list of strings to return via chat. None or empty string or list for no response

shlex = False

A boolean indicating whether or not to use shlex arg string parsing rather than naive whitespace splitting

class helga.plugins.Match(pattern='', priority=25)

A subclass of Plugin for match type plugins (see Plugin Types). Matches have a default priority of PRIORITY_LOW

match(message)

Matches a message against the pattern defined for this class. If the pattern attribute is a callable, it is called with the message as its only argument and that value is returned. Otherwise, the pattern attribute is used as a regular expression string argument to re.findall and that value is returned.

Parameters:message – the message received from the server
Returns:the result of re.findall if pattern is a string, otherwise the return value of calling the pattern attribute with the message as a parameter
pattern = ''

A regular expression string used to match against a chat message. Optionally, this attribute can be a callable that accepts a chat message string as its only argument and returns a value that can be evaluated for truthiness.

process(client, channel, nick, message)

Processes a message sent by a user on a given channel. This will return None if the message does not match the plugin’s pattern, or the return value of run if it does match. For this plugin to match an incoming message, the return value of self.match() must return value that can be evaluated for truth. Generally, subclasses should not have to worry about this method, and instead, should focus on the implementation of run.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
Returns:

None if the plugin should not run, otherwise the return value of the run method

run(client, channel, nick, message, matches)

Executes this plugin with a given message to generate a response. This should run without regard to whether it should or should not for a given message. Note, that this is where the actual work for the plugin should occur. Subclasses should implement this method.

A return value of None, an empty string, or empty list implies that no response should be sent via chat. A non-empty string, list of strings, or raised ResponseNotReady implies a response to be sent.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
  • matches – The result of re.findall if decorated with a regular expression, otherwise the return value of the callable passed to helga.plugins.match()
Returns:

String or list of strings to return via chat. None or empty string or list for no response

helga.plugins.PRIORITY_HIGH = 75

The value for high priority plugins. Configurable via setting PLUGIN_PRIORITY_HIGH

helga.plugins.PRIORITY_LOW = 25

The value for low priority plugins. Configurable via setting PLUGIN_PRIORITY_LOW

helga.plugins.PRIORITY_NORMAL = 50

The value for normal priority plugins. Configurable via setting PLUGIN_PRIORITY_NORMAL

class helga.plugins.Plugin(priority=50)

The base class for helga plugins. There are three main methods of this base class that are important for creating class-based plugins.

preprocess

Run by the plugin registry as a preprocessing mechanism. Allows plugins to modify the channel, nick, and/or message that other plugins will receive.

process

Run by the plugin registry to allow a plugin to process a chat message. This is the primary entry point for plugins according to the plugin manager, so it should either return a response or not.

run

Run internally by the plugin, generally from within the process method. This should do the actual work to generate a response. In other words, process should handle checking if the plugin should handle a message and then return whatever run returns.

decorate(fn, preprocessor=False)

A helper for decorating a function to handle this plugin. This essentially just monkey patches the run or preprocess method whith the given function. Decorated functions should accept whatever arguments the subclass implementation sends to its run method. Also, instances/subclasses of Plugin are kept in a list attribute of the decorated function. This allows chainable decorators that function as intended. Example usage:

def my_plugin(*args, **kwargs):
    pass

p = Plugin()
p.decorate(my_plugin)
assert p in my_plugin._plugins
Parameters:
  • fn – function to decorate
  • preprocessor – True if the function should be decorated as a preprocessor
preprocess(client, channel, nick, message)

A preprocessing filter for plugins. This allows a plugin to modify a received message prior to that message being handled by this plugin’s or other plugin’s process method.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
Returns:

a three-tuple (channel, nick, message) containing any modifications

priority = 50

The registered priority of the plugin

process(client, channel, nick, message)

This method of a plugin is called by helga’s plugin registry to process an incoming chat message. This should determine whether or not the plugin run method should be called. If so, it should return whatever return value run generates. If not, None should be returned.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
Returns:

None if the plugin should not run, otherwise the return value of the run method

run(client, channel, nick, message, *args, **kwargs)

Executes this plugin with a given message to generate a response. This should run without regard to whether it should or should not for a given message. Note, that this is where the actual work for the plugin should occur. Subclasses should implement this method.

A return value of None, an empty string, or empty list implies that no response should be sent via chat. A non-empty string, list of strings, or raised ResponseNotReady implies a response to be sent.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
Returns:

None if no response is to be sent back to the server, a non-empty string or list of strings if a response is to be returned

class helga.plugins.Registry

Simple plugin registry that handles dispatching messages to registered plugins. Plugins can be disabled or enabled per channel. By default, all plugins are loaded, but not enabled on a channel unless it exists in DEFAULT_CHANNEL_PLUGINS. This is done so that potentially annoying plugins can be enabled on-demand. Plugin loading can be limited to a whitelist via ENABLED_PLUGINS or restricted to a blacklist via DISABLED_PLUGINS.

plugins = {}

A dictionary mapping plugin names to decorated functions or Plugin subclasses

enabled_plugins = {}

A dictionary of enabled plugin names per channel, keyed by channel name

all_plugins

A set of all registered plugin names

disable(channel, *plugins)

Disable a plugin or plugins on a desired channel

Parameters:
  • channel – the desired chat channel
  • *plugins – a list of plugin names to disable
enable(channel, *plugins)

Enable a plugin or plugins on a desired channel

Parameters:
  • channel – the desired chat channel
  • *plugins – a list of plugin names to enable
get_plugin(name)

Get a plugin by name

Parameters:name – the name of the plugin
Returns:a plugin implementation (decorated function or Plugin sublclass)
load()

Load all plugins registered via setuptools entry point named helga_plugins and initialize them. For example:

entry_points = {
    'helga_plugins': [
        'plugin_name = mylib.mymodule:MyPluginClass',
    ],
}

Note that this loading honors plugin whitelists and blacklists from the settings ENABLED_PLUGINS and DISABLED_PLUGINS respectively. If there are no whitelisted plugins, nothing is loaded. If a plugin is in the blacklist, it is not loaded. If a plugin is not listed in the whitelist, it is not loaded.

preprocess(client, channel, nick, message)

Invoke the preprocess method for each plugin on a given channel according to plugin priority. Any exceptions from plugins will be suppressed and logged.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – the channel from which the message came
  • nick – the nick of the user sending the message
  • message – the original message received
Returns:

a three-tuple (channel, nick, message) containing modifications all preprocessor plugins have made

prioritized(channel, high_to_low=True)

Obtain a list of enabled plugins for a given channel ordered according to their priority (see Plugin Priorities). The default action is to return a list ordered from most important to least important.

Parameters:
  • channel – the chat channel for the enabled plugin list
  • high_to_low – priority ordering, True for most important to least important.
process(client, channel, nick, message)

Invoke the process method for each plugin on a given channel according to plugin priority. Any exceptions from plugins will be suppressed and logged. All return values from plugin process methods are collected unless the setting PLUGIN_FIRST_RESPONDER_ONLY is set to True or a plugin raises ResponseNotReady, in which case the first plugin to return a response or raise ResponseNotReady will prevent others from processing. All response strings are explicitly converted to unicode.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – the channel from which the message came
  • nick – the nick of the user sending the message
  • message – the original message received
Returns:

a list of non-empty unicode response strings

register(name, fn_or_cls)

Register a decorated plugin function or Plugin subclass with a given name

Parameters:
  • name – the name of the plugin
  • fn_or_cls – a decorated plugin function or Plugin subclass
Raises:

TypeError if the fn_or_cls argument is not a decorated plugin function or Plugin subclass

reload(name)

Reloads a plugin with a given name. This is equivalent to finding the registered entry point module and using the python builtin reload().

Parameters:name – the desired plugin to reload
Returns:True if reloaded, False if an exception occurred
exception helga.plugins.ResponseNotReady

Exception raised by plugins that perform some async operation using twisted deferreds. If the bot is configured to only allow the first plugin response (by default), then any plugin raising this will prevent further plugin execution

(see Communicating Asynchronously)

helga.plugins.command(command, aliases=None, help='', priority=50, shlex=False)

A decorator for creating command plugins

Parameters:
  • command – The command string, i.e. ‘search’ for a command ‘helga search foo’
  • aliases – A list of command aliases. If a command ‘search’ has an alias list [‘s’], then ‘helga search foo’ and ‘helga s foo’ will both run the command.
  • help – An optional help string for the command. This is used by the builtin help plugin.
  • priority – The priority of the plugin. Default is PRIORITY_NORMAL.
  • shlex – A boolean indicating whether to use shlex arg string parsing rather than naive whitespace splitting.

Decorated functions should follow this pattern:

helga.plugins.func(client, channel, nick, message, cmd, args)
Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
  • cmd – The parsed command string which could be the registered command or one of the command aliases
  • args – The parsed command arguments as a list, i.e. any content following the command. For example: helga foo bar baz would be ['bar', 'baz']
Returns:

String or list of strings to return via chat. None or empty string or list for no response

helga.plugins.match(pattern, priority=25)

A decorator for creating match plugins

Parameters:
  • pattern – A regular expression string used to match against a chat message. Optionally, this argument can be a callable that accepts a chat message string as its only argument and returns a value that can be evaluated for truthiness.
  • priority – The priority of the plugin. Default is PRIORITY_LOW

Decorated match functions should follow this pattern:

helga.plugins.func(client, channel, nick, message, matches)
Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
  • matches – The result of re.findall if decorated with a regular expression, otherwise the return value of the callable passed
Returns:

String or list of strings to return via chat. None or empty string or list for no response

helga.plugins.preprocessor(priority=50)

A decorator for creating preprocessor plugins

Parameters:priority – The priority of the plugin. Default is PRIORITY_NORMAL

Decorated preprocessor functions should follow this pattern:

helga.plugins.func(client, channel, nick, message, matches)
Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
Returns:

a three-tuple (channel, nick, message) containing any modifications

helga.plugins.random_ack()

Returns a random choice from ACKS

helga.plugins.webhooks

Webhook HTTP server plugin and core webhook API

Webhooks provide a way to expose HTTP endpoints that can interact with helga. A command plugin manages an HTTP server that is run on a port specified by setting helga.settings.WEBHOOKS_PORT (default 8080). An additional, optional setting that can be used for routes requiring HTTP basic auth is helga.settings.WEBHOOKS_CREDENTIALS, which should be a list of tuples, where each tuple is a pair of (username, password).

Routes are URL path endpoints. On the surface they are just python callables decorated using @route. The route decorated must be given a path regex, and optional list of HTTP methods to accept. Webhook plugins must be registered in the same way normal plugins are registered, using setuptools entry_points. However, they must belong to the entry_point group helga_webhooks. For example:

setup(entry_points={
    'helga_webhooks': [
        'api = myapi.decorated_route'
    ]
})

For more information, see Webhooks

exception helga.plugins.webhooks.HttpError(code, message=None, response=None)

A basic HTTP error.

@type status: L{bytes} @ivar status: Refers to an HTTP status code, for example C{http.NOT_FOUND}.

@type message: L{bytes} @param message: A short error message, for example “NOT FOUND”.

@type response: L{bytes} @ivar response: A complete HTML document for an error page.

class helga.plugins.webhooks.WebhookPlugin(*args, **kwargs)

A command plugin that manages running an HTTP server for webhook routes and services. Usage:

helga webhooks (start|stop|routes)

Both start and stop are privileged actions and can start and stop the HTTP listener for webhooks respectively. To use them, a user must be configured as an operator. The routes subcommand will list all of the URL routes known to the webhook listener.

Webhook routes are generally loaded automatically if they are installed. There are whitelist and blacklist controls to limit loading webhook routes (see ENABLED_WEBHOOKS and DISABLED_WEBHOOKS)

add_route(fn, path, methods)

Adds a route handler function to the root web resource at a given path and for the given methods

Parameters:
  • fn – the route handler function
  • path – the URL path of the route
  • methods – list of HTTP methods that the route should respond to
control(action)

Control the running HTTP server. Intended for helga operators.

Parameters:action – the action to perform, either ‘start’ or ‘stop’
list_routes(client, nick)

Messages a user with all webhook routes and their supported HTTP methods

Parameters:
run(client, channel, nick, msg, cmd, args)

Executes this plugin with a given message to generate a response. This should run without regard to whether it should or should not for a given message. Note, that this is where the actual work for the plugin should occur. Subclasses should implement this method.

A return value of None, an empty string, or empty list implies that no response should be sent via chat. A non-empty string, list of strings, or raised ResponseNotReady implies a response to be sent.

Parameters:
  • client – an instance of helga.comm.irc.Client or helga.comm.xmpp.Client
  • channel – The channel from which the message was received. This could be a public channel like ‘#foo’, or in the event of a private message, could be the nick of the user sending the message
  • nick – The nick of the user sending the message
  • message – The full message string received from the server
  • cmd – The parsed command string which could be the registered command or one of the command aliases
  • args – The parsed command arguments as a list, i.e. any content following the command. For example: helga foo bar baz would be ['bar', 'baz']
Returns:

String or list of strings to return via chat. None or empty string or list for no response

class helga.plugins.webhooks.WebhookRoot(*args, **kwargs)

The root HTTP resource the webhook HTTP server uses to respond to requests. This manages all registered webhook route handlers, manages running them, and manages returning any responses generated.

add_route(fn, path, methods)

Adds a route handler function to the root web resource at a given path and for the given methods

Parameters:
  • fn – the route handler function
  • path – the URL path of the route
  • methods – list of HTTP methods that the route should respond to
chat_client = None

An instance of helga.comm.irc.Client or helga.comm.xmpp.Client

render(request)

Renders a response for an incoming request. Handles finding and dispatching the route matching the incoming request path. Any response string generated will be explicitly encoded as a UTF-8 byte string.

If no route patch matches the incoming request, a 404 is returned.

If a route is found, but the request uses a method that the route handler does not support, a 405 is returned.

Parameters:request – The incoming HTTP request, twisted.web.http.Request
Returns:a string with the HTTP response content
routes = None

A dictionary of regular expression URL paths as keys, and two-tuple values of allowed methods, and the route handler function

helga.plugins.webhooks.authenticated(fn)

Decorator for declaring a webhook route as requiring HTTP basic authentication. Incoming requests validate a supplied basic auth username and password against the list configured in the setting WEBHOOKS_CREDENTIALS. If no valid credentials are supplied, an HTTP 401 response is returned.

Parameters:fn – the route handler to decorate
helga.plugins.webhooks.route(path, methods=None)

Decorator to register a webhook route. This requires a path regular expression, and optionally a list of HTTP methods to accept, which defaults to accepting GET requests only. Incoming HTTP requests that use a non-allowed method will receive a 405 HTTP response.

Parameters:
  • path – a regular expression string for the URL path of the route
  • methods – a list of accepted HTTP methods for this route, defaulting to ['GET']

Decorated routes must follow this pattern:

helga.plugins.webhooks.func(request, client)
Parameters:
Returns:

a string HTTP response

helga.settings

Default settings and configuration utilities

Chat Settings

Settings that pertain to how helga operates with and connects to a chat server

helga.settings.NICK = 'helga'

The preferred nick of the bot instance. For XMPP clients, this will be used when joining rooms.

helga.settings.CHANNELS = [('#bots',)]

A list of channels to automatically join. You can specify either a single channel name or a two-tuple of channel name, and password. For example:

CHANNELS = [
    '#bots',
    ('#foo', 'password'),
]

Note that this setting is only for hardcoded autojoined channels. Helga also responds to /INVITE commands as well offers a builtin plugin to configure autojoin channels at runtime (see operator)

For XMPP/HipChat support, channel names should either be the full room JID in the form of room@host or a simple channel name prefixed with a ‘#’ such as #room. Depending on the configuration, the room JID will be constructed using the MUC_HOST value of the SERVER setting or by prefixing ‘conference.’ to the HOST value.

helga.settings.SERVER = {'HOST': 'localhost', 'PORT': 6667, 'TYPE': 'irc'}

Dictionary of connection details. At a minimum this should contain keys HOST and PORT which default to ‘localhost’ and 6667 respectively for irc. Optionally, you can specify a boolean key SSL if you require helga to connect via SSL. You may also specify keys USERNAME and PASSWORD if your server requires authentication. For example:

SERVER = {
    'HOST': 'localhost',
    'PORT': 6667,
    'SSL': False,
    'USERNAME': 'user',
    'PASSWORD': 'pass',
}

Additional, optional keys are supported for different chat backends:

  • TYPE: the backend type to use, ‘irc’ or ‘xmpp’
  • MUC_HOST: the MUC group chat domain like ‘conference.example.com’ for group chat
  • JID: A full jabber ID to use instead of USERNAME (xmpp only)
helga.settings.AUTO_RECONNECT = True

A boolean indicating if the bot automatically reconnect on connection lost

helga.settings.AUTO_RECONNECT_DELAY = 5

An integer for the time, in seconds, to delay between reconnect attempts

helga.settings.RATE_LIMIT = None

IRC Only. An integer indicating the rate limit, in seconds, for messages sent over IRC. This may help to prevent flood, but may degrade the performance of the bot, as it applies to every message sent to IRC.

Core Settings

Settings that pertain to core helga features.

helga.settings.OPERATORS = []

A list of chat nicks that should be considered operators/administrators

helga.settings.DATABASE = {'DB': 'helga', 'HOST': 'localhost', 'PORT': 27017}

A dictionary containing connection info for MongoDB. The minimum settings that should exist here are ‘HOST’, the MongoDB host, ‘PORT, the MongoDB port, and ‘DB’ which should be the MongoDB collection to use. These values default to ‘localhost’, 27017, and ‘helga’ respectively. Both ‘USERNAME’ and ‘PASSWORD’ can be specified if MongoDB requires authentication. For example:

DATABASE = {
    'HOST': 'localhost',
    'PORT': 27017,
    'DB': 'helga',
    'USERNAME': 'foo',
    'PASSWORD': 'bar',
}

Log Settings

helga.settings.LOG_LEVEL = 'DEBUG'

A string for the logging level helga should use for process logging

helga.settings.LOG_FILE = None

A string, if set, a string indicating the log file for python logs. By default helga will log directly to stdout

helga.settings.LOG_FORMAT = '%(asctime)-15s [%(levelname)s] [%(name)s:%(lineno)d]: %(message)s'

A string that is compatible with configuring a python logging formatter.

Channel Log Settings

See Channel Logging

helga.settings.CHANNEL_LOGGING = False

A boolean, if True, will enable conversation logging on all channels

helga.settings.CHANNEL_LOGGING_DIR = '.logs'

If CHANNEL_LOGGING is enabled, this is a string of the directory to which channel logs should be written.

helga.settings.CHANNEL_LOGGING_HIDE_CHANNELS = []

A list of channel names (either with or without a ‘#’ prefix) that will be hidden in the browsable channel log web ui.

Plugin and Webhook Settings

Settings that control plugin and/or webhook behaviors. See Plugins or Webhooks

helga.settings.ENABLED_PLUGINS = True

A list of plugin names that should be loaded by the plugin manager. This effectively serves as a mechanism for explicitly including plugins that have been installed on the system. If this value is True, the plugin manager will load any plugin configured with an entry point and make it available for use. If it is None, or an empty list, no plugins will be loaded. See Plugins for more information.

helga.settings.DISABLED_PLUGINS = []

A list of plugin names that should NOT be loaded by the plugin manager. This effectively serves as a mechanism for explicitly excluding plugins that have been installed on the system. If this value is True, the plugin manager will NOT load any plugin configured with an entry point. If it is None, or an empty list, no plugins will be blacklisted. See Plugins for more information.

helga.settings.DEFAULT_CHANNEL_PLUGINS = True

A list of plugin names that should be enabled automatically for any channel. If this value is True, all plugins installed will be enabled by default. If this value is None, or an empty list, no plugins will be enabled on channels by default. See Plugins for more information.

helga.settings.ENABLED_WEBHOOKS = True

A list of whitelisted webhook names that should be loaded and enabled on process startup. If this value is True, then all webhooks available are loaded and made available. An empty list or None implies that no webhooks will be made available. See Webhooks for more details.

helga.settings.DISABLED_WEBHOOKS = None

A list of blacklisted webhook names that should NOT be loaded and enabled on process startup. If this value is True, then all webhooks available are loaded and made available. An empty list or None implies that no webhooks will be made available. See Webhooks for more details.

helga.settings.PLUGIN_PRIORITY_LOW = 25

Integer value for ‘low’ priority plugins (see Plugin Priorities)

helga.settings.PLUGIN_PRIORITY_NORMAL = 50

Integer value for ‘normal’ priority plugins (see Plugin Priorities)

helga.settings.PLUGIN_PRIORITY_HIGH = 75

Integer value for ‘high’ priority plugins (see Plugin Priorities)

helga.settings.PLUGIN_FIRST_RESPONDER_ONLY = True

A boolean, if True, the first response received from a plugin will be the only message sent back to the chat server. If False, all responses are sent.

helga.settings.COMMAND_PREFIX_BOTNICK = True

If a boolean and True, command plugins can be run by asking directly, such as ‘helga foo_command’. This can also be a string for specifically setting a nick type prefix (such as @NickName for HipChat)

helga.settings.COMMAND_PREFIX_CHAR = '!'

A string char, if non-empty, that can be used to invoke a command without requiring the bot’s nick. For example ‘helga foo’ could be run with ‘!foo’.

helga.settings.COMMAND_ARGS_SHLEX = False

A boolean that controls the behavior of argument parsing for command plugins. If False, command plugin arguments are parsed using a naive whitespace split. If True, they will be parsed using shlex.split. See Command Plugins for more information. The default is False, but this shlex parsing will be the only supported means of argument string parsing in a future version.

helga.settings.WEBHOOKS_PORT = 8080

The integer port the webhooks plugin should listen for http requests.

helga.settings.WEBHOOKS_CREDENTIALS = []

List of two-tuple username and passwords used for http webhook basic authentication

helga.settings.configure(overrides)

Applies custom configuration to global helga settings. Overrides can either be a python import path string like ‘foo.bar.baz’ or a filesystem path like ‘foo/bar/baz.py’

Parameters:overrides – an importable python path string like ‘foo.bar’ or a filesystem path to a python file like ‘foo/bar.py’

helga.util.encodings

Utilities for working with unicode and/or byte strings

helga.util.encodings.from_unicode(unistr, errors='ignore')

Safely convert unicode to a byte string by first checking if it already is a byte string before encoding. This function assumes UTF-8 for byte strings and by default will ignore any encoding errors.

Parameters:
  • unistr – either unicode or a byte string
  • errors – a string indicating how encoding errors should be handled (i.e. ‘strict’, ‘ignore’, ‘replace’)
helga.util.encodings.from_unicode_args(fn)

Decorator used to safely convert a function’s positional arguments from unicode to byte strings

helga.util.encodings.to_unicode(bytestr, errors='ignore')

Safely convert a byte string to unicode by first checking if it already is unicode before decoding. This function assumes UTF-8 for byte strings and by default will ignore any decoding errors.

Parameters:
  • bytestr – either a byte string or unicode string
  • errors – a string indicating how decoding errors should be handled (i.e. ‘strict’, ‘ignore’, ‘replace’)
helga.util.encodings.to_unicode_args(fn)

Decorator used to safely convert a function’s positional arguments from byte strings to unicode