forked from jdevoo/twecoll
-
Notifications
You must be signed in to change notification settings - Fork 3
/
twecoll3.py
391 lines (330 loc) · 13.5 KB
/
twecoll3.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import os
import click
import yaml
import json
from TwitterAPI import TwitterAPI, TwitterPager
from tqdm import tqdm
import urllib.parse
import time
import datetime
import lxml.etree as etree
FDAT_DIR = 'fdat'
def encode_query(query):
'''
To preserve the original query, the query is
url-encoded with no safe ("/") characters.
'''
return (urllib.parse.quote(query.strip(), safe=''))
def load_config(file='config.yaml'):
if os.path.exists(file):
with open(file, 'r') as ymlfile:
config = yaml.safe_load(ymlfile)
return (config)
else:
click.echo('No configuration found.')
return(twitter_setup())
def write_config(api_key, api_secret_key, file='config.yaml'):
config = dict(
twitter=dict(
api_key=api_key,
api_secret_key=api_secret_key
)
)
with open(file, 'w') as ymlfile:
yaml.dump(config, ymlfile, default_flow_style=False)
return (load_config(file))
def create_api(config):
api = TwitterAPI(config['twitter']['api_key'],
config['twitter']['api_secret_key'],
auth_type='oAuth2'
)
return (api)
def respectful_api_request(*args):
'''Respects api limits and retries after waiting.'''
r = api.request(*args)
if r.headers['x-rate-limit-remaining'] == '0':
waiting_time = int(
r.headers['x-rate-limit-reset']) - int(round(time.time()))
click.echo(
'Hit the API limit. Waiting for refresh at {}.'
.format(datetime.datetime.utcfromtimestamp(int(r.headers['x-rate-limit-reset']))
.strftime('%Y-%m-%dT%H:%M:%SZ')))
time.sleep(waiting_time)
return (respectful_api_request(*args))
return(r)
def collect_friends(account_id, cursor=-1, over5000=False):
'''Get IDs of the accounts a given account follows
over5000 allows to collect more than 5000 friends'''
ids = []
r = respectful_api_request(
'friends/ids', {'user_id': account_id, 'cursor': cursor})
# todo: wait if api requests are exhausted
if 'errors' in r.json():
if r.json()['errors'][0]['code'] == 34:
return(ids)
for item in r:
if isinstance(item, int):
ids.append(item)
elif 'message' in item:
print('{0} ({1})'.format(item['message'], item['code']))
if over5000:
if 'next_cursor' in r.json:
if r.json['next_cursor'] != 0:
ids = ids + collect_friends(account_id, r.json['next_cursor'])
return(ids)
def get_friends(friend_id):
friends = []
try:
with open('{0}/{1}.f'.format(FDAT_DIR, friend_id)) as f:
for line in f:
friends.append(int(line))
except:
pass
return (friends)
def save_friends(user, ids):
with open('{0}/{1}.f'.format(FDAT_DIR, user), 'w', encoding='utf-8') as f:
f.write(str.join('\n', (str(x) for x in ids)))
def collect_and_save_friends(user, refresh=False):
if not refresh and os.path.exists('{0}/{1}.f'.format(FDAT_DIR, user)):
return()
else:
friends = collect_friends(user)
save_friends(user, friends)
return()
@click.group()
def cli():
pass
# Collect and save Tweets
@cli.command()
@click.argument('query', required=False)
@click.option('-q',
help='Optional: search query')
def tweets(query='', filename='', q=''):
'''
Collect Tweets by a user (max. 3200) or through a
search query (max. last 10 days).
'''
if filename == '':
if q == '' or q is None:
filename = '{}.tweets.jsonl'.format(
encode_query(query))
else:
filename = '{}.tweets.jsonl'.format(encode_query(q))
if q == '' or q is None:
click.echo('Requesting Tweets by @{}'.format(query))
r = TwitterPager(api, 'statuses/user_timeline',
{'screen_name': query, 'count': 200, 'tweet_mode': 'extended'})
else:
click.echo('Requesting Tweets with the search query {}'.format(q))
r = TwitterPager(api, 'search/tweets',
{'q': q, 'count': 100, 'tweet_mode': 'extended'})
n = 0
with open(filename, 'a', encoding='utf-8') as f:
for item in r.get_iterator(wait=2):
n += 1
if n % 1000 == 0:
click.echo('{0} Tweets received. Oldest from {1}.'.format(
n, item['created_at']))
if 'full_text' in item:
json.dump(item, f)
f.write('\n')
elif 'message' in item and item['code'] == 88:
click.echo(
'SUSPEND, RATE LIMIT EXCEEDED: {}\n'.format(item['message']))
break
click.echo('Saved {0} Tweets in {1}'.format(n, filename))
return
def load_ids_from_file(filename):
ids = []
with open('{}'.format(encode_query(filename)), 'r', encoding='utf-8') as f:
for number, line in enumerate(f):
item = json.loads(line)
ids.append(item['user']['id'])
return(list(set(ids)))
def load_tweets_from_file(query):
tweets = []
with open('{}.tweets.jsonl'.format(encode_query(query)), 'r', encoding='utf-8') as f:
for number, line in enumerate(f):
item = json.loads(line)
tweets.append(item)
return(tweets)
def load_accounts_from_file(query):
accounts = []
with open('{}.accounts.jsonl'.format(encode_query(query)), 'r', encoding='utf-8') as f:
for number, line in enumerate(f):
item = json.loads(line)
accounts.append(item)
return(accounts)
@cli.command()
@click.argument('query')
def network(query):
"""Generate Retweet network .gexf."""
tweets = load_tweets_from_file(query)
filename = '{}.retweetnetwork.gexf'.format(encode_query(query))
attr_qname = etree.QName(
"http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
gexf = etree.Element('gexf',
{attr_qname: 'http://www.gexf.net/1.3draft http://www.gexf.net/1.3draft/gexf.xsd'},
nsmap={
None: 'http://graphml.graphdrawing.org/xmlns/graphml'},
version='1.3')
graph = etree.SubElement(gexf,
'graph',
defaultedgetype='directed',
mode='dynamic',
timeformat='datetime')
attributes = etree.SubElement(
graph, 'attributes', {'class': 'node', 'mode': 'static'})
etree.SubElement(attributes, 'attribute', {
'id': 'location', 'title': 'location', 'type': 'string'})
etree.SubElement(attributes, 'attribute', {
'id': 'name', 'title': 'name', 'type': 'string'})
nodes = etree.SubElement(graph, 'nodes')
edges = etree.SubElement(graph, 'edges')
for tweet in reversed(tweets):
node = etree.SubElement(nodes,
'node',
id=tweet['user']['id_str'],
Label=tweet['user']['screen_name'],
start=datetime.datetime.strptime(tweet['created_at'], '%a %b %d %X %z %Y').isoformat(
timespec='seconds'), # Fri Jul 27 07:52:57 +0000 2018
end=(datetime.datetime.strptime(
tweet['created_at'], '%a %b %d %X %z %Y') + datetime.timedelta(seconds=1)).isoformat(timespec='seconds')
)
attvalues = etree.SubElement(node, 'attvalues')
if 'location' in tweet['user']:
etree.SubElement(attvalues,
'attvalue',
for_='location',
value=tweet['user']['location']
)
if 'name' in tweet['user']:
etree.SubElement(attvalues,
'attvalue',
for_='name',
value=tweet['user']['name']
)
if 'retweeted_status' in tweet:
etree.SubElement(edges,
'edge',
{'id': tweet['id_str'],
'source': tweet['user']['id_str'],
'target': tweet['retweeted_status']['user']['id_str'],
# Fri Jul 27 07:52:57 +0000 2018
'start': datetime.datetime.strptime(tweet['created_at'], '%a %b %d %X %z %Y').isoformat(timespec='seconds'),
'end': (datetime.datetime.strptime(tweet['created_at'], '%a %b %d %X %z %Y') + datetime.timedelta(seconds=1)).isoformat(timespec='seconds')
})
# save to file
with open(filename, 'w', encoding='utf-8')as f:
f.write(etree.tostring(gexf, encoding='utf8',
method='xml').decode('utf-8'))
# fix 'for' attributes
content = ''
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
with open(filename, 'w', encoding='utf-8') as f:
content = content.replace('for_', 'for')
f.write(content)
click.echo('Generated {}'.format(filename))
return()
@cli.command()
@click.argument('query')
def edgelist(query):
'''Generate follow network .gdf.'''
accounts = load_accounts_from_file(query)
account_ids = []
filename = '{}.follownetwork.gdf'.format(encode_query(query))
with open(filename, 'w', encoding='utf-8') as f:
f.write('nodedef>name VARCHAR,label VARCHAR,location VARCHAR\n')
with click.progressbar(accounts) as accounts_bar:
for account in accounts_bar:
account_ids.append(account['id'])
f.write('{0},{1},"{2}"\n'.format(
account['id'],
account['screen_name'],
account['location'].replace('"', '\'')))
f.write('edgedef>node1 VARCHAR,node2 VARCHAR,directed BOOLEAN\n')
with click.progressbar(account_ids) as ids_bar:
for account_id in ids_bar:
friends_ids = get_friends(account_id)
for friend_id in friends_ids:
if friend_id in account_ids:
f.write('{0},{1},true\n'.format(friend_id, account_id))
@cli.command()
def twitter_setup():
click.echo('Go to https://developer.twitter.com/apps to create an app.')
api_key = click.prompt('Please enter the API key')
api_key_secret = click.prompt('Please enter the API key secret')
"""Enter and save Twitter app credentials."""
return(write_config(api_key, api_key_secret))
@cli.command()
@click.argument('query')
def init(query):
"""Extract Twitter-Accounts from Tweets JSONL."""
extracted_accounts = []
with open('{}.tweets.jsonl'.format(encode_query(query)), 'r', encoding='utf-8') as f:
with open('{}.accounts.jsonl'.format(encode_query(query)), 'w', encoding='utf-8') as output:
for number, line in enumerate(f):
item = json.loads(line)
if item['user']['id'] not in extracted_accounts:
json.dump(item['user'], output)
output.write('\n')
extracted_accounts.append(item['user']['id'])
click.echo('{} accounts extracted'.format(len(extracted_accounts)))
return()
@cli.command()
@click.argument('query')
def fetch(query):
"""Collect followings of accounts in a JSONL."""
account_ids = []
with open('{}.accounts.jsonl'.format(encode_query(query)), 'r', encoding='utf-8') as f:
for number, line in enumerate(f):
item = json.loads(line)
account_ids.append(item['id'])
account_ids = list(set(account_ids))
for account_id in tqdm(account_ids):
collect_and_save_friends(account_id)
click.echo('Tried to fetch {} accounts'.format(len(account_ids)))
return()
@cli.command()
@click.option('--goal',
type=click.Choice(
['collect tweets', 'retweet network', 'follow network', 'reset keys']),
prompt='What do you want to do?',
help='Choose a goal.')
def assistant(goal):
"""Step by step assistant for new users"""
if goal == 'collect tweets':
tweet_type = click.prompt(
'Which method do you want to use to collect tweets?',
type=click.Choice(
['query', 'user']
))
if tweet_type == 'query':
query = click.prompt('Please enter your search query')
tweets(["-q", query])
if tweet_type == 'user':
query = click.prompt('Please enter the screen name')
tweets(query)
if goal == 'retweet network':
query = click.prompt('Please enter your search query')
if not os.path.exists('{}.tweets.jsonl'.format(encode_query(query))):
click.echo('Collecting Tweets before generating the network.')
tweets(["-q", query])
network([query])
if goal == 'follow network':
click.echo('not implemented yet. sry.')
if goal == 'reset keys':
twitter_setup([])
click.echo('Assistant finished.')
config = load_config()
if not os.path.exists('{}'.format(FDAT_DIR)):
os.mkdir('{}'.format(FDAT_DIR))
try:
api = create_api(config)
except:
click.echo('Something is wrong with your config.')
config = twitter_setup()
api = create_api(config)
if __name__ == '__main__':
cli()