0% found this document useful (0 votes)
10 views34 pages

Tweepy Functions

This document provides Python code examples for using the Tweepy library and Twitter API to fetch user information, search for tweets, and handle various Twitter API functionalities. It includes authentication methods, user data retrieval, tweet searching, and stream handling techniques. The document also outlines functions for cleaning and tokenizing tweets, as well as handling events in a streaming context.

Uploaded by

Rituparna Sahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views34 pages

Tweepy Functions

This document provides Python code examples for using the Tweepy library and Twitter API to fetch user information, search for tweets, and handle various Twitter API functionalities. It includes authentication methods, user data retrieval, tweet searching, and stream handling techniques. The document also outlines functions for cleaning and tokenizing tweets, as well as handling events in a streaming context.

Uploaded by

Rituparna Sahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Chapter 13: Tweepy

Functions
Understanding and Implementing Tweepy
Functions for Twitter API
Write a Python code to fetch user information from Twitter's API using the
requests package and a Bearer Token.
 import requests

 # Replace with your actual Bearer Token from X Developer Portal


 BEARER_TOKEN = "GIVE YOUR BEARER TOKEN"

 def get_user_info(username):
 url = f"https://api.twitter.com/2/users/by/username/{username}?
user.fields=id,name,username,description,public_metrics"
 headers = {
 "Authorization": f"Bearer {BEARER_TOKEN}"
 }

 response = requests.get(url, headers=headers)

 if response.status_code == 200:
 user_data = response.json()["data"]
 print("User ID:", user_data["id"])
 print("User Name:", user_data["name"])
 print("Screen Name:", user_data["username"])
 print("Description:", user_data["description"])
 print("Followers Count:", user_data["public_metrics"]["followers_count"])
 else:
 print("Error:", response.status_code, response.text)

 # Replace 'elonmusk' with any Twitter username


 get_user_info("GIVE YOUR TWITTER USERNAME")
Write a Python code to fetch user details, including follower count, from
Twitter's API using the tweepy package and authentication credentials.
 import tweepy

 # Twitter API credentials


 API_KEY = " GIVE YOUR API KEY"
 API_SECRET = " GIVE YOUR API SECRET"
 ACCESS_TOKEN = " GIVE YOUR ACCESS TOKEN"
 ACCESS_SECRET = "GIVE YOUR ACCESS SECRET"
 BEARER_TOKEN = "GIVE YOUR BEARAER TOKEN"
 # Authenticate with Twitter API v2
 client = tweepy.Client(bearer_token=BEARER_TOKEN)

 # Twitter username (replace with your username)


 username = "GIVE YOUR TWITTER USERNAME"

 # Fetch user details


 user = client.get_user(username=username, user_fields=["public_metrics"])

 # Get follower count


 if user.data:
 print("User ID:", user.data.id)
 print("Username:", user.data.username)
 print("Name:", user.data.name)
 print("Followers Count:", user.data.public_metrics["followers_count"])
 else:
 print("User not found.")
Write a Python code to search for recent tweets containing a specific keyword
using the tweepy package and Twitter API authentication.
 import tweepy

 API_KEY = " GIVE YOUR API KEY"


 API_SECRET = " GIVE YOUR API SECRET"
 ACCESS_TOKEN = " GIVE YOUR ACCESS TOKEN"
 ACCESS_SECRET = "GIVE YOUR ACCESS SECRET"

 client = tweepy.Client(bearer_token="GIVE YOUR BEARAER


TOKEN")

 query = "Python programming" # Replace with your search term

 tweets = client.search_recent_tweets(query=query, max_results=15)

 # Print tweets
 for tweet in tweets.data:
 print(f"Tweet: {tweet.text}\n")
tweepy.OAuthHandler
Used to create an OAuthHandler object for
authentication.
It help securely authenticate your application
before making api request.
Example:
import tweepy
auth = tweepy.OAuthHandler('API_KEY',
'API_SECRET')
OAuthHandler.set_access_token
Used to set the access token and secret.

Example:
auth.set_access_token('ACCESS_TOKEN',
'ACCESS_TOKEN_SECRET')
api=tweepy.API
Used to create an API object for interacting
with Twitter.

Example:
api = tweepy.API(auth)
api.get_user()
Used to get information about a Twitter
account.

Example:
user =
api.get_user(screen_name='TwitterUser')
print(user.name, user.followers_count)
api.followers
Used to get a list of followers for an account.

Example:
followers =
api.followers(screen_name='TwitterUser')
for f in followers:
 print(f.name)
api.followers_count
Returns the number of followers.

Example:
user =
api.get_user(screen_name='TwitterUser')
print(user.followers_count)
api.followers_ids
Used to get a list of follower IDs for an
account.

Example:
follower_ids =
api.followers_ids(screen_name='TwitterUser')
print(follower_ids)
api.friends
Used to get a list of friends (accounts
followed) for an account.

Example:
friends =
api.friends(screen_name='TwitterUser')
for f in friends:
 print(f.name)
api.friends_count
Used to get number of friends (accounts
followed).

Example:
user =
api.get_user(screen_name='TwitterUser')
print(user.friends_count)
api.me()
Returns a User object for the authenticated
account.

Example:
me = api.me()
print(me.name, me.screen_name)
Tweepy.cursor
Handles pagination and rate limits when
accessing large datasets.

Example:
for tweet in tweepy.Cursor(api.user_timeline,
screen_name='TwitterUser').items(10):
 print(tweet.text)
api.user_timeline
Used to get tweets from a user's timeline.

Example:
tweets =
api.user_timeline(screen_name='TwitterUser'
, count=5)
for tweet in tweets:
 print(tweet.text)
api.home_timeline
Used to get tweets from the home timeline.

Example:
tweets = api.home_timeline(count=5)
for tweet in tweets:
 print(tweet.text)
api.search
Used to search for tweets matching a query.

Example:
tweets = api.search(q='Python', count=5)
for tweet in tweets:
 print(tweet.text)
api.trends_available
Gets a list of locations with trending topics.

Example:
trends = api.trends_available()
print(trends)
api.trends_closest
Finds locations close to a specified latitude
and longitude.

Example:
closest_trends =
api.trends_closest(lat=37.7749, long=-
122.4194)
print(closest_trends)
api.trends_place
Gets trending topics for a specific location.

Example:
trends = api.trends_place(1)
print(trends)
WordCloud
Used to create a word frequency cloud.

Example:
from wordcloud import WordCloud
wordcloud = WordCloud().generate('sample
text')
wordcloud.to_image().show()
clean(text)
Cleans a tweet by removing URLs, mentions,
hashtags, emojis, reserved words, and
numbers.

Example:
from preprocessor import clean
tweet = 'Check this out! http://example.com
#AI @user'
print(clean(tweet))
tokenize(text)
Tokenizes the tweet while keeping URLs,
mentions, and hashtags.

Example:
from preprocessor import tokenize
tweet = 'Hello #World! Visit
http://example.com'
print(tokenize(tweet))
set_options(*options)
Specifies what to remove (e.g., mentions,
URLs, hashtags).

Example:
from preprocessor import set_options, clean
set_options('urls', 'hashtags')
tweet = 'Visit http://example.com #Python'
print(clean(tweet))
clear()
Clears the set options, resetting the
preprocessor.

Example:
from preprocessor import clear
clear()
on_status
Called when a new tweet arrives.

Example:
class MyListener(tweepy.StreamListener):
 def on_status(self, status):
 print(status.text)
on_connect
Called when connection to the stream is
successful.

Example:
def on_connect(self):
 print('Connected to stream.')
on_limit
Called when tweet stream exceeds rate
limits.

Example:
def on_limit(self, track):
 print('Rate limit exceeded')
on_error
Called when Twitter sends an error code.

Example:
def on_error(self, status_code):
 print(f'Error: {status_code}')
on_delete
Called when a tweet is deleted.

Example:
def on_delete(self, status_id, user_id):
 print(f'Tweet {status_id} deleted')
on_data
Called when raw data is received from
Twitter.

Example:
def on_data(self, raw_data):
 print(raw_data)
on_timeout
Called if the connection to the stream times
out.

Example:
def on_timeout(self):
 print('Stream timeout')
on_warning
Called when Twitter sends a disconnect
warning.

Example:
def on_warning(self, notice):
 print('Warning:', notice)

You might also like