Streaming
These functions allow access to the streaming API. Since Mastodon v4.2.0 the support for anonymous streaming api access was dropped. You need to generate an access token now.
If run_async is False, these methods block forever (or until an error is encountered).
If run_async is True, the listener will listen on another thread and these methods will return a handle corresponding to the open connection. If, in addition, reconnect_async is True, the thread will attempt to reconnect to the streaming API if any errors are encountered, waiting reconnect_async_wait_sec seconds between reconnection attempts. Note that no effort is made to “catch up” - events created while the connection is broken will not be received. If you need to make sure to get absolutely all notifications / deletes / toots, you will have to do that manually, e.g. using the on_abort handler to fill in events since the last received one and then reconnecting. Both run_async and reconnect_async default to false, and you’ll have to set each to true separately to get the behaviour described above.
By default, the streaming API uses HTTP server-sent events. There is now also support for the WebSocket streaming API, which allows multiplexing of multiple streams over one connection and should probably be preferred by applications relying heavily on streaming.
Support requires the optional websocket_streaming dependencies:
pip install “Mastodon.py[websocket_streaming]”
WebSocket stream handles can carry multiple subscriptions. Open one connection
with Mastodon.stream_open_websocket(). Then, subscribe to or unsubscribe from
individual streams using the subscribe or unsubscribe methods on the returned handle:
[...]
stream = mastodon.stream_open_websocket(listener)
stream.subscribe("user")
stream.subscribe("hashtag", tag="python")
You can also pass a websocket handle as the websocket_handle parameter to the existing stream endpoint methods for a more drop in replacement experience.
Valid stream names and subscription parameters are documented in
WebSocketStreamHandle.subscribe().
The connection may be closed at any time by calling the handles close() method. The current status of the handler thread can be checked with the handles is_alive() function, and the streaming status can be checked by calling is_receiving().
The streaming functions take instances of StreamListener as the listener parameter. A CallbackStreamListener class that allows you to specify function callbacks directly is included for convenience.
For new well-known events implement the streaming function in StreamListener or CallbackStreamListener. The function name is on_ + the event name. If the event name contains dots, they are replaced with underscored, e.g. for an event called ‘status.update’ the listener function should be named on_status_update.
It may be that future Mastodon versions will come with completely new (unknown) event names. If you want to do something when such an event is received, override the listener function on_unknown_event. This has an additional parameter name which informs about the name of the event. unknown_event contains the content of the event. Alternatively, a callback function can be passed in the unknown_event_handler parameter in the CallbackStreamListener constructor.
Note that the unknown_event handler is not guaranteed to receive events once they have been implemented. Events will only go to this handler temporarily, while Mastodon.py has not been updated. Changes to what events do and do not go into the handler will not be considered a breaking change. If you want to handle a new event whose name you _do_ know, define an appropriate handler in your StreamListener, which will work even if it is not listed here.
When in not-async mode or async mode without async_reconnect, the stream functions may raise various exceptions: MastodonMalformedEventError if a received event cannot be parsed and MastodonNetworkError if any connection problems occur.
Stream endpoints
- Mastodon.stream_user(listener, run_async=False, timeout=300, reconnect_async=False, reconnect_async_wait_sec=5, websocket_handle=None)[source]
Streams events that are relevant to the authorized user, i.e. home timeline and notifications.
Added: Mastodon v1.1.0, last changed: Mastodon v1.4.2
- Mastodon.stream_user_notifications(listener, run_async=False, timeout=300, reconnect_async=False, reconnect_async_wait_sec=5, websocket_handle=None)[source]
Streams notifications for the authorized user.
Added: Mastodon v1.4.2, last changed: Mastodon v1.4.2
- Mastodon.stream_public(listener, run_async=False, timeout=300, reconnect_async=False, reconnect_async_wait_sec=5, local=False, remote=False, only_media=False, websocket_handle=None)[source]
Streams public events.
Set local to True to only get local statuses. Set remote to True to only get remote statuses. Set only_media to True to only get statuses with media attachments.
Added: Mastodon v1.1.0, last changed: Mastodon v1.4.2
- Mastodon.stream_local(listener, run_async=False, timeout=300, reconnect_async=False, reconnect_async_wait_sec=5, only_media=False, websocket_handle=None)[source]
Streams local public events.
This function is deprecated. Please use stream_public() with parameter local set to True instead.
Added: Mastodon v1.1.0, last changed: Mastodon v1.4.2
- Mastodon.stream_hashtag(tag, listener, local=False, run_async=False, timeout=300, reconnect_async=False, reconnect_async_wait_sec=5, websocket_handle=None)[source]
Stream for all public statuses for the hashtag ‘tag’ seen by the connected instance.
Set local to True to only get local statuses.
Added: Mastodon v1.1.0, last changed: Mastodon v1.4.2
- Mastodon.stream_list(id, listener, run_async=False, timeout=300, reconnect_async=False, reconnect_async_wait_sec=5, websocket_handle=None)[source]
Stream events for the current user, restricted to accounts on the given list.
Added: Mastodon v2.1.0, last changed: Mastodon v2.1.0
- Mastodon.stream_direct(listener, run_async=False, timeout=300, reconnect_async=False, reconnect_async_wait_sec=5, websocket_handle=None)[source]
Streams direct message events for the logged-in user, as conversation events.
Added: Mastodon v2.6.0, last changed: Mastodon v2.6.0
StreamListener
- class mastodon.StreamListener[source]
Callbacks for the streaming API. Create a subclass, override the on_xxx methods for the kinds of events you’re interested in, then pass an instance of your subclass to Mastodon.user_stream(), Mastodon.public_stream(), or Mastodon.hashtag_stream().
- StreamListener.on_update(status: Status)[source]
A new status has appeared. status is the parsed status dict describing the status.
- StreamListener.on_notification(notification: Notification)[source]
A new notification. notification is the object describing the notification. For more information, see the documentation for the notifications() method.
- StreamListener.on_delete(status_id: str | int | MaybeSnowflakeIdType | datetime)[source]
A status has been deleted. status_id is the status’ integer ID.
- StreamListener.on_conversation(conversation: Conversation)[source]
A direct message (in the direct stream) has been received. conversation is the parsed conversation dict dictionary describing the conversation
- StreamListener.on_status_update(status: Status)[source]
A status has been edited. ‘status’ is the parsed JSON dictionary describing the updated status.
- StreamListener.on_unknown_event(name, unknown_event=None)[source]
An unknown mastodon API event has been received. The name contains the event-name and unknown_event contains the content of the unknown event.
- StreamListener.on_abort(err)[source]
There was a connection error, read timeout or other error fatal to the streaming connection. The exception object about to be raised is passed to this function for reference.
Note that the exception will be raised properly once you return from this function, so if you are using this handler to reconnect, either never return or start a thread and then catch and ignore the exception.
- StreamListener.handle_heartbeat()[source]
The server has sent us a keep-alive message. This callback may be useful to carry out periodic housekeeping tasks, or just to confirm that the connection is still open.
CallbackStreamListener
- class mastodon.CallbackStreamListener(update_handler=None, local_update_handler=None, delete_handler=None, notification_handler=None, conversation_handler=None, unknown_event_handler=None, status_update_handler=None, filters_changed_handler=None, announcement_handler=None, announcement_reaction_handler=None, announcement_delete_handler=None, encryted_message_handler=None, notifications_merged_handler=None, stream_error_handler=None)[source]
Simple callback stream handler class. Can optionally additionally send local update events to a separate handler. Define an unknown_event_handler for new Mastodon API events. This handler is not guaranteed to receive these events forever, and should only be used for diagnostics.
StreamHandle
Both asynchronous SSE and WebSocket handles implement this lifecycle interface.
Calling close() permanently closes a handle. Use join() to wait for its
worker thread to exit.
- StreamHandle.is_alive()[source]
Return True while the connection’s worker thread is alive.
The connection may be in any state, including reconnecting.
- StreamHandle.is_receiving()[source]
Return True while the worker is running and available to receive events with the streaming connection established.
- StreamHandle.join(timeout=None)[source]
Wait for the worker thread to exit without closing the connection.
Normally called after close().
timeoutlimits the wait in seconds; None waits indefinitely. Returns None; use is_alive() to check whether the thread exited. Calling from the worker itself returns immediately.
SSEStreamHandle
- class mastodon.SSEStreamHandle(connection, connect_func, reconnect_async, reconnect_async_wait_sec, listener)[source]
An asynchronous HTTP server-sent events connection.
Returned by streaming endpoints when
run_async=True. Closing the handle permanently stops the stream.
- SSEStreamHandle.is_alive()
Return True while the connection’s worker thread is alive.
The connection may be in any state, including reconnecting.
- SSEStreamHandle.is_receiving()
Return True while the worker is running and available to receive events with the streaming connection established.
- SSEStreamHandle.join(timeout=None)
Wait for the worker thread to exit without closing the connection.
Normally called after close().
timeoutlimits the wait in seconds; None waits indefinitely. Returns None; use is_alive() to check whether the thread exited. Calling from the worker itself returns immediately.
WebSocketStreamHandle
- class mastodon.WebSocketStreamHandle(url, access_token, user_agent, listener=None, timeout=300, reconnect=False, reconnect_wait_sec=5)[source]
A live WebSocket connection that can carry multiple Mastodon streams.
- WebSocketStreamHandle.subscribe(stream, listener=None, **params)[source]
Subscribe to a stream and return a
WebSocketSubscription.Valid stream names as of Mastodon version 4.7.3 are:
user: Home timeline updates and events for the logged-in user, including notifications.
user:notification: Notifications for the logged-in user only.
direct: Direct message conversation events.
public: All public statuses known to the server.
public:local: Public statuses from local accounts.
public:remote: Public statuses from remote accounts.
public:media: Public statuses with media attachments.
public:local:media: Local public statuses with media attachments.
public:remote:media: Remote public statuses with media attachments.
hashtag: Public statuses containing the hashtag specified by tag.
hashtag:local: Local public statuses containing that hashtag.
list: Updates for the list specified by list.
For hashtag streams, pass tag=”python” (without a leading #). For list streams, pass the list ID as list=”123”. The listener defaults to the one passed to
stream_open_websocket().You can pass a separate listener for each subscription if desired. If you pass one as listener, then events will be delivered to that listener instead of the default listener passed to stream_open_websocket.
- WebSocketStreamHandle.unsubscribe(stream, **params)[source]
Unsubscribe using the same stream name and parameters as for subscribe().
- WebSocketStreamHandle.close()[source]
Permanently close this connection and all of its subscriptions.
- WebSocketStreamHandle.is_alive()
Return True while the connection’s worker thread is alive.
The connection may be in any state, including reconnecting.
- WebSocketStreamHandle.is_receiving()
Return True while the worker is running and available to receive events with the streaming connection established.
- WebSocketStreamHandle.join(timeout=None)
Wait for the worker thread to exit without closing the connection.
Normally called after close().
timeoutlimits the wait in seconds; None waits indefinitely. Returns None; use is_alive() to check whether the thread exited. Calling from the worker itself returns immediately.