Commands Overview
Many chat services have commands that users can enter in the same place as messages. These are sometimes called “slash commands” and can be used for all sorts of different things. They can be conversation specific and may by implemented by anything including libpurple, user interfaces, plugins, and protocols.
They are identified by the PurpleCommand:name
property which can be
shared by multiple commands. The PurpleCommand:source
property can be used
to find a specific command or the PurpleCommand:priority
property can be
used to decide which command to execute.
Commands are only available in conversations that have all of the PurpleTags
that are in the PurpleCommand:tags
property of the command. If the
PurpleCommand:tags
is NULL
or empty
the PurpleCommand
will be
available to all conversations.
Implementing Commands
To implement a command, you create a new instance with purple_command_new()
,
add a handler to the PurpleCommand::executed
signal, and add that command
to the default PurpleCommandManager
. The example below shows a simplified
version of creating a command that is only available in channels and adding it
to the default manager.
PurpleCommand *command = NULL;
PurpleCommandManager *manager = NULL;
PurpleTags *tags = NULL;
manager = purple_command_manager_get_default();
/* Create the command and add our signal handler. */
command = purple_command_new("example", "Commands Overview", 0);
g_signal_connect(command, "executed",
G_CALLBACK(example_command_executed), NULL);
/* Get the tags from the command and make it only work on channels. */
tags = purple_command_get_tags(command);
purple_tags_add(tags, "type=channel");
/* Finally add the command to the manager. */
purple_command_manager_add(manager, command);
Handling Commands in a User Interface
User interfaces only need to interact with the default PurpleCommandManager
to handle all commands. User interfaces can define any prefix they want for a
command, but it is recommended to use a /
as that is the common case.
When a user has entered a message that starts with the expected prefix, the
user interface can call purple_command_manager_find_and_execute()
with the
contents of the message with the prefix removed.
If a command is found and executed, the user interface is done and can clear the input field for the next message. If a command is not found, the user interface can then decide to send the message as is or present a warning about an unknown command.
There is also purple_command_manager_get_commands_for_conversation()
which the
user interface can use to present a list of commands to the user as they’re typing.