Library for accessing the X API (Twitter)
Tweepy provides rich data model classes representing Twitter objects with full field access and type safety. These models correspond to Twitter API v2 objects and include tweets, users, media, spaces, lists, polls, places, and direct message events.
Represents a Twitter tweet with all available fields from Twitter API v2.
class Tweet:
"""
Twitter tweet object with full API v2 field support.
Attributes:
- id (str): Unique tweet identifier
- text (str): Tweet text content
- edit_history_tweet_ids (list): IDs of edit history tweets
- attachments (dict): Media and poll attachments
- author_id (str): ID of tweet author
- context_annotations (list): Context annotations
- conversation_id (str): ID of conversation root tweet
- created_at (datetime): Tweet creation timestamp
- edit_controls (dict): Edit control settings
- entities (dict): Extracted entities (mentions, hashtags, URLs, etc.)
- geo (dict): Geographic information
- in_reply_to_user_id (str): ID of user being replied to
- lang (str): Language code (BCP 47)
- non_public_metrics (dict): Private engagement metrics (author only)
- organic_metrics (dict): Organic engagement metrics (author only)
- possibly_sensitive (bool): Potentially sensitive content flag
- promoted_metrics (dict): Promoted tweet metrics (author only)
- public_metrics (dict): Public engagement metrics (likes, retweets, etc.)
- referenced_tweets (list): Referenced tweets (replies, quotes, retweets)
- reply_settings (str): Reply settings ("everyone", "mentionedUsers", "following")
- source (str): Tweet source application
- withheld (dict): Content withheld information
"""Represents a Twitter user with all available fields from Twitter API v2.
class User:
"""
Twitter user object with full API v2 field support.
Attributes:
- id (str): Unique user identifier
- name (str): User's display name
- username (str): User's handle (without @)
- created_at (datetime): Account creation timestamp
- description (str): User's profile description/bio
- entities (dict): Extracted entities from profile (URLs, hashtags)
- location (str): User-provided location string
- pinned_tweet_id (str): ID of pinned tweet
- profile_image_url (str): Profile image URL
- protected (bool): Protected account flag
- public_metrics (dict): Public metrics (followers_count, following_count, etc.)
- url (str): User's website URL
- verified (bool): Legacy verification status
- verified_type (str): Verification type ("blue", "business", "government")
- withheld (dict): Account withheld information
"""Represents media attachments (images, videos, GIFs) with metadata and metrics.
class Media:
"""
Media attachment object with full metadata and metrics.
Attributes:
- media_key (str): Unique media identifier
- type (str): Media type ("photo", "video", "animated_gif")
- url (str): Media URL for photos
- duration_ms (int): Duration in milliseconds for videos
- height (int): Media height in pixels
- non_public_metrics (dict): Private media metrics (author only)
- organic_metrics (dict): Organic media metrics (author only)
- preview_image_url (str): Preview image URL for videos
- promoted_metrics (dict): Promoted media metrics (author only)
- public_metrics (dict): Public media metrics (view_count)
- width (int): Media width in pixels
- alt_text (str): Alternative text description
- variants (list): Media variants with different quality/format
"""Represents Twitter Spaces (audio conversations) with participant and scheduling information.
class Space:
"""
Twitter Space object with full metadata and participant information.
Attributes:
- id (str): Unique Space identifier
- state (str): Space state ("live", "scheduled", "ended")
- created_at (datetime): Space creation timestamp
- ended_at (datetime): Space end timestamp
- host_ids (list): List of host user IDs
- lang (str): Space language code
- is_ticketed (bool): Ticketed Space flag
- invited_user_ids (list): List of invited user IDs
- participant_count (int): Current participant count
- subscriber_count (int): Subscriber count
- scheduled_start (datetime): Scheduled start time
- speaker_ids (list): List of speaker user IDs
- started_at (datetime): Actual start timestamp
- title (str): Space title
- topic_ids (list): List of topic IDs
- updated_at (datetime): Last update timestamp
- creator_id (str): Space creator user ID
"""Represents Twitter lists with membership and metadata information.
class List:
"""
Twitter list object with metadata and membership information.
Attributes:
- id (str): Unique list identifier
- name (str): List name
- created_at (datetime): List creation timestamp
- description (str): List description
- follower_count (int): Number of list followers
- member_count (int): Number of list members
- private (bool): Private list flag
- owner_id (str): List owner user ID
"""Represents Twitter polls with voting options and results.
class Poll:
"""
Twitter poll object with voting options and results.
Attributes:
- id (str): Unique poll identifier
- options (list): Poll options with vote counts
- duration_minutes (int): Poll duration in minutes
- end_datetime (datetime): Poll end timestamp
- voting_status (str): Voting status ("open", "closed")
"""Represents geographic places referenced in tweets.
class Place:
"""
Geographic place object with location information.
Attributes:
- id (str): Unique place identifier
- full_name (str): Full place name
- name (str): Place name
- country (str): Country name
- country_code (str): Country code (ISO 3166-1 alpha-2)
- geo (dict): Geographic coordinates and bounding box
- place_type (str): Place type ("admin", "city", "country", etc.)
"""Represents direct message events with sender information and content.
class DirectMessageEvent:
"""
Direct message event object with full message information.
Attributes:
- id (str): Unique event identifier
- text (str): Message text content
- event_type (str): Event type ("MessageCreate", "ParticipantsJoin", etc.)
- created_at (datetime): Event creation timestamp
- sender_id (str): Sender user ID
- dm_conversation_id (str): Conversation identifier
- referenced_tweet (dict): Referenced tweet information
- media_keys (list): List of attached media keys
- attachments (dict): Message attachments
"""Represents tweets referenced by other tweets (replies, quotes, retweets).
class ReferencedTweet:
"""
Referenced tweet object for replies, quotes, and retweets.
Attributes:
- type (str): Reference type ("replied_to", "quoted", "retweeted")
- id (str): Referenced tweet ID
"""import tweepy
client = tweepy.Client(bearer_token="your_bearer_token")
# Get tweet with full fields
tweet = client.get_tweet(
"1234567890123456789",
tweet_fields=["created_at", "public_metrics", "entities", "context_annotations"],
expansions=["author_id", "attachments.media_keys"],
user_fields=["username", "verified", "public_metrics"]
)
# Access tweet data
print(f"Tweet: {tweet.data.text}")
print(f"Created: {tweet.data.created_at}")
print(f"Likes: {tweet.data.public_metrics['like_count']}")
print(f"Retweets: {tweet.data.public_metrics['retweet_count']}")
# Access entities
if hasattr(tweet.data, 'entities'):
entities = tweet.data.entities
if 'hashtags' in entities:
hashtags = [tag['tag'] for tag in entities['hashtags']]
print(f"Hashtags: {hashtags}")
if 'mentions' in entities:
mentions = [mention['username'] for mention in entities['mentions']]
print(f"Mentions: {mentions}")
# Access included data
if tweet.includes and 'users' in tweet.includes:
author = tweet.includes['users'][0]
print(f"Author: @{author.username} ({author.name})")
print(f"Followers: {author.public_metrics['followers_count']}")# Get user with metrics
user = client.get_user(
username="twitter",
user_fields=["created_at", "description", "public_metrics", "verified_type"],
expansions=["pinned_tweet_id"],
tweet_fields=["created_at", "public_metrics"]
)
# Access user data
print(f"User: {user.data.name} (@{user.data.username})")
print(f"Bio: {user.data.description}")
print(f"Joined: {user.data.created_at}")
print(f"Followers: {user.data.public_metrics['followers_count']:,}")
print(f"Following: {user.data.public_metrics['following_count']:,}")
print(f"Verified: {user.data.verified_type}")
# Access pinned tweet if available
if user.includes and 'tweets' in user.includes:
pinned_tweet = user.includes['tweets'][0]
print(f"Pinned tweet: {pinned_tweet.text}")# Search for tweets with media
tweets = client.search_recent_tweets(
query="cats has:images",
expansions=["attachments.media_keys"],
media_fields=["type", "url", "alt_text", "public_metrics"],
max_results=10
)
# Process media attachments
for tweet in tweets.data:
if tweet.attachments and 'media_keys' in tweet.attachments:
media_keys = tweet.attachments['media_keys']
# Find corresponding media objects in includes
if tweets.includes and 'media' in tweets.includes:
for media in tweets.includes['media']:
if media.media_key in media_keys:
print(f"Media type: {media.type}")
if hasattr(media, 'url'):
print(f"URL: {media.url}")
if hasattr(media, 'alt_text'):
print(f"Alt text: {media.alt_text}")
if hasattr(media, 'public_metrics'):
print(f"Views: {media.public_metrics.get('view_count', 0)}")# Search for live Spaces
spaces = client.search_spaces(
query="python programming",
space_fields=["host_ids", "participant_count", "started_at", "title"],
expansions=["host_ids"],
user_fields=["username", "name"]
)
# Process Space data
for space in spaces.data:
print(f"Space: {space.title}")
print(f"State: {space.state}")
print(f"Participants: {space.participant_count}")
# Access host information from includes
if spaces.includes and 'users' in spaces.includes:
hosts = [user for user in spaces.includes['users'] if user.id in space.host_ids]
host_names = [f"@{host.username}" for host in hosts]
print(f"Hosts: {', '.join(host_names)}")API responses contain data models organized in a structured format:
# Response structure
response = client.get_tweet(tweet_id, expansions=["author_id"])
# Primary data
tweet = response.data # Tweet object
# Included data (related objects)
if response.includes:
users = response.includes.get('users', []) # List of User objects
media = response.includes.get('media', []) # List of Media objects
polls = response.includes.get('polls', []) # List of Poll objects
places = response.includes.get('places', []) # List of Place objects
spaces = response.includes.get('spaces', []) # List of Space objects
# Metadata
if response.meta:
result_count = response.meta.get('result_count')
next_token = response.meta.get('next_token')Data models provide direct attribute access to all available fields:
# Direct field access
tweet_id = tweet.id
tweet_text = tweet.text
created_at = tweet.created_at
# Check field availability
if hasattr(tweet, 'public_metrics'):
likes = tweet.public_metrics['like_count']
# Safe field access with defaults
metrics = getattr(tweet, 'public_metrics', {})
likes = metrics.get('like_count', 0)Use field constants to specify which fields to include in API requests:
from tweepy import TWEET_FIELDS, USER_FIELDS, MEDIA_FIELDS
# Request specific fields
tweet = client.get_tweet(
tweet_id,
tweet_fields=TWEET_FIELDS, # All available tweet fields
user_fields=USER_FIELDS, # All available user fields
media_fields=MEDIA_FIELDS # All available media fields
)Install with Tessl CLI
npx tessl i tessl/pypi-tweepy