Create a Mastodon bot with a function to automatically reply with Python

Introduction

I tried to make a Mastodon bot and it was surprisingly easy, so I will summarize it. The only library to use is "Mastodon.py", so please pip it in advance.

Initial setting

First of all, get the application registration and authentication information on the Mastodon side. It's okay to do this once at the beginning, so delete it or comment it out when you're done.

setup.py



    from mastodon import Mastodon

    url = "imastodon.net"  #Aledres of the instance to use

    Mastodon.create_app("OtakuCDDB",  #Let's decide the client name freely
                        api_base_url=url,
                        to_file="cred.txt"
                        )

    mastodon = Mastodon(
        client_id="cred.txt",
        api_base_url=url
    )

    mastodon.log_in(
        "****@*****",  #log-in e-mail address
        "******",  #password
        to_file="auth.txt"
    )

I saved it in the authentication information, cred.txt and auth.txt, so I will use it for authentication from the next time. By the way, the client key and client secret are stored in cred.txt, and the access token is stored in auth.txt.

bot body

Now let's make the bot body. This time, we will create a bot that returns the result by hitting the API based on the content sent by the reply.

bot.py


from mastodon import Mastodon, StreamListener
import requests

class Stream(StreamListener):
    def __init__(self): #Inheritance
        super(Stream, self).__init__()
        # self.logger = logging.getLogger

    def on_notification(self,notif): #Called when a notification comes
        if notif['type'] == 'mention': #Check if the content of the notification is a reply
            content = notif['status']['content'] #It is the main body of the reply
            id = notif['status']['account']['username']
            st = notif['status']
            main(content, st, id)

def main(content,st,id):
    req = content.rsplit(">")[-2].split("<")[0].strip() #Remove extra information from the body of the reply
    r_date = requests.get(url + "?title=" + req, headers="") #Hit the api
    print(req)
    try:
        r = r_date.json()["Items"][0] #Process the returned data a little

        resr = "\n" + "Song title:" + r["Title"] + "\n" + \ #I will make the main body of the reply
               "Artist name:" + r["Artist"] + "\n" + \
               "vocal:" + ",".join(r["Vocal"]) + "\n" + \
               "Lyrics:" + ",".join(r["Word"]) + "\n" + \
               "Composition:" + ",".join(r["Composer"]) + "\n" + \
               "Arrangement:" + ",".join(r["Arranger"]) + "\n" + \
               "the work:" + ",".join(r["TieUp"]) + "\n" + \
               "brand:" + ",".join(r["Brand"]) + "\n" + \
               "Genre:" + ",".join(r["Genre"])
    except IndexError: #If the data is not registered, an error will be thrown and it will be dealt with.
        resr = "This song is not registered"

    mastodon.status_reply(st,
                          resr,
                          id,
                          visibility='unlisted') #Not listed

mastodon = Mastodon(
    client_id = "cred.txt",
    access_token = "auth.txt",
    api_base_url = "https://imastodon.net") #instance

url = "https://********" #API URL

notif = mastodon.notifications() #Get notifications
count = 0

while True:
    if notif[count]['type'] == 'mention':
        if notif[count]['status']['replies_count'] == 0: #Check if the reply has already been made
            content = notif[count]['status']['content']
            id = notif[count]['status']['account']['username']
            st = notif[count]['status']
            main(content, st, id)
            count += 1
        else:
            break
    else:
        count += 1
    count += 1

mastodon.stream_user(Stream()) #Launch stream

First of all, if you get the notification so far at startup and there is no reply, we will reply to it at once. It's okay to skip here because I just wanted to respond to the reply that flew when the program was down.

Once the stream is started, on_notification (self, notif) will be called when the notification flies, so include the reply function here. Also, there is no point in replying to reboots or favorites, so check if the notification is a reply. There seems to be no convenient way to get only replies. After that, let's do various processing appropriately and skip the reply with mastodon.status_reply that's all. Wasn't it surprisingly easy?

References

Documentation Sample using stream API in Mastodon.py 50 Python Reverse Lookup Sample Codes (Mastodon API Beginners) [Python] I made a Mastodon bot and tried it!

Recommended Posts

Create a Mastodon bot with a function to automatically reply with Python
Steps to create a Twitter bot with python
Create a Python function decorator with Class
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
Create a LINE BOT with Minette for Python
Create a tool to automatically furigana with html using Mecab from Python3
[Outlook] I tried to automatically create a daily report email with Python
Create a function in Python
Create a directory with python
I tried to automatically generate a password with Python3
[Python] How to create a 2D histogram with Matplotlib
Create folders from '01' to '12' with python
Probably the easiest way to create a pdf with Python3
Create a virtual environment with Python!
Create a Twitter BOT with the GoogleAppEngine SDK for Python
[Python] I tried to automatically create a daily report of YWT with Outlook mail
Create a message corresponding to localization with python translation string
5 Ways to Create a Python Chatbot
Let's create a program that automatically registers ID/PW from CSV to Bitwarden with Python + Selenium
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7
[Road to Python Intermediate] Call a class instance like a function with __call__
[Introduction to Python] How to split a character string with the split function
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
Try to create a python environment with Visual Studio Code & WSL
I tried to create a list of prime numbers with python
How to create a heatmap with an arbitrary domain in Python
[LINE Messaging API] Create a BOT that connects with someone with Python
Create a bot to retweet coronavirus information
Automatically create Python API documentation with Sphinx
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
[Python] [LINE Bot] Create a parrot return LINE Bot
Create a word frequency counter with Python 3.4
Let's make a Twitter Bot with Python!
[Cloudian # 3] Try to create a new object storage bucket with Python (boto3)
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
[Python] Explains how to use the range function with a concrete example
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
Steps to create a Python virtual environment with VS Code on Windows
[Introduction to Python] How to write a character string with the format function
3. Natural language processing with Python 1-2. How to create a corpus: Aozora Bunko
Create a frame with transparent background with tkinter [Python]
[Python] List Comprehension Various ways to create a list
How to read a CSV file with Python 2/3
Send a message to LINE with Python (LINE Notify)
Automatically register function arguments to argparse in Python
How to create a Python virtual environment (venv)
To execute a Python enumerate function in JavaScript
How to create a function object from a string
I want to create a window in Python
How to create a JSON file in Python
Try to draw a life curve with python
I want to make a game with Python
Create a virtual environment with conda in Python
Create a page that loads infinitely with python
[Note] Create a one-line timezone class with python
You can easily create a GUI with Python
Create a python3 build environment with Sublime Text3
Try to make a "cryptanalysis" cipher with Python