### Install Twython from source Source: https://twython.readthedocs.io/en/latest/usage/install.html Install Twython into your site-packages directory using the setup script. ```bash $ python setup.py install ``` -------------------------------- ### Install Twython with easy_install Source: https://twython.readthedocs.io/en/latest/usage/install.html Use easy_install to install Twython from PyPI. ```bash $ easy_install twython ``` -------------------------------- ### Install Twython with pip Source: https://twython.readthedocs.io/en/latest/usage/install.html Use pip to install Twython from PyPI. ```bash $ pip install twython ``` -------------------------------- ### Extract OAuth Verifier (Django example) Source: https://twython.readthedocs.io/en/latest/usage/starting_out.html In a Django view, extract the oauth_verifier from the request GET parameters after the user is redirected back. ```python oauth_verifier = request.GET['oauth_verifier'] ``` -------------------------------- ### Construct Twitter API URL with Twython Source: https://twython.readthedocs.io/en/latest/api.html Shows how to use the static construct_api_url method to build a Twitter API URL with query parameters. The example creates a Twython instance without authentication, constructs a search tweets URL with q and result_type parameters, and prints the resulting URL. ```python >>> from twython import Twython >>> twitter = Twython() >>> api_url = 'https://api.twitter.com/1.1/search/tweets.json' >>> constructed_url = twitter.construct_api_url(api_url, q='python', result_type='popular') >>> print constructed_url https://api.twitter.com/1.1/search/tweets.json?q=python&result_type=popular ``` -------------------------------- ### Cursor with return_pages=True Source: https://twython.readthedocs.io/en/latest/usage/special_functions.html Shows how to use the return_pages=True keyword argument to get entire pages of results instead of individual items. The page is a list, so nested loops are needed to access each result. ```python results = twitter.cursor(twitter.get_mentions_timeline, return_pages=True) # page is a list for page in results: for result in page: print(result['id_str']) ``` -------------------------------- ### get(endpoint, params=None, version='1.1') Source: https://twython.readthedocs.io/en/latest/api.html Shortcut for GET requests via the request method. This method allows making arbitrary GET requests to the Twitter API. ```APIDOC ## get(endpoint, params=None, version='1.1') ### Description Shortcut for GET requests via `request`. ### Method GET ### Endpoint `endpoint` (as provided) ### Parameters #### Path Parameters - **endpoint** (string) - Required - The API endpoint to call (e.g., 'statuses/user_timeline'). #### Query Parameters - **params** (dict) - Optional - Query parameters to include in the request. - **version** (string) - Optional - API version to use (default '1.1'). ### Request Example ```python twython.get('statuses/user_timeline', {'screen_name': 'twitter'}) ``` ### Response Returns the API response as parsed JSON. ### Docs Refer to the `request` method documentation. ``` -------------------------------- ### OAuth 1: Obtain Authorization URL Source: https://twython.readthedocs.io/en/latest/usage/starting_out.html Create a Twython instance with your app credentials and get authentication tokens. Pass callback_url only for web applications; desktop/mobile apps do not require it. ```python APP_KEY = 'YOUR_APP_KEY' APP_SECRET = 'YOUR_APP_SECRET' twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens(callback_url='http://mysite.com/callback') ``` -------------------------------- ### Combine headers, proxies, and timeout with Twython client_args Source: https://twython.readthedocs.io/en/latest/usage/advanced_usage.html Pass both 'headers' and 'proxies' dictionaries along with a 'timeout' value inside client_args to customize the request fully. Note: the source example has a missing comma after the proxies dictionary, which would cause a syntax error. ```python from twython import Twython client_args = { 'headers': { 'User-Agent': 'My App Name' }, 'proxies': { 'http': 'http://10.0.10.1:8000', 'https': 'https://10.0.10.1:8001', } 'timeout': 300, } twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, client_args=client_args) ``` -------------------------------- ### OAuth 1: Get Final User Tokens Source: https://twython.readthedocs.io/en/latest/usage/starting_out.html Create a new Twython instance with the temporary tokens and exchange the verifier for the final user tokens. ```python twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(oauth_verifier) ``` -------------------------------- ### get() - twython.Twython Source: https://twython.readthedocs.io/en/latest/genindex.html Performs a generic GET request to the Twitter API. This method is part of the Twython class and allows making custom GET requests. ```APIDOC ## get() ### Description Performs a generic GET request to the Twitter API. This method is part of the Twython class and allows making custom GET requests. ### Method get() ### Endpoint Generic GET endpoint (not specified in source) ### Parameters No parameters documented in source. ### Request Example No request example provided in source. ### Response No response details provided in source. ``` -------------------------------- ### Cursor with get_mentions_timeline Source: https://twython.readthedocs.io/en/latest/usage/special_functions.html Another example of using the Cursor function with twitter.get_mentions_timeline, yielding individual results. ```python results = twitter.cursor(twitter.get_mentions_timeline) for result in results: print(result['id_str']) ``` -------------------------------- ### twitter.cursor(twitter.search, q='twitter') Source: https://twython.readthedocs.io/en/latest/usage/special_functions.html Returns a generator for paginated Twitter API endpoints. This example demonstrates using cursor with the search endpoint to iterate over individual results. ```APIDOC ## Cursor ### Description Returns a generator for Twitter API endpoints that are able to be paginated in some way (either by cursor or since_id parameter). ### Method cursor ### Endpoint N/A - Twython SDK method ### Parameters - **function** (callable) - Required - The Twitter API method to paginate. - **return_pages** (boolean) - Optional - If True, yields entire pages of results instead of individual items. - **kwargs** - Additional keyword arguments passed to the API method. ### Request Example ```python from twython import Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) results = twitter.cursor(twitter.search, q='twitter') for result in results: print(result['id_str']) ``` ### Response #### Success Response Yields individual result items (or pages if return_pages=True). #### Response Example ```python # Individual items for result in results: print(result['id_str']) # Pages results = twitter.cursor(twitter.get_mentions_timeline, return_pages=True) for page in results: for result in page: print(result['id_str']) ``` ``` -------------------------------- ### Filter public statuses with statuses.filter Source: https://twython.readthedocs.io/en/latest/usage/streaming_api.html Instantiate MyStreamer with OAuth credentials and call statuses.filter to stream tweets matching the track keyword 'twitter'. This starts the streaming connection. ```python stream = MyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) stream.statuses.filter(track='twitter') ``` -------------------------------- ### Get Authorization URL Source: https://twython.readthedocs.io/en/latest/usage/starting_out.html Access the authorization URL from the auth dictionary to redirect the user for authentication. ```python auth['auth_url'] ``` -------------------------------- ### Get authenticated user's home timeline with get_home_timeline() Source: https://twython.readthedocs.io/en/latest/usage/basic_usage.html Calls the Twitter API endpoint get/statuses/home_timeline to fetch the home timeline for the authenticated user. ```python twitter.get_home_timeline() ``` -------------------------------- ### Get authenticated user's information with verify_credentials() Source: https://twython.readthedocs.io/en/latest/usage/basic_usage.html Calls the Twitter API endpoint get/account/verify_credentials to retrieve the authenticated user's profile information. ```python twitter.verify_credentials() ``` -------------------------------- ### get_application_rate_limit_status(**params) Source: https://twython.readthedocs.io/en/latest/api.html Returns the current rate limits for methods belonging to the specified resource families. This method wraps the Twitter API endpoint GET application/rate_limit_status. ```APIDOC ## get_application_rate_limit_status(**params) ### Description Returns the current rate limits for methods belonging to the specified resource families. ### Method GET ### Endpoint application/rate_limit_status ### Parameters #### Keyword Arguments - **params** (dict) - Optional - Parameters to pass to the Twitter API endpoint, such as `resources`. ### Request Example ```python twython.get_application_rate_limit_status(resources='statuses') ``` ### Response Returns the rate limit status object. ### Docs Refer to the Twitter API documentation for application/rate_limit_status. ``` -------------------------------- ### verify_credentials(**params) Source: https://twython.readthedocs.io/en/latest/api.html Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. This method corresponds to the Twitter API endpoint GET account/verify_credentials. ```APIDOC ## verify_credentials(**params) ### Description Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. ### Method GET ### Endpoint account/verify_credentials ### Parameters #### Keyword Arguments - **params** (dict) - Required - Parameters to pass to the Twitter API endpoint, such as include_entities. ### Request Example ```python twython.verify_credentials() ``` ### Response #### Success Response (200) Returns the authenticated user's profile object. #### Response Example ```json { "id_str": "1234567890", "screen_name": "example_user" } ``` #### Error Response (401) Returns an error message if authentication fails. ``` -------------------------------- ### get_account_settings(**params) Source: https://twython.readthedocs.io/en/latest/api.html Returns settings (including current trend, geo and sleep time information) for the authenticating user. This method wraps the Twitter API endpoint GET account/settings. ```APIDOC ## get_account_settings(**params) ### Description Returns settings (including current trend, geo and sleep time information) for the authenticating user. ### Method GET ### Endpoint account/settings ### Parameters #### Keyword Arguments - **params** (dict) - Optional - Parameters to pass to the Twitter API endpoint. ### Request Example ```python twython.get_account_settings() ``` ### Response Returns the user's account settings object. ### Docs [https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-settings](https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-settings) ``` -------------------------------- ### Twython.__init__ Source: https://twython.readthedocs.io/en/latest/api.html Instantiates an instance of Twython with optional authentication parameters. ```APIDOC ## Twython.__init__ ### Description Instantiates an instance of Twython. Takes optional parameters for authentication and such. ### Method Constructor ### Parameters - **app_key** (string) - Optional - Your applications key - **app_secret** (string) - Optional - Your applications secret key - **oauth_token** (string) - Optional - When using OAuth 1, combined with oauth_token_secret to make authenticated calls - **oauth_token_secret** (string) - Optional - When using OAuth 1, combined with oauth_token to make authenticated calls - **access_token** (string) - Optional - When using OAuth 2, provide a valid access token if you have one - **token_type** (string) - Optional - When using OAuth 2, provide your token type. Default: bearer - **oauth_version** (number) - Optional - Choose which OAuth version to use. Default: 1 - **api_version** (string) - Optional - Choose which Twitter API version to use. Default: 1.1 - **client_args** (object) - Optional - Accepts some requests Session parameters and some requests Request parameters. See http://docs.python-requests.org/en/latest/api/#sessionapi and requests section below it for details. [ex. headers, proxies, verify(SSL verification)] - **auth_endpoint** (string) - Optional - Lets you select which authentication endpoint will use your application. This will allow the application to have DM access if the endpoint is 'authorize'. Default: authenticate. ### Usage Example ```python from twython import Twython twitter = Twython(app_key='YOUR_APP_KEY', app_secret='YOUR_APP_SECRET', oauth_token='YOUR_OAUTH_TOKEN', oauth_token_secret='YOUR_OAUTH_TOKEN_SECRET') ``` ``` -------------------------------- ### TwythonStreamer.__init__ Source: https://twython.readthedocs.io/en/latest/api.html Initializes the TwythonStreamer with authentication credentials and optional parameters for timeout, retry, handlers, and chunk size. ```APIDOC ## TwythonStreamer.__init__ ### Description Initializes the TwythonStreamer instance with required authentication keys and optional configuration parameters. ### Method Constructor ### Signature `TwythonStreamer(app_key, app_secret, oauth_token, oauth_token_secret, timeout=300, retry_count=None, retry_in=10, client_args=None, handlers=None, chunk_size=1)` ### Parameters - **app_key** (string) - Required - Your application's key. - **app_secret** (string) - Required - Your application's secret key. - **oauth_token** (string) - Required - Used with oauth_token_secret to make authenticated calls. - **oauth_token_secret** (string) - Required - Used with oauth_token to make authenticated calls. - **timeout** (int) - Optional - How long (in seconds) the streamer should wait for a response from Twitter Streaming API. Default: 300. - **retry_count** (int) - Optional - Number of times the API call should be retried. - **retry_in** (int) - Optional - Amount of time (in seconds) the previous API call should be tried again. Default: 10. - **client_args** (dict) - Optional - Accepts some requests Session parameters and some requests Request parameters. See http://docs.python-requests.org/en/latest/api/#sessionapi for details. Example: headers, proxies, verify (SSL verification). - **handlers** (list) - Optional - Array of message types for which corresponding handlers will be called. - **chunk_size** (int) - Optional - Define the buffer size before data is actually returned from the Streaming API. Default: 1. ### Response No return value. ``` -------------------------------- ### Create Twython instance with OAuth 1 credentials Source: https://twython.readthedocs.io/en/latest/usage/basic_usage.html Instantiate Twython using your application keys and the user's OAuth tokens. Required before making authenticated API calls. ```python from twython import Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) ``` -------------------------------- ### Create Twython instance with OAuth 2 access token Source: https://twython.readthedocs.io/en/latest/usage/basic_usage.html Instantiate Twython using your application key and an OAuth 2 access token. Required for app-only authentication. ```python from twython import Twython twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN) ``` -------------------------------- ### TwythonStreamerTypesStatuses.sample Source: https://twython.readthedocs.io/en/latest/api.html Stream statuses/sample with parameters. ```APIDOC ## sample(**params) ### Description Stream statuses/sample. ### Method Streaming method (no HTTP method specified) ### Parameters - **params** (keyword arguments) - Parameters to send with your stream request. Accepted params found at: https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample ### Response No response documented. ``` -------------------------------- ### Import Twython Source: https://twython.readthedocs.io/en/latest/usage/starting_out.html Import the Twython library to use its authentication and API methods. ```python from twython import Twython ``` -------------------------------- ### Import TwythonStreamer Source: https://twython.readthedocs.io/en/latest/usage/streaming_api.html Import the TwythonStreamer class from the twython package. Required before setting up a streamer. ```python from twython import TwythonStreamer ``` -------------------------------- ### create_place() Source: https://twython.readthedocs.io/en/latest/genindex.html Creates a place. This method is part of the Twython class. ```APIDOC ## create_place() ### Description Creates a place. ### Method POST ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### post(endpoint, params=None, version='1.1', json_encoded=False) Source: https://twython.readthedocs.io/en/latest/api.html Shortcut for POST requests via request. ```APIDOC ## post(endpoint, params=None, version='1.1', json_encoded=False) ### Description Shortcut for POST requests via request. ### Method POST ### Endpoint {endpoint} ### Parameters #### Path Parameters - **endpoint** (string) - Required - Full url or Twitter API endpoint (e.g. search/tweets) #### Request Body - **params** (dict) - Optional - Dict of parameters (if any) accepted by the Twitter API endpoint. - **version** (string) - Optional - Twitter API version to access (default 1.1) - **json_encoded** (bool) - Optional - Flag to indicate if this method should send data encoded as json (default False) ### Response Returns the response from the Twitter API. ``` -------------------------------- ### Using Twython cursor to iterate over search results Source: https://twython.readthedocs.io/en/latest/api.html Shows how to use the cursor method to iterate over results from a Twython function like search. Requires a Twython instance with APP_KEY, APP_SECRET, OAUTH_TOKEN, and OAUTH_TOKEN_SECRET. ```python >>> from twython import Twython >>> twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) >>> results = twitter.cursor(twitter.search, q='python') >>> for result in results: >>> print result ``` -------------------------------- ### OAuth 2: Obtain Access Token Source: https://twython.readthedocs.io/en/latest/usage/starting_out.html Create a Twython instance with oauth_version=2 and obtain an application access token. ```python APP_KEY = 'YOUR_APP_KEY' APP_SECRET = 'YOUR_APP_SECRET' twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2) ACCESS_TOKEN = twitter.obtain_access_token() ``` -------------------------------- ### upload_video(media, media_type, media_category=None, size=None, check_progress=False) Source: https://twython.readthedocs.io/en/latest/api.html Uploads video file to Twitter servers in chunks. The file will be available to be attached to a status for 60 minutes. To attach to a update, pass a list of returned media ids to the update_status() method using the media_ids param. Upload happens in 3 stages: INIT, APPEND, and FINALIZE. ```APIDOC ## upload_video(media, media_type, media_category=None, size=None, check_progress=False) ### Description Uploads video file to Twitter servers in chunks. The file will be available to be attached to a status for 60 minutes. To attach to a update, pass a list of returned media ids to the update_status() method using the media_ids param. Upload happens in 3 stages: - INIT call with size of media to be uploaded (in bytes). If this is more than 15mb, twitter will return error. - APPEND calls each with media chunk. This returns a 204 (No Content) if chunk is received. - FINALIZE call to complete media upload. This returns media_id to be used with status update. Twitter media upload api expects each chunk to be not more than 5mb. We are sending chunk of 1mb each. ### Method POST ### Endpoint media/upload (chunked) ### Parameters #### Path Parameters - **media** (file) - Required - The video file to upload. - **media_type** (string) - Required - The MIME type of the media (e.g., 'video/mp4'). - **media_category** (string) - Optional - The category of the media (e.g., 'tweet_video'). - **size** (int) - Optional - The size of the media in bytes. If not provided, it will be computed from the file. - **check_progress** (bool) - Optional - Whether to check upload progress. ### Request Example ```python twython.upload_video(media=open('video.mp4', 'rb'), media_type='video/mp4') ``` ### Response Returns the media upload response containing the media ID. ### Response Example ```json { "media_id": 1234567890, "media_id_string": "1234567890" } ``` ``` -------------------------------- ### create_list() Source: https://twython.readthedocs.io/en/latest/genindex.html Creates a new list. This method is part of the Twython class. ```APIDOC ## create_list() ### Description Creates a new list. ### Method POST ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### New way: using cursor with search Source: https://twython.readthedocs.io/en/latest/usage/special_functions.html Demonstrates the Cursor function with twitter.search, yielding individual results. This replaces the manual pagination shown in the old way. ```python from twython import Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) results = twitter.cursor(twitter.search, q='twitter') for result in results: print(result['id_str']) ``` -------------------------------- ### Update status with video using upload_video Source: https://twython.readthedocs.io/en/latest/usage/advanced_usage.html Opens a video file, uploads it as a media object via upload_video with the media type 'video/mp4', and posts a status update referencing the returned media ID. ```python video = open('/path/to/file/video.mp4', 'rb') response = twitter.upload_video(media=video, media_type='video/mp4') twitter.update_status(status='Checkout this cool video!', media_ids=[response['media_id']]) ``` -------------------------------- ### Clone Twython repository from GitHub Source: https://twython.readthedocs.io/en/latest/usage/install.html Clone the Twython source code repository from GitHub. ```bash git clone git://github.com/ryanmcgrath/twython.git ``` -------------------------------- ### create_metadata() Source: https://twython.readthedocs.io/en/latest/genindex.html Creates metadata for a resource. This method is part of the Twython class. ```APIDOC ## create_metadata() ### Description Creates metadata for a specified resource. ### Method POST ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### Old way: manual pagination with search Source: https://twython.readthedocs.io/en/latest/usage/special_functions.html Shows the manual approach to paginating Twitter search results before using the Cursor function. It creates a Twython instance and iterates over the 'statuses' key from the search response. ```python from twython import Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) results = twitter.search(q='twitter') if results.get('statuses'): for result in results['statuses']: print(result['id_str']) ``` -------------------------------- ### obtain_access_token() (twython.Twython method) Source: https://twython.readthedocs.io/en/latest/genindex.html Obtains an access token for the user. ```APIDOC ## obtain_access_token() ### Description Obtains an access token for the user. ### Method Instance method ### Signature `obtain_access_token()` ### Returns - **object** - Access token data. ``` -------------------------------- ### Update status with image using upload_media Source: https://twython.readthedocs.io/en/latest/usage/advanced_usage.html Opens an image file, uploads it as a media object via upload_media, and posts a status update referencing the returned media ID. ```python photo = open('/path/to/file/image.jpg', 'rb') response = twitter.upload_media(media=photo) twitter.update_status(status='Checkout this cool image!', media_ids=[response['media_id']]) ``` -------------------------------- ### Send request through proxies with Twython client_args Source: https://twython.readthedocs.io/en/latest/usage/advanced_usage.html Pass a 'proxies' dictionary inside client_args to route the HTTP and HTTPS requests through specified proxy servers. ```python from twython import Twython client_args = { 'proxies': { 'http': 'http://10.0.10.1:8000', 'https': 'https://10.0.10.1:8001', } } twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, client_args=client_args) ``` -------------------------------- ### get_authentication_tokens Source: https://twython.readthedocs.io/en/latest/api.html Returns a dict including an authorization URL, auth_url, to direct a user to. This is the first step in the OAuth flow. ```APIDOC ## get_authentication_tokens ### Description Returns a dict including an authorization URL, `auth_url`, to direct a user to. ### Method GET ### Endpoint Not applicable (library method) ### Parameters - **callback_url** (string) - Optional - Url the user is returned to after they authorize your app (web clients only) - **force_login** (boolean) - Optional - Forces the user to enter their credentials to ensure the correct users account is authorized. - **screen_name** (string) - Optional - If forced_login is set OR user is not currently logged in, Prefills the username input box of the OAuth login screen with the given value ### Return Type dict ``` -------------------------------- ### list_blocks() (twython.Twython method) Source: https://twython.readthedocs.io/en/latest/genindex.html Returns a list of user objects that the authenticating user is blocking. ```APIDOC ## list_blocks() ### Description Returns a list of user objects that the authenticating user is blocking. ### Method Instance method ### Signature `list_blocks()` ### Returns - **list** - List of user objects. ``` -------------------------------- ### cursor(function, return_pages=False, **params) Source: https://twython.readthedocs.io/en/latest/api.html Returns a generator for results that match a specified query. ```APIDOC ## cursor(function, return_pages=False, **params) ### Description Returns a generator for results that match a specified query. ### Parameters - **function** (callable) - Required - Instance of a Twython function (e.g., Twython.get_home_timeline, Twython.search). - **return_pages** (bool) - Optional - If True, yields pages of results instead of individual items. - **params** (dict) - Optional - Extra parameters to send with your request (usually parameters accepted by the Twitter API endpoint). ### Returns - generator - Yields results matching the query. ### Usage Example ```python >>> from twython import Twython >>> twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) >>> results = twitter.cursor(twitter.search, q='python') >>> for result in results: >>> print(result) ``` ``` -------------------------------- ### Download Twython tarball Source: https://twython.readthedocs.io/en/latest/usage/install.html Download the Twython source code as a tarball using curl. ```bash $ curl -OL https://github.com/ryanmcgrath/twython/tarball/master ``` -------------------------------- ### construct_api_url() Source: https://twython.readthedocs.io/en/latest/genindex.html Static method to construct an API URL. This method is part of the Twython class. ```APIDOC ## construct_api_url() ### Description Constructs an API URL for a given endpoint. ### Method GET ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### cursor() Source: https://twython.readthedocs.io/en/latest/genindex.html Provides a cursor for paginating through results. This method is part of the Twython class. ```APIDOC ## cursor() ### Description Provides a cursor for paginating through results. ### Method GET ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### upload_video() Source: https://twython.readthedocs.io/en/latest/genindex.html Uploads a video to Twitter. ```APIDOC ## upload_video() ### Description Uploads a video to Twitter. ### Method `twython.Twython.upload_video` ``` -------------------------------- ### lookup_user() (twython.Twython method) Source: https://twython.readthedocs.io/en/latest/genindex.html Returns fully-hydrated user objects for up to 100 users per request. ```APIDOC ## lookup_user() ### Description Returns fully-hydrated user objects for up to 100 users per request. ### Method Instance method ### Signature `lookup_user(screen_name)` ### Parameters - **screen_name** (string) - Required - The screen name of the user to look up. ### Returns - **object** - User object. ``` -------------------------------- ### lookup_user(**params) Source: https://twython.readthedocs.io/en/latest/api.html Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters. ```APIDOC ## lookup_user(**params) ### Description Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters. ### Method GET ### Endpoint users/lookup ### Parameters #### Query Parameters - **user_id** (string) - Optional - Comma-separated list of user IDs. - **screen_name** (string) - Optional - Comma-separated list of screen names. ### Response Returns fully-hydrated user objects. ### Documentation https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup ``` -------------------------------- ### twitter.cursor(twitter.get_mentions_timeline, return_pages=True) Source: https://twython.readthedocs.io/en/latest/usage/special_functions.html Demonstrates using cursor with return_pages=True to yield entire pages of results. ```APIDOC ## Cursor with return_pages=True ### Description Returns a generator that yields entire pages of results instead of individual items. ### Method cursor ### Endpoint N/A - Twython SDK method ### Parameters - **function** (callable) - Required - The Twitter API method to paginate (get_mentions_timeline). - **return_pages** (boolean) - Optional - Set to True to yield pages. ### Request Example ```python results = twitter.cursor(twitter.get_mentions_timeline, return_pages=True) # page is a list for page in results: for result in page: print(result['id_str']) ``` ### Response #### Success Response Yields pages (lists) of results. #### Response Example ```python for page in results: for result in page: print(result['id_str']) ``` ``` -------------------------------- ### TwythonStreamerTypesStatuses.firehose Source: https://twython.readthedocs.io/en/latest/api.html Stream statuses/firehose with parameters. ```APIDOC ## firehose(**params) ### Description Stream statuses/firehose. ### Method Streaming method (no HTTP method specified) ### Parameters - **params** (keyword arguments) - Parameters to send with your stream request. Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/statuses/firehose ### Response No response documented. ``` -------------------------------- ### Posting a Status with an Editing Image Source: https://twython.readthedocs.io/en/latest/usage/advanced_usage.html Resizes a JPEG image using PIL, uploads it as a media object, and associates it with a status update. Requires a Twython instance 'twitter' with valid credentials. The image must be seeked to 0 before upload. ```python # Assume you are working with a JPEG from PIL import Image try: # Python 3 from io import StringIO except ImportError: # Python 2 from StringIO import StringIO photo = Image.open('/path/to/file/image.jpg') basewidth = 320 wpercent = (basewidth / float(photo.size[0])) height = int((float(photo.size[1]) * float(wpercent))) photo = photo.resize((basewidth, height), Image.ANTIALIAS) image_io = StringIO.StringIO() photo.save(image_io, format='JPEG') # If you do not seek(0), the image will be at the end of the file and # unable to be read image_io.seek(0) response = twitter.upload_media(media=image_io) twitter.update_status(status='Checkout this cool image!', media_ids=[response['media_id']]) ``` -------------------------------- ### Download Twython zipball Source: https://twython.readthedocs.io/en/latest/usage/install.html Download the Twython source code as a zipball using curl. ```bash $ curl -OL https://github.com/ryanmcgrath/twython/zipball/master ``` -------------------------------- ### upload_media() Source: https://twython.readthedocs.io/en/latest/genindex.html Uploads media to Twitter. ```APIDOC ## upload_media() ### Description Uploads media to Twitter. ### Method `twython.Twython.upload_media` ``` -------------------------------- ### list_blocks Source: https://twython.readthedocs.io/en/latest/api.html Returns a collection of user objects that the authenticating user is blocking. ```APIDOC ## list_blocks ### Description Returns a collection of user objects that the authenticating user is blocking. ### Method GET ### Endpoint blocks/list ### Parameters #### Query Parameters - **include_entities** (boolean) - Optional - Include entities in the response. - **skip_status** (boolean) - Optional - Skip statuses. ### Response #### Success Response (200) - **users** (array) - A collection of user objects. ``` -------------------------------- ### Search Generator Source: https://twython.readthedocs.io/en/latest/usage/advanced_usage.html Uses Twython's cursor generator to iterate over search results for a query. Requires a Twython instance with valid credentials. ```python from twython import Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) results = twitter.cursor(twitter.search, q='python') for result in results: print(result) ``` -------------------------------- ### twitter.cursor(twitter.get_mentions_timeline) Source: https://twython.readthedocs.io/en/latest/usage/special_functions.html Demonstrates using cursor with the get_mentions_timeline endpoint to iterate over mentions. ```APIDOC ## Cursor with get_mentions_timeline ### Description Returns a generator for the get_mentions_timeline endpoint, yielding individual results. ### Method cursor ### Endpoint N/A - Twython SDK method ### Parameters - **function** (callable) - Required - The Twitter API method to paginate (get_mentions_timeline). - **return_pages** (boolean) - Optional - If True, yields entire pages of results instead of individual items. ### Request Example ```python results = twitter.cursor(twitter.get_mentions_timeline) for result in results: print(result['id_str']) ``` ### Response #### Success Response Yields individual result items. #### Response Example ```python for result in results: print(result['id_str']) ``` ``` -------------------------------- ### Send custom headers with Twython client_args Source: https://twython.readthedocs.io/en/latest/usage/advanced_usage.html Pass a 'headers' dictionary inside client_args to set a custom User-Agent for the Twitter API request. ```python from twython import Twython client_args = { 'headers': { 'User-Agent': 'My App Name' } } twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, client_args=client_args) ``` -------------------------------- ### create_block() Source: https://twython.readthedocs.io/en/latest/genindex.html Blocks a user. This method is part of the Twython class. ```APIDOC ## create_block() ### Description Blocks a specified user. ### Method POST ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### create_list_members() Source: https://twython.readthedocs.io/en/latest/genindex.html Adds multiple members to a list. This method is part of the Twython class. ```APIDOC ## create_list_members() ### Description Adds multiple members to a specified list. ### Method POST ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### list_mutes() (twython.Twython method) Source: https://twython.readthedocs.io/en/latest/genindex.html Returns a list of user objects that the authenticating user is muting. ```APIDOC ## list_mutes() ### Description Returns a list of user objects that the authenticating user is muting. ### Method Instance method ### Signature `list_mutes()` ### Returns - **list** - List of user objects. ``` -------------------------------- ### create_friendship() Source: https://twython.readthedocs.io/en/latest/genindex.html Creates a friendship (follows a user). This method is part of the Twython class. ```APIDOC ## create_friendship() ### Description Follows a specified user. ### Method POST ### Endpoint Not specified in source. ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### lookup_friendships(**params) Source: https://twython.readthedocs.io/en/latest/api.html Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided. ```APIDOC ## lookup_friendships(**params) ### Description Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided. ### Method GET ### Endpoint friendships/lookup ### Parameters #### Query Parameters - **screen_name** (string) - Optional - Comma-separated list of screen names. - **user_id** (string) - Optional - Comma-separated list of user IDs. ### Response Returns the relationships of the authenticating user to the provided users. ### Documentation https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-lookup ``` -------------------------------- ### update_status_with_media() Source: https://twython.readthedocs.io/en/latest/genindex.html Updates the authenticated user's status with media. ```APIDOC ## update_status_with_media() ### Description Updates the authenticated user's status with media. ### Method `twython.Twython.update_status_with_media` ``` -------------------------------- ### request(endpoint, method='GET', params=None, version='1.1', json_encoded=False) Source: https://twython.readthedocs.io/en/latest/api.html Return dict of response received from Twitter's API. ```APIDOC ## request(endpoint, method='GET', params=None, version='1.1', json_encoded=False) ### Description Return dict of response received from Twitter's API. ### Method GET, POST, DELETE ### Endpoint {endpoint} ### Parameters #### Path Parameters - **endpoint** (string) - Required - Full url or Twitter API endpoint (e.g. search/tweets) #### Query Parameters - **method** (string) - Optional - Method of accessing data, either GET, POST or DELETE. (default GET) - **params** (dict) - Optional - Dict of parameters (if any) accepted by the Twitter API endpoint. - **version** (string) - Optional - Twitter API version to access (default 1.1) - **json_encoded** (bool) - Optional - Flag to indicate if this method should send data encoded as json (default False) ### Response Returns a dict of the response received from Twitter's API. ### Return Type dict ``` -------------------------------- ### obtain_access_token() Source: https://twython.readthedocs.io/en/latest/api.html Returns an OAuth 2 access token to make OAuth 2 authenticated read-only calls. ```APIDOC ## obtain_access_token() ### Description Returns an OAuth 2 access token to make OAuth 2 authenticated read-only calls. ### Method POST ### Endpoint oauth2/token ### Parameters None ### Response Returns an OAuth 2 access token. ### Return Type string ``` -------------------------------- ### Twython.construct_api_url Source: https://twython.readthedocs.io/en/latest/api.html Constructs a Twitter API URL with encoded parameters. ```APIDOC ## Twython.construct_api_url ### Description Construct a Twitter API url, encoded, with parameters. ### Method Static method ### Parameters - **api_url** (string) - Required - URL of the Twitter API endpoint you are attempting to construct - **params** (object) - Required - Parameters that are accepted by Twitter for the endpoint you're requesting ### Returns string - The constructed URL with query parameters. ### Usage Example ```python >>> from twython import Twython >>> twitter = Twython() >>> api_url = 'https://api.twitter.com/1.1/search/tweets.json' >>> constructed_url = twitter.construct_api_url(api_url, q='python', result_type='popular') >>> print constructed_url https://api.twitter.com/1.1/search/tweets.json?q=python&result_type=popular ``` ``` -------------------------------- ### list_block_ids() (twython.Twython method) Source: https://twython.readthedocs.io/en/latest/genindex.html Returns an array of numeric user IDs the authenticating user is blocking. ```APIDOC ## list_block_ids() ### Description Returns an array of numeric user IDs the authenticating user is blocking. ### Method Instance method ### Signature `list_block_ids()` ### Returns - **list** - List of user IDs. ``` -------------------------------- ### get_contributees Source: https://twython.readthedocs.io/en/latest/api.html Returns a collection of users that the specified user can “contribute” to. ```APIDOC ## get_contributees ### Description Returns a collection of users that the specified user can “contribute” to. ### Method GET ### Endpoint Not applicable (library method) ### Parameters - **params** (dict) - Optional - Additional parameters for the Twitter API request. ### Docs https://dev.twitter.com/docs/api/1.1/get/users/contributees ``` -------------------------------- ### upload_media(**params) Source: https://twython.readthedocs.io/en/latest/api.html Uploads media file to Twitter servers. The file will be available to be attached to a status for 60 minutes. To attach to a update, pass a list of returned media ids to the update_status() method using the media_ids param. This method corresponds to the Twitter API endpoint POST media/upload. ```APIDOC ## upload_media(**params) ### Description Uploads media file to Twitter servers. The file will be available to be attached to a status for 60 minutes. To attach to a update, pass a list of returned media ids to the update_status() method using the media_ids param. ### Method POST ### Endpoint media/upload ### Parameters #### Keyword Arguments - **params** (dict) - Required - Parameters to pass to the Twitter API endpoint, such as the media file. ### Request Example ```python twython.upload_media(media=open('image.jpg', 'rb')) ``` ### Response Returns the media upload response containing the media ID. ### Response Example ```json { "media_id": 1234567890, "media_id_string": "1234567890" } ``` ``` -------------------------------- ### update_profile_background_image() Source: https://twython.readthedocs.io/en/latest/genindex.html Updates the authenticated user's profile background image. ```APIDOC ## update_profile_background_image() ### Description Updates the authenticated user's profile background image. ### Method `twython.Twython.update_profile_background_image` ``` -------------------------------- ### get_home_timeline() - twython.Twython Source: https://twython.readthedocs.io/en/latest/genindex.html Retrieves the home timeline for the authenticated user. This method is part of the Twython class. ```APIDOC ## get_home_timeline() ### Description Retrieves the home timeline for the authenticated user. This method is part of the Twython class. ### Method get_home_timeline() ### Endpoint Home timeline endpoint (not specified in source) ### Parameters No parameters documented in source. ### Request Example No request example provided in source. ### Response No response details provided in source. ``` -------------------------------- ### update_account_settings() Source: https://twython.readthedocs.io/en/latest/genindex.html Updates the authenticated user's account settings. ```APIDOC ## update_account_settings() ### Description Updates the authenticated user's account settings. ### Method `twython.Twython.update_account_settings` ``` -------------------------------- ### delete(endpoint, params=None, version='1.1', json_encoded=False) Source: https://twython.readthedocs.io/en/latest/api.html Shortcut for delete requests via request. ```APIDOC ## delete(endpoint, params=None, version='1.1', json_encoded=False) ### Description Shortcut for delete requests via request. ### Parameters - **endpoint** (str) - Required - The API endpoint to send the delete request to. - **params** (dict) - Optional - Parameters to include in the request. - **version** (str) - Optional - API version to use (default '1.1'). - **json_encoded** (bool) - Optional - Whether to JSON-encode the parameters. ### Returns - Response from the API. ### Usage Example ```python twitter.delete('lists/destroy', params={'list_id': 12345}) ``` ``` -------------------------------- ### Search tweets with multiple keyword arguments Source: https://twython.readthedocs.io/en/latest/usage/basic_usage.html Performs a search with multiple keyword arguments, including 'result_type' to filter results. Demonstrates dynamic function arguments. ```python twitter.search(q='python', result_type='popular') ``` -------------------------------- ### get_account_settings() - twython.Twython Source: https://twython.readthedocs.io/en/latest/genindex.html Retrieves the authenticated user's account settings. This method is part of the Twython class. ```APIDOC ## get_account_settings() ### Description Retrieves the authenticated user's account settings. This method is part of the Twython class. ### Method get_account_settings() ### Endpoint Account settings endpoint (not specified in source) ### Parameters No parameters documented in source. ### Request Example No request example provided in source. ### Response No response details provided in source. ``` -------------------------------- ### on_error() (twython.TwythonStreamer method) Source: https://twython.readthedocs.io/en/latest/genindex.html Callback method for handling stream errors. ```APIDOC ## on_error() ### Description Callback method for handling stream errors. ### Method Instance method ### Signature `on_error(error)` ### Parameters - **error** (object) - The error object. ### Returns - **None** ``` -------------------------------- ### lookup_friendships() (twython.Twython method) Source: https://twython.readthedocs.io/en/latest/genindex.html Returns the relationships of the authenticating user to the specified users. ```APIDOC ## lookup_friendships() ### Description Returns the relationships of the authenticating user to the specified users. ### Method Instance method ### Signature `lookup_friendships(user_id)` ### Parameters - **user_id** (string) - Required - The ID of the user to look up. ### Returns - **object** - Friendship relationship data. ``` -------------------------------- ### TwythonStreamerTypesStatuses.filter Source: https://twython.readthedocs.io/en/latest/api.html Stream statuses/filter with parameters. ```APIDOC ## filter(**params) ### Description Stream statuses/filter. ### Method Streaming method (no HTTP method specified) ### Parameters - **params** (keyword arguments) - Parameters to send with your stream request. Accepted params found at: https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter ### Response No response documented. ``` -------------------------------- ### Define MyStreamer with signal handlers Source: https://twython.readthedocs.io/en/latest/usage/streaming_api.html Subclass TwythonStreamer to handle stream signals. on_success processes incoming data, printing text if present. on_error receives status code and data, prints the status code, and includes commented code to disconnect on error. ```python class MyStreamer(TwythonStreamer): def on_success(self, data): if 'text' in data: print(data['text']) def on_error(self, status_code, data): print(status_code) # Want to stop trying to get data because of the error? # Uncomment the next line! # self.disconnect() ``` -------------------------------- ### TwythonStreamer.on_timeout Source: https://twython.readthedocs.io/en/latest/api.html Called when the request has timed out. ```APIDOC ## TwythonStreamer.on_timeout ### Description Called when the request has timed out. ### Method Method ### Signature `on_timeout()` ### Parameters None. ### Response No return value. ```