[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】

Target

--Make a bot to return the parrot --Grasp the rough flow of Mastodon Bot created using mastodon.py

Environment

First of all, since you are programming in Python, you need to prepare ** Python **. Also, in order to make MastodonBot, you need a library [^ 2] for getting API [^ 1] prepared by some amazing person called ** mastodon.py **. Prepare the library using something called ** pip **, which makes it easy to install the Python library. Basically, pip is available when you install Python. It is necessary to prepare a ** access token ** in the bot code to determine which instance [^ 3] has the behavior written in which account. So

1-1. Python 1-2. pip 2. ** mastodon.py (library) ** 3. ** Access token **

Is necessary. Let's prepare in order.

1-1. Python preparation

https://www.python.org/downloads/ Download and install Python from this site. Basically, it is the latest, and you can download the one for the OS of your environment (Windows, Mac, etc.). Let's start the file installed earlier and perform setup. Check something like Add Python 3.X.X to PATH and put it in your PATH. [^ 4] Then press Install Now.

1-2. Preparation of pip

I think most people will go through this process because it seems to be basically installed in Python. Make sure you have pip in it. Start the terminal provided in the OS. It's the "command prompt" in Windows. For Windows, start "Run" with Win + R and type cmd to execute it, and you can start the command prompt. If you don't know how to start up, please google each one. (Abandoned) If you type python -m pip -V (be careful not to confuse the case) in the terminal and get the pip version, pip is already included.

** If pip is not included ** Please refer to the following article. https://qiita.com/Chino_Kafuu/items/6be7aa6798c7d7dcc129

2. Preparation of mastodon.py

Just type pip install mastodon.py in your terminal. pip is convenient.

3. Access token preparation

Please log in to the account you want to operate as a bot with the instance you want to operate as a bot. If you don't know what you're talking about, just access Mastodon, which you always use, with your browser. Press User Preferences (gear icon) and press the Development tab. There is a button to create a new app, so let's press it. Please like the app name. However, please note that anyone can see the app name. You can check the access token by saving and pressing the app name again. You can use this access token to make the account behave as you like.

Let's write the code

Finally, the environment for making Mastodon Bot has been completed. Create a folder for your bot to make it easier to organize, and create a python file there, like MastodonBot.py. We will write the bot code in this file. Open this file with your favorite text editor [^ 5]. First of all, please copy and paste the following code and modify the access token and URL.

Bot.py


from mastodon import Mastodon, StreamListener

#The main behavior of the bot is described here.
class Bot(StreamListener):
    #The place where the bot prepares. So-called magic.
    def __init__(self):
        super(Bot, self).__init__()
    #If there is a movement in the local timeline of the account, it will read the behavior inside with the information of the new toot.
    def on_update(self, status):
        pass

def Login():
    mastodon = Mastodon(
                access_token = "*******************",           #Put the access token you got earlier here.
                api_base_url = "https://mastodonexample.com"    #Write the URL of the Mastodon instance here
                )
    return mastodon

def LTLlisten(mastodon):
    bot = Bot()
    mastodon.stream_local(bot)

#Login process
mastodon = Login()
LTLlisten(mastodon)

The on_update function in this code is read when the LTL (local timeline) runs. And the information of the new toot that flowed to LTL is assigned to the status variable as a json file [^ 6]. We will rewrite and add the pass part in this code to create the bot process! !!

First, let's display the text of the new toot in the terminal. Let's omit the information in the text in status. You can get the information of the text by writing status ['content']. Let's display it with the print function.

Bot.py


    #If there is a movement in the local timeline of the account, it will read the behavior inside with the information of the new toot.
    def on_update(self, status):
        print(status['content'])

If you do this in a terminal, the text will appear in the terminal. But when I look at it <p> Yaharo </ p> It has an html

tag like this. Python has a method called replace that replaces part of a string. Let's use it to remove the

tag.

Bot.py


    #If there is a movement in the local timeline of the account, it will read the behavior inside with the information of the new toot.
    def on_update(self, status):
        content = status['content'].replace('<p>', '').replace('</p>', '')
        print(content)

If you write it like this, the

tag will disappear and the text will look better. With this, the information in the text can be extracted. Let's finally make a parrot return bot. There is a function that makes the bot toot. It is mastodon.toot (). If you put a character string in this (), the sentence will be tooted.

Bot.py


    #If there is a movement in the local timeline of the account, it will read the behavior inside with the information of the new toot.
    def on_update(self, status):
        mastodon.toot('That's interesting!')     #Please do not execute this as it will be annoying if you execute it as it is.

However, with this code, it becomes an annoying bot that toots something every time someone toots. Let's set the conditions for movement and control it.

Bot.py


    #If there is a movement in the local timeline of the account, it will read the behavior inside with the information of the new toot.
    def on_update(self, status):
        content = status['content'].replace('<p>', '').replace('</p>', '')
        if 'interesting?' in content:
            mastodon.toot('That's interesting!')

Is the conditional statement interesting in the string content? The condition is whether or not is included. Now you're no longer an annoying bot. Let's toot the text that you just got!

Bot.py


    #If there is a movement in the local timeline of the account, it will read the behavior inside with the information of the new toot.
    def on_update(self, status):
        content = status['content'].replace('<p>', '').replace('</p>', '')
        if '!Parrot' in content:
            mastodon.toot(content)      #Please do not execute this as it will be annoying if you execute it as it is.

I prepared a trigger like a command that the bot reacts like a bot. However, if you execute it as it is, it will be difficult. (It's annoying, but you can see it when you try it.) What will happen? When the bot is newly tooted, the LTL will move, so read the on_update function again. The body should contain ! Parrot, so the bot will react to the bot's toot. Repeat this and cause an infinite loop forever until the bot stops. Let's prevent this. There are several workarounds, but I'll show you one of them.

Bot.py


    #If there is a movement in the local timeline of the account, it will read the behavior inside with the information of the new toot.
    def on_update(self, status):
        content = status['content'].replace('<p>', '').replace('</p>', '')
        if '!Parrot' in content:
            content = content.replace('!Parrot', '')
            mastodon.toot(content)

Let's remove the trigger part from the replace method introduced earlier. When a toot containing the string'! Parrot' flows into the LTL, it is now echoed back. This completes the parrot return bot! !! !!

In addition to mastodon.toot (), there are many functions that allow bots to behave in various ways. If you study with reference to the reference here, you will be able to make your favorite bot. Japanese translation mastodon.py reference

Reference article for this article

Is your order a Mastodon Bot? For first-time users who want to move now ☕ https://qiita.com/Chino_Kafuu/items/6be7aa6798c7d7dcc129

[^ 1]: A tool-like one that returns data in a file such as json [^ 6] to make it easier to mess with data externally [^ 2]: A file that collects various useful functions in python.
Functions can be used by writing import xxx or from xxx import yyy, zzz. [^ 3]: Each Mastodon server. [^ 4]: If you put it in PATH, when you use a python command in the terminal, you can use it just by writing python without writing the location of the python file. Think of it as magic that will come in handy if you don't understand it. [^ 5]: A tool used to write programming and other code. Notepad is also a text editor, but there are free and convenient text editors such as VSCode, Vim, Atom, so let's use the one you like. By the way, when you download Python, it seems that the text editor IDLE for Python is included. [^ 6]: One of the methods of describing a file that stores data. I often see it on the web.

Recommended Posts

[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want to make a game with Python
I want to write to a file with Python
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
I want to work with a robot in python.
[Python] I want to make a nested list a tuple
I want to run a quantum computer with Python
I want to debug with Python
If you want to make a discord bot with python, let's use a framework
Create a Mastodon bot with a function to automatically reply with Python
I want to make a blog editor with django admin
I want to make a click macro with pyautogui (outlook)
I want to send a message from Python to LINE Bot
I want to make input () a nice complement in python
[Mac] I want to make a simple HTTP server that runs CGI with Python
I want to build a Python environment
I want to analyze logs with Python
I want to play with aws with python
Let's make a Twitter Bot with Python!
[5th] I tried to make a certain authenticator-like tool with python
I want to use a wildcard that I want to shell with Python remove
I want to know the weather with LINE bot feat.Heroku + Python
[2nd] I tried to make a certain authenticator-like tool with python
[3rd] I tried to make a certain authenticator-like tool with python
I want to do a full text search with elasticsearch + python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I want to make a voice changer using Python and SPTK with reference to a famous site
I want to make matplotlib a dark theme
I want to use MATLAB feval with python
Make a Twitter trend bot with heroku + Python
I want to create a window in Python
Try to make a "cryptanalysis" cipher with Python
I want to use Temporary Directory with Python2
#Unresolved I want to compile gobject-introspection with Python3
I want to solve APG4b with Python (Chapter 2)
Try to make a dihedral group with Python
I want to make C ++ code from Python code!
I made a Mattermost bot with Python (+ Flask)
Python: I tried to make a flat / flat_map just right with a generator
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I want to make a web application using React and Python flask
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
Even beginners want to say "I fully understand Python"
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I made a Twitter BOT with GAE (python) (with a reference)
I want to iterate a Python generator many times
I want to generate a UUID quickly (memorandum) ~ Python ~
I want to transition with a button in flask
Try to make a command standby tool with python
I tried to make a simple mail sending application with tkinter of Python
I want to handle optimization with python and cplex
I want to climb a mountain with reinforcement learning
I tried to draw a route map with Python
I want to write in Python! (2) Let's write a test