Creating a Twitter Collection via API
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 | |
from requests_oauthlib import OAuth1Session | |
# For a blog post describing this process more, see: | |
# https://medium.com/analytics-vidhya/creating-a-twitter-collection-via-api-1378ecfe20df | |
api_key = 'your api key' | |
api_secret_key = 'your api secret key' | |
access_token = 'your access token' | |
access_token_secret = 'your access token secret' | |
# twitter oauth | |
twitter = OAuth1Session(api_key, | |
client_secret=api_secret_key, | |
resource_owner_key=access_token, | |
resource_owner_secret=access_token_secret) | |
# create | |
url = 'https://api.twitter.com/1.1/collections/create.json' | |
params_create = { | |
'name': 'cutest puppies EVER', | |
'timeline_order': 'tweet_reverse_chron' | |
} | |
r = twitter.post(url, data=params_create) | |
print(r.json()) | |
print(r.json()['response']) | |
# 'response': {'timeline_id': 'custom-1180945428222595074'}} | |
timeline_id = r.json()['response']['timeline_id'] | |
# the collection can be viewed at, eg: https://twitter.com/laurenfratamico/timelines/1180945428222595074 | |
tweet_ids = [1148286877616803840, 1180845365542752256, 1180123991165607937] | |
# add | |
url = 'https://api.twitter.com/1.1/collections/entries/add.json' | |
for tweet_id in tweet_ids: | |
params_add = { | |
'tweet_id': tweet_id, | |
'id': timeline_id | |
} | |
r = twitter.post(url, data=params_add) | |
print(r.json()) | |
# bulk add | |
url = 'https://api.twitter.com/1.1/collections/entries/curate.json' | |
# split into batches of 100 for the uploads | |
n = 100 | |
batches = [tweet_ids[i:i + n] for i in range(0, len(tweet_ids), n)] | |
print (len(batches)) | |
for batch in batches: | |
params_add = { | |
"id": timeline_id, | |
"changes": [] | |
} | |
for tweet_id in batch: | |
sub_params_add = { | |
"tweet_id": str(tweet_id), | |
"op": "add" | |
} | |
params_add['changes'].append(sub_params_add) | |
r = twitter.post(url, data=json.dumps(params_add)) | |
print(r.json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment