Twitter Based API using Python
You can download full code from here…
Lets get Started with Code Explanation…
# IMPORT STATEMENTS
from tweepy import OAuthHandler
from tweepy import API
import time
import json
This will require tweepy
, json
and time
library to work on it. json
and time
are already installed with python. If you don’t have have tweepy
just install using pip
or pip3
pip install tweepy
pip3 install tweepy
Next Step is to add credentials and get access from twitter to use it from outside of twitter environment. You can get access keys from https://developer.twitter.com/en/apps
Just login with your twitter account and add your contact number to get access of developer…
Just make sure that this keys will be not seen by anyone else and this must be confident enough. I will genuinely say that don’t misuse it otherwise, twitter will banned you account and it will be very difficult to get it back.
#Credentials
#consumer_key = '*************************'
#consumer_secret = '**************************************************'
This keys help us to fetch the data from twitter. If you want to write twitter post you must have access_token
and access_token_secret
along with consumer_key
and consumer_secret
.
#Name of Twitter Handle
screen_name = '@iKhushPatel'
Following part will fetch your all tweets from timeline. Here I added count around 300 so it will only fetch first 300 tweets from the beginning of the account.
tweets = api.user_timeline(screen_name=screen_name, count=300, tweet_mode='extended')
Following code will give you count regarding number of photos available in the tweets and date of tweet with in YYYY-MM-DD HH:MM:SS
format. You can set are per requirements.
#Method to Get No of Images in Tweet
def getMediaCount(jsonObj):
key = 'extended_entities'
if key in jsonObj._json.keys():
return len(jsonObj._json['extended_entities']['media'])
else:
return None
#Method to Change the Twitter time stamp to YYYY-MM-DD HH:MM:SS
def getDateTime(jsonObj):
return time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(jsonObj._json['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))
Just Few Print Statements:
#Printing List
for tweet in tweets:
print('-'*10)
print("Tweet Text :: ", tweet._json['full_text'])
print("Created Datetime :: ", getDateTime(tweet))
print("Likes Count :: ", tweet._json['favorite_count'])
print("Retweet Count :: ", tweet._json['retweet_count'])
print("No of Images :: ", getMediaCount(tweet))
print('*'*10)
You can get many information from tweets object. Just print it in json format and get information as per you requirements.
If you really like my efforts, please clap 👏 it and follow me at Khush Patel
Website: http://www.khushpatel.com
LinnkedIn: https://www.linkedin.com/in/ikhushpatel