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\n{puppy_tags}", 'visibility': 'public', 'media_ids[]': [uploaded.id]} post_result = post(post_endpoint, headers=puppy_hdr, data=status_record) if post_result.reason == 'OK': print(loads(post_result.text)['url']) else: print('Something went wrong; ' + post_result.reason) else: print('Upload did not go thru; ' + upload_result.reason) else: print('Unsplash api not cooperating; ' + unsplash_result.reason)