-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetTweetsMetadata.py
executable file
·255 lines (204 loc) · 9.19 KB
/
GetTweetsMetadata.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
import configparser
import datetime
import json
import os
import random
import smtplib
import sys
import time
import unicodedata
from email.mime.text import MIMEText
from pprint import pprint
import requests
import twitter
from bs4 import BeautifulSoup
if len(sys.argv) < 2:
exit("Usage:python3 FBAdScrapeScript.py crawl_config.cfg")
config = configparser.ConfigParser()
config.read(sys.argv[1])
USERNAME = config['ACCOUNT']['USERNAME']
PASSWORD = config['ACCOUNT']['PASS']
SCRAPEREMAIL = config['ACCOUNT']['EMAIL']
CONSUMER_KEY = config['OAUTH']['CONSUMERKEY']
CONSUMER_SECRET = config['OAUTH']['CONSUMERSECRET']
ACCESS_KEY_TOKEN = config['OAUTH']['TOKENKEY']
ACCESS_KEY_SECRET = config['OAUTH']['TOKENSECRET']
MAXWAIT = int(config['SPECS']['MAXWAITTWEET'])
MINWAIT = int(config['SPECS']['MINWAITTWEET'])
ERROREMAIL = config['ACCOUNT']['ERROREMAIL']
WriteDir = config['WORKINGDIR']['CURRENT']
JSON_INDENT = int(config['SPECS']['JSON_INDENT'])
LoginPost = "https://twitter.com/sessions"
URL = "https://twitter.com"
TweetDetailsLink = "https://ads.twitter.com/transparency/line_item_metadata.json?tweet_id=%s&user_id=%s"
TweetOverviewLink = "https://ads.twitter.com/transparency/tweet_performance.json?tweet_id=%s&user_id=%s"
CampaignOverviewLink = "https://ads.twitter.com/transparency/line_item_detail.json?line_item_id=%s"
CampaignDetailsLink = "https://ads.twitter.com/transparency/line_item_targeting_criteria.json?account_id=%s&line_item_id=%s"
data = {"session[username_or_email]": USERNAME,
"session[password]": PASSWORD,
"scribe_log": "",
"redirect_after_login": "/",
"remember_me": "1"}
Headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}
def GetMetadataForTweets(Tweets, Session):
"""
Accepts a list of Tweets. Read from Tweets.json in the folder for the particular issue.
Extracts TweetID and UserID to get tweet performance overview and campaigns tweet was involved
in.
Creates
- AllTweets <dict> with TweetIDs as Keys. Every tweetID leads to another dict object.
TweetID dicts include TweetPerformance, a list of campaigns tweet was involved in, UserID, ScreenName.
Writes to file [ScreenName]/TweetMetadata.json.
- CampaingIDs <dict>
CampaignID = AccountID
NOTE: CampaignID to AccountID is a many to one relation so far. However, there is a special check in case that changes.
See line 96 to 100.
Returns
- CampaignIDs and ScreenName.
Writes
- TweetMetadata.json every 10 entries. And the entire file once the AllTweets <dict> is complete.
"""
TweetMetadataList = []
CampaignIDs = {}
AllTweets = {}
UserID = list(Tweets.keys())
if len(UserID) == 1:
UserID = UserID[0]
ScreenName = Tweets[UserID]['ScreenName']
Tweets = Tweets[UserID]['Tweets']
else:
SendErrorEmail("Multiple keys check tweets for " + ScreenName)
print(UserID, ScreenName)
for Tweet in Tweets:
TweetID = Tweet['tweetId']
AllTweets[TweetID] = {}
if Tweet['promotedMetadata']['political']:
try:
OverviewTweet = Session.get(TweetOverviewLink % (TweetID, UserID), headers=Headers)
if OverviewTweet.status_code == 200:
AllTweets[TweetID]['TweetPerformance'] = json.loads(OverviewTweet.text)
else:
SendErrorEmail("Didn't get 200 for tweet overview for " + TweetOverviewLink % (TweetID, UserID))
except Exception as e:
SendErrorEmail("Error on " + TweetOverviewLink % (TweetID, UserID) + " Error: " + str(e))
time.sleep(random.randint(MINWAIT/10,MAXWAIT/10))
try:
TweetCampaignDetails = Session.get(TweetDetailsLink % (TweetID, UserID), headers=Headers)
if TweetCampaignDetails.status_code == 200:
AllTweets[TweetID]['TweetCampaigns'] = json.loads(TweetCampaignDetails.text)
else:
SendErrorEmail("Didn't get 200 for tweet overview for " + TweetDetailsLink % (TweetID, UserID))
except Exception as e:
SendErrorEmail("Error on " + TweetDetailsLink % (TweetID, UserID) + " Error: " + str(e))
for Campaigns in AllTweets[TweetID]['TweetCampaigns']['metadata']:
if Campaigns['line_item_id'] not in CampaignIDs:
CampaignIDs[Campaigns['line_item_id']] = Campaigns['account_id']
else:
try:
assert(CampaignIDs[Campaigns['line_item_id']] == Campaigns['account_id'])
except:
print("AccountID changing for campaigns for " + str(Campaigns) + ScreenName)
SendErrorEmail("AccountID changing for campaigns for " + str(Campaigns) + ScreenName)
if TweetID in AllTweets:
if "TweetPerformance" in AllTweets[TweetID] and "TweetCampaigns" in AllTweets[TweetID]:
AllTweets[TweetID]['ScreenName'] = ScreenName
AllTweets[TweetID]['UserID'] = UserID
if len(AllTweets) % 10 == 0:
WriteToDisk(ScreenName, AllTweets, "TweetMetadata")
WriteToDisk(ScreenName, AllTweets, "TweetMetadata")
return CampaignIDs, ScreenName, UserID
def GetMetadataForCampaign(CampaignIDs, ScreenName, UserID, Session):
"""
Accepts CampaignID to request overview of particular campaign. UserID and CampaignId for the
precise targeting details of the campaign.
Creates:
- Campaign <dict> primary key of CampaignID.
Contains Overview (of campaign) <dict>, TargetDetails (of campaign) <dict>, ScreenName of the user, and UserID.
Writes:
CampaignMetadata.json every 10 entries. And then all the entries once the Campaign <dict> is complete.
"""
Campaign = {}
pprint(CampaignIDs)
for CampaignID in CampaignIDs:
print("Crawling CampaignID: ", CampaignID)
AccountID = CampaignIDs[CampaignID]
try:
CampaignOverview = Session.get(CampaignOverviewLink%CampaignID, headers=Headers)
if CampaignOverview.status_code == 200:
Campaign[CampaignID] = {}
Campaign[CampaignID]['Overview'] = json.loads(CampaignOverview.text)
else:
SendErrorEmail("Error code not 200 for " + CampaignOverviewLink%CampaignID)
except Exception as e:
SendErrorEmail("Error with "+CampaignOverviewLink%CampaignID + ' Error: ' + str(e))
time.sleep(random.randint(MINWAIT/10,MAXWAIT/10))
try:
CampaignTargetingDetails = Session.get(CampaignDetailsLink%(AccountID, CampaignID), headers=Headers)
if CampaignTargetingDetails.status_code == 200:
Campaign[CampaignID]['TargetDetails'] = json.loads(CampaignTargetingDetails.text)
else:
SendErrorEmail("Error code not 200 for campaign ID " + CampaignDetailsLink%(AccountID, CampaignID))
except Exception as e:
SendErrorEmail("Error with " + CampaignDetailsLink%(AccountID, CampaignID) + ' Error: ' + str(e))
if CampaignID in Campaign:
if 'Overview' in Campaign[CampaignID] and 'TargetDetails' in Campaign[CampaignID]:
Campaign[CampaignID]['ScreenName'] = ScreenName
Campaign[CampaignID]['UserID'] = UserID
time.sleep(random.randint(MINWAIT/5, MAXWAIT/5))
if len(Campaign)%10 == 0:
WriteToDisk(ScreenName, Campaign, 'CampaignMetadata')
WriteToDisk(ScreenName, Campaign, 'CampaignMetadata')
def WriteToDisk(ScreenName, PayloadToWrite, Type):
print("Writing to ", os.path.join(ScreenName, Type) + '.json')
File = os.path.join(ScreenName, Type) + '.json'
with open(File, 'w') as f:
json.dump(PayloadToWrite, f, indent=JSON_INDENT)
return
def SendErrorEmail(ErrorMessage):
"""
Accepts an error message (in any format) and sends email using the
creds used.
"""
msg = MIMEText(str(ErrorMessage))
msg['from'] = SCRAPEREMAIL
msg['to'] = ERROREMAIL
msg['subject'] = 'Error in Metadata script'
s = smtplib.SMTP('smtp.live.com', 25)
s.ehlo()
s.starttls()
s.login(SCRAPEREMAIL, PASSWORD)
s.sendmail(SCRAPEREMAIL, [ERROREMAIL], msg.as_string())
s.quit()
if __name__ == "__main__":
TwitterAPI = twitter.Twitter(auth=twitter.OAuth(ACCESS_KEY_TOKEN,
ACCESS_KEY_SECRET, CONSUMER_KEY, CONSUMER_SECRET))
Start=time.time()
Path = os.getcwd()
os.chdir(os.path.join(Path, WriteDir))
CurrentDirectory = os.getcwd()
with requests.Session() as Session:
Resp = Session.get(URL, headers=Headers)
# get auth token
soup = BeautifulSoup(Resp.content, "lxml")
AUTH_TOKEN = soup.select_one("input[name=authenticity_token]")["value"]
# update data, post and you are logged in.
data["authenticity_token"] = AUTH_TOKEN
Resp = Session.post(LoginPost, data=data, headers=Headers)
UsersWithPoliticalAds = {} #ScreenName:UserID
for IssueFolder in os.listdir(CurrentDirectory):
if IssueFolder[0] == '.':
continue
print(IssueFolder)
TweetFile = os.path.join(CurrentDirectory, IssueFolder, "Tweets.json")
with open(TweetFile, 'r') as f:
Tweets = json.load(f)
try:
CampaignIDs, ScreenName, UserID = GetMetadataForTweets(Tweets, Session)
#print(Campaigns)
#CampaignIDs, ScreenName, UserID = CollectCampaignIDs()
GetMetadataForCampaign(CampaignIDs, ScreenName, UserID, Session)
time.sleep(random.randint(MINWAIT, MAXWAIT))
except Exception as e:
SendErrorEmail(e)
continue
print("Total time to get metadata: ", time.time() - Start)