Introduction

Bot

Mastodon is a decentralized social networking platform that allows users to create and join communities, or “instances,” where they can share text, images, and other media. One way to enhance the user experience on Mastodon is by writing a bot, which is a program that performs automated tasks on the platform.

To get started, you will need to have a basic understanding of programming and be familiar with Mastodon’s API (Application Programming Interface). The API is a set of rules that govern how software applications can interact with Mastodon’s servers, allowing developers to build their own tools and integrations.

The first step in writing a Mastodon bot is to choose a programming language. Mastodon’s API can be accessed using a variety of languages, such as Python, Ruby, and JavaScript. For this example, we will be using Python, as it is a popular choice for writing bots and has a strong community of developers.

Once you have chosen your programming language, you will need to install the necessary libraries and tools. In the case of Python, you will need to install the “Mastodon.py” library, which is a Python wrapper for the Mastodon API. You can install this library using the Python package manager, “pip,” by running the following command in your terminal:

pip install Mastodon.py

Next, you will need to register your bot with Mastodon. This is necessary to obtain the necessary credentials to authenticate your bot with Mastodon’s servers. To register your bot, you will need to create a new application on Mastodon and obtain a client ID and client secret. You can do this by going to your Mastodon account settings and selecting the “Developers” tab. From there, you can create a new application and obtain the necessary credentials.

With the necessary libraries and credentials in place, you can now start writing your Mastodon bot. The first thing you will need to do is create a Mastodon API client. This is done by importing the Mastodon library and calling the Mastodon.Mastodon() function, passing in your client ID, client secret, and the URL of the Mastodon instance you want to connect to.

Once you have created your API client, you can use it to perform various actions on Mastodon, such as posting statuses, following other users, and more. For example, to post a new status, you can use the client’s “status_post()” function, passing in the text of your status as an argument.

It’s also a good idea to include error handling in your bot to handle any issues that may arise during its execution. For example, you can use try-except blocks to catch any exceptions that may be thrown by Mastodon’s API.

Finally, you will need to decide how you want your bot to be triggered. There are a few different options for this, such as using a scheduled task to run your bot at regular intervals or setting up a webhook to trigger your bot in response to certain events on Mastodon.

In conclusion, writing a Mastodon bot is a relatively straightforward process that can be accomplished with a basic understanding of programming and the Mastodon API. By following the steps outlined above, you can create a useful and fun tool to enhance the user experience on Mastodon.

get coordinates from a content

def getCoordinates(post):
    pos_coords = re.findall(r'(\( *-?[0-9]+\.[0-9]+ *, *-?[0-9]+\.[0-9]+ *\))', post['content'])

    if len(pos_coords) == 0:
        return None

    coord = None

    for i in pos_coords:
        c = i.replace(" ","")[1:-1].split(",")
        lat = float(c[0])
        lon = float(c[1])

        if lat <= -90 or lat >= 90:
            continue

        if lon <= -180 or lon >= 180:
            continue

        coord = f"{lat:.2f}/{lon:.2f}"
    return coord

Get the prediction image and upload to the mastodon server

def getImageAndUpload(coord, name, mastodon):
    media = None

    try:
        url = f"https://clearoutside.com/forecast_image_large/{coord}/forecast.png"
        r   = requests.get(url)
        open("/tmp/forecast.png", "wb").write(r.content)
        media = mastodon.media_post("/tmp/forecast.png", description=f"Weather prediction for astronomical observations for {coord}")

        if os.path.exists("/tmp/forecast.png"):
            os.remove("/tmp/forecast.png")
    except:
        print("error with downloads")

    return media, f"Moin @{name}, here are the current weather predictions in great details #bot #servicetoot: https://clearoutside.com/forecast/{coord}"

Get the notifications

mastodon = Mastodon(access_token = '/root/clearoutsidebot/token.secret', api_base_url = 'https://botsin.space')
toots    = mastodon.notifications(types = ["mention"], min_id = min_id)

Process toots

for toot in toots:
    min_id = toot['id']
    name   = toot['account']['acct']
    userid = toot['account']['id']
    id     = toot['status']['id']
    status = toot['status']
    mastodon.status_favourite(id)
    mastodon.account_follow(userid)
    coord  = getCoordinates(status)
    print(f"Send message to {name}")

    if coord == None:
        text = f"Moin @{name}, please use \"(lat,long)\" e.g. (52.61,13.6) in your post to get current weather predictions. #bot #servicetoot"
        mastodon.status_post(text, in_reply_to_id = id)
    else:
        media, text = getImageAndUpload(coord, name, mastodon)
        mastodon.status_post(text, in_reply_to_id = id, media_ids = [media])