Skip to content

Instantly share code, notes, and snippets.

@aparrish
Last active May 6, 2023 14:29
Show Gist options
  • Save aparrish/661fca5ce7b4882a8c6823db12d42d26 to your computer and use it in GitHub Desktop.
Save aparrish/661fca5ce7b4882a8c6823db12d42d26 to your computer and use it in GitHub Desktop.
Getting credentials for the Mastodon API with Mastodon.py. Code examples released under CC0 https://creativecommons.org/choose/zero/, other text released under CC BY 4.0 https://creativecommons.org/licenses/by/4.0/

Getting credentials for the Mastodon API with Mastodon.py, step by step

Making a bot? Making a bot in Python? Making a bot in Python that uses the Mastodon API? If so, chances are you need to get some credentials. Here's how I did it!

(The following tutorial uses Python 2.7, but if you're using Python 3+ everything should work substantially the same.)

Mastodon.py authentication

I just started using it, but it looks like Mastodon.py is a pretty great library for working with the Mastodon API! However, all of the authentication examples use static files to store credentials, which I don't like—I'm afraid I'll accidentally push them to Github. I like to keep my authentication as close to the actual command that runs the program as possible, so usually I pass them on the command line to the script running my bot. To do this, I need to get the appropriate credentials on their own, as separate strings that I can cut and paste.

Before you continue, install Mastodon.py with pip:

pip install Mastodon.py

Creating the application

An "application" in the parlance of APIs means "an entity that your bots will authenticate against." (The point of an "application" is that users can decide who can act on their behalf in a fine-grained fashion, without having to reset their authentication credentials. If you were using the API such that you were making requests on some human's behalf, and they later decided they didn't want you to do that anymore, they would be able to revoke your application's privileges while retaining privileges for other applications.)

To make an application, start up an interactive interpreter session and import the Mastodon class from the module:

>>> from mastodon import Mastodon

Now, call the create_app function, like so:

>>> Mastodon.create_app('your-app-name', scopes=['read', 'write'], api_base_url="https://botsin.space")

Replace your-app-name with the name of your app. (As far as I can tell, it doesn't matter what the name is, though it should probably be unique). Fill in the api_base_url as appropriate; this is the Mastodon instance that your bot will communicate with. (Colin Mitchell set up botsin.space specifically for bots, so consider using that!) You'll get back a 2-tuple that contains the client ID and the client secret:

(u'cff45dc4cdae1bd4342079c83155ce0a001a030739aa49ab45038cd2dd739cbe', u'd228d1b0571f880c0dc865522855a07a3f31f1dbd95ad81d34163ecb3c799fee')

What do "client ID" and "client secret" mean? Who knows and who cares. For our purposes, they're just two password-like strings that you need to pass to the Mastodon API somehow when you make a request.

Getting the access token

The next value you need is an access token. You can use the client ID and client secret strings for all of your bots, but the access token will be different for each bot that you make. At this point, make a new Mastodon account on the instance you plan to run your bot on (like botsin.space) and go through the e-mail verification process. Once you've successfully logged in to your account, switch back to your interactive interpreter. To get the access token for the user you've just created, first create a new Mastodon object, passing the client ID and client secret from earlier:

>>> api = Mastodon("cff45dc4cdae1bd4342079c83155ce0a001a030739aa49ab45038cd2dd739cbe",
...   "d228d1b0571f880c0dc865522855a07a3f31f1dbd95ad81d34163ecb3c799fee",
...   api_base_url="https://botsin.space")

Don't forget to supply the api_base_url parameter; this should match the URL you provided in the create_app() call. Now, call the .log_in() method of the resulting object (which I've assigned to the variable api):

>>> api.log_in("bot-email@example.com", "bot-password", scopes=["read", "write"])

... where bot-email@example.com is the e-mail address you used to create your bot's account and bot-password is the password you used. The call will return a string with your user's access token. It'll look something like this:

u'a2d6479451122af585d90c8a11fdd722f145f7e64273c74189c45a4816f7e303'

That's your access token!

First post

You now have the three magic strings you need to make a request to the Mastodon API on behalf of your bot's user, now and for forever. To actually post something to Mastodon, first create a Mastodon object:

>>> from mastodon import Mastodon
>>> api = Mastodon(client_id, client_secret, access_token, base_url="https://botsin.space")

... replacing client_id with your client ID and client_secret with your client secret (both obtained from the call to create_app() above) and access_token with your access token (obtained from the .log_in()). Then call the Mastodon object's .toot() method with the string you want to post:

>>> api.toot("howdy universe!")

For a full example of a Mastodon bot written with Mastodon.py, see my @iceboxbreakfast source code.

@j354374
Copy link

j354374 commented Jan 15, 2021

I am using this guide to help me setup mastodon auth in gitea v1.14.

I am stuck at: api.log_in("bot-email@example.com", "bot-password", scopes=["read", "write"])

I have entered the mastodon admin accounts e-mail and password and I get:

mastodon.Mastodon.MastodonIllegalArgumentError: Invalid user name, password, or redirect_uris: ('Mastodon API returned error', 400, 'Bad Request', 'invalid_grant')

@aparrish
Copy link
Author

Hi, this tutorial is very old and I doubt it's still accurate! Unfortunately I don't have time to update it right now, so I'd advise looking elsewhere for more up-to-date information. Sorry!

@j354374
Copy link

j354374 commented Jan 17, 2021

I think it's most likely still accurate but just not specific for what I am trying to do.
I am thinking that learning how to setup a mastodon bot may give me (at some of) the knowledge required for the integration I am attempting.

@j354374
Copy link

j354374 commented Jan 20, 2021

apparish: you are right. You can now get these details from the "development" tab inside the program.

@Coursemetry
Copy link

Coursemetry commented Apr 27, 2022

Hi, this tutorial is very old and I doubt it's still accurate! Unfortunately I don't have time to update it right now, so I'd advise looking elsewhere for more up-to-date information. Sorry!

This works well, except for the last part of the code where you have to use the parameter api_base_url and not base_url that does not exist

api = Mastodon(
    client_id, 
    client_secret, 
    access_token, 
    api_base_url = 'https://botsin.space/'
    )

@astrowonk
Copy link

I'm pretty sure once you get the access_token, you don't need anything else.

    m = Mastodon(api_base_url=api_base_url,
                 access_token=access_token)

is all you need.

My bot is posting successfully with just the access_token only which I just created directly in the Developer section of the botsin.space web ui.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment