The blog.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

97 lines
2.2 KiB

  1. from twitter import *
  2. import pprint
  3. import json
  4. import pathlib
  5. import urllib
  6. import twauth
  7. forcerefetch = False
  8. base_dir = pathlib.Path('content') / 'twitter'
  9. imgbase_dir = pathlib.Path('content') / 'media' / 'twitter'
  10. # Info for getting alt text.
  11. # Requires a project, which requires a phone number, which it rejects my home phone
  12. # https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/media
  13. def write_media(media):
  14. mediaurl = media['media_url_https']
  15. parts = urllib.parse.urlparse(mediaurl)
  16. fname = pathlib.PurePosixPath(parts.path).name
  17. imgpath = imgbase_dir / fname
  18. if not forcerefetch and imgpath.exists():
  19. print('media exists', fname)
  20. return
  21. resp = urllib.request.urlopen(mediaurl)
  22. try:
  23. if resp.getcode() == 200:
  24. with open(imgpath, 'wb') as fp:
  25. d = None
  26. while d != b'':
  27. d = resp.read1()
  28. fp.write(d)
  29. finally:
  30. resp.close()
  31. def write_tweet(tweet):
  32. twpath = base_dir / (tweet['id_str'] + '.yaml')
  33. if not forcerefetch and twpath.exists():
  34. print('exists', tweet['id_str'])
  35. return
  36. #pprint.pprint(repr(tweet))
  37. try:
  38. # Has media to d/l
  39. for i in tweet['entities']['media']:
  40. write_media(i)
  41. except KeyError as e:
  42. pass
  43. with open(twpath, 'w') as fp:
  44. print('write:', tweet['id_str'])
  45. # wrap in --- to mark as metadata for hyde/jinja2
  46. print('---', file=fp)
  47. json.dump(tweet, fp)
  48. # dump doesn't terminate w/ nl
  49. print('', file=fp)
  50. print('---', file=fp)
  51. def act_my_thread(tw, start_tw_id, stop_tw_id):
  52. tw_id = int(stop_tw_id)
  53. while True:
  54. # https://alexwlchan.net/2022/11/tweet-alt-text/
  55. base_tw = tw.statuses.show(_id=tw_id, tweet_mode='extended', include_ext_alt_text=True)
  56. write_tweet(base_tw)
  57. if start_tw_id == tw_id:
  58. break
  59. tw_id = base_tw['in_reply_to_status_id']
  60. if __name__ == '__main__':
  61. args, kwargs = twauth.twit_argskw
  62. tw = Twitter(*args, **kwargs)
  63. # https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-show-id
  64. #print(repr(tw.statuses.show(_id=1556349580932833280)))
  65. with open('tweets.txt') as fp:
  66. for i in fp:
  67. action, tw_id, *extra = i.split()
  68. tw_id = int(tw_id)
  69. locals()['act_%s' % action](tw, tw_id, *extra)
  70. print('done')