Python wrapper for the Mastodon API providing comprehensive access to social media functionality
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Complete OAuth authentication flows, application registration, and API client configuration for connecting to Mastodon instances. Handles credential persistence, token management, and various authentication scenarios.
Register a new application with a Mastodon instance to obtain client credentials required for OAuth authentication.
@staticmethod
def create_app(
client_name: str,
scopes: list = None,
redirect_uris: str = "urn:ietf:wg:oauth:2.0:oob",
website: str = None,
to_file: str = None,
api_base_url: str = None,
request_timeout: int = 300,
session: requests.Session = None
) -> tuple:
"""
Register a new application with a Mastodon instance.
Args:
client_name: Name of the application
scopes: List of requested permissions (default: ['read', 'write', 'follow', 'push'])
redirect_uris: OAuth redirect URI for authorization flow
website: URL of application website (optional)
to_file: File path to save client credentials (optional)
api_base_url: Base URL of Mastodon instance (required)
request_timeout: HTTP request timeout in seconds
session: Custom requests session (optional)
Returns:
Tuple of (client_id, client_secret) or path to saved file
"""Initialize the Mastodon API client with authentication credentials and configuration options.
def __init__(
self,
client_id: str = None,
client_secret: str = None,
access_token: str = None,
api_base_url: str = None,
client_credential_file: str = None,
access_token_file: str = None,
debug_requests: bool = False,
ratelimit_method: str = "wait",
ratelimit_pacefactor: float = 1.1,
request_timeout: int = 300,
mastodon_version: str = None,
version_check_mode: str = "created",
session: requests.Session = None,
feature_set: str = "mainline",
user_agent: str = None,
lang: str = None
):
"""
Initialize Mastodon API client.
Args:
client_id: Application client ID
client_secret: Application client secret
access_token: User access token for authenticated requests
api_base_url: Base URL of Mastodon instance (e.g., 'https://mastodon.social')
client_credential_file: Path to file containing client credentials
access_token_file: Path to file containing access token
debug_requests: Enable request debugging output
ratelimit_method: Rate limit handling ('wait', 'throw', or 'pace')
ratelimit_pacefactor: Factor for rate limit pacing
request_timeout: HTTP request timeout in seconds
mastodon_version: Target Mastodon version for compatibility
version_check_mode: Version checking behavior ('created', 'changed', or 'none')
session: Custom requests session
feature_set: Feature set compatibility ('mainline', 'fedibird', 'pleroma')
user_agent: Custom user agent string
lang: Default language for requests
"""Generate OAuth authorization URLs and handle the authorization flow for obtaining user access tokens.
def auth_request_url(
self,
client_id: str = None,
redirect_uris: str = "urn:ietf:wg:oauth:2.0:oob",
scopes: list = None,
force_login: bool = False,
state: str = None
) -> str:
"""
Generate OAuth authorization URL for user authentication.
Args:
client_id: Application client ID (uses instance default if None)
redirect_uris: OAuth redirect URI
scopes: Requested permission scopes
force_login: Force user to log in even if already authenticated
state: Random state parameter for CSRF protection
Returns:
Authorization URL for user to visit
"""
def oauth_authorization_server_info(self) -> dict:
"""
Get OAuth authorization server metadata (Mastodon 4.3.0+).
Returns:
Dictionary containing OAuth server configuration
"""
def oauth_userinfo(self) -> dict:
"""
Get authenticated user information via OAuth userinfo endpoint (Mastodon 4.3.0+).
Returns:
Dictionary containing user profile information
"""Authenticate users and obtain access tokens using various authentication methods including username/password and authorization codes.
def log_in(
self,
username: str = None,
password: str = None,
code: str = None,
redirect_uri: str = "urn:ietf:wg:oauth:2.0:oob",
refresh_token: str = None,
scopes: list = None,
to_file: str = None
) -> str:
"""
Authenticate user and obtain access token.
Args:
username: User's email or username (for password auth)
password: User's password (for password auth)
code: Authorization code from OAuth flow
redirect_uri: OAuth redirect URI (must match app registration)
refresh_token: Refresh token for token renewal
scopes: Requested permission scopes
to_file: File path to save access token
Returns:
Access token string
"""Manage, verify, and persist authentication credentials for seamless API access across sessions.
def persistable_login_credentials(self) -> dict:
"""
Get current credentials in a format suitable for persistence.
Returns:
Dictionary containing client_id, client_secret, and access_token
"""
def revoke_access_token(self) -> bool:
"""
Revoke the current access token, invalidating it.
Returns:
True if token was successfully revoked
"""
def app_verify_credentials(self) -> dict:
"""
Verify application credentials and get app information.
Returns:
Dictionary containing application details
"""Clear internal caches and reset client state for troubleshooting and memory management.
def clear_caches(self) -> None:
"""
Clear all internal caches (emoji cache, instance info, etc.).
"""from mastodon import Mastodon
# 1. Register application (do this once per application)
client_id, client_secret = Mastodon.create_app(
'My Bot Application',
api_base_url='https://mastodon.social',
to_file='clientcred.secret'
)
# 2. Create client instance
mastodon = Mastodon(
client_id=client_id,
client_secret=client_secret,
api_base_url='https://mastodon.social'
)
# 3. Get authorization URL for user
auth_url = mastodon.auth_request_url(scopes=['read', 'write'])
print(f"Visit this URL to authorize: {auth_url}")
# 4. User visits URL and gets authorization code
authorization_code = input("Enter authorization code: ")
# 5. Exchange code for access token
access_token = mastodon.log_in(
code=authorization_code,
to_file='usercred.secret'
)
# 6. Now you can make authenticated requests
user_info = mastodon.account_verify_credentials()
print(f"Logged in as: {user_info['acct']}")from mastodon import Mastodon
# Load from credential files
mastodon = Mastodon(
client_credential_file='clientcred.secret',
access_token_file='usercred.secret',
api_base_url='https://mastodon.social'
)
# Verify credentials are still valid
try:
user_info = mastodon.account_verify_credentials()
print(f"Successfully authenticated as: {user_info['acct']}")
except Exception as e:
print(f"Authentication failed: {e}")from mastodon import Mastodon
# Configure rate limiting behavior
mastodon = Mastodon(
access_token='your_token',
api_base_url='https://mastodon.social',
ratelimit_method='wait', # Wait when rate limited
ratelimit_pacefactor=1.1 # Slight delay to avoid limits
)
# Alternative: Handle rate limits manually
mastodon = Mastodon(
access_token='your_token',
api_base_url='https://mastodon.social',
ratelimit_method='throw' # Raise exception on rate limit
)
try:
timeline = mastodon.timeline_home()
except MastodonRatelimitError:
print("Rate limited! Wait before retrying.")Authentication operations can raise several specific exceptions:
from mastodon import (
MastodonError, MastodonNetworkError, MastodonAPIError,
MastodonUnauthorizedError, MastodonRatelimitError
)
try:
mastodon = Mastodon(
access_token='invalid_token',
api_base_url='https://mastodon.social'
)
user_info = mastodon.account_verify_credentials()
except MastodonUnauthorizedError:
print("Invalid or expired access token")
except MastodonNetworkError:
print("Network connection failed")
except MastodonAPIError as e:
print(f"API error: {e}")# Default OAuth scopes
_DEFAULT_SCOPES = ['read', 'write', 'follow', 'push']
# Available scope sets
_SCOPE_SETS = {
'read': ['read:accounts', 'read:blocks', 'read:bookmarks', ...],
'write': ['write:accounts', 'write:blocks', 'write:bookmarks', ...],
'follow': ['read:follows', 'write:follows'],
'push': ['push']
}Install with Tessl CLI
npx tessl i tessl/pypi-mastodon-py