Skip to content

6. Examples

Dev Jones edited this page Mar 25, 2024 · 2 revisions

The PyTweetClient serves as a comprehensive interface for engaging with a broad spectrum of Twitter API endpoints. Below, we illustrate how to utilize this client to accomplish a variety of tasks, from fetching user profiles to posting tweets and managing interactions.

Setting Up the Client

First, you need to instantiate the PyTweetClient with your Twitter API credentials. Make sure you have the authentication and CSRF tokens at your disposal.

from pytweettoolkit import PyTweetClient

# Initialize PyTweetClient with your credentials
auth_token = "YOUR_AUTH_TOKEN"
csrf_token = "YOUR_CSRF_TOKEN"
client = PyTweetClient(auth_token, csrf_token)

Example 1: Retrieve and Display a User Profile

Fetch detailed information about a Twitter user's profile using their screen name and display selected profile attributes.

# Fetching the profile for the user '@elonmusk'
user_profile = client.get_user_by_screen_name("elonmusk")

# Displaying selected information about the user
print(f"User Name: {user_profile.name}")
print(f"Description: {user_profile.description}")
print(f"Followers: {user_profile.followers_count}")
print(f"Following: {user_profile.friends_count}")

Example 2: Post a New Tweet

Create and post a new tweet with text content.

# Content of the tweet
content = "Exploring the Twitter API with #PyTweetToolkit!"

# Posting the tweet
new_tweet = client.create_tweet(content=content)

print(f"Tweeted: {new_tweet.full_text}")

Example 3: Search for Tweets

Conduct a search for the latest tweets containing a specific hashtag.

# Searching for tweets with the hashtag #Python
search_query = "#Python"
tweets, next_cursor, previous_cursor = client.search_latest(query=search_query)

print("Latest tweets about Python:")
for tweet in tweets:
    print(f"- {tweet.full_text[:50]}...")

Example 4: Follow a User

Follow another Twitter user by specifying their user ID.

# User ID of the account you wish to follow
user_id_to_follow = "123456789"

# Following the user
followed_user = client.follow_user(user_id=user_id_to_follow)

print(f"Now following {followed_user.screen_name}")

Example 5: Bookmark a Tweet

Add a tweet to your bookmarks by specifying the tweet's ID.

# ID of the tweet to bookmark
tweet_id_to_bookmark = "987654321"

# Bookmarking the tweet
client.bookmark_tweet(tweet_id=tweet_id_to_bookmark)

print("Tweet bookmarked successfully.")

These examples demonstrate the versatility and ease of use provided by the PyTweetClient, facilitating interaction with Twitter's diverse functionalities through a unified interface.