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()
> 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
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")
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)
There are 5 timelines
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)
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(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
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