-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream_tweets.py
More file actions
74 lines (51 loc) · 1.64 KB
/
stream_tweets.py
File metadata and controls
74 lines (51 loc) · 1.64 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import tweepy
import pandas as pd
import numpy as np
import json
import os
"""
Connect to Twitter using Tweepy API, stream tweets into csv file
"""
def authenticate():
# Put auth info here (must first register app at https://apps.twitter.com/)
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
return auth
class MyStreamListener(tweepy.StreamListener):
def __init__(self):
self._tweets_streamed = 0
def on_status(self, status):
print(status.text)
def on_data(self, raw_data):
try:
data = json.loads(raw_data)
print(data['text'], "\n")
if os.path.isfile('tweets.csv'):
newfile = False
else:
newfile = True
self._tweets_streamed = 0
with open('tweets.csv', 'a') as f:
if newfile:
f.write('tweets;;\n')
f.write(data['text'])
f.write(";;\n")
self._tweets_streamed += 1
# Stop stream automatically:
if self._tweets_streamed >= 20:
print("20 tweets collected, stream terminating...")
return False
except (KeyError, IOError):
pass
def on_error(self, status_code):
if status_code == 420:
return False
api = tweepy.API(authenticate())
listener = MyStreamListener()
topic = str(input("What topic would you like to know about?\n> "))
myStream = tweepy.Stream(auth = api.auth, listener = listener)
myStream.filter(track=[topic])