Created
November 23, 2022 03:15
-
-
Save PhiBabin/8a4b4712937075fb0282ce3aab68f410 to your computer and use it in GitHub Desktop.
Twitter allows you download your data. However, the list of following only contains the user id, not the username, which is basically useless if Twitter is down. This script takes the following.js from the data archive and fetch all the available data about each user (username, description, url, ...). You need to create an app to get the bearer …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
import requests | |
# You need the bearer token, to get it, go to https://developer.twitter.com/en/portal/projects-and-apps and create an app | |
bearer_token = os.environ['TWITTER_TOKEN'] | |
if __name__ == "__main__": | |
with open('following.js') as file: | |
data = json.loads(file.read().partition('window.YTD.following.part0 = ')[2]) | |
account_ids = [d['following']['accountId'] for d in data] | |
chunk_size = 100 | |
output = [] | |
for i in range(0, len(account_ids), chunk_size): | |
ids = account_ids[i:i+chunk_size] | |
res = requests.get('https://api.twitter.com/2/users', params={'ids': ",".join(ids), 'user.fields': 'id,name,username,description,location,url,entities'}, headers={"Authorization": f"Bearer {bearer_token}"}) | |
assert res.status_code == 200, str(res) | |
data = res.json() | |
assert 'error' not in data, data | |
for user in data['data']: | |
output.append(user) | |
print(f"{len(output)} users fetched, saving...") | |
with open('following.with.username.js', 'w') as file: | |
json.dump(output, file, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment