-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter_watcher.py
1807 lines (1500 loc) · 90.4 KB
/
twitter_watcher.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import threading
from datetime import datetime, timezone, timedelta
from dateutil.relativedelta import *
import json
import re
import subprocess
import sys
from configobj import ConfigObj
import xml.etree.cElementTree as ET
from io import BytesIO
import time
import pandas as pd
import os
import socket
from pyArango.connection import *
import pyArango.theExceptions as pyArangoExceptions
import tweepy
from requests import ReadTimeout
from urllib3.exceptions import ReadTimeoutError
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import emoji
import config
import politician_collection
#TODO: Integrate date to do catch up from
#catch_up_date = datetime(2022, 10, 16)
db_connection = None
db_process = None
current_person_people_collection = None
current_person = None
collecting_people = False
current_start_date = None
current_end_date = None
people = pd.DataFrame()
class SavePoint:
person = None
tweets_left = None
pagination_token = None
query = None
like_pagination = None
current_start_date = None
savepoint = SavePoint()
translated_wikidata_ids = dict()
exit_sleep = threading.Event()
#TODO: Check this, sometimes it doesnt seem to work
def sleep_interruptible(time_in_secs):
print("Rate limit hit, sleeping " + str(time_in_secs) + " seconds")
original_status = config.WatcherStatus(config.status)
config.status = config.WatcherStatus.WAITING_FOR_RATE_LIMIT
while not exit_sleep.is_set():
exit_sleep.wait(time_in_secs)
# Set() to exit the loop. Theoretically this should not be necessary:
# The wait method should theoretically call set() after the timeout in seconds. But it does not, so here we are.
exit_sleep.set()
print("DONE WAITING")
config.status = original_status
exit_sleep.clear()
# TODO: Change test length depending on academic access or not
def query_short_enough(query):
if len(query.encode("utf-8")) + 5 + 15 > 1024: # extra length that would come from the "from:username" part where the username can be 15 chars max
return False
return True
# TODO: Get actual length of emojis, currently its a bit hacky and just assumes maximal(hopefully?) possible size
def build_query_disjunction(query, query_tail, elements):
need_another_query = False
changed_elements = []
for element in elements:
if not query_short_enough(query + element + " OR " + query_tail):
if query_short_enough(query + element + query_tail):
query += element
changed_elements = elements[elements.index(element):] # remove all elements until current one
need_another_query = True
break
query += element + " OR "
return query, need_another_query, changed_elements
def build_queries(filter_emojis=[], filter_keywords=[], filter_hashtags=[], filter_handles=[]):
built_queries = [""]
queries_done = False
query_tail = ")"
i = 0
# Remove empty strings from the lists
filter_emojis[:] = [el for el in filter_emojis if el != ""]
filter_keywords[:] = [el for el in filter_keywords if el != ""]
filter_hashtags[:] = [el for el in filter_hashtags if el != ""]
filter_handles[:] = [el for el in filter_handles if el != ""]
# If we don't use any filters at all
if (len(filter_emojis) == 0)\
and (len(filter_keywords) == 0) \
and (len(filter_hashtags) == 0) \
and (len(filter_handles) == 0):
return built_queries
#TODO: Check emoji and word syntax, try to understand how to check for non-english letters etc
while not queries_done:
need_another_query = False
#if user_handle.startswith("@"):
# user_handle = user_handle.lstrip(user_handle[0])
#if len(user_handle) > 0:
built_queries[i] = "("
if len(filter_emojis) > 0 and filter_emojis[0] != "" and not need_another_query:
built_queries[i], need_another_query, filter_emojis = build_query_disjunction(built_queries[i], query_tail,
filter_emojis)
if len(filter_keywords) > 0 and filter_keywords[0] != "" and not need_another_query:
built_queries[i], need_another_query, filter_keywords = build_query_disjunction(built_queries[i], query_tail,
filter_keywords)
if len(filter_hashtags) > 0 and filter_hashtags[0] != "" and not need_another_query:
built_queries[i], need_another_query, filter_hashtags = build_query_disjunction(built_queries[i], query_tail,
filter_hashtags)
if len(filter_handles) > 0 and filter_handles[0] != "" and not need_another_query:
built_queries[i], need_another_query, filter_handles = build_query_disjunction(built_queries[i], query_tail,
filter_handles)
#TODO: This here is probably unnecessary, so likely remove first if
if built_queries[i].endswith(" OR "):
built_queries[i] = built_queries[i][:-4]
elif built_queries[i].endswith(" OR )"):
built_queries[i] = built_queries[i][:-5] + ")"
built_queries[i] += query_tail
if need_another_query:
built_queries.append("")
i += 1
else:
queries_done = True
if built_queries[0] == "()":
built_queries[0] = ""
return built_queries
def setup_database():
global db_connection
db_config = ConfigObj("db_config.properties")
if len(db_config) == 0:
raise ValueError("database config empty/not found")
arango_url = db_config['database_connection_type'] + "://" + db_config['database_address'] + ":" + db_config['database_port']
username = db_config['username']
password = db_config['password']
db_running = False
try: # Check if something is already bound to the db port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((db_config['database_address'], int(db_config['database_port'])))
s.close()
except OSError: # If yes, check if its arangodb
print("Something already running on database port, checking if its the database...")
try:
db_connection = Connection(username=username, password=password, arangoURL=arango_url)
print(db_connection.getDatabasesURL())
db_running = True
except ConnectionError:
print("ConnectionError: Could not connect to database. Check that nothing else is running on " + arango_url + " and that this is the right address")
if not db_running: # Else start the db ourselves
arango_filepath = os.path.dirname(os.path.abspath(__file__))
if 'linux' in sys.platform:
arango_filepath += "/DB/usr/bin/arangod"
if 'win32' in sys.platform:
arango_filepath += "\\DB\\usr\\bin\\arangod.exe"
print("PATH IS: " + arango_filepath)
print("Database was not running. Starting it...")
global db_process
#TODO: REMOVE CUSTOM DIRECTORY
#"--database.directory", "TestDBFiles",
db_process = subprocess.Popen([arango_filepath, "--http.trusted-origin", "*", "--server.endpoint", db_config['database_connection_type'] + "+tcp://" + db_config['database_address'] + ":" + db_config['database_port']])
db_running = False
while not db_running: # Wait for the db to start
try:
db_connection = Connection(username=username, password=password, arangoURL=arango_url)
print("Database is running")
db_running = True
except ConnectionError as dbex:
if json.loads(dbex.errors)["code"] == 503:
time.sleep(1)
else:
raise dbex
# Create TwitterWatcher database and add collections
if not db_connection.hasDatabase("TwitterWatcher"):
db_connection.createDatabase("TwitterWatcher")
database = db_connection["TwitterWatcher"]
if not db_connection["TwitterWatcher"].hasCollection("People"):
database.createCollection(className="Collection", name="People", allowUserKeys=True)
if not db_connection["TwitterWatcher"].hasCollection("Tweets"):
database.createCollection(className="Collection", name="Tweets", allowUserKeys=True)
if not db_connection["TwitterWatcher"].hasCollection("Retweets"):
database.createCollection(className="Edges", name="Retweets", allowUserKeys=True)
if not db_connection["TwitterWatcher"].hasCollection("QuoteTweets"):
database.createCollection(className="Edges", name="QuoteTweets", allowUserKeys=True)
if not db_connection["TwitterWatcher"].hasCollection("Replies"):
database.createCollection(className="Edges", name="Replies", allowUserKeys=True)
if not db_connection["TwitterWatcher"].hasCollection("Mentions"):
database.createCollection(className="Edges", name="Mentions", allowUserKeys=True)
if not db_connection["TwitterWatcher"].hasCollection("Likes"):
database.createCollection(className="Edges", name="Likes", allowUserKeys=True)
if not db_connection["TwitterWatcher"].hasCollection("UserBotDetectionValues"): # Check if I'm actually doing this
database.createCollection(className="Collection", name="UserBotDetectionValues", allowUserKeys=True)
#TODO: Refactor method
# Stops the database (if it was started by the watcher)
#def stop_database():
# if db_process is not None:
# print("Shutting down started database...")
# subprocess.Popen.kill(db_process)
#TODO: botness average
#def create_person_document(twitter_data,wikidata_data):
def collect_ids_from_wikidata_claims(claims):
global translated_wikidata_ids
ids_to_be_translated = dict(translated_wikidata_ids)
for w_property in claims.keys():
if ids_to_be_translated.get(w_property) is None:
ids_to_be_translated[w_property] = "" # If it is not None, then we already know that key
for property_value in claims[w_property]:
if property_value["mainsnak"].get("datavalue") is not None: # May have unknown value, then we ignore
if isinstance(property_value["mainsnak"]["datavalue"]["value"], dict) and \
property_value["mainsnak"]["datavalue"]["value"].get("id") is not None:
if ids_to_be_translated.get(property_value["mainsnak"]["datavalue"]["value"]["id"]) is None:
ids_to_be_translated[property_value["mainsnak"]["datavalue"]["value"]["id"]] = ""
if property_value.get("qualifiers") is not None:
for qualifier in property_value["qualifiers"].keys():
# print(" ", qualifier)
if ids_to_be_translated.get(qualifier) is None:
ids_to_be_translated[qualifier] = ""
for qualifier_value in property_value["qualifiers"][qualifier]:
if qualifier_value.get("datavalue") is not None: # May have unknown value, then we ignore
if isinstance(qualifier_value["datavalue"]["value"], dict) and qualifier_value["datavalue"]["value"].get("id") is not None:
if ids_to_be_translated.get(qualifier_value["datavalue"]["value"]["id"]) is None:
ids_to_be_translated[qualifier_value["datavalue"]["value"]["id"]] = ""
#print(str(list(ids_to_be_translated.keys())).replace("'", "").replace("'", "").replace(", ", "|")[1:-1], "\n")
smaller_list = []
i = 0
for item in ids_to_be_translated.keys():
if i == 0:
smaller_list = []
if ids_to_be_translated[item] == "": # Only translate those that need to be translated
smaller_list.append(item)
i += 1
if i == 50 or (len(ids_to_be_translated) != 0 and item == list(ids_to_be_translated.keys())[-1]):
i = 0
# Get id translations, this needs to be changed for more languages if we expand to more countries
if len(smaller_list) != 0: # Happens when we already translated many ids
request_successful = False
while not request_successful:
response = requests.get("https://www.wikidata.org/w/api.php?action=wbgetentities&ids="
+ str(smaller_list).replace("'", "").replace("'", "").replace(", ", "|")[
1:-1] + "&format=json&props=labels&languages=en|gd|de|es|ca|it|fr|da|cs")
time.sleep(0.1)
if response.status_code == 200:
request_successful = True
elif response.status_code == 429:
sleep_interruptible(60)
else:
print("Wikidata id translation request not successful: " + str(response))
return ids_to_be_translated
if config.stop_collection:
return None
# print(response.content)
content_json = json.loads(response.content)
for w_property in content_json["entities"].keys():
# print(content_json["entities"][key], ":", content_json["entities"][key]["labels"])
if content_json["entities"][w_property].get("labels") is None:
ids_to_be_translated[w_property] = ids_to_be_translated[w_property]
elif content_json["entities"][w_property]["labels"].get("en") is not None:
ids_to_be_translated[w_property] = content_json["entities"][w_property]["labels"]["en"]["value"]
elif len(content_json["entities"][w_property]["labels"]) != 0:
# print("got non eng")
ids_to_be_translated[w_property] = list(content_json["entities"][w_property]["labels"].values())[0]["value"]
return ids_to_be_translated
#TODO: Case for just name
def collect_person_from_wikidata(label=None, wikidata_id=None):
global translated_wikidata_ids
if wikidata_id is not None:
#entity_dict = get_entity_dict_from_api(wikidata_id) #TODO: Replace this library to catch a proper requests error.
response = requests.get("https://www.wikidata.org/wiki/Special:EntityData/" + wikidata_id + ".json?flavor=dumps")
if response.status_code == 400:
raise FileNotFoundError("Wikidata")
entity_dict = json.loads(response.content)["entities"][list(json.loads(response.content)["entities"].keys())[0]]
claims = dict(entity_dict["claims"])
# Remove external id claims as we don't need them for our database
for key in entity_dict["claims"].keys():
# print(key)
if claims[key][0]["mainsnak"]["datatype"] == "external-id":
claims.pop(key)
translated_wikidata_ids = collect_ids_from_wikidata_claims(claims)
if translated_wikidata_ids is None and config.stop_collection:
return None
#print(translated_wikidata_ids)
transformed_data = dict()
transformed_data["id"] = entity_dict["id"]
if entity_dict["labels"].get("en") is not None:
transformed_data["name"] = entity_dict["labels"]["en"]["value"]
else:
transformed_data["name"] = entity_dict["labels"][list(entity_dict["labels"].keys())[0]]["value"]
if entity_dict["descriptions"].get("en") is not None:
transformed_data["description"] = entity_dict["descriptions"]["en"]["value"]
elif len(entity_dict["descriptions"]) != 0:
transformed_data["description"] = entity_dict["descriptions"][list(entity_dict["descriptions"].keys())[0]]["value"]
if entity_dict["aliases"].get("en") is not None:
aliases_slim = []
for alias in entity_dict["aliases"]["en"]:
aliases_slim.append(alias["value"])
transformed_data["aliases"] = aliases_slim
elif len(entity_dict["aliases"]) != 0:
aliases_slim = []
for alias in entity_dict["aliases"][list(entity_dict["aliases"].keys())[0]]:
aliases_slim.append(alias["value"])
transformed_data["aliases"] = aliases_slim
for w_property in claims.keys():
transformed_data[translated_wikidata_ids[w_property]] = []
for property_value in claims[w_property]:
if property_value["mainsnak"].get("datavalue") is not None: # May have unknown value, then we ignore
if not isinstance(property_value["mainsnak"]["datavalue"]["value"], dict):
transformed_data[translated_wikidata_ids[w_property]].append(dict({"value": property_value["mainsnak"]["datavalue"]["value"]}))
elif property_value["mainsnak"]["datavalue"]["type"] == "time":
transformed_data[translated_wikidata_ids[w_property]].append(dict({"value": property_value["mainsnak"]["datavalue"]["value"]["time"].removeprefix("+")}))
elif property_value["mainsnak"]["datavalue"]["type"] == "quantity":
transformed_data[translated_wikidata_ids[w_property]].append(dict({"value": property_value["mainsnak"]["datavalue"]["value"]["amount"].removeprefix("+")}))
elif property_value["mainsnak"]["datavalue"]["value"].get("text") is not None:
transformed_data[translated_wikidata_ids[w_property]].append(dict({"value": property_value["mainsnak"]["datavalue"]["value"]["text"]}))
elif property_value["mainsnak"]["datavalue"]["value"].get("id") is not None:
transformed_data[translated_wikidata_ids[w_property]].append(dict({"value": translated_wikidata_ids[property_value["mainsnak"]["datavalue"]["value"]["id"]]}))
else:
print("UNKNOWN BEHAVIOUR FOR PROPERTY VALUE: " + w_property + "; " + str(property_value["mainsnak"]["datavalue"]["value"]) + ", getting first element of value dict")
transformed_data[translated_wikidata_ids[w_property]].append(dict({"value": list(property_value["mainsnak"]["datavalue"]["value"].values())[0]}))
if property_value.get("qualifiers") is not None:
transformed_qualifiers = {}
for w_qualifier in property_value["qualifiers"].keys():
transformed_qualifiers[translated_wikidata_ids[w_qualifier]] = []
for qualifier_value in property_value["qualifiers"][w_qualifier]:
if qualifier_value.get("datavalue") is not None: # May have unknown value, then we ignore
if not isinstance(qualifier_value["datavalue"]["value"], dict):
transformed_qualifiers[translated_wikidata_ids[w_qualifier]].append(qualifier_value["datavalue"]["value"])
elif qualifier_value["datavalue"]["type"] == "time":
transformed_qualifiers[translated_wikidata_ids[w_qualifier]].append(qualifier_value["datavalue"]["value"]["time"].removeprefix("+"))
elif qualifier_value["datavalue"]["type"] == "quantity":
transformed_qualifiers[translated_wikidata_ids[w_qualifier]].append(qualifier_value["datavalue"]["value"]["amount"].removeprefix("+"))
elif qualifier_value["datavalue"]["value"].get("text") is not None:
transformed_qualifiers[translated_wikidata_ids[w_qualifier]].append(qualifier_value["datavalue"]["value"]["text"])
elif qualifier_value["datavalue"]["value"].get("id") is not None:
transformed_qualifiers[translated_wikidata_ids[w_qualifier]].append(translated_wikidata_ids[qualifier_value["datavalue"]["value"]["id"]])
else:
print("UNKNOWN BEHAVIOUR FOR QUALIFIER VALUE: " + w_qualifier + "; " + str(qualifier_value["datavalue"]["value"]) + ", getting first element of value dict")
transformed_qualifiers[translated_wikidata_ids[w_qualifier]].append(list(qualifier_value["datavalue"]["value"].values())[0])
transformed_data[translated_wikidata_ids[w_property]][-1]["qualifiers"] = transformed_qualifiers
# TODO:Remove
#print(json.dumps(transformed_data))
#f = open("Scholzi.json", "w")
#f.write(json.dumps(transformed_data) + "\n")
# TODO:Remove
return json.dumps(transformed_data)
def collect_twitter_user(t_handle, t_client):
request_successful = False
while not request_successful:
try:
response = t_client.get_user(username=t_handle,
user_fields=["id", "name", "username", "created_at", "protected", "withheld",
"location", "url", "description", "verified", "verified_type",
"profile_image_url", "public_metrics", "pinned_tweet_id"],
user_auth=False)
if len(response.errors) != 0 and response.errors[0]["title"] == "Not Found Error":
raise FileNotFoundError("Twitter")
request_successful = True
except tweepy.errors.TooManyRequests:
sleep_interruptible(15 * 60)
except tweepy.errors.TwitterServerError as t_servErr:
print("Twitter unavailable: " + str(t_servErr) + ", Waiting...")
sleep_interruptible(15 * 60)
except requests.exceptions.ConnectionError as r_connErr:
print("Twitter closed connection: " + str(r_connErr) + ", Waiting...")
sleep_interruptible(15 * 60)
if config.stop_collection:
return None
# print(response)
# TODO: Remove
#print(response)
#f = open("TwitterScholzi.json", "w")
#f.writelines("")
#f = open("TwitterScholzi.json", "a")
#f.write(json.dumps(response.data.data) + "\n")
# TODO: Remove
return json.dumps(response.data.data)
def store_person(wikidata_data, twitter_data):
collection = db_connection["TwitterWatcher"]["People"]
doc = None
wikidata_data = json.loads(wikidata_data)
twitter_data = json.loads(twitter_data)
try:
doc = collection.fetchDocument(wikidata_data["id"])
print("Person found in database, editing...")
except pyArangoExceptions.DocumentNotFoundError:
doc = collection.createDocument()
print("Creating new Person in database...")
doc._key = wikidata_data["id"]
doc["name"] = wikidata_data["name"] if "name" in wikidata_data else wikidata_data["id"]
doc["twitter_object"] = twitter_data
doc["wikidata_object"] = wikidata_data
doc.save()
def get_id_by_thandle_from_database(t_handle):
result = db_connection["TwitterWatcher"].AQLQuery(query='FOR person IN People FILTER person.twitter_object.username == "'
+ t_handle + '" RETURN person._key',
rawResults=True)
if len(result) == 0:
return None
return result[0]
def get_id_by_tid_from_database(t_id):
result = db_connection["TwitterWatcher"].AQLQuery(query='FOR person IN People FILTER person.twitter_object.id == "'
+ str(t_id) + '" RETURN person._key',
rawResults=True)
if len(result) == 0:
return None
return result[0]
def get_first_tweet_edge_from_database(t_id):
found_doc = None
try:
found_doc = db_connection["TwitterWatcher"]["Retweets"].fetchDocument(str(t_id) + "_retweeted")
except pyArangoExceptions.DocumentNotFoundError:
try:
found_doc = db_connection["TwitterWatcher"]["QuoteTweets"].fetchDocument(str(t_id) + "_quoted")
except pyArangoExceptions.DocumentNotFoundError:
try:
found_doc = db_connection["TwitterWatcher"]["Replies"].fetchDocument(str(t_id) + "_replied_to")
except pyArangoExceptions.DocumentNotFoundError:
found_doc = None
return found_doc
def create_tweet_document(tweet_json, references=[], sentiment_value=None, avg_botness=None, avg_maliciousness=None, liking_users=None):
collection = db_connection["TwitterWatcher"]["Tweets"]
try:
collection.fetchDocument(tweet_json["id"])
print("Tweet doc already exists in database, skipping...")
except pyArangoExceptions.DocumentNotFoundError:
doc = collection.createDocument()
doc._key = tweet_json["id"]
# Retrieve referenced user handles from quotes and replies without querying twitter
retweeted = ""
quoted = ""
replied_to = ""
simple_mentions = []
# if tweet_json.get("referenced_tweets") is not None:
# if tweet_json["referenced_tweets"][0]["type"] == "retweeted":
# retweeted = tweet_json["entities"]["mentions"][0]["username"]
# else:
# for ref_tweet in tweet_json["referenced_tweets"]:
# if ref_tweet["type"] == "quoted":
# if match := re.search("^twitter[.]com/([^/]+)/.*$",
# tweet_json["entities"]["urls"][-1]["display_url"], re.IGNORECASE):
# quoted = match.group(1)
# if ref_tweet["type"] == "replied_to":
# replied_to_id = tweet_json["in_reply_to_user_id"]
for ref in references:
if ref[0] == "retweeted":
retweeted = ref[1]
elif ref[0] == "quoted":
quoted = ref[1]
elif ref[0] == "replied_to":
replied_to = ref[1]
if tweet_json.get("entities") is not None and tweet_json["entities"].get("mentions") is not None:
if retweeted == "":
for m_index in range(0, len(tweet_json["entities"]["mentions"])):
if not (m_index == 0 and replied_to != ""):
simple_mentions.append(tweet_json["entities"]["mentions"][m_index]["id"])
doc["retweeted"] = retweeted
doc["quoted"] = quoted
doc["replied_to"] = replied_to
if len(simple_mentions) != 0:
doc["mentions"] = simple_mentions
doc["tweet"] = tweet_json
if sentiment_value is not None:
doc["sentiment_value"] = sentiment_value
doc["weight"] = sentiment_value
if is_not_retweet(tweet_json) and avg_botness is not None:
doc["avg_response_botness"] = avg_botness
doc["avg_response_bot_maliciousness"] = avg_maliciousness
if liking_users is not None:
doc["liking_users"] = liking_users
print("Tweet stored")
doc.save()
def create_tweet_edge(tweet_type, tweet_json, _from_tid, _to_tid, sentiment_value=None, avg_botness=None, avg_maliciousness=None, ref_tweet=None):
switch_case_print = {"retweeted": "Retweet", "quoted": "Quote tweet", "replied_to": "Reply", "mentioned": "Mention"}
switch_case = {"retweeted": "Retweets", "quoted": "QuoteTweets", "replied_to": "Replies", "mentioned": "Mentions"}
collection = db_connection["TwitterWatcher"][switch_case[tweet_type]]
_from = get_id_by_tid_from_database(_from_tid)
_to = get_id_by_tid_from_database(_to_tid)
if _from is not None and _to is not None:
try: #TODO: Remove this, likely not needed anymore
if tweet_type != "mentioned":
collection.fetchDocument(tweet_json["id"] + "_" + tweet_type)
print(switch_case_print[tweet_type] + " already exists in database, skipping...")
else:
collection.fetchDocument(tweet_json["id"] + "_" + tweet_type + "_" + _from + "_" + _to)
print(switch_case_print[tweet_type] + " already exists in database, skipping...")
except pyArangoExceptions.DocumentNotFoundError:
doc = collection.createDocument()
if tweet_type != "mentioned":
doc._key = tweet_json["id"] + "_" + tweet_type
else: # Mentions need involved people too to have unique ids
doc._key = tweet_json["id"] + "_" + tweet_type + "_" + _from + "_" + _to
doc._from = "People/" + _from
doc._to = "People/" + _to
doc["twitter_object"] = {}
doc["twitter_object"]["tweet_id"] = tweet_json["id"]
doc["twitter_object"]["text"] = tweet_json["text"]
doc["point_in_time"] = tweet_json["created_at"]
doc["twitter_object"]["author_id"] = tweet_json["author_id"]
doc["twitter_object"]["edit_history_tweet_ids"] = tweet_json["edit_history_tweet_ids"]
if tweet_json.get("geo") is not None:
doc["twitter_object"]["geo"] = {}
doc["twitter_object"]["geo"]["place_id"] = tweet_json["geo"]["place_id"]
if ref_tweet is not None: # If we don't reference any tweet, happens when we mention someone
doc["twitter_object"]["referenced_tweet_id"] = ref_tweet["id"]
#if tweet_json.get("entities") is not None: # Check if there even are hashtags/urls in the text
# if tweet_json["entities"].get("urls") is not None:
# doc["urls"] = tweet_json["entities"]["urls"]
# if tweet_json["entities"].get("hashtags") is not None:
# doc["hashtags"] = tweet_json["entities"]["hashtags"]
if tweet_json.get("withheld") is not None:
doc["twitter_object"]["withheld"] = {}
if tweet_json["withheld"].get("country_codes") is not None:
doc["twitter_object"]["withheld"]["country_codes"] = tweet_json["withheld"]["country_codes"]
if tweet_json["withheld"].get("scope") is not None:
doc["twitter_object"]["withheld"]["scope"] = tweet_json["withheld"]["scope"]
doc["twitter_object"]["public_metrics"] = tweet_json["public_metrics"]
doc["twitter_object"]["possibly_sensitive"] = tweet_json["possibly_sensitive"]
doc["twitter_object"]["lang"] = tweet_json["lang"]
#Include tweet app source as well?
if sentiment_value is not None:
doc["sentiment_value"] = sentiment_value
doc["weight"] = sentiment_value
if is_not_retweet(tweet_json) and avg_botness is not None:
doc["avg_response_botness"] = avg_botness
doc["avg_response_bot_maliciousness"] = avg_maliciousness
doc.save()
print(switch_case_print[tweet_type] + " stored")
else:
print("Cant find one of the people for the tweet in database, skipping...")
# TODO: Give info on stored tweets what other kinds it exists in
def store_tweet(t_client, tweet_json, sentiment_value=None, avg_botness=None, avg_maliciousness=None, liking_users=None):
print("TWEET:" + str(tweet_json)) # TODO: Remove
references = []
# Collect Retweet/Quote Tweet/Replies
if tweet_json.get("referenced_tweets") is not None:
for ref_tweet in tweet_json["referenced_tweets"]:
# Look up the id of the replied_to user by its handle
if ref_tweet["type"] == "retweeted" or ref_tweet["type"] == "quoted":
request_got_through = False
while not request_got_through:
try:
author_lookup_response = t_client.get_tweet(id=ref_tweet["id"], expansions=["author_id"]) #TODO: Remove and just lookup handles here
# print(author_lookup_response)
refed_user_id = author_lookup_response.includes["users"][0]["id"]
references.append((ref_tweet["type"], refed_user_id))
request_got_through = True
except tweepy.errors.TooManyRequests:
sleep_interruptible(15*60)
except tweepy.errors.TwitterServerError as servErr:
print("Twitter unavailable: " + str(servErr) + ", Waiting...")
sleep_interruptible(15 * 60)
except requests.exceptions.ConnectionError as r_connErr:
print("Twitter closed connection: " + str(r_connErr) + ", Waiting...")
sleep_interruptible(15 * 60)
if config.stop_collection:
return
else:
refed_user_id = tweet_json["in_reply_to_user_id"]
references.append((ref_tweet["type"], refed_user_id))
create_tweet_edge(ref_tweet["type"], tweet_json, tweet_json["author_id"], str(refed_user_id), sentiment_value,
avg_botness, avg_maliciousness, ref_tweet=ref_tweet)
# Store actual tweet as non-edge for checking new users later
create_tweet_document(tweet_json, references, sentiment_value, avg_botness, avg_maliciousness, liking_users)
# Collect Mentions
if tweet_json.get("entities") is not None and tweet_json["entities"].get("mentions") is not None:
for mention in tweet_json["entities"]["mentions"]:
# If this tweet is not a retweet, retweets don't have text and with that no mentions
if is_not_retweet(tweet_json):
# If this tweet is a reply, all users in the conversation exist as mentions
# We then need to ignore the first mentioned person since this is the one that was replied to
is_reply = False
if tweet_json.get("referenced_tweets") is not None:
for reference in tweet_json["referenced_tweets"]:
if reference["type"] == "replied_to":
is_reply = True # This is (also) a reply tweet
if is_reply and mention["start"] == 0:
continue # Ignore the first mention
create_tweet_edge("mentioned", tweet_json, tweet_json["author_id"], mention["id"], sentiment_value,
avg_botness, avg_maliciousness, ref_tweet=None)
def create_like_document(liked_user_id, liking_user_id, tweet_json, tweet_created_at):
collection = db_connection["TwitterWatcher"]["Likes"]
try:
collection.fetchDocument(tweet_json["id"] + "_liked_" + liking_user_id + "_" + liked_user_id)
print("Like already exists in database, skipping...")
except pyArangoExceptions.DocumentNotFoundError:
doc = collection.createDocument()
doc._key = tweet_json["id"] + "_liked_" + liking_user_id + "_" + liked_user_id
doc._from = "People/" + liking_user_id
doc._to = "People/" + liked_user_id
doc["twitter_object"] = {}
doc["twitter_object"]["tweet_id"] = tweet_json["id"]
doc["twitter_object"]["text"] = tweet_json["text"]
doc["point_in_time"] = tweet_json["created_at"]
doc["twitter_object"]["author_id"] = tweet_json["author_id"]
doc["twitter_object"]["edit_history_tweet_ids"] = tweet_json["edit_history_tweet_ids"]
if tweet_json.get("geo") is not None:
doc["twitter_object"]["geo"] = {}
doc["twitter_object"]["geo"]["place_id"] = tweet_json["geo"]["place_id"]
# if tweet_json.get("entities") is not None: # Check if there even are hashtags/urls in the text
# if tweet_json["entities"].get("urls") is not None:
# doc["urls"] = tweet_json["entities"]["urls"]
# if tweet_json["entities"].get("hashtags") is not None:
# doc["hashtags"] = tweet_json["entities"]["hashtags"]
if tweet_json.get("withheld") is not None:
doc["twitter_object"]["withheld"] = {}
if tweet_json["withheld"].get("country_codes") is not None:
doc["twitter_object"]["withheld"]["country_codes"] = tweet_json["withheld"]["country_codes"]
if tweet_json["withheld"].get("scope") is not None:
doc["twitter_object"]["withheld"]["scope"] = tweet_json["withheld"]["scope"]
doc["twitter_object"]["public_metrics"] = tweet_json["public_metrics"]
doc["twitter_object"]["possibly_sensitive"] = tweet_json["possibly_sensitive"]
doc["twitter_object"]["lang"] = tweet_json["lang"]
doc["point_in_time"] = tweet_created_at
doc["sentiment_value"] = 0.5
doc["weight"] = 0.5
doc.save()
# Store edges for people liking others and dump a list of all collected liking users into corresponding tweet doc
def store_likes(t_id, liking_users_in_db, tweet_json, tweet_created_at):
liked_user_id = get_id_by_tid_from_database(t_id)
if liked_user_id is not None: # TODO: Delete, should not be necessary since tweet author should always exist in db
for liking_user_id in liking_users_in_db:
create_like_document(liked_user_id, liking_user_id, tweet_json, tweet_created_at)
else:
print("Can't store likes for unknown user")
# TODO: Use rest of liking users for bot detection as well?
def collect_liking_users(tweet_id, t_client, page_limit=sys.maxsize):
global savepoint
liking_users = []
liking_users_in_db = []
all_results_found = False
if savepoint.like_pagination is not None:
pagination_start = savepoint.like_pagination[0]
pagination_token = savepoint.like_pagination[1]
else:
pagination_start = 0
pagination_token = None
for i in range(pagination_start, page_limit):
if all_results_found:
break
request_got_through = False
while not request_got_through:
try:
t_response = t_client.get_liking_users(tweet_id,
max_results=100,
pagination_token=pagination_token)
time.sleep(.018)
#print(t_response)
if t_response.meta.get("next_token") is None:
all_results_found = True
else:
pagination_token = t_response.meta["next_token"]
if t_response.data is not None: # A Tweet can also have no likes, in this case we skip
for user in t_response.data:
liking_users.append(user.id)
data_id = get_id_by_tid_from_database(user.id)
if data_id is not None:
liking_users_in_db.append(data_id)
request_got_through = True
except tweepy.errors.TooManyRequests:
sleep_interruptible(15*60)
except tweepy.errors.TwitterServerError as t_servErr:
print("Twitter unavailable: " + str(t_servErr) + ", Waiting...")
sleep_interruptible(15*60)
except requests.exceptions.ConnectionError as r_connErr:
print("Twitter closed connection: " + str(r_connErr) + ", Waiting...")
sleep_interruptible(15*60)
if config.stop_collection:
savepoint.like_pagination = (i, pagination_token)
break
if config.stop_collection:
savepoint.like_pagination = (i, pagination_token)
break
return liking_users_in_db, liking_users
def get_tweet_sentiment_value(tweet_json):
analyzer = SentimentIntensityAnalyzer()
if is_not_retweet(tweet_json): # Retweets dont have own text
tweet_text = tweet_json["text"]
if "in_reply_to_user_id" in tweet_json: # Replies have many mentions at the beginning that are not from the actual text, remove them
tweet_text = re.sub("(@[^ ]* )+", "", tweet_text)
tweet_text = re.sub("https://[^ ]+", "", tweet_text) # Remove links
if tweet_json["lang"] != "en": # Translate non-english text
tweet_text = tweet_text.encode('utf-16','surrogatepass').decode('utf-16') # Transform to utf-16 to cope with emojis
api_url = "http://mymemory.translated.net/api/get?q={}&langpair={}|en&[email protected]".format(tweet_text, tweet_json["lang"])
headers = {
'User-Agent': 'TwitterWatcher/0.1 [email protected]',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
request_successful = False
while not request_successful:
translator_response = requests.get(api_url, headers=headers)
response_json = json.loads(translator_response.text)
if translator_response.status_code == 429 or json.loads(translator_response.content)["quotaFinished"]:
next_day = False
while not next_day: # Wait until next day TODO: Test this
sleep_interruptible(60*60)
if datetime.now(timezone.utc).hour == 0:
next_day = True
if config.stop_collection:
return None
else:
request_successful = True
if config.stop_collection:
return None
tweet_text = response_json["responseData"]["translatedText"]
sentiment_values = {"compound": 0}
if tweet_json["lang"] != "en" and response_json["responseStatus"] == "403":
print("TRANSLATION FAILED. Likely invalid language: " + str(tweet_json["lang"]))
else:
#print("TRANSLATION:" + tweet_text)
sentiment_values = analyzer.polarity_scores(tweet_text)
return sentiment_values["compound"]
else:
return 0.75
def get_bot_response(user_list):
if user_list is None and config.stop_collection:
return None, None
bot_detection_db = db_connection["TwitterWatcher"]["UserBotDetectionValues"]
avg_botness = 0
avg_maliciousness = 0
for user in user_list:
print("Checking user " + user)
vals_found_in_db = False
try:
doc = bot_detection_db.fetchDocument(user)
print("Bot values found")
avg_botness += doc["botness"]
avg_maliciousness += doc["maliciousness"]
vals_found_in_db = True
except pyArangoExceptions.DocumentNotFoundError:
pass
request_successful = False
while not vals_found_in_db and not request_successful:
try:
headers = {
'User-Agent': 'TwitterWatcher/0.1 [email protected]',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
response = requests.get("https://milki-psy.dbis.rwth-aachen.de/bot-detector/api/user-check/" + user
, headers=headers, timeout=8)
response_json = json.loads(response.text)
avg_botness += response_json["signals"]["is_bot_probability"]
avg_maliciousness += response_json["signals"]["intentions_are_bad_probability"]
doc = bot_detection_db.createDocument()
print("Saving bot values...")
doc._key = user
doc["botness"] = response_json["signals"]["is_bot_probability"]
doc["maliciousness"] = response_json["signals"]["intentions_are_bad_probability"]
doc.save()
request_successful = True
except ReadTimeout:
print("Bot detector timeout likely cause of rate limit, waiting")
#TODO Test this
sleep_interruptible(15*60)
except ConnectionError as connection_ex:
print(connection_ex)
#TODO Test this
sleep_interruptible(15*60)
except JSONDecodeError as json_ex:
print(json_ex)
print(response.text)
#TODO Test this
sleep_interruptible(15*60)
if config.stop_collection:
return None, None
if config.stop_collection:
return None, None
avg_botness = avg_botness/len(user_list) if len(user_list) != 0 else 0
avg_maliciousness = avg_maliciousness/len(user_list) if len(user_list) != 0 else 0
return avg_botness, avg_maliciousness
def get_responding_users(tweet_data, t_client):
request_got_through = False
while not request_got_through:
try:
t_response = t_client.search_all_tweets(query="in_reply_to_tweet_id:" + tweet_data["id"] + " OR "
+ "retweets_of_tweet_id:" + tweet_data["id"] + " OR "
+ "quotes_of_tweet_id:" + tweet_data["id"],
start_time=datetime.fromisoformat(tweet_data["created_at"].replace("Z", "+00:00")), # fromisoformat() can not parse all variants of iso 8601 utc time, hence the replacing
end_time=None,#datetime_lib.datetime(2023, 1, 16),
expansions=["author_id"],
max_results=100,
media_fields=None,
next_token=None,
place_fields=None,
poll_fields=None,
since_id=None,#tweet_data["id"],
sort_order=None,
tweet_fields=None,
until_id=None,
user_fields=["username"])
request_got_through = True
time.sleep(2) # Mandatory wait between all full active tweet search requests is > 1 second
except tweepy.errors.TooManyRequests:
sleep_interruptible(15*60)
except tweepy.errors.TwitterServerError as servErr:
print("Twitter unavailable: " + str(servErr) + ", Waiting...")
sleep_interruptible(15*60)
except requests.exceptions.ConnectionError as r_connErr:
print("Twitter closed connection: " + str(r_connErr) + ", Waiting...")
sleep_interruptible(15 * 60)
if config.stop_collection:
return None
users = []
if t_response.includes.get("users") is not None: # Sometimes there may be no responses
for user in t_response.includes["users"]:
users.append(user.username)
return users
def is_not_retweet(tweet_json):
if ("referenced_tweets" not in tweet_json) or tweet_json["referenced_tweets"][0]["type"] != "retweeted":
return True
else:
return False
# TODO: Abort on config.stop_collection is true, Save (current person to be collected, date, tweets) to know where left off
def collect_tweets_by_query(person, t_query, t_client, start_date, end_date, catch_up=False, catch_up_date=config.start_date):
global savepoint
tweets = []
pagination_token = None
all_results_found = False
#start_date = config.start_date
#if catch_up:
# print("Catching up")
# start_date = catch_up_date
# if start_date < config.start_date:
# return