The bot and its state

class sopel.bot.Sopel(config, daemon=False)

Bases: sopel.irc.AbstractBot

action(text, dest)

Send a CTCP ACTION PRIVMSG to a user or channel.

Parameters
  • text (str) – the text to send in the CTCP ACTION

  • dest (str) – the destination of the CTCP ACTION

The same loop detection and length restrictions apply as with say(), though automatic message splitting is not available.

add_plugin(plugin, callables, jobs, shutdowns, urls)

Add a loaded plugin to the bot’s registry.

Parameters
  • plugin (sopel.plugins.handlers.AbstractPluginHandler) – loaded plugin to add

  • callables (iterable) – an iterable of callables from the plugin

  • jobs (iterable) – an iterable of functions from the plugin that are periodically invoked

  • shutdowns (iterable) – an iterable of functions from the plugin that should be called on shutdown

  • urls (iterable) – an iterable of functions from the plugin to call when matched against a URL

backend

IRC connection backend.

call(func, sopel, trigger)

Call a function, applying any rate limits or other restrictions.

Parameters
  • func (function) – the function to call

  • sopel (SopelWrapper) – a SopelWrapper instance

  • trigger (Trigger) – the Trigger object for the line from the server that triggered this call

cap_req(plugin_name, capability, arg=None, failure_callback=None, success_callback=None)

Tell Sopel to request a capability when it starts.

Parameters
  • plugin_name (str) – the plugin requesting the capability

  • capability (str) – the capability requested, optionally prefixed with - or =

  • arg (str) – arguments for the capability request

  • failure_callback (function) – a function that will be called if the capability request fails

  • success_callback (function) – a function that will be called if the capability is successfully requested

By prefixing the capability with -, it will be ensured that the capability is not enabled. Similarly, by prefixing the capability with =, it will be ensured that the capability is enabled. Requiring and disabling is “first come, first served”; if one plugin requires a capability, and another prohibits it, this function will raise an exception in whichever plugin loads second. An exception will also be raised if the plugin is being loaded after the bot has already started, and the request would change the set of enabled capabilities.

If the capability is not prefixed, and no other plugin prohibits it, it will be requested. Otherwise, it will not be requested. Since capability requests that are not mandatory may be rejected by the server, as well as by other plugins, a plugin which makes such a request should account for that possibility.

The actual capability request to the server is handled after the completion of this function. In the event that the server denies a request, the failure_callback function will be called, if provided. The arguments will be a Sopel object, and the capability which was rejected. This can be used to disable callables which rely on the capability. It will be be called either if the server NAKs the request, or if the server enabled it and later DELs it.

The success_callback function will be called upon acknowledgment of the capability from the server, whether during the initial capability negotiation, or later.

If arg is given, and does not exactly match what the server provides or what other plugins have requested for that capability, it is considered a conflict.

change_current_nick(new_nick)

Change the current nick without configuration modification.

Parameters

new_nick (str) – new nick to be used by the bot

channels

A map of the channels that Sopel is in.

The keys are sopel.tools.Identifiers of the channel names, and map to sopel.tools.target.Channel objects which contain the users in the channel and their permissions.

property command_groups

A mapping of plugin names to lists of their commands.

Changed in version 7.1: This attribute is now generated on the fly from the registered list of commands and nickname commands.

property config

The sopel.config.Config for the current Sopel instance.

connection_registered

Flag stating whether the IRC Connection is registered yet.

db

The bot’s database, as a sopel.db.SopelDB instance.

dispatch(pretrigger)

Dispatch a parsed message to any registered callables.

Parameters

pretrigger (PreTrigger) – a parsed message from the server

The pretrigger (a parsed message) is used to find matching rules; it will retrieve them by order of priority, and execute them. It runs triggered rules in separate threads, unless they are marked otherwise.

However, it won’t run triggered blockable rules at all when they can’t be executed for blocked nickname or hostname.

See also

The pattern matching is done by the Rules Manager.

property doc

A dictionary of command names to their documentation.

Each command is mapped to its docstring and any available examples, if declared in the plugin’s code.

Changed in version 3.2: Use the first item in each callable’s commands list as the key, instead of the function name as declared in the source code.

Changed in version 7.1: This attribute is now generated on the fly from the registered list of commands and nickname commands.

enabled_capabilities

A set containing the IRCv3 capabilities that the bot has enabled.

error(trigger=None, exception=None)

Called internally when a plugin causes an error.

Parameters
get_irc_backend()

Set up the IRC backend based on the bot’s settings.

Returns

the initialized IRC backend object

Return type

an object implementing the interface of AbstractIRCBackend

get_plugin_meta(name)

Get info about a registered plugin by its name.

Parameters

name (str) – name of the plugin about which to get info

Returns

the plugin’s metadata (see get_meta_description())

Return type

dict

Raises

plugins.exceptions.PluginNotRegistered – when there is no name plugin registered

has_channel_privilege(channel, privilege)

Tell if the bot has a privilege level or above in a channel.

Parameters
  • channel (str) – a channel the bot is in

  • privilege (int) – privilege level to check

Raises

ValueError – when the channel is unknown

This method checks the bot’s privilege level in a channel, i.e. if it has this level or higher privileges:

>>> bot.channels['#chan'].privileges[bot.nick] = plugin.OP
>>> bot.has_channel_privilege('#chan', plugin.VOICE)
True

The channel argument can be either a str or a sopel.tools.Identifier, as long as Sopel joined said channel. If the channel is unknown, a ValueError will be raised.

has_plugin(name)

Check if the bot has registered a plugin of the specified name.

Parameters

name (str) – name of the plugin to check for

Returns

whether the bot has a plugin named name registered

Return type

bool

property hostmask

The current hostmask for the bot sopel.tools.target.User.

Returns

the bot’s current hostmask

Return type

str

Bot must be connected and in at least one channel.

property isupport

Features advertised by the server.

Type

ISupport instance

join(channel, password=None)

Join a channel.

Parameters
  • channel (str) – the channel to join

  • password (str) – an optional channel password

If channel contains a space, and no password is given, the space is assumed to split the argument into the channel to join and its password. channel should not contain a space if password is given.

kick(nick, channel, text=None)

Kick a nick from a channel.

Parameters
  • nick (str) – nick to kick out of the channel

  • channel (str) – channel to kick nick from

  • text (str) – optional text for the kick

The bot must be an operator in the specified channel for this to work.

New in version 7.0.

log_raw(line, prefix)

Log a raw line to the raw log.

Parameters
  • line (str) – the raw line

  • prefix (str) – additional information to prepend to the log line

The prefix is usually either >> for an outgoing line or << for a received one.

memory

A thread-safe dict for storage of runtime data to be shared between plugins. See sopel.tools.SopelMemory.

msg(recipient, text, max_messages=1)

Old way to make the bot say something on IRC.

Parameters
  • recipient (str) – nickname or channel to which to send message

  • text (str) – message to send

  • max_messages (int) – split text into at most this many messages if it is too long to fit in one (optional)

Deprecated since version 6.0: Use say() instead. Will be removed in Sopel 8.

property myinfo

Server/network information.

Type

MyInfo instance

New in version 7.0.

property name

Sopel’s “real name”, as used for WHOIS responses.

property nick

Sopel’s current nick.

Changing this while Sopel is running is unsupported and can result in undefined behavior.

notice(text, dest)

Send an IRC NOTICE to a user or channel (dest).

Parameters
  • text (str) – the text to send in the NOTICE

  • dest (str) – the destination of the NOTICE

on_close()

Call shutdown methods.

on_connect()

Handle successful establishment of IRC connection.

on_error()

Handle any uncaptured error in the bot itself.

on_job_error(scheduler, job, exc)

Called when a job from the Job Scheduler fails.

Parameters

See also

Sopel.error()

on_message(message)

Handle an incoming IRC message.

Parameters

message (str) – the received raw IRC message

on_message_sent(raw)

Handle any message sent through the connection.

Parameters

raw (str) – raw text message sent through the connection

When a message is sent through the IRC connection, the bot will log the raw message. If necessary, it will also simulate the echo-message feature of IRCv3.

on_scheduler_error(scheduler, exc)

Called when the Job Scheduler fails.

Parameters

See also

Sopel.error()

part(channel, msg=None)

Leave a channel.

Parameters
  • channel (str) – the channel to leave

  • msg (str) – the message to display when leaving a channel

post_setup()

Perform post-setup actions.

This method handles everything that should happen after all the plugins are loaded, and before the bot can connect to the IRC server.

At the moment, this method checks for undefined configuration options, and starts the job scheduler.

New in version 7.1.

privileges

A dictionary of channels to their users and privilege levels.

The value associated with each channel is a dictionary of sopel.tools.Identifiers to a bitwise integer value, determined by combining the appropriate constants from sopel.plugin.

Deprecated since version 6.2.0: Use channels instead. Will be removed in Sopel 8.

quit(message)

Disconnect from IRC and close the bot.

register(callables, jobs, shutdowns, urls)

Register rules, jobs, shutdown methods, and URL callbacks.

Parameters
  • callables (iterable) – an iterable of callables to register

  • jobs (iterable) – an iterable of functions to periodically invoke

  • shutdowns (iterable) – an iterable of functions to call on shutdown

  • urls (iterable) – an iterable of functions to call when matched against a URL

The callables argument contains a list of “callable objects”, i.e. objects for which callable() will return True. They can be:

  • a callable with rules (will match triggers with a regex pattern)

  • a callable without rules (will match any triggers, such as events)

  • a callable with commands

  • a callable with nick commands

  • a callable with action commands

It is possible to have a callable with rules, commands, and nick commands configured. It should not be possible to have a callable with commands or nick commands but without rules.

register_url_callback(pattern, callback)

Register a callback for URLs matching the regex pattern.

Parameters
  • pattern (re.Pattern) – compiled regex pattern to register

  • callback (function) – callable object to handle matching URLs

New in version 7.0: This method replaces manual management of url_callbacks in Sopel’s plugins, so instead of doing this in setup():

if 'url_callbacks' not in bot.memory:
    bot.memory['url_callbacks'] = tools.SopelMemory()

regex = re.compile(r'http://example.com/path/.*')
bot.memory['url_callbacks'][regex] = callback

use this much more concise pattern:

regex = re.compile(r'http://example.com/path/.*')
bot.register_url_callback(regex, callback)

It’s recommended you completely avoid manual management of URL callbacks through the use of sopel.plugin.url().

Deprecated since version 7.1: Made obsolete by fixes to the behavior of sopel.plugin.url(). Will be removed in Sopel 9.

reload_plugin(name)

Reload a plugin.

Parameters

name (str) – name of the plugin to reload

Raises

plugins.exceptions.PluginNotRegistered – when there is no name plugin registered

This function runs the plugin’s shutdown routine and unregisters the plugin from the bot. Then this function reloads the plugin, runs its setup routines, and registers it again.

reload_plugins()

Reload all registered plugins.

First, this function runs all plugin shutdown routines and unregisters all plugins. Then it reloads all plugins, runs their setup routines, and registers them again.

remove_plugin(plugin, callables, jobs, shutdowns, urls)

Remove a loaded plugin from the bot’s registry.

Parameters
  • plugin (sopel.plugins.handlers.AbstractPluginHandler) – loaded plugin to remove

  • callables (iterable) – an iterable of callables from the plugin

  • jobs (iterable) – an iterable of functions from the plugin that are periodically invoked

  • shutdowns (iterable) – an iterable of functions from the plugin that should be called on shutdown

  • urls (iterable) – an iterable of functions from the plugin to call when matched against a URL

reply(text, dest, reply_to, notice=False)

Send a PRIVMSG to a user or channel, prepended with a nickname.

Parameters
  • text (str) – the text of the reply

  • dest (str) – the destination of the reply

  • reply_to (str) – the nickname that will be prepended to text

  • notice (bool) – whether to send the reply as a NOTICE or not, defaults to False

If notice is True, send a NOTICE rather than a PRIVMSG.

The same loop detection and length restrictions apply as with say(), though automatic message splitting is not available.

restart(message)

Disconnect from IRC and restart the bot.

Parameters

message (str) – QUIT message to send (e.g. “Be right back!”)

property rules

Rules manager.

run(host, port=6667)

Connect to IRC server and run the bot forever.

Parameters
  • host (str) – the IRC server hostname

  • port (int) – the IRC server port

property running_triggers

Current active threads for triggers.

Returns

the running thread(s) currently processing trigger(s)

Return type

iterable

This is for testing and debugging purposes only.

say(text, recipient, max_messages=1, truncation='', trailing='')

Send a PRIVMSG to a user or channel.

Parameters
  • text (str) – the text to send

  • recipient (str) – the message recipient

  • max_messages (int) – split text into at most this many messages if it is too long to fit in one (optional)

  • truncation (str) – string to append if text is too long to fit in a single message, or into the last message if max_messages is greater than 1 (optional)

  • trailing (str) – string to append after text and (if used) truncation (optional)

By default, this will attempt to send the entire text in one message. If the text is too long for the server, it may be truncated.

If max_messages is given, the text will be split into at most that many messages. The split is made at the last space character before the “safe length” (which is calculated based on the bot’s nickname and hostmask), or exactly at the “safe length” if no such space character exists.

If the text is too long to fit into the specified number of messages using the above splitting, the final message will contain the entire remainder, which may be truncated by the server. You can specify truncation to tell Sopel how it should indicate that the remaining text was cut off. Note that the truncation parameter must include leading whitespace if you desire any between it and the truncated text.

The trailing parameter is always appended to text, after the point where truncation would be inserted if necessary. It’s useful for making sure e.g. a link is always included, even if the summary your plugin fetches is too long to fit.

Here are some examples of how the truncation and trailing parameters work, using an artificially low maximum line length:

# bot.say() outputs <text> + <truncation?> + <trailing>
#                   always     if needed       always

bot.say(
    '"This is a short quote.',
    truncation=' […]',
    trailing='"')
# Sopel says: "This is a short quote."

bot.say(
    '"This quote is very long and will not fit on a line.',
    truncation=' […]',
    trailing='"')
# Sopel says: "This quote is very long […]"

bot.say(
    # note the " included at the end this time
    '"This quote is very long and will not fit on a line."',
    truncation=' […]')
# Sopel says: "This quote is very long […]
# The ending " goes missing

New in version 7.1: The truncation and trailing parameters.

property scheduler

Job Scheduler. See sopel.plugin.interval().

search_url_callbacks(url)

Yield callbacks whose regex pattern matches the url.

Parameters

url (str) – URL found in a trigger

Returns

yield 2-value tuples of (callback, match)

For each pattern that matches the url parameter, it yields a 2-value tuple of (callable, match) for that pattern.

The callable is the one registered with register_url_callback(), and the match is the result of the regex pattern’s search method.

New in version 7.0.

See also

The Python documentation for the re.search function and the match object.

server_capabilities

A dict mapping supported IRCv3 capabilities to their options.

For example, if the server specifies the capability sasl=EXTERNAL, it will be here as {"sasl": "EXTERNAL"}. Capabilities specified without any options will have None as the value.

For servers that do not support IRCv3, this will be an empty set.

set_signal_handlers()

Set signal handlers for the bot.

Before running the bot, this method can be called from the main thread to setup signals. If the bot is connected, upon receiving a signal it will send a QUIT message. Otherwise, it raises a KeyboardInterrupt error.

Note

Per the Python documentation of signal.signal():

When threads are enabled, this function can only be called from the main thread; attempting to call it from other threads will cause a ValueError exception to be raised.

settings

Bot settings.

setup()

Set up Sopel bot before it can run.

The setup phase is in charge of:

  • setting up logging (configure Python’s built-in logging)

  • setting up the bot’s plugins (load, setup, and register)

  • starting the job scheduler

setup_logging()

Set up logging based on config options.

setup_plugins()

Load plugins into the bot.

shutdown_methods

List of methods to call on shutdown.

unregister(obj)

Unregister a shutdown method.

Parameters

obj (object) – the shutdown method to unregister

This method was used to unregister anything (rules, commands, urls, jobs, and shutdown methods), but since everything can be done by other means, there is no use for it anymore.

unregister_url_callback(pattern, callback)

Unregister the callback for URLs matching the regex pattern.

Parameters
  • pattern (re.Pattern) – compiled regex pattern to unregister callback

  • callback (function) – callable object to remove

New in version 7.0: This method replaces manual management of url_callbacks in Sopel’s plugins, so instead of doing this in shutdown():

regex = re.compile(r'http://example.com/path/.*')
try:
    del bot.memory['url_callbacks'][regex]
except KeyError:
    pass

use this much more concise pattern:

regex = re.compile(r'http://example.com/path/.*')
bot.unregister_url_callback(regex, callback)

It’s recommended you completely avoid manual management of URL callbacks through the use of sopel.plugin.url().

Deprecated since version 7.1: Made obsolete by fixes to the behavior of sopel.plugin.url(). Will be removed in Sopel 9.

property user

Sopel’s user/ident.

users

A map of the users that Sopel is aware of.

The keys are sopel.tools.Identifiers of the nicknames, and map to sopel.tools.target.User instances. In order for Sopel to be aware of a user, it must share at least one mutual channel.

write(args, text=None)

Send a command to the server.

Parameters
  • args (iterable) – an iterable of strings, which will be joined by spaces

  • text (str) – a string that will be prepended with a : and added to the end of the command

args is an iterable of strings, which are joined by spaces. text is treated as though it were the final item in args, but is preceded by a :. This is a special case which means that text, unlike the items in args, may contain spaces (though this constraint is not checked by write).

In other words, both sopel.write(('PRIVMSG',), 'Hello, world!') and sopel.write(('PRIVMSG', ':Hello, world!')) will send PRIVMSG :Hello, world! to the server.

Newlines and carriage returns ('\n' and '\r') are removed before sending. Additionally, if the message (after joining) is longer than than 510 characters, any remaining characters will not be sent.

See also

The connection backend is responsible for formatting and sending the message through the IRC connection. See the sopel.irc.abstract_backends.AbstractIRCBackend.send_command() method for more information.

class sopel.bot.SopelWrapper(sopel, trigger, output_prefix='')

Wrapper around a Sopel instance and a Trigger.

Parameters
  • sopel (Sopel) – Sopel instance

  • trigger (Trigger) – IRC Trigger line

  • output_prefix (str) – prefix for messages sent through this wrapper (e.g. plugin tag)

This wrapper will be used to call Sopel’s triggered commands and rules as their bot argument. It acts as a proxy to send messages to the sender (either a channel or in a private message) and even to reply to someone in a channel.

action(message, destination=None)

Override Sopel.action to use trigger source by default.

Parameters
  • message (str) – action message

  • destination (str) – channel or nickname; defaults to trigger.sender

The destination will default to the channel in which the trigger happened (or nickname, if received in a private message).

kick(nick, channel=None, message=None)

Override Sopel.kick to kick in a channel

Parameters
  • nick (str) – nick to kick out of the channel

  • channel (str) – optional channel to kick nick from

  • message (str) – optional message for the kick

The channel will default to the channel in which the call was triggered. If triggered from a private message, channel is required.

notice(message, destination=None)

Override Sopel.notice to use trigger source by default.

Parameters
  • message (str) – notice message

  • destination (str) – channel or nickname; defaults to trigger.sender

The destination will default to the channel in which the trigger happened (or nickname, if received in a private message).

reply(message, destination=None, reply_to=None, notice=False)

Override Sopel.reply to reply_to sender by default.

Parameters
  • message (str) – reply message

  • destination (str) – channel or nickname; defaults to trigger.sender

  • reply_to (str) – person to reply to; defaults to trigger.nick

  • notice (bool) – reply as an IRC notice or with a simple message

The destination will default to the channel in which the trigger happened (or nickname, if received in a private message).

reply_to will default to the nickname who sent the trigger.

say(message, destination=None, max_messages=1, truncation='', trailing='')

Override Sopel.say to use trigger source by default.

Parameters
  • message (str) – message to say

  • destination (str) – channel or nickname; defaults to trigger.sender

  • max_messages (int) – split message into at most this many messages if it is too long to fit into one line (optional)

  • truncation (str) – string to indicate that the message was truncated (optional)

  • trailing (str) – string that should always appear at the end of message (optional)

The destination will default to the channel in which the trigger happened (or nickname, if received in a private message).

See also

For more details about the optional arguments to this wrapper method, consult the documentation for sopel.bot.Sopel.say().