--Make a bot to return the parrot --Grasp the rough flow of Mastodon Bot created using mastodon.py
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.
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.
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
Just type pip install mastodon.py
in your terminal. pip is convenient.
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.
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
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