API explanation to touch mastodon from python

2017/04/16 update </ font>

Updated because I figured out how to toot media files

From suzuryu as comment Rewrite Mastodon.py It depends on each environment \Python27\Lib\site-packages\mastodon

Mastodon.py


    ###
    # Writing data: Media
    ###
    def media_post(self, media_file, mime_type = None):
        """
        Post an image. media_file can either be image data or
        a file name. If image data is passed directly, the mime
        type has to be specified manually, otherwise, it is
        determined from the file name.

        Throws a MastodonIllegalArgumentError if the mime type of the
        passed data or file can not be determined properly.

        Returns a media dict. This contains the id that can be used in
        status_post to attach the media file to a toot.
        """
        if os.path.isfile(media_file) and mime_type == None:
            mime_type = mimetypes.guess_type(media_file)[0]
            media_file = open(media_file, 'rb')

        if mime_type == None:
            raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.')

        random_suffix = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
        file_name = "mastodonpyupload_" + str(time.time()) + "_" + str(random_suffix) + mimetypes.guess_extension(mime_type)

        media_file_description = (file_name, media_file, mime_type)

        #Rewrite below
        #return self.__api_request('POST', '/api/v1/media', files = {'file': media_file_description}) #Old
        return self.__api_request("POST", "/api/v1/media", files = {"file" : (file_name, open(media_file, "rb"))}) #new

And you can rewrite the media file with the following code!

# -*- coding: utf-8 -*-
from mastodon import *

import warnings
warnings.simplefilter("ignore", UnicodeWarning)

def login():
    mastodon = Mastodon(
        client_id="my_clientcred_pawoo.txt",
        access_token="my_usercred_pawoo.txt",
        api_base_url="https://pawoo.net"
    )
    return mastodon

def main():
    mastodon = login()
    media_files = [mastodon.media_post(media, "image/jpeg") for media in ["test.jpg "]]
    mastodon.status_post(status="test", media_ids=media_files)

if __name__ == '__main__':
    main()

environment

  • Windows
  • Python2.7

Preparation

Installation

Download from here

> pip install Mastodon.py
Collecting Mastodon.py
  Downloading Mastodon.py-1.0.6-py2.py3-none-any.whl
Collecting dateutils (from Mastodon.py)
  Downloading dateutils-0.6.6.tar.gz
Requirement already satisfied: requests in c:\python27\lib\site-packages (from Mastodon.py)
Collecting argparse (from dateutils->Mastodon.py)
  Downloading argparse-1.4.0-py2.py3-none-any.whl
Requirement already satisfied: python-dateutil in c:\python27\lib\site-packages (from dateutils->Mastodon.py)
Requirement already satisfied: pytz in c:\python27\lib\site-packages (from dateutils->Mastodon.py)
Requirement already satisfied: six>=1.5 in c:\python27\lib\site-packages (from python-dateutil->dateutils->Mastodon.py)
Building wheels for collected packages: dateutils
  Running setup.py bdist_wheel for dateutils ... done
  Stored in directory: C:\Users\Shirokuma\AppData\Local\pip\Cache\wheels\61\60\af\2081d0cb3cfaebaab704b6012d5b1a3bdba9e0c4be33ff7e65
Successfully built dateutils
Installing collected packages: argparse, dateutils, Mastodon.py
Successfully installed Mastodon.py-1.0.6 argparse-1.4.0 dateutils-0.6.6

Registration

I will do it only once, so I will do it from the console This time, register with an instance of pawoo.net

> python
>> from mastodon import Mastodon
>> Mastodon.create_app("client name", api_base_url = "https://pawoo.net", to_file = "my_clientcred_pawoo.txt")
>> mastodon = Mastodon(client_id="my_clientcred_pawoo.txt",api_base_url = "https://pawoo.net")
>> mastodon.log_in("mail address", "passwd",to_file = "my_usercred_pawoo.txt")

API explanation

Toot relationship

Tweet on Twitter

from mastodon import *

def login():
    mastodon = Mastodon(
        client_id="my_clientcred_pawoo.txt",
        access_token="my_usercred_pawoo.txt",
        api_base_url = "https://pawoo.net"
    )
    return mastodon

def main():
    mastodon = login()
    #Toot
    mastodon.toot("Hello World Toot by Python!")

    #When tooting media files
    #I couldn't toot well for some reason(´;ω;`)
    mastodon.media_post("test.jpg ", mime_type="image/jpeg")

    #You can toot with detailed settings (for rip etc.)
    mastodon.status_post(u"Fucking lip", in_reply_to_id=None, media_ids=None, sensitive=False, visibility='', spoiler_text=None)

if __name__ == '__main__':
    main()
    

Other...

#Returns information about the user of a particular toot
status(id)

#Returns a statement or reply to a specific toot
status_context(id)

#Remove certain toots (boost?)? Confirmation required
status_delete(id)

#Favorite a particular toot
status_favourite(id)

#Returns a List of users who like a particular toot
status_favourited_by(id)

#Boost a particular toot? Confirmation required
status_reblog(id)

#Returns a List of users who boosted a particular toot
status_reblogged_by(id)

#Unfavorable for a particular toot
status_unfavourite(id)

#Unboosting certain toots
status_unreblog(id)

Timeline related

There are 5 timelines

  • home
  • local
  • public
  • hashtag
  • mentions
timeline(timeline="", max_id=None, since_id=None, limit=None)
#timeline=""Home is the default and other local, public, tag/hashtag and mentions can be specified

#If it's a hassle to specify
#home
timeline_home(max_id=None, since_id=None, limit=None)
#local
timeline_local(max_id=None, since_id=None, limit=None)
#public
timeline_publicl(max_id=None, since_id=None, limit=None)
#hashtag
timeline_hashtag(hashtag, max_id=None, since_id=None, limit=None)
#mentaions
timeline_mentaions(max_id=None, since_id=None, limit=None)

Contents of the timeline

Since timeline is a List type, take a look inside

tl = mastodon.timeline_local(limit=1)
for row in tl:
    print row

Contents (example) If you look at the Key, you can see what it is.


timeline_dict = {
    'account' : {
        'username': 'test',
        'display_name': 'hello',
        'statuses_count': 114,
        'following_count': 514,
        'url': 'https://pawoo.net/@test',
        'locked': False,
        'created_at': '2017-04-15T17:41:30.053Z',
        'avatar_static': 'https://img.pawoo.net/accounts/avatars/***.jpg?****',
        'note': 'test',
        'header': '/headers/original/missing.png', 
        'followers_count': 3, 
        'avatar': 'https://img.pawoo.net/accounts/avatars/***.jpg?****', 
        'header_static': '/headers/original/missing.png', 
        'acct': 'test',
        'id': 114514
    }
    'reblogged' : None,
    'favourites_count' : 0,
    'media_attachments' : [],
    'in_reply_to_id', None,
    'application' : {u'website': None, u'name': u'Web'},
    'reblog' : None,
    'in_reply_to_account_id' : None,
    'tags', None,
    'uri', "tag:pawoo.net,2017-04-15:objectId=114514:objectType=Status",
    'visibility' : 'public',
    'id' : 114514,
    'content' : 'hogehoge',
    'sensitive' : False,
    'favourited' : None,
    'mentions' : [],
    'reblogs_count' : 0,
    'spoiler_text': ,
    'created_at' : '2017-04-15T18:21:15.197Z'
}

Account relationship

account(id)

Then, the timeline_dict key returns the contents of the account Other...


#To block a specific user
account_block(id)

#When following a specific user
account_follow(id)

#Returns a list of followers for a particular user
account_followers(id)

#Returns a List of users that a particular user is following
account_following(id)

#Mute a specific user
account_mute(id)

#Returns whether a specific user is following, etc.
account_relationships(id)
#Example
[{u'requested': False, u'muting': False, u'followed_by': False, u'blocking': False, u'following': False, u'id': id}]

#@Search for the user with name and return the applicable result in List
account_search(q, limit=None)

#Returns a list of what a specific user said
account_statuses(id, max_id=None, since_id=None, limit=None)

#Unblock a specific user
account_unblock(id)

#Unfollow a specific user
account_unfollow(id)

#Unmute a specific user
account_unmute(id)

#Returns authenticated user information
account_verify_credentials()

#Returns a list of blocked users as a List
blocks()

#Returns a list of favorites as a List
favourites()

#Return a list of follow requests as a List
follow_requests(id, max_id=None, since_id=None, limit=None)

#Reject follow requests for specific users
follow_request_reject(id)

#Approve follow requests for specific users
follow_request_authorize(id)

#Returns a list of muted users as a List
mutes()

#Return a list of notifications as a List (toots of following users, etc.)
notifications()

That's all the functions

Download images with sensitive True

It's a bonus Since I created an account with pawoo mackerel, the code to download the chomechome image in the lawless area


# -*- coding: utf-8 -*-
from mastodon import *
import urllib2

#To silence Unicode Warning
import warnings
warnings.simplefilter("ignore", UnicodeWarning)

#log in
def login():
    mastodon = Mastodon(
        client_id="my_clientcred_pawoo.txt",
        access_token="my_usercred_pawoo.txt",
        api_base_url="https://pawoo.net"
    )
    return mastodon

#to download
def download(url, save_path):
    def get_file_name(url):
        return url.split("/")[-1]

    req = urllib2.Request(url)
    req.add_header("User-agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)")
    source = urllib2.urlopen(url).read()
    with open(save_path + "/" + get_file_name(url), 'wb') as file:
        file.write(source)

def main():
    #Login
    mastodon = login()
    
    #Get local timeline
    tl = mastodon.timeline_local()
    for row in tl:
        #Download only media files and sensitive is True
        if len(row["media_attachments"]) != 0 and row["sensitive"] == True:
            url = row["media_attachments"][0]["url"].split("?")[0]
            print row["account"]["username"], "is uploaded picture"
            download(url, "dl")
if __name__ == '__main__':
    main()
    

Recommended Posts

API explanation to touch mastodon from python
Connect to coincheck's Websocket API from Python
How to get followers and followers from python using the Mastodon API
Touch MySQL from Python 3
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Post from Python to Slack
Cheating from PHP to Python
Push notifications from Python to Android using Google's API
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Switch from python2.7 to python3.6 (centos7)
Connect to sqlite from python
Use e-Stat API from Python
Until Toot to Mastodon (Python)
I tried to create API list.csv in Python from swagger.yaml
Call Matlab from Python to optimize
Touch a Python object from Elixir
I tried to touch Python (installation)
Create folders from '01' to '12' with python
Post from python to facebook timeline
[Lambda] [Python] Post to Twitter from Lambda!
Connect to utf8mb4 database from python
Use kabu Station® API from Python
Post images from Python to Tumblr
I tried to touch Tesla's API
How to use OpenPose's Python API
Use the Flickr API from Python
Get upcoming weather from python weather api
How to access wikipedia from python
Python to switch from another language
[Python] How to use Typetalk API
Use Google Analytics API from Python
[Python] Create API to send Gmail
Handle SOAP API from Python (Zeep)
Did not change from Python 2 to 3
Update Python on Mac from 2 to 3
Make a request from Device Farm (appium python) to API Gateway
Let's touch Google's Vision API from Python for the time being
Collecting information from Twitter with Python (Twitter API)
[Python] Web application from 0! Hands-on (3) -API implementation-
[Python] Fluid simulation: From linear to non-linear
From Python to using MeCab (and CaboCha)
How to update Google Sheets from Python
Send a message from Python to Slack
Private Python handbook (updated from time to time)
[python] How to use __command__, function explanation
I want to use jar from python
Convert from katakana to vowel kana [python]
Push notification from Python server to Android
Connecting from python to MySQL on CentOS 6.4
I tried using UnityCloudBuild API from Python
Porting and modifying doublet-solver from python2 to python3.
How to access RDS from Lambda (python)
I tried to touch the COTOHA API
Python> Output numbers from 1 to 100, 501 to 600> For csv
I tried to touch Python (basic syntax)
Convert from Markdown to HTML in Python
[Amazon Linux] Switching from Python 2 series to Python 3 series
Send a message from Slack to a Python server
Edit Excel from Python to create a PivotTable
How to open a web browser from python