im — Instant Messaging Utilities and Services

This subpackage provides tools for Instant Messaging applications based on XMPP. The tools are meant to be useful for both user-facing as well as automated IM applications.

Warning

aioxmpp.im is highly experimental, even more than aioxmpp by itself is. This is not a threat, this is a chance. Please play with the API, try to build an application around it, and let us know how it feels! This is your chance to work with us on the API.

On the other hand, yes, there is a risk that we’ll restructure the API massively in the next release, even though it works quite well for our applications currently.

Terminology

This is a short overview of the terminology. The full definitions can be found in the glossary and are linked.

Conversation

Communication context for two or more parties.

Conversation Member

An entity taking part in a Conversation.

Conversation Implementation

A Service which provides means to create and manage specific AbstractConversation subclasses.

Service Member

A Conversation Member which represents the service over which the conversation is run inside the conversation.

im.p2p — One-on-one conversations

class aioxmpp.im.p2p.Service(client, **kwargs)[source]

Manage one-to-one conversations.

See also

AbstractConversationService

for useful common signals

This service manages one-to-one conversations, including private conversations running in the framework of a multi-user chat. In those cases, the respective multi-user chat conversation service requests a conversation from this service to use.

For each bare JID, there can either be a single conversation for the bare JID or zero or more conversations for full JIDs. Mixing conversations to bare and full JIDs of the same bare JID is not allowed, because it is ambiguous.

This service creates conversations if it detects them as one-on-one conversations. Subscribe to aioxmpp.im.ConversationService.on_conversation_added() to be notified about new conversations being auto-created.

get_conversation(peer_jid, *, current_jid=None)[source]

Get or create a new one-to-one conversation with a peer.

Parameters
  • peer_jid (aioxmpp.JID) – The JID of the peer to converse with.

  • current_jid (aioxmpp.JID) – The current JID to lock the conversation to (see RFC 6121).

Return type

Conversation

Returns

The new or existing conversation with the peer.

peer_jid must be a full or bare JID. See the Service documentation for details.

Changed in version 0.10: In 0.9, this was a coroutine. Sorry.

class aioxmpp.im.p2p.Conversation(service, peer_jid, parent=None)[source]

Implementation of AbstractConversation for one-on-one conversations.

See also

im.conversation.AbstractConversation

for documentation on the interface implemented by this class.

class aioxmpp.im.p2p.Member(peer_jid, is_self)[source]

Member of a one-on-one conversation.

direct_jid

The JID of the peer.

aioxmpp.muc — Multi-User-Chats (XEP-0045)

See also

aioxmpp.muc

has a Conversation Implementation for MUCs.

Core Services

class aioxmpp.im.ConversationService(client, **kwargs)[source]

Central place where all im.conversation.AbstractConversation subclass instances are collected.

It provides discoverability of all existing conversations (in no particular order) and signals on addition and removal of active conversations. This is useful for front ends to track conversations globally without needing to know about the specific conversation providers.

signal on_conversation_added(conversation)

A new conversation has been added.

Parameters

conversation (AbstractConversation) – The conversation which was added.

This signal is fired when a new conversation is added by a Conversation Implementation.

Note

If you are looking for a “on_conversation_removed” event or similar, there is none. You should use the AbstractConversation.on_exit() event of the conversation.

on_message(conversation,
*args, **kwargs)

Emits whenever any active conversation emits its on_message() event. The arguments are forwarded 1:1, with the AbstractConversation instance pre-pended to the argument list.

conversations

Return an iterable of conversations in which the local client is participating.

get_conversation(conversation_address)[source]

Return the im.AbstractConversation for a given JID.

Raises

KeyError – if there is currently no matching conversation

For Conversation Implementations, the following methods are intended; they should not be used by applications.

_add_conversation(conversation)[source]

Add the conversation and fire the on_conversation_added() event.

Parameters

conversation (AbstractConversation) – The conversation object to add.

The conversation is added to the internal list of conversations which can be queried at conversations. The on_conversation_added() event is fired.

In addition, the ConversationService subscribes to the on_exit() event to remove the conversation from the list automatically. There is no need to remove a conversation from the list explicitly.

Enumerations

class aioxmpp.im.ConversationState(value)[source]

State of a conversation.

Note

The members of this enumeration closely mirror the states of XEP-0085, with the addition of the internal PENDING state. The reason is that XEP-0085 is a Final Standard and is state-of-the-art for conversation states in XMPP.

PENDING

The conversation has been created, possibly automatically, and the application has not yet set the conversation state.

ACTIVE

User accepts an initial content message, sends a content message, gives focus to the chat session interface (perhaps after being inactive), or is otherwise paying attention to the conversation.

—from XEP-0085

INACTIVE

User has not interacted with the chat session interface for an intermediate period of time (e.g., 2 minutes).

—from XEP-0085

GONE

User has not interacted with the chat session interface, system, or device for a relatively long period of time (e.g., 10 minutes).

—from XEP-0085

COMPOSING

User is actively interacting with a message input interface specific to this chat session (e.g., by typing in the input area of a chat window).

—from XEP-0085

PAUSED

User was composing but has not interacted with the message input interface for a short period of time (e.g., 30 seconds).

—from XEP-0085

When any of the above states is entered, a notification is sent out to the participants of the conversation.

class aioxmpp.im.ConversationFeature(value)[source]

Represent individual features of a Conversation of a Conversation Implementation.

See also

The AbstractConversation.features provides a set of features offered by a specific Conversation.

BAN

Allows use of ban().

BAN_WITH_KICK

Explicit support for setting the request_kick argument to True in ban().

INVITE

Allows use of invite().

INVITE_DIRECT

Explicit support for the DIRECT invite mode when calling invite().

INVITE_DIRECT_CONFIGURE

Explicit support for configuring the conversation to allow the invitee to join when using DIRECT with invite().

INVITE_MEDIATED

Explicit support for the MEDIATED invite mode when calling invite().

INVITE_UPGRADE

Explicit support and requirement for allow_upgrade when calling invite().

KICK

Allows use of kick().

LEAVE

Allows use of leave().

SEND_MESSAGE

Allows use of send_message().

SEND_MESSAGE_TRACKED

Allows use of send_message_tracked().

SET_NICK

Allows use of set_nick().

SET_NICK_OF_OTHERS

Explicit support for changing the nickname of other members when calling set_nick().

SET_TOPIC

Allows use of set_topic().

class aioxmpp.im.InviteMode(value)[source]

Represent different possible modes for sending an invitation.

DIRECT

The invitation is sent directly to the invitee, without going through a service specific to the conversation.

MEDIATED

The invitation is sent indirectly through a service which is providing the conversation. Advantages of using this mode include most notably that the service can automatically add the invitee to the list of allowed participants in configurations where such restrictions exist (or deny the request if the inviter does not have the permissions to do so).

Abstract base classes

Conversations

class aioxmpp.im.conversation.AbstractConversation(service, parent=None, **kwargs)[source]

Interface for a conversation.

Note

All signals may receive additional keyword arguments depending on the specific subclass implementing them. Handlers connected to the signals must support arbitrary keyword arguments.

To support future extensions to the base specification, subclasses must prefix all keyword argument names with a common, short prefix which ends with an underscore. For example, a MUC implementation could use muc_presence.

Future extensions to the base class will use either names without underscores or the base_ prefix.

Note

In the same spirit, methods defined on subclasses should use the same prefix. However, the base class does not guarantee that it won’t use names with underscores in future extensions.

To prevent collisions, subclasses should avoid the use of prefixes which are verbs in the english language.

Signals:

Note

The member argument common to many signals is never None and always an instance of a subclass of AbstractConversationMember. However, the member may not be part of the members of the conversation. For example, it may be the service_member object which is never part of members. Other cases where a non-member is passed as member may exist depending on the conversation subclass.

signal on_message(msg, member, source, tracker=None, **kwargs)

A message occurred in the conversation.

Parameters

This signal is emitted on the following events:

  • A message was sent to the conversation and delivered directly to us. This is the classic case of “a message was received”. In this case, source is STREAM and member is the AbstractConversationMember of the originator.

  • A message was sent from this client. This is the classic case of “a message was sent”. In this case, source is STREAM and member refers to ourselves.

  • A carbon-copy of a message received by another resource of our account which belongs to this conversation was received. source is CARBONS and member is the AbstractConversationMember of the originator.

  • A carbon-copy of a message sent by another resource of our account was sent to this conversation. In this case, source is CARBONS and member refers to ourselves.

Often, you don’t need to distinguish between carbon-copied and non-carbon-copied messages.

All messages which are not handled otherwise (and for example dispatched as on_state_changed() signals) are dispatched to this event. This may include messages not understood and/or which carry no textual payload.

tracker is set only for messages sent by the local member. If a message is sent from the client without tracking, tracker is None; otherwise, the tracker is always set, even for messages sent by other clients. It depends on the conversation implementation as well as timing in which state a tracker is at the time the event is emitted.

signal on_state_changed(member, new_state, msg, **kwargs)

The conversation state of a member has changed.

Parameters

This signal also fires for state changes of the local occupant. The exact point at which this signal fires for the local occupant is determined by the implementation.

signal on_presence_changed(member, resource, presence, **kwargs)

The presence state of a member has changed.

Parameters

If the presence stanza affects multiple resources, resource holds the affected resource and the event is emitted once per affected resource.

However, the presence stanza affects only a single resource, resource is None; the affected resource can be extracted from the from_ of the presence stanza in that case. This is to help implementations to know whether a bunch of resources was shot offline by a single presence (resource is not None), e.g. due to an error or whether a single resource went offline by itself. Implementations may want to only show the former case.

Note

In some implementations, unavailable presence implies that a participant leaves the room, in which case on_leave() is emitted instead.

signal on_nick_changed(member, old_nick, new_nick, **kwargs)

The nickname of a member has changed

Parameters
  • member (AbstractConversationMember) – The member object of the member whose nick has changed.

  • old_nick (str or None) – The old nickname of the member.

  • new_nick (str) – The new nickname of the member.

The new nickname is already set in the member object, if the member object has an accessor for the nickname.

In some cases, old_nick may be None. These cases include those where it is not trivial for the protocol to actually determine the old nickname or where no nickname was set before.

signal on_topic_changed(member, new_topic, **kwargs)

The topic of the conversation has changed.

Parameters
signal on_uid_changed(member, old_uid, **kwargs)

This rare signal notifies that the uid of a member has changed.

Parameters

The new uid is already available at the members uid attribute.

This signal can only fire for multi-user conversations where the visibility of identifying information changes. In many cases, it will be irrelevant for the application, but for some use-cases it might be important to be able to re-write historical messages to use the new uid.

signal on_enter()

The conversation was entered.

This event is emitted up to once for a AbstractConversation.

One of on_enter() and on_failure() is emitted exactly once for each AbstractConversation instance.

See also

aioxmpp.callbacks.first_signal() can be used nicely to await the completion of entering a conversation:

conv = ... # let this be your conversation
await first_signal(conv.on_enter, conv.on_failure)
# await first_signal() will either return None (success) or
# raise the exception passed to :meth:`on_failure`.

Note

This and on_failure() are the only signals which must not receive keyword arguments, so that they continue to work with AdHocSignal.AUTO_FUTURE and first_signal().

New in version 0.10.

signal on_failure(exc)

The conversation could not be entered.

Parameters

exc (Exception) – The exception which caused the operation to fail.

Often, exc will be a aioxmpp.errors.XMPPError indicating an error emitted from an involved server, such as permission problems, conflicts or non-existent peers.

This signal can only be emitted instead of on_enter() and not after the room has been entered. If the conversation is terminated due to a remote cause at a later point, on_exit() is used.

One of on_enter() and on_failure() is emitted exactly once for each AbstractConversation instance.

Note

This and on_failure() are the only signals which must not receive keyword arguments, so that they continue to work with AdHocSignal.AUTO_FUTURE and first_signal().

New in version 0.10.

signal on_join(member, **kwargs)

A new member has joined the conversation.

Parameters

member (AbstractConversationMember) – The member object of the new member.

When this signal is called, the member is already included in the members.

signal on_leave(member, **kwargs)

A member has left the conversation.

Parameters

member (AbstractConversationMember) – The member object of the previous member.

When this signal is called, the member has already been removed from the members.

signal on_exit(**kwargs)

The local user has left the conversation.

When this signal fires, the conversation is defunct in the sense that it cannot be used to send messages anymore. A new conversation needs to be started.

Properties:

features

A set of features supported by this Conversation.

The members of the set are usually drawn from the ConversationFeature enumeration; Conversation Implementations are free to add custom elements from other enumerations to this set.

Unless stated otherwise, the methods of AbstractConversation and its subclasses always may throw one of the following exceptions, unless support for those methods is explicitly stated with an appropriate ConversationFeature member in the features.

If support for the method is claimed in features, these exceptions must not be raised (for the given reason; of course, a method may still raise an aioxmpp.XMPPCancelError due for other conditions such as item-not-found).

jid

The address of the conversation.

members

An iterable of members of this conversation.

me

The member representing the local member.

service_member

The member representing the service on which the conversation is hosted, if available.

This is never included in members. It may be used as member argument in events to make it clear that the message originates from the service and not an unknown occupant.

This may be None.

New in version 0.10.

Methods:

Note

See features for discovery of support for individual methods at a given conversation instance.

async ban(member, reason=None, *, request_kick=True)[source]

Ban a member from re-joining the conversation.

Parameters
  • member – The member to ban.

  • reason (str) – A reason to show to the members of the conversation including the banned member.

  • request_kick (bool) – A flag indicating that the member should be removed from the conversation immediately, too.

If request_kick is true, the implementation attempts to kick the member from the conversation, too, if that does not happen automatically. There is no guarantee that the member is not removed from the conversation even if request_kick is false.

Additional features:

BAN_WITH_KICK

If request_kick is true, the member is kicked from the conversation.

See also

The corresponding feature for this method is ConversationFeature.BAN. See features for details on the semantics of features.

async invite(address, text=None, *, mode=<InviteMode.DIRECT: 0>, allow_upgrade=False)[source]

Invite another entity to the conversation.

Parameters
  • address (aioxmpp.JID) – The address of the entity to invite.

  • text – A reason/accompanying text for the invitation.

  • mode (InviteMode) – The invitation mode to use.

  • allow_upgrade (bool) – Whether to allow creating a new conversation to satisfy the invitation.

Raises
Returns

The stanza token for the invitation and the possibly new conversation object

Return type

tuple of StanzaToken and AbstractConversation

Note

Even though this is a coroutine, it returns a stanza token. The coroutine-ness may be needed to generate the invitation in the first place. Sending the actual invitation is done non-blockingly and the stanza token for that is returned. To wait until the invitation has been sent, unpack the stanza token from the result and await it.

Return the new conversation object to use. In many cases, this will simply be the current conversation object, but in some cases (e.g. when someone is invited to a one-on-one conversation), a new conversation must be created and used.

If allow_upgrade is false and a new conversation would be needed to invite an entity, ValueError is raised.

Additional features:

INVITE_DIRECT

Support for DIRECT mode.

INVITE_DIRECT_CONFIGURE

If a direct invitation is used, the conversation will be configured to allow the invitee to join before the invitation is sent. This may fail with a aioxmpp.errors.XMPPError, in which case the error is re-raised and the invitation not sent.

INVITE_MEDIATED

Support for MEDIATED mode.

INVITE_UPGRADE

If allow_upgrade is True, an upgrade will be performed and a new conversation is returned. If allow_upgrade is False, the invite will fail.

See also

The corresponding feature for this method is ConversationFeature.INVITE. See features for details on the semantics of features.

async kick(member, reason=None)[source]

Kick a member from the conversation.

Parameters
  • member – The member to kick.

  • reason (str) – A reason to show to the members of the conversation including the kicked member.

Raises

aioxmpp.errors.XMPPError – if the server returned an error for the kick command.

See also

The corresponding feature is ConversationFeature.KICK. See features for details.

async leave()[source]

Leave the conversation.

See also

The corresponding feature is ConversationFeature.LEAVE. See features for details.

send_message(body)[source]

Send a message to the conversation.

Parameters

msg (aioxmpp.Message) – The message to send.

Returns

The stanza token obtained from sending.

Return type

StanzaToken

The default implementation simply calls send_message_tracked() and immediately cancels the tracking object, returning only the stanza token.

There is no need to provide proper address attributes on msg. Implementations will override those attributes with the values appropriate for the conversation. Some implementations may allow the user to choose a type_, but others may simply stamp it over.

Subclasses may override this method with a more specialised implementation. Subclasses which do not provide tracked message sending must override this method to provide untracked message sending.

See also

The corresponding feature is ConversationFeature.SEND_MESSAGE. See features for details.

abstract send_message_tracked(msg, *, timeout=None)[source]

Send a message to the conversation with tracking.

Parameters
Raises

NotImplementedError – if tracking is not implemented

Returns

The stanza token obtained from sending and the aioxmpp.tracking.MessageTracker tracking the delivery.

Return type

StanzaToken, MessageTracker

There is no need to provide proper address attributes on msg. Implementations will override those attributes with the values appropriate for the conversation. Some implementations may allow the user to choose a type_, but others may simply stamp it over.

Tracking may not be supported by all implementations, and the degree of support varies with implementation. Please check the documentation of the respective subclass.

timeout is the number of seconds (or a datetime.timedelta object which defines the timespan) after which the tracking expires and is closed if no response has been received in the mean time. If timeout is set to None, the tracking never expires.

See also

The corresponding feature is ConversationFeature.SEND_MESSAGE_TRACKED. See features for details.

async set_nick(new_nickname)[source]

Change our nickname.

Parameters

new_nickname (str) – The new nickname for the member.

Raises

ValueError – if the nickname is not a valid nickname

Sends the request to change the nickname and waits for the request to be sent.

There is no guarantee that the nickname change will actually be applied; listen to the on_nick_changed() event.

Implementations may provide a different method which provides more feedback.

See also

The corresponding feature for this method is ConversationFeature.SET_NICK. See features for details on the semantics of features.

async set_topic(new_topic)[source]

Change the (possibly publicly) visible topic of the conversation.

Parameters

new_topic (str) – The new topic for the conversation.

Sends the request to change the topic and waits for the request to be sent.

There is no guarantee that the topic change will actually be applied; listen to the on_topic_chagned() event.

Implementations may provide a different method which provides more feedback.

See also

The corresponding feature for this method is ConversationFeature.SET_TOPIC. See features for details on the semantics of features.

Interface solely for subclasses:

_client

The client as passed to the constructor.

class aioxmpp.im.conversation.AbstractConversationMember(conversation_jid, is_self)[source]

Represent a member in a AbstractConversation.

While all implementations will have their own additional attributes, the following attributes must exist on all subclasses:

conversation_jid

The JID of the conversation member relative to the conversation.

direct_jid

If available, this is the JID address of the member for direct contact, outside of the conversation. It is independent of the conversation itself.

If not available, this attribute reads as None.

is_self

True if the member refers to ourselves in the conversation, false otherwise.

uid

This is a unique ID for the occupant. It can be used across sessions and restarts to assert equality between occupants. It is guaranteed to be equal if and only if the entity is the same (up to a uncertainty caused by the limited length of the unique ID, somewhere in the order of 2**(-120)).

The identifier is always a bytes and must be treated as opaque by users. The only guarantee which is given is that its length will be less than 4096 bytes.

Conversation Service

class aioxmpp.im.conversation.AbstractConversationService[source]

Abstract base class for Conversation Services.

Useful implementations:

aioxmpp.im.p2p.Service(client, **kwargs)

Manage one-to-one conversations.

aioxmpp.muc.MUCClient(client, **kwargs)

Conversation Implementation for Multi-User Chats (XEP-0045).

In general, conversation services should provide a method (not a coroutine method) to start a conversation using the service. That method should return the fresh AbstractConversation object immediately and start possibly needed background tasks to actually initiate the conversation. The caller should use the on_enter() and on_failure() signals to be notified of the result of the join operation.

Signals:

signal on_conversation_new(conversation)

Fires when a new conversation is created in the service.

Parameters

conversation (AbstractConversation) – The new conversation.

See also

ConversationService.on_conversation_added()

is a signal shared among all Conversation Implementations which gets emitted whenever a new conversation is added. If you need all conversations, that is the signal to listen for.

signal on_spontaneous_conversation(conversation)

Like on_conversation_new(), but is only emitted for conversations which are created without local interaction.

Parameters

conversation (AbstractConversation) – The new conversation.

New in version 0.10.