Building a Mastodon Chatbot With ChatGPT


I had a random thought, triggered perhaps by the tinnitus that is constantly eeeeeeee-ing in the background of everything. What if there was a Mastodon bot that just replied to every toot that mentioned it, with a string of eeeeeee’s of the same length as the message?

The second semi-random thought was that I had no idea how to even start to build such a thing.

The third obvious-in-2023 thought was that I’d bet ChatGPT could help with this somehow.

So… I fired up the Infernal Stochastic Gibberish Generator and fed it this prompt:

screenshot of a prompt fed to ChatGPT: Build a Mastodon bot that replies to every message by converting the message into “eeeeee” of corresponding message length"

I figured it’d maybe give me a skeleton of a file that I could cobble into eventually working. I mean. I didn’t even specify a language or anything. Friends, expectations were not high.

screenshot of 2 toots, one asking @tinnitus “hey, tinnitus but. is this thing on?” and the other responding “eeeeeeeeeeeeeeeeeeeeeeeeeeee”

Colour me surprised.

See below for the full response from ChatGPT. There were a few intermediate steps. ChatGPT’s response actually generated a pretty amazing walkthrough for building the bot, complete with instructions and source code. I had to tweak it a bit because I have python3 installed via brew.sh, but aside from having to use pip3 instead of pip, and python3 instead of python, this just worked (after creating an account and setting up an application in that account’s development area and copying an access token…

The bot currently lives on Mastodon at @tinnitus@social.ds106.us

The whole thing took me less than 30 minutes, from start to publishing this post.

So now I have a file, saved on my laptop as tinnitus_bot.py, that I can run periodically and it will automatically respond to messages with “eeeeeeee” of appropriate length.

And now I can add Software Engineer to my LinkedIn profile…

[SpongeBob “5 minutes later” title card goes here]

So… the python script below doesn’t have a way to track if the bot has already responded to the message previously, so every time it runs it responds to all messages that mentions it. That’s probably non-optimal behaviour? I did a follow-up to ask ChatGPT to only respond to new messages, but it only generated a weird for-loop test that didn’t seem to actually do anything?

Maybe there’s still a role for humans after all? If nothing else, for verifying and rewriting the code that looks like it works but doesn’t quite do what you want. I’ll poke around to see if I can do the human-code-cobbling bit to make it work as intended.

[SpongeBob “1 eternity later” title card goes here]

I decided not to cobble it manually - the point was to see if ChatGPT could produce a workable bot. A few back-and-forths, pointing out that it was replying to previous messages and pointing out error messages that were thrown due to type casting of values, and it works! I think.

I also had ChatGPT generate the crontab entry so that the script will run every 15 minutes (as long as my laptop is awake anyway) and use Dall-E to create an avatar and header images for the account.

screenshot of the Mastodon profile for Tinnutus Bot

eeeeeeeeeeeeeeeeeeeeee.

The tinnitus-bot is now running on a Raspberry Pi, on my home internet connection. It will occasionally be fighting RetroPie for CPU time. Probably not the most reliable hosting setup, but it’s just an experimental bot, a piece of performance art. It’s currently set to run every 5 minutes, assuming everything is working as expected…

The response from ChatGPT, after some back-and-forth to troubleshoot and convince it to only reply to new messages:

Building a Mastodon bot that replies to every message with “eeeeeeeee” of corresponding message length involves using the Mastodon API and a programming language like Python. I’ll provide you with a basic Python script using the Mastodon.py library to achieve this. Please note that you need to have Python and the Mastodon.py library installed on your system.

  1. Install the Mastodon.py library:
pip install Mastodon.py
  1. Create a Python script (e.g., mastodon_bot.py) with the following code:
from mastodon import Mastodon
import re

# Replace these with your Mastodon credentials
instance_url = 'https://your-mastodon-instance.com'
access_token = 'your-access-token'

# Create an instance of Mastodon
mastodon = Mastodon(
    access_token=access_token,
    api_base_url=instance_url
)

# File to store the replied message IDs
data_file = 'replied_messages.txt'

def load_replied_messages():
    replied_messages = set()
    if os.path.exists(data_file):
        with open(data_file, 'r') as file:
            replied_messages = set(line.strip() for line in file)
    return replied_messages

def save_replied_messages(replied_messages):
    with open(data_file, 'w') as file:
        file.write('\n'.join(str(message_id) for message_id in replied_messages))

# Set to keep track of replied messages
replied_messages = load_replied_messages()

def get_unreplied_mentions():
    # Fetching mentions
    mentions = mastodon.notifications()
    unreplied_mentions = []
    
    for mention in mentions:
        if mention["type"] == "mention":
            status_id = mention["status"]["id"]
            if str(status_id) not in replied_messages:  # Ensure message ID is a string
                unreplied_mentions.append(mention)
                replied_messages.add(str(status_id))  # Ensure message ID is a string
    
    return unreplied_mentions

def reply_to_mentions():
    unreplied_mentions = get_unreplied_mentions()

    for mention in unreplied_mentions:
        account_id = mention["account"]["id"]
        content = mention["status"]["content"]
        
        # Extract the message content without any HTML tags
        message = re.sub(r'<.*?>', '', content)
        
        # Reply with 'e' repeated based on the message length
        reply_text = 'e' * len(message)
        
        # Post the reply
        mastodon.status_post(f"@{mention['account']['acct']} {reply_text}", in_reply_to_id=mention["status"]["id"], visibility="direct")

    # Save the replied message IDs
    save_replied_messages(replied_messages)

if __name__ == '__main__':
    reply_to_mentions()
  1. Fill in your Mastodon instance URL and access token in the script.

  2. Run the script:

python mastodon_bot.py

The script will check for new mentions on your Mastodon account and reply to each mention with “e” repeated the number of times corresponding to the length of the original message.

Remember that running a bot should be done responsibly and following the rules and guidelines set by the Mastodon instance you are using. Always respect other users’ privacy and consent before interacting with their content.


comments powered by Disqus