Last active
October 22, 2021 09:10
-
-
Save Isopach/7bf566b52928592b54d35c40302e9915 to your computer and use it in GitHub Desktop.
Get latest 3200 tweets of a user using tweepy
This file contains hidden or 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 tweepy | |
import sys | |
import os | |
cwd = os.getcwd() | |
this_dir = cwd + '/' | |
consumer_key ="redacted" | |
consumer_secret ="redacted" | |
access_token="redacted" | |
access_token_secret ="redacted" | |
def getTweets(): | |
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) | |
auth.set_access_token(access_token, access_token_secret) | |
api = tweepy.API(auth) | |
userID = sys.argv[1] | |
fullpath = touchFile() | |
output = open(fullpath, 'w', encoding='utf-8') | |
for pages in tweepy.Cursor(api.user_timeline, screen_name=userID, count=3000).pages(): | |
num = 1 # init counter | |
for tweet in pages: | |
print('twid : ', tweet.id) # Tweet ID | |
output.write('twid : ' + str(tweet.id)) | |
output.write('\n') | |
#print('user : ', tweet.user.screen_name) # Tweet author | |
print('date : ' + str(datetime_from_utc_to_local(tweet.created_at))[:-6]) # Time in your local timezone | |
output.write('date : ' + str(datetime_from_utc_to_local(tweet.created_at))[:-6]) | |
output.write('\n') | |
print(tweet.text) # Content | |
output.write(tweet.text) | |
output.write('\n') | |
#print('favo : ', tweet.favorite_count) # Fav count | |
#print('retw : ', tweet.retweet_count) # RT count | |
#print('counter : ', num) # tweet count | |
num += 1 # Add 1 to counter | |
def touchFile(): | |
try: | |
filename = str(sys.argv[1]) + ".txt" | |
except IndexError: | |
sys.exit("Please input the username of target user as argument") | |
savepath = this_dir + 'tweets/' | |
if not os.path.exists(os.path.dirname(savepath + filename)): | |
try: | |
os.makedirs(os.path.dirname(savepath + filename)) | |
except OSError: | |
if errno != errno.EEXIST: | |
raise | |
fullpath = savepath + filename | |
return fullpath | |
def datetime_from_utc_to_local(utc_datetime): | |
import time | |
import datetime | |
now_timestamp = time.time() | |
offset = datetime.datetime.fromtimestamp(now_timestamp) - datetime.datetime.utcfromtimestamp(now_timestamp) | |
return utc_datetime + offset | |
if __name__ == '__main__': | |
getTweets() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment