Skip to content

Instantly share code, notes, and snippets.

@jwoglom
Created November 18, 2022 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwoglom/7847d8b2089684d513e9ebb803879503 to your computer and use it in GitHub Desktop.
Save jwoglom/7847d8b2089684d513e9ebb803879503 to your computer and use it in GitHub Desktop.
Download all tweets liked by a user from Twitter
# pip3 install tweepy
import tweepy
import json
import time
# Follow the instructions to create a new development project and API keys
# from https://developer.twitter.com/en/portal/petition/essential/basic-info
# and enter the key, secret, and bearer token.
apiv2 = tweepy.Client(
consumer_key='',
consumer_secret='',
bearer_token=''
)
# Enter the user ID associated with your username.
# You can find this by entering your username at https://tweeterid.com/
YOUR_USER_ID = 123456
def get_tweets(apiv2, **kwargs):
return apiv2.get_liked_tweets(YOUR_USER_ID,
media_fields=['media_key','url','type','duration_ms','preview_image_url','alt_text','variants'],
place_fields=['full_name','id','contained_within','country','country_code','geo','name','place_type'],
poll_fields=['id','options','duration_minutes','end_datetime','voting_status'],
tweet_fields=['id','text','edit_history_tweet_ids','attachments','author_id','context_annotations','conversation_id','created_at','edit_controls','entities','in_reply_to_user_id','lang','public_metrics','referenced_tweets','reply_settings','source','withheld'],
user_fields=['id','name','username','created_at','description','entities','location','pinned_tweet_id','profile_image_url','protected','public_metrics','url','verified','withheld'],
**kwargs)
# If you need to re-run the script after a failure,
# add `, pagination_token='xxx'` with the pagination token
# which was logged out before the failure.
l = get_tweets(apiv2)
items = []
while l and l.data:
for item in l.data:
items.append(item.data)
open("data.json", "w").write(json.dumps(items, default=str))
print(l.meta, len(items))
if 'next_token' not in l.meta:
break
next_token = l.meta['next_token']
while True:
try:
print('getting tweets')
l = get_tweets(apiv2, pagination_token=next_token)
break
except tweepy.errors.TooManyRequests as e:
print(e)
print('sleeping')
time.sleep(60)
if not l:
print('no l!', l)
if not l.data:
print('no l.data!', l.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment