errbot package

Module contents

class errbot.BotPlugin(bot)[source]

Bases: errbot.botplugin.BotPluginBase

activate() → None[source]

Triggered on plugin activation.

Override this method if you want to do something at initialization phase (don't forget to super().activate()).

build_identifier(txtrep: str) → errbot.backends.base.Identifier[source]

Transform a textual representation of a user identifier to the correct Identifier object you can set in Message.to and Message.frm.

Return type:Identifier
Parameters:txtrep (str) -- the textual representation of the identifier (it is backend dependent).
Returns:a user identifier.
callback_botmessage(message: errbot.backends.base.Message)[source]

Triggered on every message coming from the bot itself.

Override this method to get notified on all messages coming from the bot itself (including those from other plugins).

Parameters:message (Message) -- An instance of Message representing the message that was received.
callback_connect() → None[source]

Triggered when the bot has successfully connected to the chat network.

Override this method to get notified when the bot is connected.

callback_mention(message: errbot.backends.base.Message, mentioned_people: typing.Sequence[errbot.backends.base.Identifier]) → None[source]

Triggered if there are mentioned people in message.

Override this method to get notified when someone was mentioned in message. [Note: This might not be implemented by all backends.]

Parameters:
  • message (Message) -- representing the message that was received.
  • mentioned_people (Sequence) -- all mentioned people in this message.
callback_message(message: errbot.backends.base.Message) → None[source]

Triggered on every message not coming from the bot itself.

Override this method to get notified on ANY message.

Parameters:message (Message) -- representing the message that was received.
callback_presence(presence: errbot.backends.base.Presence) → None[source]

Triggered on every presence change.

Parameters:presence (Presence) -- An instance of Presence representing the new presence state that was received.
callback_room_joined(room: errbot.backends.base.Room)[source]

Triggered when the bot has joined a MUC.

Parameters:room (Room) -- An instance of MUCRoom representing the room that was joined.
callback_room_left(room: errbot.backends.base.Room)[source]

Triggered when the bot has left a MUC.

Parameters:room (Room) -- An instance of MUCRoom representing the room that was left.
callback_room_topic(room: errbot.backends.base.Room)[source]

Triggered when the topic in a MUC changes.

Parameters:room (Room) -- An instance of MUCRoom representing the room for which the topic changed.
callback_stream(stream: errbot.backends.base.Stream) → None[source]

Triggered asynchronously (in a different thread context) on every incoming stream request or file transfert requests. You can block this call until you are done with the stream. To signal that you accept / reject the file, simply call stream.accept() or stream.reject() and return.

Parameters:stream (Stream) -- the incoming stream request.
change_presence(status: str = 'online', message: str = '') → None[source]
Changes the presence/status of the bot.
Parameters:
  • status (str) -- One of the constant defined in base.py : ONLINE, OFFLINE, DND,...
  • message (str) -- Additional message
Returns:

None

check_configuration(configuration: typing.Mapping) → None[source]

By default, this method will do only a BASIC check. You need to override it if you want to do more complex checks. It will be called before the configure callback. Note if the config_template is None, it will never be called.

It means recusively:

  1. in case of a dictionary, it will check if all the entries and from the same type are there and not more.
  2. in case of an array or tuple, it will assume array members of the same type of first element of the template (no mix typed is supported)

In case of validation error it should raise a errbot.utils.ValidationException

Parameters:configuration (Mapping) -- the configuration to be checked.
configure(configuration: typing.Mapping) → None[source]

By default, it will just store the current configuration in the self.config field of your plugin. If this plugin has no configuration yet, the framework will call this function anyway with None.

This method will be called before activation so don't expect to be activated at that point.

Parameters:configuration (Mapping) -- injected configuration for the plugin.
deactivate() → None[source]

Triggered on plugin deactivation.

Override this method if you want to do something at tear-down phase (don't forget to super().deactivate()).

get_configuration_template() → typing.Mapping[source]

If your plugin needs a configuration, override this method and return a configuration template.

For example a dictionary like: return {'LOGIN' : 'example@example.com', 'PASSWORD' : 'password'}

Note: if this method returns None, the plugin won't be configured

query_room(room: str) → errbot.backends.base.Room[source]

Query a room for information.

Return type:Room
Parameters:room (str) -- The JID/identifier of the room to query for.
Returns:An instance of MUCRoom.
Raises:RoomDoesNotExistError if the room doesn't exist.
rooms() → typing.Sequence[errbot.backends.base.Room][source]

The list of rooms the bot is currently in.

send(identifier: errbot.backends.base.Identifier, text: str, in_reply_to: errbot.backends.base.Message = None, groupchat_nick_reply: bool = False) → None[source]

Send a message to a room or a user.

Parameters:
  • groupchat_nick_reply (bool) -- if True the message will mention the user in the chatroom.
  • in_reply_to (Message) -- the original message this message is a reply to (optional).
  • text (str) -- markdown formatted text to send to the user.
  • identifier (Identifier) -- An Identifier representing the user or room to message. Identifiers may be created with build_identifier().
send_card(body: str = '', to: errbot.backends.base.Identifier = None, in_reply_to: errbot.backends.base.Message = None, summary: str = None, title: str = '', link: str = None, image: str = None, thumbnail: str = None, color: str = 'green', fields: typing.Tuple[typing.Tuple[str, str], ...] = ()) → None[source]

Sends a card.

A Card is a special type of preformatted message. If it matches with a backend similar concept like on Slack or Hipchat it will be rendered natively, otherwise it will be sent as a regular formatted message.

Parameters:
  • body (str) -- main text of the card in markdown.
  • to (Identifier) -- the card is sent to this identifier (Room, RoomOccupant, Person...).
  • in_reply_to (Message) -- the original message this message is a reply to (optional).
  • summary (str) -- (optional) One liner summary of the card, possibly collapsed to it.
  • title (str) -- (optional) Title possibly linking.
  • link (str) -- (optional) url the title link is pointing to.
  • image (str) -- (optional) link to the main image of the card.
  • thumbnail (str) -- (optional) link to an icon / thumbnail.
  • color (str) -- (optional) background color or color indicator.
  • fields (Tuple) -- (optional) a tuple of (key, value) pairs.
send_stream_request(user: errbot.backends.base.Identifier, fsource: io.IOBase, name: str = None, size: int = None, stream_type: str = None)[source]

Sends asynchronously a stream/file to a user.

Parameters:
  • user (Identifier) -- is the identifier of the person you want to send it to.
  • fsource (IOBase) -- is a file object you want to send.
  • name (str) -- is an optional filename for it.
  • size (int) -- is optional and is the espected size for it.
  • stream_type (str) -- is optional for the mime_type of the content.

It will return a Stream object on which you can monitor the progress of it.

send_templated(identifier: errbot.backends.base.Identifier, template_name: str, template_parameters: typing.Mapping, in_reply_to: errbot.backends.base.Message = None, groupchat_nick_reply: bool = False) → None[source]

Sends asynchronously a message to a room or a user.

Same as send but passing a template name and parameters instead of directly the markdown text. :type groupchat_nick_reply: bool :type in_reply_to: Message :type template_parameters: Mapping :type template_name: str :type identifier: Identifier :param template_parameters: arguments for the template. :param template_name: name of the template to use. :param groupchat_nick_reply: if True it will mention the user in the chatroom. :param in_reply_to: optionally, the original message this message is the answer to. :param identifier: identifier of the user or room to which you want to send a message to.

start_poller(interval: float, method: typing.Callable[..., NoneType], args: typing.Tuple = None, kwargs: typing.Mapping = None)[source]

Start to poll a method at specific interval in seconds.

Note: it will call the method with the initial interval delay for the first time Also, you can program for example : self.program_poller(self, 30, fetch_stuff) where you have def fetch_stuff(self) in your plugin

Parameters:
  • kwargs (Mapping) -- kwargs for the method to callback.
  • args (Tuple) -- args for the method to callback.
  • method (Callable) -- method to callback.
  • interval (float) -- interval in seconds.
stop_poller(method: typing.Callable[..., NoneType], args: typing.Tuple = None, kwargs: typing.Mapping = None)[source]

stop poller(s).

If the method equals None -> it stops all the pollers you need to regive the same parameters as the original start_poller to match a specific poller to stop

Parameters:
  • kwargs (Mapping) -- The initial kwargs you gave to start_poller.
  • args (Tuple) -- The initial args you gave to start_poller.
  • method (Callable) -- The initial method you passed to start_poller.
warn_admins(warning: str) → None[source]

Send a warning to the administrators of the bot.

Parameters:warning (str) -- The markdown-formatted text of the message to send.
exception errbot.CommandError(reason: str, template: str = None)[source]

Bases: Exception

Use this class to report an error condition from your commands, the command did not proceed for a known "business" reason.

__init__(reason: str, template: str = None)[source]
Parameters:
  • reason (str) -- the reason for the error in the command.
  • template (str) -- apply this specific template to report the error.
class errbot.Command(function, cmd_type=None, cmd_args=None, cmd_kwargs=None, name=None, doc=None)[source]

Bases: object

This is a dynamic definition of an errbot command.

__init__(function, cmd_type=None, cmd_args=None, cmd_kwargs=None, name=None, doc=None)[source]

Create a Command definition.

Parameters:
  • function -- a function or a lambda with the correct signature for the type of command to inject for example def mycmd(plugin, msg, args) for a botcmd. Note: the first parameter will be the plugin itself (equivalent to self).
  • cmd_type -- defaults to botcmd but can be any decorator function used for errbot commands.
  • cmd_args -- the parameters of the decorator.
  • cmd_kwargs -- the kwargs parameter of the decorator.
  • name -- defaults to the name of the function you are passing if it is a first class function or needs to be set if you use a lambda.
  • doc -- defaults to the doc of the given function if it is a first class function. It can be set for a lambda or overridden for a function with this.
errbot.webhook(*args, methods: typing.Tuple[str] = ('POST', 'GET'), form_param: str = None, raw: bool = False) → typing.Callable[[errbot.botplugin.BotPlugin, typing.Any], str][source]

Decorator for webhooks

Return type:

Callable

Parameters:
  • uri_rule --

    The URL to use for this webhook, as per Bottle request routing syntax. For more information, see:

  • methods (Tuple) -- A tuple of allowed HTTP methods. By default, only GET and POST are allowed.
  • form_param (str) -- The key who's contents will be passed to your method's payload parameter. This is used for example when using the application/x-www-form-urlencoded mimetype.
  • raw (bool) -- When set to true, this overrides the request decoding (including form_param) and passes the raw http request to your method's payload parameter. The value of payload will be a Bottle BaseRequest.

This decorator should be applied to methods of BotPlugin classes to turn them into webhooks which can be reached on Err's built-in webserver. The bundled Webserver plugin needs to be configured before these URL's become reachable.

Methods with this decorator are expected to have a signature like the following:

@webhook
def a_webhook(self, payload):
    pass
errbot.webroute(obj)

Check for functions to route in obj and route them.

errbot.cmdfilter(*args, **kwargs)[source]

Decorator for command filters.

This decorator should be applied to methods of BotPlugin classes to turn them into command filters.

These filters are executed just before the execution of a command and provide the means to add features such as custom security, logging, auditing, etc.

These methods are expected to have a signature and tuple response like the following:

@cmdfilter
def some_filter(self, msg, cmd, args, dry_run):
    """
    :param msg: The original chat message.
    :param cmd: The command name itself.
    :param args: Arguments passed to the command.
    :param dry_run: True when this is a dry-run.
       Dry-runs are performed by certain commands (such as !help)
       to check whether a user is allowed to perform that command
       if they were to issue it. If dry_run is True then the plugin
       shouldn't actually do anything beyond returning whether the
       command is authorized or not.
    """
    # If wishing to block the incoming command:
    return None, None, None
    # Otherwise pass data through to the (potential) next filter:
    return msg, cmd, args

Note that a cmdfilter plugin could modify cmd or args above and send that through in order to make it appear as if the user issued a different command.

errbot.botcmd(*args, hidden: bool = None, name: str = None, split_args_with: str = '', admin_only: bool = False, historize: bool = True, template: str = None, flow_only: bool = False, syntax: str = None) → typing.Callable[[errbot.botplugin.BotPlugin, errbot.backends.base.Message, typing.Any], typing.Any][source]

Decorator for bot command functions

Return type:

Callable

Parameters:
  • hidden (bool) -- Prevents the command from being shown by the built-in help command when True.
  • name (str) -- The name to give to the command. Defaults to name of the function itself.
  • split_args_with (str) -- Automatically split arguments on the given separator. Behaviour of this argument is identical to str.split()
  • admin_only (bool) -- Only allow the command to be executed by admins when True.
  • historize (bool) -- Store the command in the history list (!history). This is enabled by default.
  • template (str) -- The markdown template to use.
  • syntax (str) -- The argument syntax you expect for example: '[name] <mandatory>'.
  • flow_only (bool) -- Flag this command to be available only when it is part of a flow. If True and hidden is None, it will switch hidden to True.

This decorator should be applied to methods of BotPlugin classes to turn them into commands that can be given to the bot. These methods are expected to have a signature like the following:

@botcmd
def some_command(self, msg, args):
    pass

The given msg will be the full message object that was received, which includes data like sender, receiver, the plain-text and html body (if applicable), etc. args will be a string or list (depending on your value of split_args_with) of parameters that were given to the command by the user.

errbot.re_botcmd(*args, hidden: bool = None, name: str = None, admin_only: bool = False, historize: bool = True, template: str = None, pattern: str = None, flags: int = 0, matchall: bool = False, prefixed: bool = True, flow_only: bool = False) → typing.Callable[[errbot.botplugin.BotPlugin, errbot.backends.base.Message, typing.Any], typing.Any][source]

Decorator for regex-based bot command functions

Return type:

Callable

Parameters:
  • pattern (str) -- The regular expression a message should match against in order to trigger the command.
  • flags (int) -- The flags parameter which should be passed to re.compile(). This allows the expression's behaviour to be modified, such as making it case-insensitive for example.
  • matchall (bool) -- By default, only the first match of the regular expression is returned (as a re.MatchObject). When matchall is True, all non-overlapping matches are returned (as a list of re.MatchObject items).
  • prefixed (bool) -- Requires user input to start with a bot prefix in order for the pattern to be applied when True (the default).
  • hidden (bool) -- Prevents the command from being shown by the built-in help command when True.
  • name (str) -- The name to give to the command. Defaults to name of the function itself.
  • admin_only (bool) -- Only allow the command to be executed by admins when True.
  • historize (bool) -- Store the command in the history list (!history). This is enabled by default.
  • template (str) -- The template to use when using markdown output
  • flow_only (bool) -- Flag this command to be available only when it is part of a flow. If True and hidden is None, it will switch hidden to True.

This decorator should be applied to methods of BotPlugin classes to turn them into commands that can be given to the bot. These methods are expected to have a signature like the following:

@re_botcmd(pattern=r'^some command$')
def some_command(self, msg, match):
    pass

The given msg will be the full message object that was received, which includes data like sender, receiver, the plain-text and html body (if applicable), etc. match will be a re.MatchObject containing the result of applying the regular expression on the user's input.

errbot.arg_botcmd(*args, hidden: bool = None, name: str = None, admin_only: bool = False, historize: bool = True, template: str = None, flow_only: bool = False, unpack_args: bool = True, **kwargs) → typing.Callable[[errbot.botplugin.BotPlugin, errbot.backends.base.Message, typing.Any], typing.Any][source]

Decorator for argparse-based bot command functions

https://docs.python.org/3/library/argparse.html

This decorator creates an argparse.ArgumentParser and uses it to parse the commands arguments.

This decorator can be used multiple times to specify multiple arguments.

Any valid argparse.add_argument() parameters can be passed into the decorator. Each time this decorator is used it adds a new argparse argument to the command.

Return type:

Callable

Parameters:
  • hidden (bool) -- Prevents the command from being shown by the built-in help command when True.
  • name (str) -- The name to give to the command. Defaults to name of the function itself.
  • admin_only (bool) -- Only allow the command to be executed by admins when True.
  • historize (bool) -- Store the command in the history list (!history). This is enabled by default.
  • template (str) -- The template to use when using markdown output
  • flow_only (bool) -- Flag this command to be available only when it is part of a flow. If True and hidden is None, it will switch hidden to True.
  • unpack_args (bool) -- Should the argparser arguments be "unpacked" and passed on the the bot command individually? If this is True (the default) you must define all arguments in the function separately. If this is False you must define a single argument args (or whichever name you prefer) to receive the result of ArgumentParser.parse_args().

This decorator should be applied to methods of BotPlugin classes to turn them into commands that can be given to the bot. The methods will be called with the original msg and the argparse parsed arguments. These methods are expected to have a signature like the following (assuming unpack_args=True):

@arg_botcmd('value', type=str)
@arg_botcmd('--repeat-count', dest='repeat', type=int, default=2)
def repeat_the_value(self, msg, value=None, repeat=None):
    return value * repeat

The given msg will be the full message object that was received, which includes data like sender, receiver, the plain-text and html body (if applicable), etc. value will hold the value passed in place of the value argument and repeat will hold the value passed in place of the --repeat-count argument.

If you don't like this automatic "unpacking" of the arguments, you can use unpack_args=False like this:

@arg_botcmd('value', type=str)
@arg_botcmd('--repeat-count', dest='repeat', type=int, default=2, unpack_args=False)
def repeat_the_value(self, msg, args):
    return arg.value * args.repeat

Note

The unpack_args=False only needs to be specified once, on the bottom @args_botcmd statement.

errbot.botflow(*args, **kwargs)[source]

Decorator for flow of commands.

TODO(gbin): example / docs

class errbot.BotFlow(bot)[source]

Bases: yapsy.IPlugin.IPlugin

Defines a Flow plugin ie. a plugin that will define new flows from its methods with the @botflow decorator.

__init__(bot)[source]
activate() → None[source]

Override if you want to do something at initialization phase (don't forget to super(Gnagna, self).activate())

deactivate() → None[source]

Override if you want to do something at tear down phase (don't forget to super(Gnagna, self).deactivate())

get_command(command_name: str)[source]

Helper to get a specific command.

class errbot.FlowRoot(name: str, description: str)[source]

Bases: errbot.flow.FlowNode

This represent the entry point of a flow description.

__init__(name: str, description: str)[source]
Parameters:
  • name (str) -- The name of the conversation/flow.
  • description (str) -- A human description of what this flow does.
connect(node_or_command: typing.Union[typing.FlowNode, str], predicate: typing.Callable[[typing.Mapping[str, typing.Any]], bool] = <function FlowRoot.<lambda>>, auto_trigger: bool = False, room_flow: bool = False)[source]
See:

FlowNode except fot auto_trigger

Parameters:
  • predicate (Callable) --
    see:FlowNode
  • node_or_command (Union) --
    see:FlowNode
  • auto_trigger (bool) -- Flag this root as autotriggering: it will start a flow if this command is executed in the chat.
  • room_flow (bool) -- Bind the flow to the room instead of a single person
class errbot.Flow(root: errbot.flow.FlowRoot, requestor: errbot.backends.base.Identifier, initial_context: typing.Mapping[str, typing.Any], next_step_hinting: int = True)[source]

Bases: object

This is a live Flow. It keeps context of the conversation (requestor and context). Context is just a python dictionary representing the state of the conversation.

__init__(root: errbot.flow.FlowRoot, requestor: errbot.backends.base.Identifier, initial_context: typing.Mapping[str, typing.Any], next_step_hinting: int = True)[source]
Parameters:
  • root (FlowRoot) -- the root of this flow.
  • requestor (Identifier) -- the user requesting this flow.
  • initial_context (Mapping) -- any data we already have that could help executing this flow automatically.
  • next_step_hinting (int) -- toggle display of the "you are now in the flow xxx, you may continue with yyy, zzz"

messages after each flow step

advance(next_step: errbot.flow.FlowNode, enforce_predicate=True)[source]

Move on along the flow. :type enforce_predicate: bool :type next_step: FlowNode :param next_step: Which node you want to move the flow forward to. :param enforce_predicate: Do you want to check if the predicate is verified for this step or not.

Usually, if it is a manual step, the predicate is irrelevant because the user will give the missing information as parameters to the command.
check_identifier(identifier: errbot.backends.base.Identifier)[source]
current_step

The current step this Flow is waiting on.

name

Helper property to get the name of the flow.

next_autosteps() → typing.List[errbot.flow.FlowNode][source]

Get the next steps that can be automatically executed according to the set predicates.

next_steps() → typing.List[errbot.flow.FlowNode][source]

Get all the possible next steps after this one (predicates statisfied or not).

root

The original flowroot of this flow.