mastocats.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python3
  2. from mastodon import Mastodon
  3. import os
  4. import requests
  5. import datetime
  6. #import json
  7. def mastocats(tag = 'mastocats', server = 'mastodon.social', maxres = 10):
  8. print("Tag: %s" % tag)
  9. print("Server: %s" % server)
  10. print("Downloading toots")
  11. def default(o):
  12. if isinstance(o, (datetime.date, datetime.datetime)):
  13. return o.isoformat()
  14. mastodon = Mastodon(api_base_url = "https://" + server)
  15. toots = []
  16. last_id = None
  17. while True:
  18. statuses = list(mastodon.timeline_hashtag(tag, local=False, max_id=last_id))
  19. if not statuses:
  20. break
  21. if len(toots) >= maxres:
  22. break
  23. toots += list(map(
  24. lambda s: {
  25. 'id': s['id'],
  26. 'created': s['created_at'],
  27. 'media': s['media_attachments'],
  28. 'account': s['account']['url']
  29. }
  30. , statuses))
  31. last_id = statuses[-1]['id']
  32. print(len(toots))
  33. #print(toots)
  34. #print(json.dumps(toots, indent=4, default=default))
  35. print("Downloading media")
  36. os.makedirs('media', exist_ok=True)
  37. for toot in toots:
  38. for media in toot['media']:
  39. ext = os.path.splitext(media['preview_url'])[1]
  40. acc = toot['account'].replace("http://","").replace("https://","").replace("/","_")
  41. fname = "|".join([toot['created'].strftime('%Y%m%d-%H%M%S'), acc, str(toot['media'].index(media) + 1)]) + ext
  42. img_name = os.path.join('media', fname)
  43. if not os.path.isfile(img_name):
  44. print(img_name)
  45. img_data = requests.get(media['preview_url']).content
  46. with open(img_name, 'wb') as handler:
  47. handler.write(img_data)
  48. print("")
  49. if __name__ == "__main__":
  50. for tag in ['mastocats', 'catsofmastodon', 'cats', 'caturday', 'catstodon']:
  51. for server in ['mastodon.social', 'mastodon.bida.im', 'chaos.social']:
  52. mastocats(tag, server, 100)