archive-tweets.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/python
  2. import tweepy
  3. import pytz
  4. import os
  5. # Parameters.
  6. me = 'username'
  7. urlprefix = 'http://twitter.com/%s/status/' % me
  8. tweetdir = os.environ['HOME'] + '/Dropbox/twitter/'
  9. tweetfile = tweetdir + 'twitter.txt'
  10. idfile = tweetdir + 'lastID.txt'
  11. datefmt = '%B %-d, %Y at %-I:%M %p'
  12. homeTZ = pytz.timezone('US/Central')
  13. utc = pytz.utc
  14. def setup_api():
  15. """Authorize the use of the Twitter API."""
  16. a = {}
  17. with open(os.environ['HOME'] + '/.twitter-credentials') as credentials:
  18. for line in credentials:
  19. k, v = line.split(': ')
  20. a[k] = v.strip()
  21. auth = tweepy.OAuthHandler(a['consumerKey'], a['consumerSecret'])
  22. auth.set_access_token(a['token'], a['tokenSecret'])
  23. return tweepy.API(auth)
  24. # Authorize.
  25. api = setup_api()
  26. # Get the ID of the last downloaded tweet.
  27. with open(idfile, 'r') as f:
  28. lastID = f.read().rstrip()
  29. # Collect all the tweets since the last one.
  30. tweets = api.user_timeline(me, since_id=lastID, count=200, include_rts=True)
  31. # Write them out to the twitter.txt file.
  32. with open(tweetfile, 'a') as f:
  33. for t in reversed(tweets):
  34. ts = utc.localize(t.created_at).astimezone(homeTZ)
  35. lines = ['',
  36. t.text,
  37. ts.strftime(datefmt).decode('utf8'),
  38. urlprefix + t.id_str,
  39. '- - - - -',
  40. '']
  41. f.write('\n'.join(lines).encode('utf8'))
  42. lastID = t.id_str
  43. # Update the ID of the last downloaded tweet.
  44. with open(idfile, 'w') as f:
  45. lastID = f.write(lastID)