Notifications and filtering

Notifications

This function allows you to get information about a user’s notifications as well as to clear all or some notifications and to mark conversations as read.

Reading

Mastodon.notifications(id: Notification | str | int | MaybeSnowflakeIdType | None = None, account_id: Account | str | int | MaybeSnowflakeIdType | None = None, max_id: Notification | str | int | MaybeSnowflakeIdType | None = None, min_id: Notification | str | int | MaybeSnowflakeIdType | None = None, since_id: Notification | str | int | MaybeSnowflakeIdType | None = None, limit: int | None = None, exclude_types: List[str] | None = None, types: List[str] | None = None, mentions_only: bool | None = None) PaginatableList[Notification][source]

Fetch notifications (mentions, favourites, reblogs, follows) for the logged-in user. Pass account_id to get only notifications originating from the given account.

There are different types of notifications:
  • follow - A user followed the logged in user

  • follow_request - A user has requested to follow the logged in user (for locked accounts)

  • favourite - A user favourited a post by the logged in user

  • reblog - A user reblogged a post by the logged in user

  • mention - A user mentioned the logged in user

  • poll - A poll the logged in user created or voted in has ended

  • update - A status the logged in user has reblogged (and only those, as of 4.0.0) has been edited

  • status - A user that the logged in user has enabned notifications for has enabled notify (see account_follow())

  • admin.sign_up - For accounts with appropriate permissions (TODO: document which those are when adding the permission API): A new user has signed up

  • admin.report - For accounts with appropriate permissions (TODO: document which those are when adding the permission API): A new report has been received

Parameters exclude_types and types are array of these types, specifying them will in- or exclude the types of notifications given. It is legal to give both parameters at the same tine, the result will then be the intersection of the results of both filters. Specifying mentions_only is a deprecated way to set exclude_types to all but mentions.

Can be passed an id to fetch a single notification.

Returns a list of notification dicts.

Added: Mastodon v1.0.0, last changed: Mastodon v3.5.0

Writing

Mastodon.notifications_clear()[source]

Clear out a user’s notifications

Added: Mastodon v1.0.0, last changed: Mastodon v1.0.0

Mastodon.notifications_dismiss(id: Notification | str | int | MaybeSnowflakeIdType)[source]

Deletes a single notification

Added: Mastodon v1.3.0, last changed: Mastodon v2.9.2

Mastodon.conversations_read(id: Conversation | str | int | MaybeSnowflakeIdType)[source]

Marks a single conversation as read.

The returned object reflects the conversation’s new read status.

Added: Mastodon v2.6.0, last changed: Mastodon v2.6.0

Keyword filters

These functions allow you to get information about keyword filters as well as to create and update filters.

Very Important Note: The filtering system was revised in 4.0.0. This means that these functions will now not work anymore if an instance is on Mastodon 4.0.0 or above. When updating Mastodon.py for 4.0.0, we’ll make an effort to emulate old behaviour, but this will not always be possible. Consider these methods deprecated, for now.

Reading

Mastodon.filters()[source]

Fetch all of the logged-in user’s filters.

Returns a list of filter dicts. Not paginated.

Added: Mastodon v2.4.3, last changed: Mastodon v2.4.3

Mastodon.filter(id)[source]

Fetches information about the filter with the specified id.

Returns a filter dict.

Added: Mastodon v2.4.3, last changed: Mastodon v2.4.3

Mastodon.filters_apply(objects, filters, context)[source]

Helper function: Applies a list of filters to a list of either statuses or notifications and returns only those matched by none. This function will apply all filters that match the context provided in context, i.e. if you want to apply only notification-relevant filters, specify ‘notifications’. Valid contexts are ‘home’, ‘notifications’, ‘public’ and ‘thread’.

Added: Mastodon v2.4.3, last changed: Mastodon v2.4.3

Writing

Mastodon.filter_create(phrase, context, irreversible=False, whole_word=True, expires_in=None)[source]

Creates a new keyword filter. phrase is the phrase that should be filtered out, context specifies from where to filter the keywords. Valid contexts are ‘home’, ‘notifications’, ‘public’ and ‘thread’.

Set irreversible to True if you want the filter to just delete statuses server side. This works only for the ‘home’ and ‘notifications’ contexts.

Set whole_word to False if you want to allow filter matches to start or end within a word, not only at word boundaries.

Set expires_in to specify for how many seconds the filter should be kept around.

Returns the filter dict of the newly created filter.

Added: Mastodon v2.4.3, last changed: Mastodon v2.4.3

Mastodon.filter_update(id, phrase=None, context=None, irreversible=None, whole_word=None, expires_in=None)[source]

Updates the filter with the given id. Parameters are the same as in filter_create().

Returns the filter dict of the updated filter.

Added: Mastodon v2.4.3, last changed: Mastodon v2.4.3

Mastodon.filter_delete(id)[source]

Deletes the filter with the given id.

Added: Mastodon v2.4.3, last changed: Mastodon v2.4.3

Push notifications

Mastodon supports the delivery of notifications via webpush.

These functions allow you to manage webpush subscriptions and to decrypt received pushes. Note that the intended setup is not Mastodon pushing directly to a user’s client - the push endpoint should usually be a relay server that then takes care of delivering the (encrypted) push to the end user via some mechanism, where it can then be decrypted and displayed.

Mastodon allows an application to have one webpush subscription per user at a time.

All crypto utilities require Mastodon.py’s optional “webpush” feature dependencies (specifically, the “cryptography” and “http_ece” packages).

Mastodon.push_subscription() WebPushSubscription[source]

Fetch the current push subscription the logged-in user has for this app.

Only one webpush subscription can be active at a time for any given app.

Added: Mastodon v2.4.0, last changed: Mastodon v2.4.0

Mastodon.push_subscription_set(endpoint: str, encrypt_params: Dict[str, str], follow_events: bool | None = None, favourite_events: bool | None = None, reblog_events: bool | None = None, mention_events: bool | None = None, poll_events: bool | None = None, follow_request_events: bool | None = None, status_events: bool | None = None, policy: str = 'all', update_events: bool | None = None, admin_sign_up_events: bool | None = None, admin_report_events: bool | None = None) WebPushSubscription[source]

Sets up or modifies the push subscription the logged-in user has for this app.

endpoint is the endpoint URL mastodon should call for pushes. Note that mastodon requires https for this URL. encrypt_params is a dict with key parameters that allow the server to encrypt data for you: A public key pubkey and a shared secret auth. You can generate this as well as the corresponding private key using the push_subscription_generate_keys() function.

policy controls what sources will generate webpush events. Valid values are all, none, follower and followed.

The rest of the parameters controls what kind of events you wish to subscribe to. Events whose names start with “admin” require admin privileges to subscribe to.

  • follow_events controls whether you receive events when someone follows the logged in user.

  • favourite_events controls whether you receive events when someone favourites one of the logged in users statuses.

  • reblog_events controls whether you receive events when someone boosts one of the logged in users statuses.

  • mention_events controls whether you receive events when someone mentions the logged in user in a status.

  • poll_events controls whether you receive events when a poll the logged in user has voted in has ended.

  • follow_request_events controls whether you receive events when someone requests to follow the logged in user.

  • status_events controls whether you receive events when someone the logged in user has subscribed to notifications for posts a new status.

  • update_events controls whether you receive events when a status that the logged in user has boosted has been edited.

  • admin_sign_up_events controls whether you receive events when a new user signs up.

  • admin_report_events controls whether you receive events when a new report is received.

Returns a push subscription dict.

Added: Mastodon v2.4.0, last changed: Mastodon v4..0

Mastodon.push_subscription_update(follow_events: bool | None = None, favourite_events: bool | None = None, reblog_events: bool | None = None, mention_events: bool | None = None, poll_events: bool | None = None, follow_request_events: bool | None = None, status_events: bool | None = None, policy: str | None = 'all', update_events: bool | None = None, admin_sign_up_events: bool | None = None, admin_report_events: bool | None = None) WebPushSubscription[source]

Modifies what kind of events the app wishes to subscribe to.

Parameters are as in push_subscription_create().

Returned object reflects the updated push subscription.

Added: Mastodon v2.4.0, last changed: Mastodon v2.4.0

Mastodon.push_subscription_generate_keys() Tuple[Dict[str, str], Dict[str, str]][source]

Generates a private key, public key and shared secret for use in webpush subscriptions.

Returns two dicts: One with the private key and shared secret and another with the public key and shared secret.

Mastodon.push_subscription_decrypt_push(data: bytes, decrypt_params: Dict[str, str], encryption_header: str, crypto_key_header: str) PushNotification[source]

Decrypts data received in a webpush request. Requires the private key dict from push_subscription_generate_keys() (decrypt_params) as well as the Encryption and server Crypto-Key headers from the received webpush

Added: Mastodon v2.4.0, last changed: Mastodon v2.4.0

Usage example

This is a minimal usage example for the push API, including a small http server to receive webpush notifications.

api = Mastodon(...)
keys = api.push_subscription_generate_keys()
api.push_subscription_set(endpoint, keys[1], mention_events=1)

class Handler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        self.send_response(201)
        self.send_header('Location', '')  # Mastodon doesn't seem to care about this
        self.end_headers()
        data = self.rfile.read(int(self.headers['content-length']))
        np = api.push_subscription_decrypt_push(data, keys[0], self.headers['Encryption'], self.headers['Crypto-Key'])
        n = api.notifications(id=np.notification_id)
        s = n.status
        self.log_message('\nFrom: %s\n%s', s.account.acct, s.content)
httpd = http.server.HTTPServer(('', 42069), Handler)

try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass
finally:
    httpd.server_close()
    api.push_subscription_delete()