Skip to content

API reference

Generated from pinhook's own code and type hints. The context, Typed commands and TestBot show them in use.

Writing plugins

command

command(name: str, help: str | None = None, ops: bool = False, restricted: bool = False, denied_msg: str = '', error_msg: str = '', timeout: float | None = None, hide: bool = False, aliases: str | Sequence[str] = ()) -> Callable[[Handler], Handler]

Make an async function a command. Its arguments after ctx come from the message, typed.

Parameters:

Name Type Description Default
name str

the command's name, without a prefix: 'roll' answers to !roll.

required
help str | None

shown in !help. Defaults to the first line of the function's docstring.

None
ops bool

if True, only bot operators can run it.

False
restricted bool

if True, only ops and the people they give access to can run it.

False
denied_msg str

what anyone who can't run it is told when they try. Empty means no reply.

''
error_msg str

said in chat if the command fails. Empty means the failure is only logged.

''
timeout float | None

seconds before the bot stops waiting for it, instead of the bot's default.

None
hide bool

if True, leave it out of !help.

False
aliases str | Sequence[str]

other names that run it, like ['r', 'dice'] for roll.

()

on

on(event: str, timeout: float | None = None, name: str | None = None) -> Callable[[Handler], Handler]

Make an async function handle an event, like 'join'. It gets a ctx about the event.

Parameters:

Name Type Description Default
event str

one of message, addressed, notice, join, part, kick, quit, nick, topic, invite, mode, netsplit, netjoin, connected or disconnected. addressed is a message that starts with the bot's nick, with the rest in ctx.arg. While a plugin handles it, a command after the nick goes to that plugin, so only commands written with their prefix run. A netsplit or netjoin is one event for everyone who left or came back, with their nicks in ctx.nicks.

required
timeout float | None

seconds before the bot stops waiting for it, instead of the bot's default.

None
name str | None

what !enable and !disable call it, and !help lists a message handler as. Defaults to the function's name.

None

every

every(seconds: float = 0, minutes: float = 0, hours: float = 0, timeout: float | None = None, name: str | None = None) -> Callable[[Handler], Handler]

Make an async function run on a timer, first one interval after its plugin loads.

It gets a ctx with no channel or sender, so it answers with ctx.send(target, text). It only runs while the bot is connected, and a run still going when the next one is due is left to finish instead of starting another.

Parameters:

Name Type Description Default
seconds float

how often, in seconds, added to minutes and hours.

0
minutes float

how often, in minutes, like every(minutes=30).

0
hours float

how often, in hours.

0
timeout float | None

seconds before the bot stops waiting for it, instead of the bot's default.

None
name str | None

what !enable and !disable call it. Defaults to the function's name.

None

Plugin

A plugin written as a class, whose methods are its commands and event handlers.

The bot makes one instance of each Plugin class in a plugin file. setup runs when it loads, with previous as None. On !reload the bot makes a new instance and calls its setup with the old one as previous, so it can copy across any state it wants to keep. Then it calls the old instance's teardown, so take anything you keep away from previous, like self.conn, previous.conn = previous.conn, None. teardown also runs when the plugin is removed and when the bot quits.

self.bot is the bot, as handlers see it in ctx.bot, and self.config the plugin's plugin_config section, as ctx.config, both from setup on. !reload reads plugin_config again, so a new instance gets the new settings.

The bot is read only to a plugin, apart from the plugin's own commands: set_recipes adds recipes as commands of its own, and allow gives someone access to one of them.

setup

setup(previous: Any) -> None

Called when the plugin loads. previous is the old instance on !reload, or None.

teardown

teardown() -> None

Called when this instance is replaced or removed, or the bot quits.

set_recipes

set_recipes(recipes: Sequence[Recipe]) -> list[str]

Add recipes as commands of this plugin, in place of the ones it added before.

They're added after the recipe folder's, so a name that's taken is left out, and access and !disable treat them as this plugin's commands. Works from setup on. Returns the problems, as text.

allow

allow(command: str, who: Any) -> bool

Give who, a Source, access to one of this plugin's restricted commands, as an op's !allow does: by account when they're logged in, by user and host when not.

Works from setup on, and each grant is logged as an audit line. Returns False if they had access already, or the command is open to everyone. Raises ValueError for a command that isn't this plugin's, or is ops only.

The context

Context

One message or event, as a plugin sees it, and how to answer it.

Attributes:

Name Type Description
event

what happened: 'message', 'notice', 'join', 'part', 'kick', 'quit', 'nick', 'topic', 'invite', 'mode', 'netsplit', 'netjoin', 'connected' or 'disconnected'.

nick, (user, host, account)

who sent it, or who did it. account is their services account, or None when the server doesn't say.

source Source | None

the same four as a Source, or None when nobody did it, like a timer.

channel str | None

where to answer: the channel, or the sender for a private message. None when there's nowhere, like a nick change or a quit.

is_private

True for a private message to the bot.

is_op

True if the sender is one of the bot's ops.

is_chanop

True if the sender is a channel operator (+o, or more) in this channel.

is_bot

True if the server marks the sender as a bot.

addressed

True when the message started with the bot's nick, like "pinhook: hi".

text

the whole message, a part, kick or quit's reason, or a new topic.

kind

a message's 'privmsg', 'action' or 'notice'.

kicked

who was kicked, for a kick.

invited

who was invited, for an invite: the bot, or with invite-notify, anyone invited to a channel the bot is in.

new_nick

the new nick, for a nick change. nick is the old one.

modes

for a mode change, like ['+o', 'mal'].

nicks

everyone who left in a netsplit, or came back in a netjoin. text holds the two servers.

command

the command's name, without a prefix, for a command. None otherwise.

arg

everything after the command word, for a command. For an @on('addressed') handler, the message after the bot's nick.

time

when the message was sent, timezone-aware. The server's time when it says.

tags

the message's IRCv3 tags.

msgid

the message's ID, when the server gives one.

store dict[str, Any]

the plugin's saved data, a dict kept between restarts.

config

the plugin's settings from plugin_config, read only.

bot BotInfo

the bot's nick and channels, read only.

logger

the bot's logger.

reply async

reply(text: Text, thread: bool = False, private: bool = False, prefix: str = '') -> None

Answer where the message came from: the channel, or the sender if private.

Parameters:

Name Type Description Default
text Text

what to say. Each line is sent as its own message.

required
thread bool

answer this message in particular. Clients that show threads show it under the message, and elsewhere it starts with the sender's nick.

False
private bool

answer the sender in a private message instead, which their client can show with the channel it's about.

False
prefix str

text to start every line with, like '[bot] '. A line too long for the network is split, and each part starts with it too.

''

send async

send(target: str, text: Text, prefix: str = '') -> None

Send text to another channel or nick, with prefix at the start of every line.

action async

action(text: Text) -> None
action(target: str, text: Text) -> None
action(*args: Any) -> None

action(text) answers with a /me, action(target, text) sends one somewhere else.

notice async

notice(text: Text) -> None
notice(target: str, text: Text) -> None
notice(*args: Any) -> None

notice(text) sends the sender a notice, notice(target, text) sends one to anyone.

Where the network has no notices from bots, like Twitch, a notice to a channel is sent as a message, and one to a person isn't sent: the bot logs a warning, once per plugin. ctx.supports('notice') says which.

typing async

typing() -> AsyncIterator[None]

Show the bot as typing while a slow command works:

async with ctx.typing():
    forecast = await fetch_forecast(city)
await ctx.reply(forecast)

Does nothing where the network can't show it.

members

members(channel: str | None = None) -> tuple[Member, ...]

Who is in channel, this one by default, as Members: each one's nick, account, modes and whether they're a bot. From member tracking, so it never waits on the server. Empty for a private message.

member

member(nick: str, channel: str | None = None) -> Member | None

nick's Member in channel, this one by default, or None if they aren't in it.

whois async

whois(nick: str) -> Whois | None

Ask the server about nick, and return a Whois, or None if there's no one by that name. This waits for the server, unlike members().

history

history(limit: int | None = None) -> tuple[Entry, ...]

This channel's recent messages, oldest first, as history Entries: nick, text, kind, time, msgid and own, True for the bot's. Empty unless the history option lists the channel. limit keeps only that many of the newest.

commands

commands() -> list[CommandInfo]

The commands the sender can trigger here, from the command listing: each one's name, help, typed arguments and access level. Empty when nobody sent this.

run async

run(command: str, arg: str = '') -> RunResult

Run a command as the sender, here, with their access, and return how it went, with what it said where it ran instead of saying it. command is its name, like 'roll', and arg the text after it.

supports

supports(feature: str) -> bool

True if the network supports feature, like 'account-tag'.

BotInfo

What a plugin can see of the bot: ctx.bot in a handler, and self.bot in a Plugin class, from setup on. Read only.

nick property

nick: str

The bot's nick right now.

channels property

channels: tuple[str, ...]

The channels the bot is in.

logger property

logger: Logger

The bot's logger, as ctx.logger.

prefix property

prefix: str

The command prefix, like '!'. The first one, when there are several.

data_dir property

data_dir: str

The bot's data folder, where a plugin can keep files of its own.

split

split(target: str, text: Text, prefix: str = '') -> list[str]

The lines text would go to target as: a line for each of its lines, and more where one is too long for the network, each without prefix, which every line starts with.

is_op

is_op(who: Any) -> bool

True if who, a Source or a Member, is one of the bot's ops.

matches

matches(entry: str, who: Any) -> bool

True if an entry like '$a:mal', a hostmask or a nick names who, a Source or a Member, the way ops, bans and grants are matched.

keeps_history

keeps_history(channel: str) -> bool

True if the history option lists channel, so ctx.history() is kept for it.

Member dataclass

Someone in a channel, as member tracking knows them.

modes are the channel modes they have there, like {'o'} for a channel operator. account is None when they're not logged in or the server doesn't say. is_bot is True when the server marks them as a bot.

is_chanop property

is_chanop: bool

True for a channel operator: +o, or the +a and +q some servers have above it.

is_voiced property

is_voiced: bool

True for +v, or any mode above it, like halfop or op.

Whois dataclass

What the server says about someone, from await ctx.whois(nick).

channels are the ones the server shows, which leaves out secret channels the bot isn't in. away is their away message, or None. idle is seconds since they last spoke, when the server says.

Entry dataclass

One message in a channel's history.

kind is 'privmsg', 'action' or 'notice'. own is True for the bot's own lines. time is when it was sent, the server's time when it says.

Saved data and settings

Store

Bases: dict[str, Any]

A plugin's saved data: a dict that's kept between messages, reloads and restarts.

Plugins get theirs as msg.store. The bot saves it after each plugin call if anything in it changed, nested changes included.

Values have to be things JSON can hold: strings, numbers, lists, dicts, True, False and None. Keys are saved as strings.

PluginConfig

Bases: Mapping[str, Any]

A plugin's settings from plugin_config in the bot's config. Read only.

Plugins get theirs as msg.config: their own section, keyed by plugin file name, and msg.config.shared for the section every plugin can read.

Recipes

step

step(name: str, fields: dict[str, str], required: Iterable[str] = (), saves: str | None = None, one_of: Iterable[Iterable[str]] = (), check: CheckFunc | None = None) -> Callable[[StepFunc], StepFunc]

Register a step type, for plugins. The function runs it, with a Run, which fills in templates and runs commands as the person who started the recipe, and the step's fields, templates parsed.

@recipes.step('weather', {'weather': 'template', 'save': 'name'}, saves='save')
async def weather(run, fields):
    run.save(fields.get('save'), await forecast(run.render(fields['weather'])))

Parameters:

Name Type Description Default
name str

the step's name, and its key in a recipe file.

required
fields dict[str, str]

each field's kind, the step's own key included.

required
required Iterable[str]

fields it can't do without. Its own key always is.

()
saves str | None

the field naming the variable it saves to, so later steps can use it.

None
one_of Iterable[Iterable[str]]

sets of fields of which exactly one must be given.

()
check CheckFunc | None

a function that looks a step's fields over when its recipe loads, after their kinds are checked, and returns what's wrong with them, or None. A recipe with a problem doesn't load.

None

template_filter

template_filter(name: str) -> Callable[[FilterFunc], FilterFunc]

Register a filter, for plugins: a function taking the value and the text after a colon, like 'everyone' in {arg|default:everyone}, or None.

@recipes.template_filter('shout')
def shout(value, arg):
    return text(value).upper() + '!'

Bots

load_bot

load_bot(path: str, conf_format: str | None = None, warn: Callable[[str], Any] | None = None, **overrides: Any) -> Bot

The bot the config at path describes, ready to start(), the way pinhook run makes it.

secrets.env beside the config is read first. Relative paths start from the config's folder, and !reload reads plugin_config and access from the file again.

Parameters:

Name Type Description Default
path str

the config file, YAML or JSON.

required
conf_format str | None

'yaml' or 'json', when the file's extension doesn't say.

None
warn Callable[[str], Any] | None

called with each warning about secrets.env. They're logged by default.

None
**overrides Any

options set over the config's, like log_level='debug'.

{}

ConfigError

Bases: ValueError

A config, or secrets.env, with a mistake, and what it is.

Bot

An IRC bot that loads plugins from a folder and runs them.

Parameters:

Name Type Description Default
channels

channels to join once connected.

required
nickname

the bot's nick.

required
server

the server to connect to.

required
**kwargs

any of the bot's options, like port, ssl_required or ops. See https://archangelic.github.io/pinhook/latest/options/ config_dir is the folder relative paths are in, including bot_dir's: the config file's folder when pinhook run starts the bot, and the working directory by default.

{}

Call start() to connect and run until the bot quits.

start

start()

Connect, and run until the bot quits.

quit

quit(reason='')

Stop taking messages, send what's waiting, and quit with reason.

commands

commands(who=None, channel=None)

Every command, as CommandInfo: name, help, typed arguments, plugin, access level and whether it's hidden, sorted by name. Structured data for code, like a tool list, where !help is for people.

Parameters:

Name Type Description Default
who

a Source, to list only what that person can trigger.

None
channel

where they'd trigger it, for chanops and voiced, or None if private.

None

run_as async

run_as(who, command, arg='', channel=None, capture=True)

Run a command as someone, with their access, the way a recipe step or a tool call does, and say how it went.

Parameters:

Name Type Description Default
who

a Source, the person it runs as. Their bans, grants and denies apply.

required
command

the command's name, or how it's typed, like 'roll' or '!roll'.

required
arg

the text after the command.

''
channel

the channel it runs in, or None for a private message.

None
capture

True to return what the command says where it runs, instead of sending it. Captured lines never go to the output queue. A private reply or a notice still goes to whoever it's for.

True

Returns a RunResult.

store

store(name)

The saved data for the plugin file called name, the same dict as its msg.store.

TwitchBot

Bases: Bot

A bot for Twitch chat, connecting to irc.chat.twitch.tv over ssl.

Parameters:

Name Type Description Default
nickname

the bot account's name.

required
channel

the channel to join, like '#channel'.

required
token

the bot account's oauth token, without 'oauth:'.

required
**kwargs

any of the options TwitchBot takes, see https://archangelic.github.io/pinhook/latest/twitch/

{}

RunResult dataclass

How running a command as someone went, from bot.run_as.

status is 'ran', 'refused' (no access, banned, or switched off here), 'busy' (their last run of it is still going), 'failed' (bad arguments, an error or a timeout) or 'unknown' (no such command). lines are what it said, when captured. error says what went wrong, or is None.

CommandInfo dataclass

A command, as the command listing gives it: everything needed to show it, or to build a tool definition from it.

Attributes:

Name Type Description
name str

the name, without a prefix, like 'roll'.

label str

how it's typed, like '!roll'.

help str

its one-line help.

usage str

its usage line, like roll [dice=1d6] [times=1].

args tuple[Arg, ...]

its arguments. A 1.x command has one, arg, the text after the command.

plugin str

the plugin file it comes from.

level str

its access level, 'open', 'restricted' or 'ops'.

hidden bool

True if it's left out of !help.

typed bool

False for a 1.x command, whose arguments aren't typed.

aliases tuple[str, ...]

its other names, without a prefix.

Testing

TestBot

Bases: Bot

A Bot that never connects, for testing plugins.

Plugins, ops, bans and the built-in commands all work as they do on a real server. What the bot sends is recorded in sent instead, and a plugin that raises an exception fails the test with a PluginError. Stores stay in memory, and data_dir is a new folder, removed with the bot, unless the options give one.

say

say(text: str, nick: str = 'tester', channel: str | None = None, **who: str | None) -> list[str]

Send a message to a channel as nick, and return the bot's replies there.

who can be user, host and account, to test ops and bans by hostmask or account.

action

action(text: str, nick: str = 'tester', channel: str | None = None, **who: str | None) -> list[str]

Send a /me action to a channel as nick, and return the bot's replies there.

private

private(text: str, nick: str = 'tester', **who: str | None) -> list[str]

Send a private message to the bot as nick, and return the bot's replies to them.

event

event(kind: str, nick: str = 'tester', channel: str | None = None, text: str = '', user: str | None = None, host: str = 'example.com', account: str | None = None, **data: Any) -> list[Sent]

Something other than a message happens, and returns what the bot sent, as Sent.

kind is join, part, kick, quit, nick, topic, invite, mode, netsplit, netjoin or notice. channel is the bot's first channel unless given, or none for nick, quit, netsplit and netjoin. data is the rest: kicked='troll' for a kick, new_nick='mal_' for a nick change, modes=['+o', 'mal'] for a mode change, which gives mal +o in the channel the way a real one would, invited='ana' for an invite of someone other than the bot, and nicks=['ana', 'bob'] for a netsplit or netjoin, with the two servers as text. A notice's channel can be the bot's nick.

tick

tick(seconds: float) -> list[Sent]

Let seconds pass, run any @every timers that come due, and return what the bot sent.

Time only moves when you call this, so a timer every 30 minutes runs on bot.tick(1800).

sent_to

sent_to(target: str) -> list[str]

Every message and action the bot has sent to target, like a nick for !help.

PluginError

Bases: Exception

A plugin raised an exception, or returned something it shouldn't.