from requests import get, post from globals import * from json import loads from munch import DefaultMunch, Munch from urllib.request import urlopen post_endpoint = bots_endpoint + '/api/v1/statuses' media_endpoint = bots_endpoint + '/api/v1/media' puppy_tags = '#PuppyBot #Bot #Puppies #PetBot #Puppy #Unsplash' unsplash_hdr = {'Authorization': 'Client-ID ' + unsplash_token} puppy_hdr = {'Authorization': 'Bearer ' + puppybot_token} unsplash_result = get(unsplash_ep, headers=unsplash_hdr) if unsplash_result.reason == 'OK': picture_details = DefaultMunch.fromDict(loads(unsplash_result.text)) alt_text = picture_details.alt_description or picture_details.description file = {'file': (picture_details.slug, urlopen(picture_details.urls.raw), 'image/jpg')} payload = {'description': alt_text} upload_result = post(media_endpoint, headers=puppy_hdr, data=payload, files=file) if upload_result.reason == 'OK': uploaded = DefaultMunch.fromDict(loads(upload_result.text)) status_record = {'spoiler_text': 'Random puppy image courtesy of Unplash.com', 'status': f"{picture_details.description or picture_details.alt_description}\n({picture_details.user.name} - {picture_details.links.html})\n\n{puppy_tags}\n and because unsplash photos don\'t always have it ... #AltText4Me", 'visibility': 'public', 'media_ids[]': [uploaded.id]} post_result = post(post_endpoint, headers=puppy_hdr, data=status_record) if post_result.reason == 'OK': notify(-1, 'puppybot: ' + loads(post_result.text)['url']) else: notify(0, 'Status update did not go through; ' + post_result.reason) else: notify(0, 'Upload did not go through; ' + upload_result.reason) else: notify(0, 'Unsplash api call did not go through; ' + unsplash_result.reason)