-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitter_stream_utils.py
231 lines (201 loc) · 8.04 KB
/
twitter_stream_utils.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import time
import csv
import sys
# Create a streamer object
class StdOutListener(StreamListener):
# Define a function that is initialized when the miner is called
def __init__(self, api = None):
# That sets the api
self.api = api
# Create a file with 'data_' and the current time
self.filename = 'data'+'_'+ time.strftime('%Y%m%d-%H%M%S') +'.csv'
# Create a new file with that filename
csvFile = open(self.filename, 'w')
# Create a csv writer
csvWriter = csv.writer(csvFile)
# Write a single row with the headers of the columns
csvWriter.writerow(['text',
'created_at',
'geo',
'lang',
'place',
'coordinates',
'user.favourites_count',
'user.statuses_count',
'user.description',
'user.location',
'user.id',
'user.created_at',
'user.verified',
'user.following',
'user.url',
'user.listed_count',
'user.followers_count',
'user.default_profile_image',
'user.utc_offset',
'user.friends_count',
'user.default_profile',
'user.name',
'user.lang',
'user.screen_name',
'user.geo_enabled',
'user.profile_background_color',
'user.profile_image_url',
'user.time_zone',
'id',
'favorite_count',
'retweeted',
'source',
'favorited',
'retweet_count'])
# When a tweet appears
def on_status(self, status):
# Open the csv file created previously
csvFile = open(self.filename, 'a')
# Create a csv writer
csvWriter = csv.writer(csvFile)
# If the tweet is not a retweet
if not 'RT @' in status.text:
# Try to
try:
# Write the tweet's information to the csv file
csvWriter.writerow([status.text,
status.created_at,
status.geo,
status.lang,
status.place,
status.coordinates,
status.user.favourites_count,
status.user.statuses_count,
status.user.description,
status.user.location,
status.user.id,
status.user.created_at,
status.user.verified,
status.user.following,
status.user.url,
status.user.listed_count,
status.user.followers_count,
status.user.default_profile_image,
status.user.utc_offset,
status.user.friends_count,
status.user.default_profile,
status.user.name,
status.user.lang,
status.user.screen_name,
status.user.geo_enabled,
status.user.profile_background_color,
status.user.profile_image_url,
status.user.time_zone,
status.id,
status.favorite_count,
status.retweeted,
status.source,
status.favorited,
status.retweet_count])
# If some error occurs
except Exception as e:
# Print the error
print(e)
# and continue
pass
# Close the csv file
csvFile.close()
# Return nothing
return
# When an error occurs
def on_error(self, status_code):
# Print the error code
print('Encountered error with status code:', status_code)
# If the error code is 401, which is the error for bad credentials
if status_code == 401:
# End the stream
return False
# When a deleted tweet appears
def on_delete(self, status_id, user_id):
# Print message
print("Delete notice")
# Return nothing
return
# When reach the rate limit
def on_limit(self, track):
# Print rate limiting error
print("Rate limited, continuing")
# Continue mining tweets
return True
# When timed out
def on_timeout(self):
# Print timeout message
print(sys.stderr, 'Timeout...')
# Wait 10 seconds
time.sleep(10)
# Return nothing
return
def start_mining(keywords):
#Variables that contains the user credentials to access Twitter API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
stream = Stream(auth, l)
stream.filter(track = keywords)
# start_mining(['#eleicaobrasil', '#eleiçãobrasil'])
#import json
#from tweepy import Cursor
#from twitter_client import get_twitter_client
#
#
#if __name__ == '__main__':
# client = get_twitter_client()
#
# with open('home_timeline.jsonl', 'w') as f:
# for page in Cursor(client.home_timeline, count=200).pages(4):
# for status in page:
# f.write(json.dumps(status._json)+"\n")
#import string
#import time
#from tweepy import Stream
#from tweepy.streaming import StreamListener
#from twitter_client import get_twitter_auth
#
#class CustomListener(StreamListener):
# def __init__(self, fname):
# safe_fname = format_filename(fname)
# self.outfile ="stream_%s.jsonl" %safe_fname
#
# def on_data(self,data):
# try:
# with open(self.outfile, 'a') as f:
# f.write(data)
# return True
# except BaseException as e:
# sys.stderr.write("Error on_data: {}\n".format(e))
# time.sleep(5)
# return True
#
# def on_error(selg, status):
# if status == 420:
# sys.stderr.write("Rate limit exceeded\n")
# return False
# else:
# sys.stderr.write("Error {}\n".format(status))
# return True
#
#def format_filename(fname):
# return ' '.join(convert_valid(one_char) for one_char in fname)
#
#def convert_valid(one_char):
# valid_chars ="-_.%s%s" % (string.ascii_letters, string.digits)
# if one_char in valid_chars:
# return one_char
# else:
# return '_'
#
#if __name__ == '__main__':
# query = sys.argv[1:]
# query_fname = ' '.join(query)
# auth = get_twitter_auth()
# twitter_stream = Stream(auth, CustomListener(query_fname))
# twitter_stream.filter(track=query, async=True)