The bot and its state

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

Sopel’s current nick. Changing this while Sopel is running is unsupported.

user

Sopel’s user/ident.

name

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

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

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(module_name, capability, arg=None, failure_callback=None, success_callback=None)

Tell Sopel to request a capability when it starts.

Parameters
  • module_name (str) – the module 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 module requires a capability, and another prohibits it, this function will raise an exception in whichever module loads second. An exception will also be raised if the module 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 module 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 modules, a module 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 modules have requested for that capability, it is considered a conflict.

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.

property config

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

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 callables; it will retrieve them by order of priority, and run them. It runs triggered callables in separate threads, unless they are marked otherwise with the sopel.module.thread() decorator.

However, it won’t run triggered callables at all when they can’t be run for blocked nickname or hostname (unless marked “unblockable” with the sopel.module.unblockable() decorator).

See also

To get a list of triggered callables by priority, it uses get_triggered_callables(). This method is also responsible for telling dispatch if the function is blocked or not.

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.

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

get_triggered_callables(priority, pretrigger, blocked)

Get triggered callables by priority.

Parameters
  • priority (str) – priority to retrieve callables

  • pretrigger (PreTrigger) – Sopel pretrigger object

  • blocked (bool) – true if nick or channel is blocked from triggering callables

Returns

a tuple with the callable, the trigger, and if it’s blocked

Return type

tuple

This methods retrieves all triggered callables for this priority level. It yields each function with its trigger object and a boolean flag to tell if this callable is blocked or not.

To be triggered, a callable must match the pretrigger using a regex pattern. Then it must comply with other criteria (if any) such as event, intents, and echo-message filters.

A triggered callable won’t actually be invoked by Sopel if the nickname or hostname is blocked, unless the nickname is an admin or the callable is marked as “unblockable”.

See also

Sopel invokes triggered callables in its dispatch() method. The priority of a callable can be set with the sopel.module.priority() decorator. Other decorators from sopel.module provide additional criteria and conditions.

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 operator in the specified channel for this to work.

New in version 7.0.

log_raw(line, prefix)

Log raw line to the raw log.

Parameters
  • line (str) – the raw line

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

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”, to be displayed in WHOIS responses.

property nick

Sopel’s current Identifier.

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.

This method is an override of asyncore.dispatcher.handle_error(), the asynchat.async_chat being a subclass of asyncore.dispatcher.

on_job_error(scheduler, job, exc)

Called when a job from the Job Scheduler fails.

Parameters
  • scheduler (sopel.tools.jobs.JobScheduler) – the JobScheduler responsible for the errored job

  • job (sopel.tools.jobs.Job) – the Job that errored

  • exc (Exception) – the raised exception

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
  • scheduler (sopel.tools.jobs.JobScheduler) – the JobScheduler that errored

  • exc (Exception) – the raised exception

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

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.module.

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.module.url().

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 reply_to.

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

  • dest (str) – the destination of the reply

  • reply_to (str) – the nickname that the reply will be prepended with

  • 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!”)

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)

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)

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, each no more than 400 bytes. The split is made at the last space character before the 400th byte, or at the 400th byte if no such space 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.

scheduler

Job Scheduler. See sopel.module.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.

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 callable.

Parameters

obj (object) – the callable to unregister

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.module.url().

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)

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 text into at most this many messages if it is too long to fit in one (optional)

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