| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- import json
- import requests
- from mastodon import Mastodon
- import config
- import sys
-
- def get_images(album_api):
- return requests.get(album_api).json()['result']['images']
-
- def get_next_image(images, previous_creation_date):
- tail = [image for image in images if image['date_creation']>previous_creation_date]
- return tail and sorted(tail, key=lambda image: image['date_creation'])[0] or None
-
- def get_previous_creation_date():
- try:
- return json.load(open("previous_creation_date.txt"))
- except Exception:
- return ""
-
- def set_previous_creation_date(previous_creation_date):
- json.dump(previous_creation_date, open("previous_creation_date.txt", "w"))
-
- def toot_next_image():
- mastodon = Mastodon(access_token="secrets.txt")
- image = get_next_image(get_images(config.ALBUM_API), get_previous_creation_date())
- if image:
- if image['comment'] is None:
- image['comment'] = "" # Better not mess up templates when no comment.
- media = mastodon.media_post(
- requests.get(
- image["derivatives"][config.MEDIA_SIZE]["url"]).content,
- mime_type="image/jpeg",
- description = config.ALT_TEXT_TEMPLATE.format(**image))
- mastodon.status_post(
- config.TOOT_TEMPLATE.format(**image),
- media_ids=[media],
- visibility=config.TOOT_VISIBILITY,
- language=config.TOOT_LANGUAGE)
- set_previous_creation_date(image['date_creation'])
-
- if __name__=='__main__':
- toot_next_image()
|