Realtime Client

class pyryver.ryver_ws.RyverWS(ryver: Ryver, auto_reconnect: bool = False)

A live Ryver session using websockets.

You can construct this manually, although it is recommended to use Ryver.get_live_session().

Warning

This does not work when using a custom integration token to sign in.

Parameters
  • ryver – The Ryver object this live session came from.

  • auto_reconnect – Whether to automatically reconnect on a connection loss.

@on_chat(func: Callable[[pyryver.ws_data.WSChatMessageData], Awaitable])

Decorate a coroutine to be run when a new chat message is received.

This coroutine will be started as a task when a new chat message arrives. It should take a single argument of type WSChatMessageData, which contains the data for the message.

@on_chat_deleted(func: Callable[[pyryver.ws_data.WSChatDeletedData], Awaitable])

Decorate a coroutine to be run when a chat message is deleted.

This coroutine will be started as a task when a chat message is deleted. It should take a single argument of type WSChatDeletedData, which contains the data for the message.

@on_chat_updated(func: Callable[[pyryver.ws_data.WSChatUpdatedData], Awaitable])

Decorate a coroutine to be run when a chat message is updated (edited).

This coroutine will be started as a task when a chat message is updated. It should take a single argument of type WSChatUpdatedData, which contains the data for the message.

@on_presence_changed(func: Callable[[pyryver.ws_data.WSPresenceChangedData], Awaitable])

Decorate a coroutine to be run when a user’s presence changed.

This coroutine will be started as a task when a user’s presence changes. It should take a single argument of type WSPresenceChangedData, which contains the data for the presence change.

@on_user_typing(func: Callable[[pyryver.ws_data.WSUserTypingData], Awaitable])

Decorate a coroutine to be run when a user starts typing.

This coroutine will be started as a task when a user starts typing in a chat. It should take a single argument of type WSUserTypingData, which contains the data for the user typing.

@on_connection_loss(func: Callable[], Awaitable])

Decorate a coroutine to be run when the connection is lost.

This coroutine will be started as a task when the connection is lost. It should take no arguments.

A connection loss is determined using a ping task. A ping is sent to Ryver once every 10 seconds, and if the response takes over 5 seconds, this coroutine will be started. (These numbers roughly match those used by the official web client.)

If auto-reconnect is enabled, no action needs to be taken. Otherwise, applications are suggested to clean up and terminate, or try to reconnect using RyverWS.try_reconnect(). If RyverWS.run_forever() is used, RyverWS.terminate() should be called to make it return, unless you wish to reconnect.

A simple but typical implementation is shown below for applications that do not wish to recover:

async with ryver.get_live_session() as session:
    @session.on_connection_loss
    async def on_connection_loss():
        await session.terminate()
@on_reconnect(func: Callable[], Awaitable])

Decorate a coroutine to be run when auto-reconnect succeeds.

This coroutine will be started as a task when auto-reconnect is successful. It should take no arguments. If auto-reconnect is not enabled, this coroutine will never be started.

EVENT_REACTION_ADDED = '/api/reaction/added'

A reaction was added to a message (includes topics, tasks and replies/comments).

data field format:

  • "type": The entity type of the thing that was reacted to.

  • "id": The ID of the thing that was reacted to. String for chat messages, int for everything else.

  • "userId": The ID of the user that reacted.

  • "reaction": The name of the emoji that the user reacted with.

EVENT_REACTION_REMOVED = '/api/reaction/removed'

A reaction was removed from a message (includes topics, tasks and replies/comments).

data field format:

  • "type": The entity type of the thing that was reacted to.

  • "id": The ID of the thing that was reacted to. String for chat messages, int for everything else.

  • "userId": The ID of the user that reacted.

  • "reaction": The name of the emoji that the user reacted with.

EVENT_TOPIC_CHANGED = '/api/activityfeed/posts/changed'

A topic was changed (created, updated, deleted).

data field format:

  • "created": A list of objects containing data for topics that were newly created.

  • "updated": A list of objects containing data for topics that were updated.

  • "deleted": A list of objects containing data for topics that were deleted.

EVENT_TASK_CHANGED = '/api/activityfeed/tasks/changed'

A task was changed (created, updated, deleted).

data field format:

  • "created": A list of objects containing data for tasks that were newly created.

  • "updated": A list of objects containing data for tasks that were updated.

  • "deleted": A list of objects containing data for tasks that were deleted.

EVENT_ENTITY_CHANGED = '/api/entity/changed'

Some entity was changed (created, updated, deleted).

data field format:

  • "change": The type of the change, could be “created”, “updated”, or “deleted”.

  • "entity": The entity that was changed and some of its data after the change.

EVENT_ALL = ''

All unhandled events.

@on_event(event_type: str)

Decorate a coroutine to be run when an event occurs.

This coroutine will be started as a task when a new event arrives with the specified type. If the event_type is None or an empty string, it will be called for all events that are unhandled.

It should take a single argument of type WSEventData, which contains the data for the event.

Parameters

event_type – The event type to listen to, one of the constants in this class starting with EVENT_ or RyverWS.EVENT_ALL to receive all otherwise unhandled messages.

MSG_TYPE_CHAT = 'chat'

A chat message was received.

MSG_TYPE_CHAT_UPDATED = 'chat_updated'

A chat message was updated.

MSG_TYPE_CHAT_DELETED = 'chat_deleted'

A chat message was deleted.

MSG_TYPE_PRESENCE_CHANGED = 'presence_change'

A user changed their presence.

MSG_TYPE_USER_TYPING = 'user_typing'

A user is typing in a chat.

MSG_TYPE_EVENT = 'event'

An event occurred.

MSG_TYPE_ALL = ''

All unhandled messages.

@on_msg_type(msg_type: str)

Decorate a coroutine to be run when for a type of websocket messages or for all unhandled messages.

This coroutine will be started as a task when a new websocket message arrives with the specified type. If the msg_type is None or an empty string, it will be called for all messages that are otherwise unhandled.

It should take a single argument of type WSMessageData, which contains the data for the event.

Parameters

msg_type – The message type to listen to, one of the constants in this class starting with MSG_TYPE_ or RyverWS.MSG_TYPE_ALL to receive all otherwise unhandled messages.

await send_chat(to_chat: Union[pyryver.objects.Chat, str], msg: str, timeout: float = 5.0)None

Send a chat message to a chat.

Parameters
  • to_chat – The chat or the JID of the chat to send the message to.

  • msg – The message contents.

  • timeout – The timeout for waiting for an ack. If None, waits forever. By default waits for 5s.

Raises
async with typing(to_chat: pyryver.objects.Chat)pyryver.ryver_ws.RyverWSTyping

Get an async context manager that keeps sending a typing indicator to a chat.

Useful for wrapping long running operations to make sure the typing indicator is kept, like:

async with session.typing(chat):
    print("do something silly")
    await asyncio.sleep(4)
    await session.send_chat(chat, "done") # or do it outside the with, doesn't matter
Parameters

to_chat – Where to send the typing status.

await send_typing(to_chat: Union[pyryver.objects.Chat, str], timeout: float = 5.0)None

Send a typing indicator to a chat.

The typing indicator automatically clears after a few seconds or when a message is sent. In private messages, you can also clear it with RyverWS.send_clear_typing() (does not work for group chats).

If you want to maintain the typing indicator for an extended operation, consider using RyverWS.typing(), which returns an async context manager that can be used to maintain the typing indicator for as long as desired.

Parameters
  • to_chat – The chat or the JID of the chat to send the typing status to.

  • timeout – The timeout for waiting for an ack. If None, waits forever. By default waits for 5s.

Raises
await send_clear_typing(to_chat: Union[pyryver.objects.Chat, str], timeout: float = 5.0)None

Clear the typing indicator for a chat.

Warning

For unknown reasons, this method only works in private messages.

Parameters
  • to_chat – The chat or the JID of the chat to clear the typing status for.

  • timeout – The timeout for waiting for an ack. If None, waits forever. By default waits for 5s.

Raises
PRESENCE_AVAILABLE = 'available'

“Available” presence (green).

PRESENCE_AWAY = 'away'

“Away” presence (yellow clock).

PRESENCE_DO_NOT_DISTURB = 'dnd'

“Do Not Disturb” presence (red stop sign).

PRESENCE_OFFLINE = 'unavailable'

“Offline” presence (grey).

await send_presence_change(presence: str, timeout: float = 5.0)None

Send a presence change message.

The presence change is global and not restricted to a single chat.

Parameters
  • presence – The new presence, one of the PRESENCE_ constants.

  • timeout – The timeout for waiting for an ack. If None, waits forever. By default waits for 5s.

Raises
is_connected()bool

Get whether the websocket connection has been established.

Returns

True if connected, False otherwise.

set_auto_reconnect(auto_reconnect: bool)None

Set whether the live session should attempt to auto-reconnect on connection loss.

Parameters

auto_reconnect – Whether to automatically reconnect.

await run_forever()None

Run forever, or until RyverWS.terminate() is called.

Note

Since v0.4.0, this method will no longer return if RyverWS.close() is called. RyverWS.terminate() must be called instead, which closes the session if it is unclosed.

Note

By default, this method will only return if a fatal connection loss occurs and auto-reconnect is not enabled. If the connection loss is recoverable, this method will not return even if auto-reconnect is off.

You should use the RyverWS.on_connection_loss() decorator if you want to automatically close the connection and return on connection loss. See its documentation for an example.

await terminate()None

Close the session and cause RyverWS.run_forever() to return.

This method will have no effect if called twice.

Note

If you use this class as an async with context manager, you don’t need to call the following two methods.

await start(timeout: float = 5.0)None

Start the session, or reconnect after a connection loss.

Note

If there is an existing connection, it will be closed.

Parameters

timeout – The connection timeout in seconds. If None, waits forever. By default, waits for 5 seconds.

await close(cancel_rx: bool = True, cancel_ping: bool = True)None

Close the session.

Any future operation after closing will result in a ClosedError being raised, unless the session is reconnected using RyverWS.start() or RyverWS.try_reconnect().

When used as an async context manager, this method does not need to be called.

Note

Since v0.4.0, this method no longer causes RyverWS.run_forever() to return. Use RyverWS.terminate() if you want to close the session and exit run_forever().

Parameters
  • cancel_rx – Whether to cancel the rx task. For internal use only.

  • cancel_ping – Whether to cancel the ping task. For internal use only.

class pyryver.ryver_ws.RyverWSTyping(rws: pyryver.ryver_ws.RyverWS, to: pyryver.objects.Chat)

A context manager returned by RyverWS to keep sending a typing indicator.

You should not create this class yourself, rather use RyverWS.start_typing() instead.

start()None

Start sending the typing indicator.

await stop()None

Stop sending the typing indicator.

Note

This method will attempt to clear the typing indicator using RyverWS.send_clear_typing(). However, it only works in private messages. Outside of private messages, the typing indicator doesn’t clear immediately. It will clear by itself after about 3 seconds, or when a message is sent.

class pyryver.ryver_ws.WSConnectionError

Bases: Exception

An exception raised by the real-time websockets session to indicate some kind of connection issue.

class pyryver.ryver_ws.ClosedError

Bases: pyryver.ryver_ws.WSConnectionError

An exception raised to indicate that the session has been closed.

class pyryver.ryver_ws.ConnectionLossError

Bases: pyryver.ryver_ws.WSConnectionError

An exception raised to indicate that the connection was lost in the middle of an operation.

Callback Task Data Types

class pyryver.ws_data.WSMessageData(ryver: Ryver, data: dict)

The data for any websocket message in pyryver.ryver_ws.RyverWS.

Variables
  • ryver – The Ryver session that the data came from.

  • ws_msg_type – The type of this websocket message. This can be one of the MSG_TYPE_ constants in pyryver.ryver_ws.RyverWS (except MSG_TYPE_ALL). However, do note that the constants listed there do not cover all valid values of this field.

  • raw_data – The raw websocket message data.

class pyryver.ws_data.WSChatMessageData(ryver: Ryver, data: dict)

Bases: pyryver.ws_data.WSMessageData

The data for a chat message in pyryver.ryver_ws.RyverWS.

Variables
  • message_id – The ID of the message (a string).

  • from_jid – The JID of the sender of this message.

  • to_jid – The JID of the chat this message was sent to.

  • text – The contents of the message.

  • subtype – The subtype of the message. This will be one of the SUBTYPE_ constants in ChatMessage.

  • attachment – The file attached to this message, or None if there isn’t one.

  • creator – The overridden message creator (see Creator), or None if there isn’t one.

class pyryver.ws_data.WSChatUpdatedData(ryver: Ryver, data: dict)

Bases: pyryver.ws_data.WSChatMessageData

The data for a chat message edited in pyryver.ryver_ws.RyverWS.

Variables
  • message_id – The ID of the message (a string).

  • from_jid – The JID of the user that edited the message.

  • to_jid – The JID of the chat this message was sent to.

  • text – The contents of the message after the edit. Note: In very rare circumstances, this field is known to be None.

  • subtype – The subtype of the message. This will be one of the SUBTYPE_ constants in ChatMessage.

  • attachment – The file attached to this message, or None if there isn’t one.

class pyryver.ws_data.WSChatDeletedData(ryver: Ryver, data: dict)

Bases: pyryver.ws_data.WSChatMessageData

The data for a chat message deleted in pyryver.ryver_ws.RyverWS.

Variables
  • message_id – The ID of the message (a string).

  • from_jid – The JID of the sender of this message.

  • to_jid – The JID of the chat this message was sent to.

  • text – The contents of the message that was deleted.

  • subtype – The subtype of the message. This will be one of the SUBTYPE_ constants in ChatMessage.

  • attachment – The file attached to this message, or None if there isn’t one.

class pyryver.ws_data.WSPresenceChangedData(ryver: Ryver, data: dict)

Bases: pyryver.ws_data.WSMessageData

The data for a presence changed in pyryver.ryver_ws.RyverWS.

Variables
  • presence – The new presence. This will be one of the PRESENCE_ constants in RyverWS.

  • from_jid – The JID of the user that changed their presence.

  • client – The client the user is using.

  • timestamp – An ISO 8601 timestamp of this event. You can use pyryver.util.iso8601_to_datetime() to convert it into a datetime.

class pyryver.ws_data.WSUserTypingData(ryver: Ryver, data: dict)

Bases: pyryver.ws_data.WSMessageData

The data for a user typing in pyryver.ryver_ws.RyverWS.

Variables
  • from_jid – The JID of the user that started typing.

  • to_jid – The JID of the chat the user started typing in.

  • state – The “state” of the typing. This is almost always “composing” (for typing in progress), but it could also very rarely be “done”, for when the user has finished typing.

class pyryver.ws_data.WSEventData(ryver: Ryver, data: dict)

Bases: pyryver.ws_data.WSMessageData

The data for an event in pyryver.ryver_ws.RyverWS.

Variables
  • event_type – The type of this event. This can be one of the EVENT_ constants in pyryver.ryver_ws.RyverWS (except EVENT_ALL). However, do note that the constants listed there do not cover all valid values of this field.

  • event_data – The data of this event. This is a dictionary mapping strings to values of any type. The format depends on the event type. The format of some events are documented in the docs of the EVENT_ constants.