forked from pybites/challenges
-
Notifications
You must be signed in to change notification settings - Fork 11
/
usertweets.py
54 lines (39 loc) · 1.42 KB
/
usertweets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from collections import namedtuple
import csv
import os
import tweepy
from config import CONSUMER_KEY, CONSUMER_SECRET
from config import ACCESS_TOKEN, ACCESS_SECRET
DEST_DIR = 'data'
EXT = 'csv'
NUM_TWEETS = 100
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
API = tweepy.API(auth)
Tweet = namedtuple('Tweet', 'id_str created_at text')
class UserTweets(object):
def __init__(self, handle, max_id=None):
self.handle = handle
self.max_id = max_id
self.output_file = '{}.{}'.format(os.path.join(DEST_DIR, self.handle), EXT)
self._tweets = list(self._get_tweets())
self._save_tweets()
def _get_tweets(self):
tweets = API.user_timeline(self.handle, count=NUM_TWEETS, max_id=self.max_id)
return (Tweet(s.id_str, s.created_at, s.text.replace('\n', '')) for s in tweets)
def _save_tweets(self):
with open(self.output_file, 'w') as f:
writer = csv.writer(f)
writer.writerow(Tweet._fields)
writer.writerows(self._tweets)
def __len__(self):
return len(self._tweets)
def __getitem__(self, pos):
return self._tweets[pos]
if __name__ == "__main__":
for handle in ('pybites', 'techmoneykids', 'bbelderbos'):
print('--- {} ---'.format(handle))
user = UserTweets(handle)
for tw in user[:5]:
print(tw)
print()