Python wrapper for the Mastodon API providing comprehensive access to social media functionality
npx @tessl/cli install tessl/pypi-mastodon-py@2.1.00
# Mastodon.py
1
2
A comprehensive Python wrapper for the Mastodon social media platform API, enabling developers to create applications that interact with Mastodon instances. Supports the complete Mastodon API (v4.4.3) including authentication, posting, media handling, real-time streaming, and administrative functionality.
3
4
## Package Information
5
6
- **Package Name**: Mastodon.py
7
- **Language**: Python
8
- **Installation**: `pip install Mastodon.py`
9
- **Optional Dependencies**: `pip install Mastodon.py[webpush,blurhash]`
10
11
## Core Imports
12
13
```python
14
from mastodon import Mastodon
15
```
16
17
For streaming functionality:
18
19
```python
20
from mastodon import Mastodon, StreamListener, CallbackStreamListener
21
```
22
23
For error handling:
24
25
```python
26
from mastodon import (
27
Mastodon, MastodonError, MastodonAPIError,
28
MastodonNetworkError, MastodonRatelimitError,
29
MastodonNotFoundError, MastodonUnauthorizedError,
30
MastodonVersionError, MastodonIllegalArgumentError
31
)
32
```
33
34
## Basic Usage
35
36
```python
37
from mastodon import Mastodon
38
39
# Create API client
40
mastodon = Mastodon(
41
client_id='your_clientcred.secret',
42
client_secret='your_clientcred.secret',
43
access_token='your_usercred.secret',
44
api_base_url='https://mastodon.social'
45
)
46
47
# Post a status
48
status = mastodon.status_post("Hello, Mastodon!")
49
print(f"Posted status: {status['id']}")
50
51
# Get home timeline
52
timeline = mastodon.timeline_home()
53
for toot in timeline:
54
print(f"{toot['account']['acct']}: {toot['content']}")
55
56
# Follow an account
57
account = mastodon.account_lookup("gargron@mastodon.social")
58
mastodon.account_follow(account['id'])
59
```
60
61
## Architecture
62
63
The library uses a modular architecture with the main `Mastodon` class inheriting functionality from specialized mixins:
64
65
- **Authentication**: OAuth flows, app registration, and credential management
66
- **Accounts**: User profiles, relationships, and social interactions
67
- **Statuses**: Creating, editing, and managing posts (toots)
68
- **Timelines**: Accessing home, public, and specialized feeds
69
- **Media**: File uploads and media attachment handling
70
- **Streaming**: Real-time event processing via WebSocket connections
71
- **Administration**: Instance management and moderation tools
72
73
This design provides comprehensive API coverage while maintaining code organization and allowing fine-grained access control.
74
75
## Capabilities
76
77
### Authentication & Setup
78
79
Complete OAuth authentication flows, application registration, and API client configuration. Handles credential persistence and token management for seamless integration.
80
81
```python { .api }
82
def create_app(
83
client_name: str,
84
scopes: list = None,
85
redirect_uris: str = "urn:ietf:wg:oauth:2.0:oob",
86
website: str = None,
87
to_file: str = None,
88
api_base_url: str = None,
89
request_timeout: int = 300,
90
session: requests.Session = None
91
) -> tuple: ...
92
93
def __init__(
94
self,
95
client_id: str = None,
96
client_secret: str = None,
97
access_token: str = None,
98
api_base_url: str = None,
99
client_credential_file: str = None,
100
access_token_file: str = None,
101
debug_requests: bool = False,
102
ratelimit_method: str = "wait",
103
ratelimit_pacefactor: float = 1.1,
104
request_timeout: int = 300,
105
mastodon_version: str = None,
106
version_check_mode: str = "created",
107
session: requests.Session = None,
108
feature_set: str = "mainline",
109
user_agent: str = None,
110
lang: str = None
111
): ...
112
113
def log_in(
114
self,
115
username: str = None,
116
password: str = None,
117
code: str = None,
118
redirect_uri: str = "urn:ietf:wg:oauth:2.0:oob",
119
refresh_token: str = None,
120
scopes: list = None,
121
to_file: str = None
122
) -> str: ...
123
```
124
125
[Authentication & Setup](./authentication.md)
126
127
### Account Management
128
129
User account operations including profile management, following/blocking, and relationship handling. Supports both personal account actions and account discovery features.
130
131
```python { .api }
132
def account(self, id: int) -> dict: ...
133
def account_verify_credentials(self) -> dict: ...
134
def account_update_credentials(
135
self,
136
display_name: str = None,
137
note: str = None,
138
avatar: str = None,
139
header: str = None,
140
locked: bool = None,
141
bot: bool = None,
142
discoverable: bool = None,
143
fields_attributes: list = None,
144
source: dict = None
145
) -> dict: ...
146
147
def account_follow(self, id: int, reblogs: bool = True, notify: bool = False) -> dict: ...
148
def account_unfollow(self, id: int) -> dict: ...
149
def account_block(self, id: int) -> dict: ...
150
def account_mute(self, id: int, notifications: bool = True, duration: int = None) -> dict: ...
151
```
152
153
[Account Management](./accounts.md)
154
155
### Status Operations
156
157
Creating, editing, and managing posts (statuses/toots) including media attachments, polls, and scheduling. Handles all status-related actions like favoriting, boosting, and bookmarking.
158
159
```python { .api }
160
def status_post(
161
self,
162
status: str,
163
in_reply_to_id: int = None,
164
media_ids: list = None,
165
sensitive: bool = False,
166
visibility: str = None,
167
spoiler_text: str = None,
168
language: str = None,
169
idempotency_key: str = None,
170
content_type: str = None,
171
scheduled_at: datetime = None,
172
poll: dict = None,
173
quote_id: int = None
174
) -> dict: ...
175
176
def status_delete(self, id: int) -> dict: ...
177
def status_favourite(self, id: int) -> dict: ...
178
def status_reblog(self, id: int, visibility: str = None) -> dict: ...
179
def status_bookmark(self, id: int) -> dict: ...
180
```
181
182
[Status Operations](./statuses.md)
183
184
### Timeline Access
185
186
Accessing various timeline feeds including home, public, hashtag, and list timelines. Provides paginated access to status streams with filtering options.
187
188
```python { .api }
189
def timeline_home(
190
self,
191
max_id: int = None,
192
min_id: int = None,
193
since_id: int = None,
194
limit: int = None,
195
local: bool = False,
196
remote: bool = False
197
) -> list: ...
198
199
def timeline_public(
200
self,
201
max_id: int = None,
202
min_id: int = None,
203
since_id: int = None,
204
limit: int = None,
205
only_media: bool = False,
206
local: bool = False,
207
remote: bool = False
208
) -> list: ...
209
210
def timeline_hashtag(
211
self,
212
hashtag: str,
213
local: bool = False,
214
max_id: int = None,
215
min_id: int = None,
216
since_id: int = None,
217
limit: int = None,
218
only_media: bool = False,
219
remote: bool = False
220
) -> list: ...
221
```
222
223
### Media & File Handling
224
225
Upload and manage media attachments including images, videos, and audio files. Supports metadata editing, focus points, and thumbnails for enhanced media presentation.
226
227
```python { .api }
228
def media_post(
229
self,
230
media_file: str,
231
mime_type: str = None,
232
description: str = None,
233
focus: tuple = None,
234
file_name: str = None,
235
thumbnail: str = None,
236
thumbnail_mime_type: str = None,
237
synchronous: bool = False
238
) -> dict: ...
239
240
def media_update(
241
self,
242
id: int,
243
description: str = None,
244
focus: tuple = None,
245
thumbnail: str = None,
246
thumbnail_mime_type: str = None
247
) -> dict: ...
248
```
249
250
### Real-time Streaming
251
252
WebSocket-based streaming for real-time updates from timelines, notifications, and user events. Implements event handlers for different types of streaming data.
253
254
```python { .api }
255
def stream_user(
256
self,
257
listener: StreamListener,
258
run_async: bool = False,
259
timeout: int = 300,
260
reconnect_async: bool = False,
261
reconnect_async_wait_sec: int = 5
262
): ...
263
264
def stream_public(
265
self,
266
listener: StreamListener,
267
run_async: bool = False,
268
timeout: int = 300,
269
reconnect_async: bool = False,
270
reconnect_async_wait_sec: int = 5
271
): ...
272
273
class StreamListener:
274
def on_update(self, status: dict): ...
275
def on_notification(self, notification: dict): ...
276
def on_delete(self, status_id: int): ...
277
```
278
279
[Real-time Streaming](./streaming.md)
280
281
### Search & Discovery
282
283
Comprehensive search functionality across accounts, statuses, and hashtags with support for both v1 and v2 search APIs.
284
285
```python { .api }
286
def search(
287
self,
288
q: str,
289
resolve: bool = True,
290
result_type: str = None,
291
account_id: int = None,
292
max_id: int = None,
293
min_id: int = None,
294
limit: int = None,
295
offset: int = 0,
296
following: bool = False
297
) -> dict: ...
298
299
def search_v2(
300
self,
301
q: str,
302
resolve: bool = True,
303
result_type: str = None,
304
account_id: int = None,
305
max_id: int = None,
306
min_id: int = None,
307
limit: int = None,
308
offset: int = 0,
309
following: bool = False
310
) -> dict: ...
311
```
312
313
[Search & Discovery](./search.md)
314
315
### Content Filtering
316
317
Create and manage content filters using both v1 and v2 API versions for automated content moderation.
318
319
```python { .api }
320
def filters(self) -> list: ...
321
def filter_create(
322
self,
323
phrase: str,
324
context: str,
325
irreversible: bool = False,
326
whole_word: bool = True,
327
expires_in: int = None
328
) -> dict: ...
329
330
def filters_v2(self) -> list: ...
331
def create_filter_v2(
332
self,
333
title: str,
334
context: list,
335
filter_action: str = "warn",
336
expires_in: int = None,
337
keywords_attributes: list = None
338
) -> dict: ...
339
```
340
341
[Content Filtering](./filters.md)
342
343
### Lists Management
344
345
Create and manage user lists for organizing followed accounts and customizing timeline feeds.
346
347
```python { .api }
348
def lists(self) -> list: ...
349
def list_create(
350
self,
351
title: str,
352
replies_policy: str = "list",
353
exclusive: bool = False
354
) -> dict: ...
355
356
def list_accounts(
357
self,
358
id: int,
359
max_id: int = None,
360
since_id: int = None,
361
limit: int = None
362
) -> list: ...
363
364
def list_accounts_add(self, id: int, account_ids: list): ...
365
```
366
367
[Lists Management](./lists.md)
368
369
### Notifications
370
371
Comprehensive notification management including the new grouped notifications API and notification policies.
372
373
```python { .api }
374
def notifications(
375
self,
376
id: int = None,
377
account_id: int = None,
378
max_id: int = None,
379
min_id: int = None,
380
since_id: int = None,
381
limit: int = None,
382
exclude_types: list = None,
383
types: list = None
384
) -> list: ...
385
386
def grouped_notifications(
387
self,
388
max_id: str = None,
389
since_id: str = None,
390
limit: int = None,
391
types: list = None,
392
exclude_types: list = None,
393
grouped_types: list = None
394
) -> dict: ...
395
```
396
397
[Notifications](./notifications.md)
398
399
### Polls
400
401
Create, vote on, and manage polls attached to statuses.
402
403
```python { .api }
404
def poll(self, id: int) -> dict: ...
405
def poll_vote(self, id: int, choices: list) -> dict: ...
406
def make_poll(
407
self,
408
options: list,
409
expires_in: int,
410
multiple: bool = False,
411
hide_totals: bool = False
412
) -> dict: ...
413
```
414
415
[Polls](./polls.md)
416
417
### Timeline Management
418
419
Access various timeline feeds including specialized timelines like link and list timelines.
420
421
```python { .api }
422
def timeline_list(
423
self,
424
id: int,
425
max_id: int = None,
426
min_id: int = None,
427
since_id: int = None,
428
limit: int = None
429
) -> list: ...
430
431
def timeline_link(
432
self,
433
url: str,
434
local: bool = False,
435
max_id: int = None,
436
min_id: int = None,
437
since_id: int = None,
438
limit: int = None
439
) -> list: ...
440
```
441
442
[Timeline Management](./timelines.md)
443
444
### Administrative Tools
445
446
Instance management and moderation functionality for admin users including account and report management.
447
448
```python { .api }
449
def admin_accounts(
450
self,
451
remote: bool = False,
452
by_domain: str = None,
453
status: str = "active",
454
username: str = None,
455
display_name: str = None,
456
email: str = None,
457
ip: str = None,
458
staff: bool = None,
459
max_id: int = None,
460
since_id: int = None,
461
limit: int = None
462
) -> list: ...
463
464
def admin_account_moderate(
465
self,
466
id: int,
467
action: str = None,
468
report_id: int = None,
469
warning_preset_id: int = None,
470
text: str = None,
471
send_email_notification: bool = True
472
) -> dict: ...
473
```
474
475
[Administrative Tools](./admin.md)
476
477
## Types
478
479
```python { .api }
480
class Mastodon:
481
"""Main API client class for interacting with Mastodon instances."""
482
pass
483
484
class StreamListener:
485
"""Base class for handling streaming events."""
486
def on_update(self, status: dict): pass
487
def on_notification(self, notification: dict): pass
488
def on_delete(self, status_id: int): pass
489
def on_abort(self, err: Exception): pass
490
491
class AttribAccessDict(dict):
492
"""Dictionary with attribute-style access to keys."""
493
pass
494
495
# Exception hierarchy
496
class MastodonError(Exception):
497
"""Base exception for all Mastodon.py errors."""
498
pass
499
500
class MastodonAPIError(MastodonError):
501
"""Errors returned by the Mastodon API."""
502
pass
503
504
class MastodonNetworkError(MastodonError):
505
"""Network communication errors."""
506
pass
507
508
class MastodonRatelimitError(MastodonError):
509
"""Rate limit exceeded errors."""
510
pass
511
512
class MastodonUnauthorizedError(MastodonAPIError):
513
"""Authentication and authorization errors."""
514
pass
515
516
class MastodonNotFoundError(MastodonAPIError):
517
"""Resource not found errors."""
518
pass
519
520
class MastodonVersionError(MastodonError):
521
"""Raised when a function is called that the version of Mastodon does not support."""
522
pass
523
524
class MastodonIllegalArgumentError(ValueError, MastodonError):
525
"""Raised when an incorrect parameter is passed to a function."""
526
pass
527
528
class MastodonIOError(IOError, MastodonError):
529
"""Base class for Mastodon.py I/O errors."""
530
pass
531
532
class MastodonFileNotFoundError(MastodonIOError):
533
"""Raised when a file requested to be loaded can not be opened."""
534
pass
535
536
class MastodonReadTimeout(MastodonNetworkError):
537
"""Raised when a stream times out."""
538
pass
539
540
class MastodonServerError(MastodonAPIError):
541
"""Raised if the Server is malconfigured and returns a 5xx error code."""
542
pass
543
544
class CallbackStreamListener(StreamListener):
545
"""Stream listener that calls registered callback functions for events."""
546
def __init__(self,
547
update_handler=None,
548
local_update_handler=None,
549
delete_handler=None,
550
notification_handler=None,
551
conversation_handler=None,
552
unknown_event_handler=None): ...
553
```