Mastodon.py Documentation

repository·master·Indexed 21 days ago

https://github.com/halcy/mastodon.py

A feature-complete Python wrapper for the Mastodon API (version 2.2.1). It provides tools for interacting with Mastodon instances programmatically, including support for OAuth authentication, API rate limiting (wait, pace, and throw modes), paginated results, and async refresh headers. The library features a fully typed system using AttribAccessDict for dot-notation access to API entities and handles Snowflake ID conversion for date-based searches.

Tokens
11.9K
Snippets
22
Records
75
Agent score
75%

What's inside Mastodon.py

  1. Overview of Mastodon.py API Surface

    master
    Mastodon.py provides a comprehensive Python interface for interacting with Mastodon instances. The library is centered around the Mastodon class, which exposes methods for almost every aspect of the Mastodon API, including account management, status (post) creation, timelines, notifications, following/blocking, and administrative tasks. It also includes specialized classes for handling return types (like Account, Status, Notification) and streaming data via StreamListener.
  2. How return values are structured in Mastodon.py

    master

    Unless otherwise specified, all data returned by Mastodon.py matches the JSON format used by the Mastodon API.

    Key behaviors:

    • Data Format: Data is returned as Python dictionaries.
    • Date Handling: Dates in ISO 8601 format are automatically parsed into Python datetime objects.
    • Attribute Access: To simplify data access, dictionaries are wrapped in an AttribAccessDict. This allows you to access keys as read-only attributes using dot notation instead of bracket notation.
    • Typing: Since version 2.0.0, the library is fully typed. While specific return types (classes) are provided for most entities, they inherit from AttribAccessDict, meaning you can still access any returned value as an attribute even if it isn't explicitly defined in the class.
    • JSON Conversion: All return values can be converted to and from JSON using the to_json() and from_json() methods provided by the mastodon.types_base.Entity class.
    # Instead of dictionary bracket notation:
    # description = mastodon.account_verify_credentials()["source"]["note"]
    
    # You can use attribute access:
    # description = mastodon.account_verify_credentials().source.note
  3. Requirements for Administration and Moderation

    master

    To perform moderation actions or process reports using the Mastodon class, your application and access token must meet the following requirements:

    1. Scopes: You must have access to the admin:read and/or admin:write scopes (or their more granular variants).
    2. Permissions: The account associated with the token must have at least moderator access.

    SECURITY WARNING: Access tokens with admin credentials are extremely sensitive. Exposure of these tokens can expose the personal data of all users on the instance. Always revoke tokens after testing and never leave them in plain text files.

  4. Navigate paginated API results

    master

    Many endpoints return paginated data. You can control pagination using these parameters:

    • since_id: Smallest ID you want (returns newest data first).
    • min_id: Returns statuses with this minimum ID and newer.
    • max_id: Returns statuses with this maximum ID and older.
    • limit: Number of results to return (Note: Mastodon instances often cap this at 40 for statuses or 80 for accounts).

    Accessing Pages: When a response is paginated, Mastodon.py parses the link header and attaches pagination metadata to the returned list items via attribute-style access:

    • _pagination_prev: Link to the previous page (found on the first item of the list).
    • _pagination_next: Link to the next page (found on the last item of the list).

    Convenience Methods: Use the following methods to simplify navigation:

    • fetch_next(): Fetch the next page.
    • fetch_previous(): Fetch the previous page.
    • fetch_remaining(): Fetch all remaining pages.
  5. Access timelines with Mastodon.py

    master

    The Mastodon class provides several methods to retrieve different types of timelines. You can access timelines visible to a logged-in user (like the home timeline), as well as hashtag, public (federated), and local timelines.

    Note that for public, local, and hashtag timelines, access may be permitted even without authentication if the Mastodon instance administrator has enabled that functionality.

    # Example conceptual usage
    # timelines = mastodon.timeline_home()
    # timelines = mastodon.timeline_local()
    # timelines = mastodon.timeline_public()
    # timelines = mastodon.timeline_hashtag(hashtag='python')
  6. How streaming works in Mastodon.py

    master

    Streaming allows you to receive real-time events from a Mastodon server. Since Mastodon v4.2.0, you must use an access token; anonymous streaming is no longer supported.

    Execution Modes

    • Blocking Mode (run_async=False): The streaming method will block the current thread indefinitely until an error occurs or the connection is closed.
    • Async Mode (run_async=True): The listener runs in a separate thread. The method returns a handle to the connection.

    Reconnection Behavior

    If you set run_async=True and reconnect_async=True, the library will attempt to reconnect automatically if errors occur, waiting for reconnect_async_wait_sec seconds between attempts.

    Warning: Reconnection does not 'catch up' on missed events. Any events created while the connection was broken will be lost. To ensure no data loss, you must manually handle the gap (e.g., using the on_abort handler to fetch missed events) before reconnecting.

  7. Manage timeline 'last read' markers

    master

    You can use marker functions to interact with the timeline "last read" markers. This allows your application to persist the user's reading position across different sessions and devices.

    • Use Mastodon.markers_get to retrieve the current markers.
    • Use Mastodon.markers_set to update or set new markers.
  8. Register a new application with Mastodon.py

    master

    Before interacting with the API, you must register your application. This is typically a one-time process per server. Use Mastodon.create_app to register and save the client credentials to a file.

    Arguments:

    • app_name: A string identifier for your application.
    • api_base_url: The base URL of the Mastodon instance (e.g., https://mastodon.social).
    • to_file: The filename where the client credentials will be persisted.
    from mastodon import Mastodon
    
    Mastodon.create_app(
        'pytooterapp',
        api_base_url = 'https://mastodon.social',
        to_file = 'pytooter_clientcred.secret'
    )
  9. Use ID unpacking and Snowflake IDs

    master

    ID Unpacking

    Instead of passing raw ID strings to parameters, you can pass the entire dictionary object representing the entity. Mastodon.py will automatically extract the id field.

    # Instead of this:
    api.status_post("Hello!", in_reply_to_id=toot['id'])
    
    # You can do this:
    api.status_post("Hello!", in_reply_to_id=toot)

    Snowflake IDs

    On Mastodon and its forks, status IDs are Snowflake IDs, which correspond to timestamps. You can pass a datetime object directly as an ID parameter, and Mastodon.py will convert it to a Snowflake ID for you. This allows you to search for posts between specific dates.

    Note: This is not compatible with non-Mastodon servers like Pleroma or Misskey.

    import datetime
    # Searching for posts using a datetime object (Snowflake conversion)
    api.statuses_search(since_id=datetime.datetime(2023, 1, 1))
  10. Register your application with Mastodon

    master

    To use the Mastodon API, you must first register your application to obtain a client_id and client_secret. This is a one-time process per server. You should persist these credentials rather than registering a new application every time your application starts.

    Use Mastodon.create_app() to register the application. Once registered, you can verify credentials using Mastodon.app_verify_credentials().

  11. Log in using a direct access token (for bots)

    master

    If you are building a bot, you can bypass the OAuth flow by generating an access token manually in the Mastodon web UI (under Settings > Applications). You can then initialize the Mastodon class directly using this token.

    from mastodon import Mastodon
    
    # Use the access token directly
    mastodon = Mastodon(access_token = 'YOUR_ACCESS_TOKEN')
  12. Register a new Mastodon application

    master

    Before interacting with a Mastodon server, you must register your application. This is typically a one-time process per server or per device. Use Mastodon.create_app to register and save your client credentials to a file for future use.

    from mastodon import Mastodon
    
    Mastodon.create_app(
        'pytooterapp',
        api_base_url = 'https://mastodon.social',
        to_file = 'pytooter_clientcred.secret'
    )