python-twitter-v2

repository·master·Indexed 42 days ago

https://github.com/sns-sdks/python-twitter

A simple Python wrapper for Twitter API v2 (version 0.9.3) providing a Pythonic interface to interact with tweets, users, trends, spaces, direct messages, and media uploads. It supports OAuth 2.0 and 3-legged OAuth flows and requires Python 3.6 or higher.

Tokens
17.7K
Snippets
96
Records
108
Agent score
54%

What's inside python-twitter

  1. Introduction to Python-Twitter

    master

    Python-Twitter is a Python wrapper specifically designed for the Twitter API V2. It provides a Pythonic interface to interact with the V2 endpoints.

    Important Compatibility Notes:

    • Python Version: Requires Python 3.6 or higher.
    • API Version: This library supports only Twitter API V2. It does not contain any APIs for version 1.1.
  2. Understand the two types of Twitter access tokens

    master

    When using the python-twitter SDK, authentication is categorized into two distinct types of tokens. You will typically need to manage two separate API instances to perform different types of operations:

    1. App Access Token: Used for application-level requests.
    2. User Access Token: Used for requests on behalf of a specific user.

    In typical usage patterns, you should maintain two instances, for example, api for App Access and my_api for User Access.

  3. Initialize the StreamApi

    master

    To use the streaming endpoints, you must instantiate a StreamApi object. This is independent of the main Api class. You can authenticate using either a bearer_token or a combination of consumer_key and consumer_secret.

    from pytwitter import StreamApi
    
    # Using a bearer token
    stream_api = StreamApi(bearer_token="bearer token")
    
    # OR using consumer key and secret
    # stream_api = StreamApi(consumer_key="consumer key", consumer_secret="consumer secret")
  4. Hide or unhide replies using hidden_reply()

    master

    You can programmatically hide or unhide replies to a specific tweet by using the hidden_reply method.

    • To hide a reply: Call hidden_reply with only the tweet_id.
    • To unhide a reply: Call hidden_reply and set the hidden parameter to False.
    # To hide a reply
    my_api.hidden_reply(tweet_id="tweet id")
    # Returns: {"data":{"hidden":true}}
    
    # To unhide a reply
    my_api.hidden_reply(tweet_id="tweet id", hidden=False)
    # Returns: {"data":{"hidden":false}}
  5. Use batch compliance endpoints to check dataset compliance

    master

    Batch compliance endpoints allow you to upload large datasets of Tweet or user IDs to retrieve their compliance status. This helps determine which data requires action to bring your datasets into compliance.

    Note: Use of these endpoints is strictly restricted to compliance use cases. Any other purpose is prohibited and may result in enforcement action.

    The workflow typically involves four steps:

    1. Create a compliance job to get an upload_url.
    2. Upload your dataset to the provided upload_url as a plain text file (one ID per line).
    3. Check the job status to see if it is created, in_progress, failed, or complete.
    4. Download the result using the provided download_url once the job is complete.
  6. Initialize the Api instance for OAuth2.0

    master

    To use OAuth2.0, initialize the Api class with your client_id. If your application is a Confidential client, you must also provide the client_secret.

    Important: By default, the callback URI is set to https://localhost/. You must add this exact URL to your application's Authentication settings in the Twitter developer portal.

    from pytwitter import Api
    
    # For Public Clients
    api = Api(client_id='your client id', oauth_flow=True)
    
    # For Confidential Clients
    api = Api(client_id='your client id', client_secret="your client secret", oauth_flow=True)
  7. Initialize the Api instance for 3-legged OAuth

    master

    To perform actions on behalf of a Twitter user using the 3-legged OAuth flow, initialize the Api class with your consumer credentials and set oauth_flow=True.

    Important Configuration: By default, the callback URI is https://localhost/. You must add this exact URL to your Twitter App's Authentication settings in the developer portal for the flow to work.

    from pytwitter import Api
    
    api = Api(consumer_key='your consumer key', consumer_secret='your consumer secret', oauth_flow=True)
  8. Mute or unmute a user

    master

    You can manage account mutes for an authenticated user using the mute_user and unmute_user methods.

    • Use mute_user to mute a specific account.
    • Use unmute_user to unmute a specific account.

    Rate Limits: There is a user rate limit of 50 requests per 15 minutes for both muting and unmuting operations.

    # Mute a user
    my_api.mute_user(user_id=my_api.auth_user_id, target_user_id="target user id")
    # Returns: {'data': {'muting': True}}
    
    # Unmute a user
    my_api.unmute_user(user_id=my_api.auth_user_id, target_user_id="target user id")
    # Returns: {'data': {'muting': False}}
  9. Instantiate the pytwitter Api

    master

    The main entry point for the library is the pytwitter.Api class. You can initialize it using one of three authentication methods:

    1. Bearer Token: For simple read-only or app-level access.
    2. OAuth 1.0A: For user-context actions (like following/unfollowing) using consumer and access credentials.
    3. OAuth 2.0 Flow: For modern OAuth 2.0 authentication using a client_id and a manual authorization flow.
    from pytwitter import Api
    
    # 1. Using Bearer Token
    api = Api(bearer_token="Your bearer token")
    
    # 2. Using OAuth 1.0A
    api = Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="access token",
        access_secret="access secret"
    )
    
    # 3. Using OAuth 2.0 Flow
    api = Api(client_id="You client ID", oauth_flow=True)
  10. Search for Spaces by title and status

    master

    Use the search_spaces method to discover live or upcoming Twitter Spaces. You can search using keywords, mentioned users, or hashtags found in the Space title.

    Results can be filtered using the state parameter to specify whether you want to find live or scheduled Spaces. If no state is provided, the request returns both by default.

    api.search_spaces(query="hello", state="live")
    # Response(data=[Space(id='1yoKMAybPkjKQ', state='live')])