• Skip to main content
  • Skip to after header navigation
  • Skip to site footer

Free-Mail

  • Events
  • Images
    • Instagram Goodness
  • Music
  • News
  • Software

Automate Mastodon interactions with Python

Automate Mastodon interactions with Python: Automate Mastodon interactions with Python Moshe Zadka Tue, 01/31/2023 – 03:00

The federated Mastodon social network has gotten very popular lately. It’s fun to post on social media, but it’s also fun to automate your interactions. There is some documentation of the client-facing API, but it’s a bit light on examples. This article aims to help with that.

You should be fairly confident with Python before trying to follow along with this article. If you’re not comfortable in Python yet, check out Seth Kenlon’s Getting started with Python article and my Program a simple game article.

More Python resources
What is an IDE?
Cheat sheet: Python 3.7 for beginners
Top Python GUI frameworks
Download: 7 essential PyPI libraries
Red Hat Developers
Latest Python articles

Create an application

The first step is to go to Preferences in Mastodon and select the Development category. In the Development panel, click on the New Applications button.

After creating an application, copy the access token. Be careful with it. This is your authorization to post to your Mastodon account.

There are a few Python modules that can help.

  • The httpx module is useful, given that it is a web API.
  • The getpass module allows you to paste the token into the session safely.
  • Mastodon uses HTML as its post content, so a nice way to display HTML inline is useful.
  • Communication is all about timing, and the dateutil and zoneinfo modules will help deal with that.

Here’s what my typical import list looks like:

 import httpx import getpass from IPython.core import display from dateutil import parser import zoneinfo

Paste in the token into the getpass input:

 token=getpass.getpass()

Create the httpx.Client:

 client = httpx.Client(headers=dict(Authorization=f"Bearer {token}"))

The verify_credentials method exists to verify that the token works. It’s a good test, and it gives you useful metadata about your account:

 res = client.get("https://mastodon.social/api/v1/accounts/verify_credentials")

You can query your Mastodon identity:

 res.raise_for_status() result = res.json() result["id"], result["username"]  >>> ('27639', 'moshez')

Your mileage will vary, but you get your internal ID and username in response. The ID can be useful later.

For now, abstract away the raise_for_status and parse the JSON output:

 def parse(result):     result.raise_for_status()     return result.json()

Here’s how this can be useful. Now you can check your account data by ID. This is a nice way to cross-check consistency:

 result = parse(client.get("https://mastodon.social/api/v1/accounts/27639")) result["username"]  >>> 'moshez'

But the interesting thing, of course, is to get your timeline. Luckily, there’s an API for that:

 statuses = parse(client.get("https://mastodon.social/api/v1/timelines/home")) len(statuses)  >>> 20

It’s just a count of posts, but that’s enough for now. There’s no need to deal with paging just yet. The question is, what can you do with a list of your posts? Well, you can query it for all kinds of interesting data. For instance, who posted the fourth status?

 some_status = statuses[3] some_status["account"]["username"]  >>> 'donwatkins'

Wonderful, a tweet from fellow Opensource.com correspondent Don Watkins! Always great content. I’ll check it out:

 display.HTML(some_status["content"])  

Just finished installed @fedora #Silverblue 37 on @system76 #DarterPro

“Just” finished? Wait, when was this tweet posted? I live in California, so I want the time in my local zone:

 california = zoneinfo.ZoneInfo("US/Pacific") when = parser.isoparse(some_status["created_at"]) print(when.astimezone(california))  >>> 2022-12-29 13:56:56-08:00

Today (at the time of this writing), a little before 2 PM. Talk about timeliness.

Do you want to see the post for yourself? Here’s the URL:

 some_status["url"]  >>> 'https://fosstodon.org/@donwatkins/109599196234639478'

Enjoy tooting, now with 20% more API!

Follow along as I play with the Mastodon API to create a new application.

Women in computing and open source v5
Image by:

kris krüg

Python
Alternatives

What to read next
Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.
Register or Login to post a comment.

: Opensource.com Moshe Zadka

Supporting Open Source.

Have you tried: Farking?

Share this:

  • Share on Facebook (Opens in new window) Facebook
  • Share on X (Opens in new window) X
  • Share on Pinterest (Opens in new window) Pinterest
  • Email a link to a friend (Opens in new window) Email
  • More
  • Share on Tumblr (Opens in new window) Tumblr
  • Print (Opens in new window) Print
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
Published on 31 January 2023 by Alan Category: SoftwareTag: Automate, interactions, Mastodon, Python

AmaranthCX launches detailed map of South Africa’s coal rights

South Africa in the news: AmaranthCX launches detailed map of South Africa’s coal rights: Mining …

Read moreAmaranthCX launches detailed map of South Africa’s coal rights

Staff Sports – Drop-In

Staff Sports – Drop-In – a Sport interest event taking place on 2020-01-06 00:00:00 in …

Read moreStaff Sports – Drop-In

Nice DSC_0020 photo

A nice South African Music image: DSC_0020 Image by Shaun Dewberry Image automatically curated and …

Read moreNice DSC_0020 photo

About Alan

Previous Post:Crafting An Icon: The New Moments Studded Chain
Next Post:Ukraine war: attitudes to women in the military are changing as thousands serve on front lines

Reach Trust

Reach Trust is a holding trust for a number of companies within the Stratlec Group.

Copyright © 2026 · Free-Mail · All Rights Reserved · Powered by Straton Electrical

Back to top