Chris Amico

Journalist & programmer

Automatically posting shared links to Mastodon with Toot

I jumped from Twitter to Mastodon in November, shortly after Elon Musk took over and fired half the company’s workforce. I’ve spent less and less time on Twitter in the last few years, but it was still a good place to watch for interesting discussions and links, and to share my own work. I took the app off my phone and, for the most part, I don’t miss it.

Years ago, I set up a feed that piped stories I liked on Instapaper to my Twitter account. I honestly can’t remember how I did that, and I’m not sure how to turn it off. Twitter’s new API pricing will probably take care of that for me.

I finally got something similar – better, even – set up on Mastodon last night. It’s part of this codebase, which means I can tweak it or turn it off or turn it up whenever I want. I’m using toot, a Python client for Mastodon, on Simon Willison’s recommendation. It’s a great library, though it seems mostly intended as a CLI tool.

I decided to use it directly from Python, because I wanted to record which links I’ve already posted. That part of toot isn’t documented, but the code is easy enough to read. We’ll see if this comes back to bite me. The whole script is here.

The relevant part of the code, which posts to Mastodon and updates a SQLite table, is this function:

def post_link(link):
    "post the update and record that I did it"
    updates = get_updated_table()
    app = load_app(HOST)
    user = load_user(f"{USER}@{HOST}")
    text = link_text(link)

    update = {"link_id": link["id"]}
    try:
        result = post_status(app, user, text)
        update.update(
            {
                "posted": result["created_at"],
                "status": UpdateStatus.success,
                "post_url": result["url"],
            }
        )
    except Exception as e:
        update.update({"status": UpdateStatus.failed, "error": str(e)})

    updates.insert(update)

It’s ultimately a lot more code than Simon is using to update his COVID sewage bot, but I think I have a better understanding of what’s possible with the Mastodon API now. It definitely feels like something from the early days of Twitter, when people were inventing new ways to use a new platform, and it was fun.

I might build a bot or two.