### Install from source Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/installation.md Installs the python-twitter-v2 library from source using Poetry. ```shell $ git clone https://github.com/sns-sdks/python-twitter.git $ cd python-twitter $ make env $ poetry build ``` -------------------------------- ### Install from PyPI Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/installation.md Installs the python-twitter-v2 library using pip. ```shell $ pip install python-twitter-v2 ``` -------------------------------- ### Run tests Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/installation.md Executes the test suite for the library. ```shell make test ``` -------------------------------- ### Create virtual environment Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/installation.md Creates a virtual environment for the project. ```shell make env ``` -------------------------------- ### View test coverage Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/installation.md Displays test coverage information in the terminal. ```shell make cov-term ``` -------------------------------- ### Clone and install from source Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Checkout latest development version with git clone. ```shell $ git clone https://github.com/sns-sdks/python-twitter.git $ cd python-twitter $ make env ``` -------------------------------- ### Get User by ID or Username Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Examples of fetching user information using either their ID or username. ```python # By id >>> api.get_user(user_id="783214") Response(data=User(id='783214', name='Twitter', username='Twitter')) # By username >>> api.get_user(username="Twitter") Response(data=User(id='783214', name='Twitter', username='Twitter')) ``` -------------------------------- ### Get jobs info Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/compliance/batch_compliance.md Example of retrieving a list of compliance jobs for a given type. ```python api.get_compliance_jobs(job_type="users") # Response(data=[ComplianceJob(id='1430902035449143303', type='users', status='expired'), ComplianceJob(id='1430919027786797056', type='users', status='created')]) ``` -------------------------------- ### Get User Following Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of retrieving a list of users that a specific user is following, with a maximum number of results. ```python >>> api.get_following(user_id="2244994945", max_results=5) Response(data=[User(id='459860328', name='julie✨', username='JulieMendoza206'), User(id='273830767', name='🄿🅄🅂🄷', username='rahul_pushkarna')...]) ``` -------------------------------- ### Get User Followers Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of retrieving a list of users that are following a specific user, with a maximum number of results. ```python >>> api.get_followers(user_id="2244994945", max_results=5) Response(data=[User(id='715131097332518912', name='Daniel', username='RGIDaniel'), User(id='1176323137757048832', name='Joyce Wang', username='joycew67')...]) ``` -------------------------------- ### Sample Stream Tweets Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of using the sample_stream function to connect to the sample stream. ```python >>> stream_api.sample_stream() ``` -------------------------------- ### Initialize StreamApi Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Examples of initializing the StreamApi using either bearer token or consumer key and secret. ```python >>> from pytwitter import StreamApi >>> stream_api = StreamApi(bearer_token="bearer token") # or use consumer key and secret >>> stream_api = StreamApi(consumer_key="consumer key", consumer_secret="consumer secret") ``` -------------------------------- ### Get Current Stream Rules Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of retrieving the current rules configured for the filtered stream. ```python >>> stream_api.get_rules() Response(data=[StreamRule(id='1369580714056843266', value='twitter api ')]) ``` -------------------------------- ### Get Group of Tweets Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of retrieving information for multiple tweets by their IDs, with options for expansions and tweet/user fields. ```python >>> api.get_tweets(["1261326399320715264","1278347468690915330"],expansions="author_id",tweet_fields=["created_at"], user_fields=["username","verified"]) Response(data=[Tweet(id=1261326399320715264, text=Tune in to the @MongoDB @Twitch stream...), Tweet(id=1278347468690915330, text=Good news and bad news: 2020 is half over)]) ``` -------------------------------- ### Get lists for user followed Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-follows.md Returns all Lists a specified user follows. ```python api.get_user_followed_lists(user_id="User ID") # Response(data=[TwitterList(id='1403322685870940160', name='SNS-sdks'), TwitterList(id='1402926710174089222', name='🧑🏻\u200d💻 Geeks')]) ``` -------------------------------- ### Follow User Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of following a user using their user ID. ```python >>> api.follow_user(user_id="123456", target_user_id="654321") {'data': {'following': True, 'pending_follow': False}} ``` -------------------------------- ### Get Single Tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of retrieving information for a single tweet by its ID, with options for expansions and media fields. ```python >>> api.get_tweet("1354143047324299264", expansions=["attachments.media_keys"], media_fields=["type","duration_ms"]) Response(data=Tweet(id=1354143047324299264, text=Academics are one of the biggest groups using...)) ``` -------------------------------- ### Post a Tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/tweet-manage.md Example of how to post a simple text tweet using the Twitter API. ```python my_api.create_tweet(text="Hello world!") # Response(data=Tweet(id=1354143047324299264, text=Hello world!)) ``` -------------------------------- ### Get Quote Tweets Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/qutoe_tweets.md Example of how to get Quote Tweets for a given Tweet ID using the Python SDK. ```python api.get_tweet_quote_tweets(tweet_id="1409931481552543749", max_results=10) # Response(data=[Tweet(id=1503982413004914689, text=RT @suhemparack: Super excited to share our...), Tweet(id=1503982413004914689, text=RT @suhemparack: Super excited to share our...), Tweet(id=1495979553889697792, text=RT @chris_bail: Twitter has created an entire...), Tweet(id=1486385372401737728, text=RT @suhemparack: Super excited to share our...), Tweet(id=1480954678447857669, text=RT @suhemparack: Super excited to share our...), Tweet(id=1480639272721940486, text=RT @suhemparack: Super excited to share our...), Tweet(id=1471614967207976961, text=RT @chris_bail: Twitter has created an entire...), Tweet(id=1470423243513372679, text=RT @suhemparack: Super excited to share our...), Tweet(id=1469125403373568001, text=RT @suhemparack: Super excited to share our...), Tweet(id=1468633446935318529, text=RT @suhemparack: Super excited to share our...), Tweet(id=1438256410417143809, text=RT @suhemparack: Super excited to share our...)]) ``` -------------------------------- ### Get list's followers Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-follows.md Returns a list of users who are followers of the specified List. ```python api.get_list_followers(list_id="List ID") # Response(data=[User(id='1301152652357595137', name='realllkk520', username='realllkk520')]) ``` -------------------------------- ### Get group of users by usernames Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Get information about a group of users specified by their usernames. ```python # By username >>> api.get_users(usernames="Twitter,TwitterDev") Response(data=[User(id='2244994945', name='Twitter Dev', username='TwitterDev'), User(id='783214', name='Twitter', username='Twitter')]) ``` -------------------------------- ### Create a compliance job Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/compliance/batch_compliance.md Example of creating a new compliance job for user IDs. ```python api.create_compliance_job(job_type="users", name="test-job") # ComplianceJob(id='1430902035449143303', type='users', status='created') ``` -------------------------------- ### Search Users Example Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/search.md This code snippet demonstrates how to search for users using the `search_users` method with a query. ```python my_api.search_users(query="developers") # Response(data=[User(id='866707894389141505', name='Refinitiv Developers', username='Developers'), User(id='2244994945', name='Developers', username='XDevelopers')]) ``` -------------------------------- ### Search Stream Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of using the search_stream function to retrieve tweets that match the configured rules. ```python >>> stream_api.search_stream() ``` -------------------------------- ### Get Authorization URL Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/authorization.md Generates the URL for the user to authenticate with Twitter. ```python api.get_authorize_url() # https://api.x.com/oauth/authorize?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0 ``` -------------------------------- ### Get group of users by IDs Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Get information about a group of users specified by their IDs. ```python # By ids >>> api.get_users(ids=["783214", "2244994945"]) Response(data=[User(id='2244994945', name='Twitter Dev', username='TwitterDev'), User(id='783214', name='Twitter', username='Twitter')]) ``` -------------------------------- ### Get trends for a location Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/trends/trends.md Retrieves trends for a specified WOEID. ```python api.get_trends_by_woeid(woeid=1) # Response(data=[Trend(trend_name='#QuietOnSet', tweet_count=14060), Trend(trend_name='King Charles', tweet_count=42315), Trend(trend_name='Drake Bell', tweet_count=1234)]) ``` -------------------------------- ### Check the job status Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/compliance/batch_compliance.md Example of checking the status of a specific compliance job. ```python api.get_compliance_job("1430902035449143303") # Response(data=ComplianceJob(id='1430902035449143303', type='users', status='expired')) ``` -------------------------------- ### Unfollow User Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of unfollowing a user using their user ID. ```python >>> api.unfollow_user(user_id="123456", target_user_id="654321") {'data': {'following': False}} ``` -------------------------------- ### Get multiple users by one request Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/user-lookup.md Demonstrates how to retrieve data for multiple users by providing a list of their IDs or a comma-separated string of their usernames. ```python # Get by ids api.get_users(ids=["783214", "2244994945"]) # Response(data=[User(id='2244994945', name='Twitter Dev', username='TwitterDev'), User(id='783214', name='Twitter', username='Twitter')]) # Get by usernames api.get_users(usernames="Twitter,TwitterDev") # Response(data=[User(id='2244994945', name='Twitter Dev', username='TwitterDev'), User(id='783214', name='Twitter', username='Twitter')]) ``` -------------------------------- ### Get Tweet Usage Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/usage/tweets.md This code snippet demonstrates how to retrieve Tweet usage for a project within a specified number of days. ```python from pytwitter import Api api = Api(bearer_token='your bearer token') resp = api.get_usage_tweets(days=10, usage_fields=["daily_client_app_usage", "daily_project_usage"]) print(resp.data) # Usage(cap_reset_day=28, project_id='123456789', project_cap='50000000', project_usage='11910737',...) ``` -------------------------------- ### Manage Filtered Stream Rules Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/streaming.md Manages rules for the filtered stream API, demonstrating adding new rules with values and tags. Includes a dry_run example. ```python np = { "add": [ {"value": "cat has:media", "tag": "cats with media"}, {"value": "cat has:media -grumpy", "tag": "happy cats with media"} ] } stream_api.manage_rules(rules=np, dry_run=True) # Response(data=[StreamRule(id='1370406958721732610', value='cat has:media -grumpy'), StreamRule(id='1370406958721732609', value='cat has:media')]) ``` -------------------------------- ### Get lists for user joined Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-members.md Retrieves all Lists a specified user is a member of. ```python api.get_user_memberships_lists(user_id="User ID") # Response(data=[TwitterList(id='1402926710174089222', name='🧑🏻 1402926710174089222', name='SNS-sdks')] ``` -------------------------------- ### Get user pinned lists Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/pinned-lists.md Returns the Lists pinned by a specified user. ```python my_api.get_user_pinned_lists(user_id=my_api.auth_user_id) # Response(data=[TwitterList(id='1403322685870940160', name='SNS-sdks')]) ``` -------------------------------- ### Add New Stream Rules Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of adding new rules to the filtered stream, with an option for dry run validation. ```python >>> np = { "add": [ {"value": "cat has:media", "tag": "cats with media"}, {"value": "cat has:media -grumpy", "tag": "happy cats with media"} ] } >>> stream_api.manage_rules(rules=np, dry_run=True) Response(data=[StreamRule(id='1370406958721732610', value='cat has:media -grumpy'), StreamRule(id='1370406958721732609', value='cat has:media')]) ``` -------------------------------- ### Get one user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/user-lookup.md Shows how to fetch information for a single user by providing either their user ID or their username. ```python # By id api.get_user(user_id="783214") # Response(data=User(id='783214', name='Twitter', username='Twitter')) # By username api.get_user(username="Twitter") # Response(data=User(id='783214', name='Twitter', username='Twitter')) ``` -------------------------------- ### Delete Stream Rules Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Example of deleting existing rules from the filtered stream using their IDs. ```python >>> stream_api.manage_rules(rules={"delete": {"ids": ["1369580714056843266"]}}) Response(data=[]) ``` -------------------------------- ### Get spaces by multi creator IDs Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/spaces/spaces-lookup.md Retrieves Twitter Spaces created by multiple specified creator IDs. ```python api.get_spaces_by_creator(creator_ids=["2244994945", "6253282"]) # Response(data=[Space(id='1DXxyRYNejbKM', state='live'), Space(id='1nAJELYEEPvGL', state='live')]) ``` -------------------------------- ### Delete a Tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/tweet-manage.md Example of how to delete a specific tweet using its ID via the Twitter API. ```python my_api.delete_tweet(tweet_id="1354143047324299264") # {'data': {'deleted': True}} ``` -------------------------------- ### Get users a target user is following Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/follows.md Retrieves a list of users that a specified target user is following, with a maximum of 5 results. ```python api.get_following(user_id="2244994945", max_results=5) # Response(data=[User(id='459860328', name='julie✨', username='JulieMendoza206'), User(id='273830767', name='🄿🅄🅂🄷', username='rahul_pushkarna')...]) ``` -------------------------------- ### Get space buyers by space ID Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/spaces/spaces-lookup.md Retrieves a list of users who have purchased or are associated with a specific Twitter Space. ```python api.get_buyers_by_space(space_id="1DXxyRYNejbKM") # Response(data=[User(id='2244994945', name='Twitter Dev', username='TwitterDev'), User(id='783214', name='Twitter', username='Twitter')]) ``` -------------------------------- ### Get Authorization URL Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/authorization_oauth2.md Generates the OAuth 2.0 authorization URL, along with the code verifier and state for subsequent steps. ```python authorization_url, code_verifier, state = api.get_oauth2_authorize_url() #('https://x.com/i/oauth2/authorize?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Flocalhost%2F&scope=users.read+tweet.read&state=HVLpccax4G57jMJu1yddJtP55HYMQA&code_challenge=jntz4xjHJ0XHzWA7_Wa6rrA8zHwu4qPZt2MQsv6&code_challenge_method=S256', # '01wNLFIFeh310NpRLt837gcrvK1JqFrFvoYFU0DnH', # 'HVLpccax4G57jMJu1yddJtP55HYMQA') ``` -------------------------------- ### Get users following a target user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/follows.md Retrieves a list of users who are following a specified target user, with a maximum of 5 results. ```python api.get_followers(user_id="2244994945", max_results=5) # Response(data=[User(id='715131097332518912', name='Daniel', username='RGIDaniel'), User(id='1176323137757048832', name='Joyce Wang', username='joycew67')...]) ``` -------------------------------- ### Get space by space ID Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/spaces/spaces-lookup.md Retrieves a specific Twitter Space using its unique ID. ```python api.get_space(space_id="1DXxyRYNejbKM") # Response(data=[Space(id='1DXxyRYNejbKM', state='live')]) ``` -------------------------------- ### Get user muting Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/mutes.md Retrieves a list of users that the authenticated user is muting. ```python my_api.get_user_muting(my_api.auth_user_id) # Response(data=[User(id='id', name='xxx', username='xxx')]) ``` -------------------------------- ### Get blocked users Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/blocks.md This code snippet demonstrates how to retrieve a list of users blocked by the authenticated user. ```python my_api.get_blocking_users(my_api.auth_user_id) # Response(data=[User(id='1065249714214457345', name='Spaces', username='TwitterSpaces'), User(id='783214', name='Twitter', username='Twitter')]) ``` -------------------------------- ### Get list's members Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-members.md Retrieves a list of users who are members of a specified List. ```python api.get_list_members(list_id="List ID") # Response(data=[User(id='1301152652357595137', name='realllkk520', username='realllkk520')]) ``` -------------------------------- ### Get spaces by multi spaces IDs Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/spaces/spaces-lookup.md Retrieves multiple Twitter Spaces using a list of their unique IDs. ```python api.get_spaces(space_ids=["1DXxyRYNejbKM", "1nAJELYEEPvGL"]) # Response(data=[Space(id='1DXxyRYNejbKM', state='live'), Space(id='1nAJELYEEPvGL', state='live')]) ``` -------------------------------- ### Get space tweets by space ID Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/spaces/spaces-lookup.md Retrieves tweets associated with a specific Twitter Space. ```python api.get_tweets_by_space(space_id="1DXxyRYNejbKM") # Response(data=[Tweet(id=1389270063807598594, text=now, everyone with 600 or more followers can...), Tweet(id=1354143047324299264, text=Academics are one of the biggest groups using...), Tweet(id=1293595870563381249, text=Twitter API v2: Early Access releasednnToday we...)]) ``` -------------------------------- ### Get tweets liked by the authenticated user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/likes.md This code snippet demonstrates how to fetch tweets that have been liked by the authenticated user. ```python api.get_user_liked_tweets(user_id=my_api.auth_user_id) ``` -------------------------------- ### Get users who are liking the tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/likes.md This code snippet shows how to retrieve a list of users who have liked a specific tweet. ```python api.get_tweet_liking_users(tweet_id="1395803619614679041") ``` -------------------------------- ### Get all messages across a user's DM conversations (both sent and received, group and 1-1 conversations) Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/direct-messages/direct-messages-lookup.md Returns a list of Direct Messages for the authenticated user, both sent and received. Direct Message events are returned in reverse chronological order. Supports retrieving events from the previous 30 days. ```python my_api.get_dm_events(max_results=2) # Response(data=[DirectMessageEvent(id='1593226454237487108', event_type='MessageCreate', text='from api to III'), DirectMessageEvent(id='1593226322066567177', event_type='MessageCreate', text='from api to III')]) ``` -------------------------------- ### Get all messages in a 1-1 conversation Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/direct-messages/direct-messages-lookup.md Returns a list of Direct Messages (DM) events within a 1-1 conversation with the user specified in the participant_id path parameter. Messages are returned in reverse chronological order. ```python my_api.get_dm_events_by_participant("1334059193268011010", max_results=1) # Response(data=[DirectMessageEvent(id='1593226322066567177', event_type='MessageCreate', text='from api to III')]) ``` -------------------------------- ### Get all messages in a specific conversation (both group and 1-1 conversations) Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/direct-messages/direct-messages-lookup.md Returns a list of Direct Messages within a conversation specified in the dm_conversation_id path parameter. Messages are returned in reverse chronological order. ```python my_api.get_dm_events_by_conversation("1593091374437781506", max_results=1) # Response(data=[DirectMessageEvent(id='1593091374437781510', event_type='MessageCreate', text='New group by api')]) ``` -------------------------------- ### Get single tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/tweet-lookup.md Retrieves information about a single tweet using its ID. Optional parameters can be used to expand related data like media and specify media fields. ```python api.get_tweet("1354143047324299264", expansions=["attachments.media_keys"], media_fields=["type","duration_ms"]) # Response(data=Tweet(id=1354143047324299264, text=Academics are one of the biggest groups using...)) ``` -------------------------------- ### Get multi tweets by one request Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/tweet-lookup.md Retrieves information about multiple tweets in a single request using a list of Tweet IDs. Optional parameters can expand related data like author ID and specify tweet and user fields. ```python api.get_tweets(["1261326399320715264","1278347468690915330"],expansions="author_id",tweet_fields=["created_at"], user_fields=["username","verified"]) # Response(data=[Tweet(id=1261326399320715264, text=Tune in to the @MongoDB @Twitch stream...), Tweet(id=1278347468690915330, text=Good news and bad news: 2020 is half over)]) ``` -------------------------------- ### Step 1: Initialize the upload Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/media-upload-v2/chunked-upload.md Initializes the media upload process by sending the total file size, media type, and media category to the API. ```python import os filename = "/path/to/video.mp4" init_resp = myapi.upload_media_chunked_init_v2( total_bytes=os.path.getsize(filename), media_type="video/mp4", media_category="tweet_video", ) print(init_resp) # Response(data=MediaUpload(id='1912334964932374529', media_key='7_1912334964932374529', processing_info=None, image=None, video=None)) ``` -------------------------------- ### Initial API Instance Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/authorization.md Initializes the API instance with consumer key and secret, enabling the OAuth flow. ```python from pytwitter import Api api = Api(consumer_key='your consumer key', consumer_secret='your consumer secret', oauth_flow=True) ``` -------------------------------- ### Instantiate with OAuth 1.0A user context token Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Initialize the Api with OAuth 1.0A user context token. ```python >>> api = Api( consumer_key="consumer key", consumer_secret="consumer secret", access_token="access token", access_secret="access secret" ) ``` -------------------------------- ### Step 2: Append the file by chunks Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/media-upload-v2/chunked-upload.md Uploads the media file in chunks, using the media ID obtained from the initialization step and a specified segment index for each chunk. ```python media_id = init_resp.data.id chunk_size = 2 * 1024 * 1024 segment_index = 0 with open(filename, "rb") as f: while True: chunk = f.read(chunk_size) if not chunk: break chunk_resp = myapi.upload_media_chunked_append_v2( media_id=media_id, media=chunk, segment_index=segment_index, ) print(chunk_resp) segment_index += 1 # True ``` -------------------------------- ### Instantiate with authorization done by user (OAuth 1.0A) Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Initialize the Api with OAuth 1.0A and initiate user authorization flow. ```python >>> api = Api(consumer_key="consumer key",consumer_secret="consumer secret",oauth_flow=True) # get url for user to authorize >>> api.get_authorize_url() # copy the response url >>> api.generate_access_token("https://localhost/?oauth_token=oauth_token&oauth_verifier=oauth_verifier") {'oauth_token': 'oauth_token', 'oauth_token_secret': 'oauth_token_secret', 'user_id': '123456', 'screen_name': 'screen name'} ``` -------------------------------- ### Run tests Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Run tests with make test. ```shell $ make test ``` -------------------------------- ### Step 5: Create tweet with media Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/media-upload-v2/chunked-upload.md Creates a tweet that includes the uploaded media, using the media ID. ```python tweet_resp = myapi.create_tweet(text="My first tweet with a video", media_media_ids=[media_id]) # Tweet(id=1912338879258194343, text=My first tweet with a video...) ``` -------------------------------- ### Instantiate with OAuth 2.0 client ID Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Initialize the Api with OAuth 2.0 client ID and initiate user authorization flow. ```python >>> api = Api(client_id="You client ID", oauth_flow=True) # get the url and code verifier for user to authorize >>> url, code_verifier, _ = api.get_oauth2_authorize_url() # copy the response url >>> api.generate_oauth2_access_token("https://localhost/?state=state&code=code", code_verifier) {'token_type': 'bearer', 'expires_in': 7200, 'access_token': 'access_token', 'scope': 'users.read tweet.read', 'expires_at': 1631775928} ``` -------------------------------- ### Follow a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-follows.md Allows an authenticated user to follow a specified List. ```python my_api.follow_list(user_id=my_api.auth_user_id, list_id="1448302476780871685") # {'data': {'following': True}} ``` -------------------------------- ### Step 3: Finalize the upload Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/media-upload-v2/chunked-upload.md Completes the media upload process by sending the media ID to the API. ```python finalize_resp = myapi.upload_media_chunked_finalize_v2(media_id=media_id) print(finalize_resp) # Response(data=MediaUpload(id='1912090619981471744', media_key='7_1912090619981471744', processing_info=MediaUploadResponseProcessingInfo(state='succeeded', check_after_secs=None, progress_percent=None, error=None), image=None, video=None)) ``` -------------------------------- ### Instantiate with bearer token Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst You can initialize the Api with a bearer token. ```python >>> from pytwitter import Api >>> api = Api(bearer_token="Your bearer token") ``` -------------------------------- ### Initialize StreamApi Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/streaming.md Initializes the StreamApi with either a bearer token or consumer key and secret. ```python from pytwitter import StreamApi stream_api = StreamApi(bearer_token="bearer token") # or use consumer key and secret # stream_api = StreamApi(consumer_key="consumer key", consumer_secret="consumer secret") ``` -------------------------------- ### Initial API with Client ID and Client Secret Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/authorization_oauth2.md Initializes the Api instance for a Confidential client, requiring both Client ID and Client Secret. ```python from pytwitter import Api api = Api(client_id='your client id', client_secret="your client secret", oauth_flow=True) ``` -------------------------------- ### Simple Media Upload Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/media-upload-v2/simple-upload.md Upload a simple media file (image or GIF) using the `upload_media_simple_v2` method. ```python with open("path/to/image", "rb") as media: resp = my_api.upload_media_simple_v2(media=media) print(resp) ``` -------------------------------- ### Run tests with coverage Source: https://github.com/sns-sdks/python-twitter/blob/master/README.rst Run tests with coverage using make cov-term or make cov-html. ```shell $ make cov-term $ make cov-html ``` -------------------------------- ### Step 4 (Optional): Check the processing status Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/media-upload-v2/chunked-upload.md Checks the processing status of the uploaded media using the media ID. ```python status_resp = myapi.upload_media_chunked_status_v2(media_id=media_id) print(status_resp) # Response(data=MediaUpload(id='1912090619981471744', media_key='7_1912090619981471744', processing_info=MediaUploadResponseProcessingInfo(state='succeeded', check_after_secs=None, progress_percent=100, error=None), image=None, video=None)) ``` -------------------------------- ### Initial API with Client ID Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/authorization_oauth2.md Initializes the Api instance with a Client ID for OAuth 2.0 flow. ```python from pytwitter import Api api = Api(client_id='your client id', oauth_flow=True) ``` -------------------------------- ### Generate Access Token Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/authorization.md Generates the user access token after the callback URL receives the response. ```python api.generate_access_token(response="You response url") # {'oauth_token': 'oauth-token','oauth_token_secret': 'oauth-token-secret', 'user_id': 'user id', 'screen_name': 'screen name'} ``` -------------------------------- ### Search spaces Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/spaces/search.md This code snippet demonstrates how to search for live Twitter Spaces using a query. ```python api.search_spaces(query="hello", state="live") # Response(data=[Space(id='1yoKMAybPkjKQ', state='live')]) ``` -------------------------------- ### Retweet a tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/retweet.md This code snippet demonstrates how to retweet a specific tweet using the Python SDK. ```python my_api.retweet_tweet(user_id=my_api.auth_user_id, tweet_id="target tweet id") # {'data': {'retweeted': True}} ``` -------------------------------- ### Create a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/manage-lists.md Enables the authenticated user to create a List. ```python my_api.create_list(name="pytwitter") # TwitterList(id='1451603640167194629', name='pytwitter') ``` -------------------------------- ### Generate Access Token Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/authorization_oauth2.md Generates the user access token using the redirect response from the callback URL and the previously saved code verifier. ```python api.generate_oauth2_access_token(response="response", code_verifier="code_verifier") # {'token_type':'bearer','expires_in':7200,'access_token':'access_token','scope':'users.read tweet.read','expires_at':1632852223} ``` -------------------------------- ### Like a tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/likes.md This code snippet demonstrates how to like a tweet using the `like_tweet` method. ```python my_api.like_tweet(user_id=my_api.auth_user_id, tweet_id="target tweet id") # {'data': {'liked': True}} ``` -------------------------------- ### Create a group conversation and add a DM to it Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/direct-messages/manage-direct-messages.md Creates a Direct Message on behalf of an authenticated user, and adds it to the specified conversation. ```python my_api.create_message_to_conversation("1593091374437781506", text="message by api") # DirectMessageCreateResponse(dm_conversation_id='1301152652357595137-1334059193268011010', dm_event_id='1593234034146279428') ``` -------------------------------- ### Unblock a user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/blocks.md This code snippet demonstrates how to unblock a user using the Python Twitter SDK. ```python my_api.unblock_user(user_id=my_api.auth_user_id, target_user_id="target user id") # {'data': {'blocking': False}} ``` -------------------------------- ### Adding a DM to an existing conversation (for both group and 1-1) Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/direct-messages/manage-direct-messages.md Creates a new group conversation and adds a Direct Message to it on behalf of an authenticated user. ```python my_api.create_conversation( conversation_type="group", message={"text": "hello"}, participant_ids=["1334059193268011010", "906948460078698496"] ) # DirectMessageCreateResponse(dm_conversation_id='1301152652357595137-1334059193268011010', dm_event_id='1593234034146279428') ``` -------------------------------- ### Create a message in a 1-1 conversation with the participant Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/direct-messages/manage-direct-messages.md Creates a one-to-one Direct Message and adds it to the one-to-one conversation. This method either creates a new one-to-one conversation or retrieves the current conversation and adds the Direct Message to it. ```python my_api.create_message_to_participant("1334059193268011010", text="dm by api") # DirectMessageCreateResponse(dm_conversation_id='1301152652357595137-1334059193268011010', dm_event_id='1593234034146279428') ``` -------------------------------- ### Follow a user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/follows.md Initiates a follow action for the authenticated user towards a specified target user. Requires user access token. ```python my_api.follow_user(user_id=my_api.auth_user_id, target_user_id="target user id") # {'data': {'following': True, 'pending_follow': False}} ``` -------------------------------- ### Block a user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/blocks.md This code snippet demonstrates how to block a user using the Python Twitter SDK. ```python my_api.block_user(user_id=my_api.auth_user_id, target_user_id="target user id") # {'data': {'blocking': True}} ``` -------------------------------- ### Unfollow a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-follows.md Allows an authenticated user to unfollow a specified List. ```python my_api.unfollow_list(user_id=my_api.auth_user_id, list_id="1448302476780871685") # {'data': {'following': False}} ``` -------------------------------- ### Lookup Tweets from a specified List Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-tweets-lookup.md This Python code snippet demonstrates how to retrieve Tweets from a specified List using the `python-twitter` library. It shows the function call and a sample response structure. ```python api.get_list_tweets("1403322685870940160") # Response(data=[Tweet(id=1458088293904654340, text=Simple tweet from python-twitter-v2....), Tweet(id=1301154770489499650, text=Hey this is new begin.)]) ``` -------------------------------- ### un-hide reply Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/hide_reply.md This code snippet shows how to unhide a reply to a tweet. ```python my_api.hidden_reply(tweet_id="tweet id", hidden=False) # {"data":{"hidden":false}} ``` -------------------------------- ### hide reply Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/hide_reply.md This code snippet shows how to hide a reply to a tweet. ```python my_api.hidden_reply(tweet_id="tweet id") # {"data":{"hidden":true}} ``` -------------------------------- ### User mention timeline Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/timelines.md Requests Tweets mentioning a specific Twitter user. ```python api.get_mentions(user_id="2244994945") # Response(data=[Tweet(id=1364407587207213056, text=@scottmathson @TwitterDev What would you want...), Tweet(id=1364398068313903104, text=@Twitter should consider supporting...), Tweet(id=1364377794327633925, text=@sugan2424 @TwitterDev @threadreaderapp You...), Tweet(id=1364377404156772352, text=@TwitterDev What kind of tweet / attachment is...), Tweet(id=1364373969852366849, text=• Thirdly, that @Twitter, @Twittersafety,...), Tweet(id=1364367885582352386, text=@Twitter @TwitterSafety @TwitterDev @jack...), Tweet(id=1364366114998870016, text=@Twitter /...), Tweet(id=1364364744916951040, text=@Casanovacane @jack @TwitterDev can we get a...), Tweet(id=1364359199795240961, text=@TwitterDev @suhemparack A Blue app going to...), Tweet(id=1364338409494503425, text=@FairyMaitre @TwitterDev tkt)]) ``` -------------------------------- ### Pin a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/pinned-lists.md Enables the authenticated user to pin a List. ```python my_api.pin_list(user_id=my_api.auth_user_id, list_id="ID for list to pin") # {'data': {'pinned': True}} ``` -------------------------------- ### Filtered Stream Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/streaming.md Connects to the filtered stream endpoint after rules have been managed. ```python stream_api.search_stream() ``` -------------------------------- ### Reverse chronological home timeline Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/timelines.md Retrieves the most recent Tweets, Retweets, and replies posted by the authenticated user and the accounts they follow. ```python my_api.get_timelines_reverse_chronological(user_id="2244994945") # Response(data=[Tweet(id=1524796546306478083, text=Today marks the launch of Devs in the Details...), Tweet(id=1524468552404668416, text=📢 Join @jessicagarson @alanbenlee and @i_am_daniele tomorrow...)) ``` -------------------------------- ### Unlike a tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/likes.md This code snippet demonstrates how to unlike a tweet using the `unlike_tweet` method. ```python my_api.unlike_tweet(user_id=my_api.auth_user_id, tweet_id="target tweet id") # {'data': {'liked': False}} ``` -------------------------------- ### User Tweet timeline Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/timelines.md Retrieves Tweets published by a specific Twitter account. ```python api.get_timelines(user_id="2244994945") # Response(data=[Tweet(id=1364275610764201984, text=If you're newly approved for the Academic...), Tweet(id=1362876655061073928, text=From our living rooms to yours 🐱‍💻🛋️Our...), Tweet(id=1362439338978467841, text=“To quote my creator Jerome Gangneux, I always...), Tweet(id=1362439338169016324, text=“In the 20th century, managers managed humans,...), Tweet(id=1362439336910675970, text=Meet one of the useful Twitter bots out there:...), Tweet(id=1359912509940011010, text=Valentine’s Day is approaching! 💙 Over the...), Tweet(id=1359554366051504129, text=Go ahead, follow another puppy account. We...), Tweet(id=1357371424487268354, text=Learn how academics can get historical Tweets...), Tweet(id=1356991771553583106, text=Who knew an API could be delicious?...), Tweet(id=1354215875998437376, text=RT @TwitterOSS: Today we’re happy to share...)]) ``` -------------------------------- ### Update a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/manage-lists.md Enables the authenticated user to update the meta data of a specified List that they own. ```python my_api.update_list(list_id="1448302476780871685", name="lists for tw") # {'updated': True} ``` -------------------------------- ### Lookup a user's owned Lists Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-lookup.md Retrieves all Lists owned by the specified user. ```python api.get_user_owned_lists(user_id="User ID") # Response(data=[TwitterList(id='1403322685870940160', name='SNS-sdks')]) ``` -------------------------------- ### Search by recent tweets Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/search_tweets.md This code snippet demonstrates how to search for recent tweets using the `search_tweets` method with a query. ```python api.search_tweets(query="python") # Response(data=[Tweet(id=1364512148865564675, text=RT @jesss_codes: Your resume: Git SSL Vue CSS...), Tweet(id=1364512106385702914, text=RT @theweeflea: Sturgeon goes on TV to declare...), Tweet(id=1364512102606467074, text=RT @tkEzaki:...), Tweet(id=1364512092343070721, text=RT @ore57436902: #Python #pyxel #ドルアーガの塔...), Tweet(id=1364512076601856007, text=RT @shosen_bt_pc:...), Tweet(id=1364512071866605568, text=RT @CatherineAdenle: 6 ways learning coding can...), Tweet(id=1364512071614889987, text=RT @giswqs: #geemap v0.8.11 has been released....), Tweet(id=1364512066770509824, text=RT @Akpanannang: Today when coming out from the...), Tweet(id=1364512053252284419, text=RT @HarbRimah: New Off-the-Shelf (OTS) Datasets...), Tweet(id=1364512030800171011, text=RT @gzadkowski: Day 5 - #100DaysOfCode...)]) ``` -------------------------------- ### Sampled Stream Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/streaming.md Connects to the sampled stream endpoint to receive a random sample of public Tweets. ```python stream_api.sample_stream() ``` -------------------------------- ### Unpin a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/pinned-lists.md Enables the authenticated user to unpin a List. ```python my_api.unpin_list(user_id=my_api.auth_user_id, list_id="ID for list to unpin") # {'data': {'pinned': False}} ``` -------------------------------- ### Tweet retweeted tweets Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/retweet.md This code snippet demonstrates how to retrieve a list of tweets that have been retweeted. ```python api.get_tweet_retweeted_tweets(tweet_id="target tweet id") # Response(data=[Tweet(id=1724975633908789418, text=RT @XDevelopers: You can now monitor your usage...), Tweet(id=1724805194280730931, text=RT @XDevelopers: You can now monitor your usage...)]) ``` -------------------------------- ### Lookup a specific list by ID Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-lookup.md Retrieves the details of a specified List by its ID. ```python api.get_list(list_id="1403322685870940160") # Response(data=TwitterList(id='1403322685870940160', name='SNS-sdks')) ``` -------------------------------- ### Add member to a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/list-members.md Enables the authenticated user to add a member to a List they own. ```python my_api.add_list_member(list_id="1448302476780871685", user_id="ID for user added to the list") # {'data': {'is_member': True}} ``` -------------------------------- ### Search by full-archive tweets Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/search_tweets.md This code snippet shows how to search for full-archive tweets using the `search_tweets` method with the `query_type` parameter set to 'all'. This feature is only available for the Academic Research product track. ```python api.search_tweets(query="python", query_type="all") # Response(data=[Tweet(id=1364512148865564675, text=RT @jesss_codes: Your resume: Git SSL Vue CSS...), Tweet(id=1364512106385702914, text=RT @theweeflea: Sturgeon goes on TV to declare...), Tweet(id=1364512102606467074, text=RT @tkEzaki:...), Tweet(id=1364512092343070721, text=RT @ore57436902: #Python #pyxel #ドルアーガの塔...), Tweet(id=1364512076601856007, text=RT @shosen_bt_pc:...), Tweet(id=1364512071866605568, text=RT @CatherineAdenle: 6 ways learning coding can...), Tweet(id=1364512071614889987, text=RT @giswqs: #geemap v0.8.11 has been released....), Tweet(id=1364512066770509824, text=RT @Akpanannang: Today when coming out from the...), Tweet(id=1364512053252284419, text=RT @HarbRimah: New Off-the-Shelf (OTS) Datasets...), Tweet(id=1364512030800171011, text=RT @gzadkowski: Day 5 - #100DaysOfCode...)]) ``` -------------------------------- ### Delete a list Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/lists/manage-lists.md Enables the authenticated user to delete a List that they own. ```python my_api.delete_list(list_id="1448302476780871685") # {'data': {'deleted': True}} ``` -------------------------------- ### Bookmarks Lookup Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/bookmarks.md Retrieves information about an authenticated user's 800 most recent bookmarked Tweets. ```python my_api.get_bookmark_tweets(user_id="1301152652357595137") # Response(data=[Tweet(id=1511645952418885636, text=https://t.co/Hl9Sa0uP9W)]) ``` -------------------------------- ### Bookmark Tweet Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/bookmarks.md Causes the user ID of an authenticated user to bookmark the target Tweet. ```python my_api.bookmark_tweet(user_id="1301152652357595137", tweet_id="1511645952418885636") # {'data': {'bookmarked': True}} ``` -------------------------------- ### Tweet retweeted users Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/retweet.md This code snippet shows how to retrieve a list of users who have retweeted a specific tweet. ```python api.get_tweet_retweeted_users(tweet_id="target tweet id") # Response(data=[User(id='1301152652357595137', name='realllkk520', username='realllkk520')]) ``` -------------------------------- ### Mute a user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/mutes.md Mutes a specified user account. ```python my_api.mute_user(user_id=my_api.auth_user_id, target_user_id="target user id") # {'data': {'muting': True}} ``` -------------------------------- ### Unmute a user Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/users/mutes.md Unmutes a specified user account. ```python my_api.unmute_user(user_id=my_api.auth_user_id, target_user_id="target user id") # {'data': {'muting': False}} ``` -------------------------------- ### Full-archive Tweet counts Source: https://github.com/sns-sdks/python-twitter/blob/master/docs/docs/usage/tweets/tweets_counts.md Retrieves the numerical count of Tweets for a query from the entire archive of public Tweets. Currently, this endpoint is only available in the Academic Research product track and uses the OAuth 2.0 Bearer Token for authentication. ```python api.get_tweets_counts(query="lakers", search_type="all") # Response(data=[TweetCount(start='2021-06-18T09:09:23.000Z', end='2021-06-18T10:00:00.000Z', tweet_count=15), TweetCount(start='2021-06-18T10:00:00.000Z', end='2021-06-18T11:00:00.000Z', tweet_count=36)...]) ```