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.
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.
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?
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