Plugin API#

With from slidge import * you get access to these classes. At the very minimum, BaseGateway and BaseSession must be subclassed for a plugin to work.

The main slidge entrypoint will automatically detect which classes have been subclassed and use them automagically. Just subclass await, and launch your plugin with slidge --legacy-network=your.importable.plugin.

class slidge.BaseGateway[source]#

Must be subclassed by a plugin to set up various aspects of the XMPP component behaviour, such as its display name or its registration process.

On slidge launch, a singleton is instantiated, and it will be made available to public classes such LegacyContact or BaseSession as the .xmpp attribute. Since it inherits from slixmpp.componentxmpp.ComponentXMPP, this gives you a hand on low-level XMPP interactions via slixmpp plugins, e.g.:

self.send_presence(
    pfrom="somebody@component.example.com",
    pto="someonwelse@anotherexample.com",
)

However, you should not need to do so often since the classes of the plugin API provides higher level abstractions around most commonly needed use-cases, such as sending messages, or displaying a custom status.

CHAT_COMMANDS: dict[str, str] = {}#

Keys of this dict can be used to trigger a command by a simple chat message to the gateway component. Extra words after the key are passed as *args to the handler. Values of the dict are strings, and handlers are resolved using getattr() on the BaseGateway instance.

Handlers are coroutines with following signature:

The original slixmpp.stanza.Message is also passed to the handler as the msg kwarg. If the command comes from a registered gateway user, its session attribute is also passed to the handler.

COMPONENT_AVATAR: Optional[Union[bytes, str, Path]] = None#

Path, bytes or URL used by the component as an avatar.

COMPONENT_NAME: str = NotImplemented#

Name of the component, as seen in service discovery by XMPP clients

COMPONENT_TYPE: Optional[str] = ''#

Type of the gateway, should ideally follow https://xmpp.org/registrar/disco-categories.html

REGISTRATION_FIELDS: Iterable[FormField] = [FormField(var='username', label='User name', required=True, private=False, type='text-single', value='', options=None), FormField(var='password', label='Password', required=True, private=True, type='text-private', value='', options=None)]#

Iterable of fields presented to the gateway user when registering using XEP-0077 extended by XEP-0004.

REGISTRATION_INSTRUCTIONS: str = 'Enter your credentials'#

The text presented to a user that wants to register (or modify) their legacy account configuration.

REGISTRATION_MULTISTEP = False#

If the network requires a multistep registration, set this to True to prevent name squatting. Registrations that did not successfully login withing SLIDGE_PARTIAL_REGISTRATION_TIMEOUT seconds will automatically be removed from the user_store.

ROSTER_GROUP: str = 'slidge'#

Roster entries added by the plugin in the user’s roster will be part of the group specified here.

SEARCH_FIELDS: Sequence[FormField] = [FormField(var='first', label='First name', required=True, private=False, type='text-single', value='', options=None), FormField(var='last', label='Last name', required=True, private=False, type='text-single', value='', options=None), FormField(var='phone', label='Last name', required=False, private=False, type='text-single', value='', options=None)]#

Fields used for searching items via the component, through XEP-0055 (jabber search). A common use case is to allow users to search for legacy contacts by something else than their usernames, eg their phone number.

Plugins should implement search by overriding BaseSession.search(), effectively restricting search to registered users by default.

SEARCH_INSTRUCTIONS: str = ''#

Instructions of the search form.

SEARCH_TITLE: str = 'Search for legacy contacts'#

Title of the search form.

WELCOME_MESSAGE = "Thank you for registering. Type 'help' to list the available commands, or just start messaging away!"#

A welcome message displayed to users on registration. This is useful notably for clients that don’t consider component JIDs as a valid recipient in their UI, yet still open a functional chat window on incoming messages from components.

add_adhoc_commands()#

Override this if you want to provide custom adhoc commands (XEP-0050) for your plugin, using slixmpp.plugins.xep_0050.XEP_0050

Basic example:

config(argv)#

Override this to access CLI args to configure the slidge plugin

Parameters

argv (list[str]) – CLI args that were not parsed by the slidge main entrypoint parser

slidge.__main__.get_parser()

exception(exception)#

Called when a task created by slixmpp’s internal (eg, on slix events) raises an Exception.

Stop the event loop and exit on unhandled exception.

The default :class:slixmpp.basexmpp.BaseXMPP` behaviour is just to log the exception, but we want to avoid undefined behaviour.

Parameters

exception (Exception) – An unhandled Exception object.

async input(jid, text=None, mtype='chat', **msg_kwargs)#

Request arbitrary user input using a simple chat message, and await the result.

You shouldn’t need to call directly bust instead user BaseSession.input() to directly target a user.

NB: When using this, the next message that the user sent to the component will not be transmitted to BaseGateway.on_gateway_message(), but rather intercepted. Await the coroutine to get its content.

Parameters
  • jid (JID) – The JID we want input from

  • text – A prompt to display for the user

  • mtype (Literal['chat', 'error', 'groupchat', 'headline', 'normal']) – Message type

Returns

The user’s reply

Return type

str

async static on_gateway_message(msg, session=None)#

Called when the gateway component receives a direct gateway message.

Can be used to implement bot like commands, especially in conjunction with BaseGateway.input()

Parameters
  • msg (Message) –

  • session (Optional[SessionType]) – If the message comes from a registered gateway user, their :.BaseSession:

async send_file(filename, **msg_kwargs)#

Upload a file using XEP-0363 and send the link as out of band (XEP-0066) content in a message.

Parameters
  • filename (str) –

  • msg_kwargs

Returns

async send_qr(text, **msg_kwargs)#

Sends a QR Code to a JID

Parameters
  • text (str) – The text that will be converted to a QR Code

  • msg_kwargs – Optional additional arguments to pass to BaseGateway.send_file(), such as the recipient of the QR code.

shutdown()#

Called by the slidge entrypoint on normal exit.

Sends offline presences from all contacts of all user sessions and from the gateway component itself. No need to call this manually, slidge.__main__.main() should take care of it.

async unregister(user)#

Optionally override this if you need to clean additional stuff after a user has been removed from the permanent user_store.

Parameters

user (GatewayUser) –

Returns

async validate(user_jid, registration_form)#

Validate a registration form from a user.

Since XEP-0077 is pretty limited in terms of validation, it is OK to validate anything that looks good here and continue the legacy auth process via direct messages to the user (using BaseGateway.input() for instance)

Parameters
class slidge.BaseSession(user)[source]#

Represents a gateway user logged in to the network and performing actions.

Will be instantiated automatically when a user sends an online presence to the gateway component, as per XEP-0100.

Must be subclassed for a functional slidge plugin.

Parameters

user (GatewayUser) –

async active(c)#

Triggered when the user sends an ‘active’ chat state to the legacy network (XEP-0085)

Parameters

c (LegacyContactType) – Recipient of the active chat state

async composing(c)#

Triggered when the user starts typing in the window of a legacy contact (XEP-0085)

Parameters

c (LegacyContactType) –

async correct(text, legacy_msg_id, c)#

Triggered when the user corrected a message using XEP-0308

This is only possible if a valid legacy_msg_id was passed when transmitting a message from a contact to the user in LegacyContact.send_text() or slidge.LegacyContact.send_file().

Parameters
  • text (str) –

  • legacy_msg_id (Any) –

  • c (LegacyContactType) –

Return type

Optional[Union[str, int]]

async displayed(legacy_msg_id, c)#

Triggered when the user reads a message sent by a legacy contact. (XEP-0333)

This is only possible if a valid legacy_msg_id was passed when transmitting a message from a contact to the user in LegacyContact.sent_text() or slidge.LegacyContact.send_file().

Parameters
classmethod from_stanza(s)#

Get a user’s LegacySession using the “from” field of a stanza

Meant to be called from BaseGateway only.

Parameters

s

Returns

Return type

T

async inactive(c)#

Triggered when the user sends an ‘inactive’ chat state to the legacy network (XEP-0085)

Parameters

c (LegacyContactType) –

async input(text, **msg_kwargs)#

Request user input via direct messages.

Wraps call to BaseSession.input()

Parameters
  • text (str) – The prompt to send to the user

  • msg_kwargs – Extra attributes

Returns

static legacy_msg_id_to_xmpp_msg_id(legacy_msg_id)#

Convert a legacy msg ID to a valid XMPP msg ID. Needed for read marks and message corrections.

The default implementation just converts the legacy ID to a str, but this should be overridden in case some characters needs to be escaped, or to add some additional, legacy network-specific logic.

Parameters

legacy_msg_id (Any) –

Returns

Should return a string that is usable as an XMPP stanza ID

Return type

str

async login()#

Login the gateway user to the legacy network.

Triggered when the gateway start and on user registration. It is recommended that this function returns once the user is logged in, so if you need to await forever (for instance to listen to incoming events), it’s a good idea to wrap your listener in an asyncio.Task.

Returns

Optionally, a text to use as the gateway status, e.g., “Connected as ‘dude@legacy.network’”

Return type

Optional[str]

async logout()#

Logout the gateway user from the legacy network.

Called on user unregistration and gateway shutdown.

async paused(c)#

Triggered when the user pauses typing in the window of a legacy contact (XEP-0085)

Parameters

c (LegacyContactType) –

re_login()#

Logout then re-login

No reason to override this

async react(legacy_msg_id, emojis, c)#

Triggered when the user sends message reactions (XEP-0444).

Parameters
  • legacy_msg_id (Any) – ID of the message the user reacts to

  • emojis (list[str]) – Unicode characters representing reactions to the message legacy_msg_id. An empty string means “no reaction”, ie, remove all reactions if any were present before

  • c (LegacyContactType) – Contact the reaction refers to

async retract(legacy_msg_id, c)#

Triggered when the user retracts (XEP-0424) a message.

Parameters
  • legacy_msg_id (Any) – Legacy ID of the retracted message

  • c (LegacyContactType) – The contact this retraction refers to

async search(form_values)#

Triggered when the user uses Jabber Search (XEP-0055) on the component

Form values is a dict in which keys are defined in BaseGateway.SEARCH_FIELDS

Parameters

form_values (dict[str, str]) – search query, defined for a specific plugin by overriding in BaseGateway.SEARCH_FIELDS

Returns

Return type

Optional[SearchResult]

async send_file(u, c, *, reply_to_msg_id=None)#

Triggered when the user has sends a file using HTTP Upload (XEP-0363)

Parameters
  • u (str) – URL of the file

  • c (LegacyContactType) – Recipient of the file

  • reply_to_msg_id (Optional[Union[str, int]]) –

Returns

An ID of some sort that can be used later to ack and mark the message as read by the user

Return type

Optional[Union[str, int]]

send_gateway_message(text, **msg_kwargs)#

Send a message from the gateway component to the user.

Can be used to indicate the user session status, ie “SMS code required”, “connected”, …

Parameters

text – A text

send_gateway_status(status=None, show=typing.Optional[typing.Literal['away', 'chat', 'dnd', 'xa']], **kwargs)#

Send a presence from the gateway to the user.

Can be used to indicate the user session status, ie “SMS code required”, “connected”, …

Parameters
  • status (Optional[str]) – A status message

  • show – Presence stanza ‘show’ element. I suggest using “dnd” to show that the gateway is not fully functional

async send_qr(text)#

Sends a QR code generated from ‘text’ via HTTP Upload and send the URL to self.user

Parameters

text (str) – Text to encode as a QR code

async send_text(t, c, *, reply_to_msg_id=None)#

Triggered when the user sends a text message from xmpp to a bridged contact, e.g. to translated_user_name@slidge.example.com.

Override this and implement sending a message to the legacy network in this method.

Parameters
  • t (str) – Content of the message

  • c (LegacyContactType) – Recipient of the message

  • reply_to_msg_id (Optional[Union[str, int]]) –

Returns

An ID of some sort that can be used later to ack and mark the message as read by the user

Return type

Optional[Union[str, int]]

sent: BiDict[Union[str, int], str]#

Since we cannot set the XMPP ID of messages sent by XMPP clients, we need to keep a mapping between XMPP IDs and legacy message IDs if we want to further refer to a message that was sent by the user. This also applies to ‘carboned’ messages, ie, messages sent by the user from the official client of a legacy network.

xmpp: GatewayType#

The gateway instance singleton. Use it for low-level XMPP calls or custom methods that are not session-specific.

static xmpp_msg_id_to_legacy_msg_id(i)#

Convert a legacy XMPP ID to a valid XMPP msg ID. Needed for read marks and message corrections.

The default implementation just converts the legacy ID to a str, but this should be overridden in case some characters needs to be escaped, or to add some additional, legacy network-specific logic.

The default implementation is an identity function

Parameters

i (str) – The XMPP stanza ID

Returns

An ID that can be used to identify a message on the legacy network

Return type

Union[str, int]

You may get away with the generic versions of these twos, but depending on how users are identified on a legacy network, you might need to subclass the following classes.

Even if you use their generic implementations, you most likely will need to call the methods they provide.

class slidge.LegacyRoster(session)[source]#

Virtual roster of a gateway user, that allows to represent all of their contacts as singleton instances (if used properly and not too bugged).

Every BaseSession instance will have its own LegacyRoster instance accessible via the BaseSession.contacts attribute.

Typically, you will mostly use the LegacyRoster.by_legacy_id() function to retrieve a contact instance.

You might need to override LegacyRoster.legacy_id_to_jid_username() and/or LegacyRoster.jid_username_to_legacy_id() to incorporate some custom logic if you need some characters when translation JID user parts and legacy IDs.

Parameters

session (SessionType) –

by_jid(contact_jid)#

Retrieve a contact by their JID

If the contact was not instantiated before, it will be created using slidge.LegacyRoster.jid_username_to_legacy_id() to infer their legacy user ID.

Parameters

contact_jid (JID) –

Returns

Return type

LegacyContactType

by_legacy_id(legacy_id)#

Retrieve a contact by their legacy_id

If the contact was not instantiated before, it will be created using slidge.LegacyRoster.legacy_id_to_jid_username() to infer their legacy user ID.

Parameters

legacy_id (Any) –

Returns

Return type

LegacyContactType

by_stanza(s)#

Retrieve a contact by the destination of a stanza

See slidge.Roster.by_legacy_id() for more info.

Parameters

s

Returns

Return type

LegacyContactType

static jid_username_to_legacy_id(jid_username)#

Convert a JID user part to a legacy ID.

Should be overridden in case legacy IDs are not strings, or more generally for any case where the username part of a JID (unescaped with to the mapping defined by XEP-0106) is not enough to identify a contact on the legacy network.

Default implementation is an identity operation

Parameters

jid_username (str) – User part of a JID, ie “user” in “user@example.com

Returns

An identifier for the user on the legacy network.

Return type

Union[str, int]

static legacy_id_to_jid_username(legacy_id)#

Convert a legacy ID to a valid ‘user’ part of a JID

Should be overridden for cases where the str conversion of the legacy_id is not enough, e.g., if it is case-sensitive or contains forbidden characters not covered by XEP-0106.

Parameters

legacy_id (Any) –

Return type

str

class slidge.LegacyContact(session, legacy_id, jid_username)[source]#

This class centralizes actions in relation to a specific legacy contact.

You shouldn’t create instances of contacts manually, but rather rely on LegacyRoster.by_legacy_id() to ensure that contact instances are singletons. The LegacyRoster instance of a session is accessible through the BaseSession.contacts attribute.

Typically, your plugin should have methods hook to the legacy events and call appropriate methods here to transmit the “legacy action” to the xmpp user. This should look like this:

Parameters
  • session (SessionType) – The session this contact is part of

  • legacy_id (Union[str, int]) – The contact’s legacy ID

  • jid_username (str) – User part of this contact’s ‘puppet’ JID. NB: case-insensitive, and some special characters are not allowed

CLIENT_TYPE = 'pc'#

https://xmpp.org/registrar/disco-categories.html#client

REPLIES = True#

A list of features advertised through service discovery and client capabilities.

RESOURCE: str = 'slidge'#

A full JID, including a resource part is required for chat states (and maybe other stuff) to work properly. This is the name of the resource the contacts will use.

ack(legacy_msg_id)#

Send an “acknowledged” message marker (XEP-0333) from this contact to the user.

Parameters

legacy_msg_id (Union[str, int]) – The message this marker refers to

active()#

Send an “active” chat state (XEP-0085) from this contact to the user.

async add_to_roster()#

Add this contact to the user roster using XEP-0356

property avatar#

An image that represents this contact

away(status=None, *, last_seen=None)#

Send an “away” presence from this contact to the user.

This is a global status, as opposed to LegacyContact.inactive() which concerns a specific conversation, ie a specific “chat window”

Parameters
busy(status=None, *, last_seen=None)#

Send a “busy” presence from this contact to the user,

Parameters
carbon(body, legacy_id=None, when=None, *, reply_to_msg_id=None)#

Call this when the user sends a message to a legacy network contact.

This synchronizes the outgoing message history on the XMPP side, using XEP-0356 to impersonate the XMPP user and send a message from the user to the contact. Thw XMPP server should in turn send carbons (XEP-0280) to online XMPP clients +/- write the message in server-side archives (XEP-0313), depending on the user’s and the server’s archiving policy.

Parameters
carbon_correct(legacy_msg_id, text, when=None, *, reply_to_msg_id=None)#

Call this when the user corrects their own (last) message from an official client

Parameters
carbon_react(legacy_msg_id, reactions=(), when=None)#

Call this to modify the user’s own reactions (XEP-0444) about a message.

Can be called when the user reacts from the official client, or to modify a user’s reaction when the legacy network has constraints about acceptable reactions.

Parameters
carbon_read(legacy_msg_id, when=None)#

Synchronize user read state from official clients.

Parameters
carbon_retract(legacy_msg_id, when=None)#

Call this when the user calls retracts (XEP-0424) a message from an official client

Parameters
Returns

composing()#

Send a “composing” (ie “typing notification”) chat state (XEP-0085) from this contact to the user.

correct(legacy_msg_id, new_text)#

Call this when a legacy contact has modified his last message content.

Uses last message correction (XEP-0308)

Parameters
  • legacy_msg_id (Any) – Legacy message ID this correction refers to

  • new_text (str) – The new text

displayed(legacy_msg_id)#

Send a “displayed” message marker (XEP-0333) from this contact to the user.

Parameters

legacy_msg_id (Union[str, int]) – The message this marker refers to

extended_away(status=None, *, last_seen=None)#

Send an “extended away” presence from this contact to the user.

This is a global status, as opposed to LegacyContact.inactive() which concerns a specific conversation, ie a specific “chat window”

Parameters
gone()#

Send an “inactive” (ie “typing paused notification”) chat state (XEP-0085) from this contact to the user.

inactive()#

Send an “inactive” (ie “typing paused notification”) chat state (XEP-0085) from this contact to the user.

property jid: JID#

Full JID (including the ‘puppet’ resource) of the contact

Return type

slixmpp.JID

property name#

Friendly name of the contact, as it should appear in the user’s roster

offline(*, last_seen=None)#

Send an “offline” presence from this contact to the user.

Parameters

last_seen (Optional[datetime]) – For XEP-0319

online(status=None, *, last_seen=None)#

Send an “online” presence from this contact to the user.

Parameters
paused()#

Send a “paused” (ie “typing paused notification”) chat state (XEP-0085) from this contact to the user.

react(legacy_msg_id, emojis=())#

Call this when a legacy contact reacts to a message

Parameters
  • legacy_msg_id (Union[str, int]) – The message which the reaction refers to.

  • emojis (Iterable[str]) – A iterable of emojis used as reactions

Returns

received(legacy_msg_id)#

Send a “received” message marker (XEP-0333) and a “message delivery receipt” (XEP-0184) from this contact to the user

Parameters

legacy_msg_id (Union[str, int]) – The message this marker refers to

retract(legacy_msg_id)#

Call this when a legacy contact retracts (XEP-0424) a message

Parameters

legacy_msg_id (Union[str, int]) – Legacy ID of the message to delete

async send_file(filename, content_type=None, input_file=None, url=None, *, legacy_msg_id=None, reply_to_msg_id=None, when=None, caption=None)#

Send a file using HTTP upload (XEP-0363)

Parameters
  • filename (Union[Path, str]) – Filename to use or location on disk to the file to upload

  • content_type (Optional[str]) – MIME type, inferred from filename if not given

  • input_file (Optional[IO[bytes]]) – Optionally, a file like object instead of a file on disk. filename will still be used to give the uploaded file a name

  • legacy_msg_id (Optional[Union[str, int]]) – If you want to be able to transport read markers from the gateway user to the legacy network, specify this

  • url (Optional[str]) – Optionally, a URL of a file that slidge will download and upload to the default file upload service on the xmpp server it’s running on. url and input_file are mutually exclusive.

  • reply_to_msg_id (Optional[Union[str, int]]) –

  • when (Optional[datetime]) – when the file was sent, for a “delay” tag (XEP-0203)

  • caption (Optional[str]) – an optional text that is linked to the file

Returns

The msg stanza that was sent

Return type

Message

send_text(body='', *, chat_state='active', legacy_msg_id=None, reply_to_msg_id=None, when=None)#

Transmit a message from the contact to the user

Parameters
  • body (str) – Context of the message

  • chat_state (Optional[str]) – By default, will send an “active” chat state (XEP-0085) along with the message. Set this to None if this is not desired.

  • legacy_msg_id (Optional[Union[str, int]]) – If you want to be able to transport read markers from the gateway user to the legacy network, specify this

  • reply_to_msg_id (Optional[Union[str, int]]) –

  • when (Optional[datetime]) – when the message was sent, for a “delay” tag (XEP-0203)

Returns

the XMPP message that was sent

Return type

Message

status(text)#

Set a contact’s status

Parameters

text (str) –

unsubscribe()#

Send an “unsubscribe”, “unsubscribed”, “unavailable” presence sequence from this contact to the user, ie, “this contact has removed you from their ‘friends’”.