### Video Download Example Source: https://twikit.readthedocs.io/en/latest/twikit.html This example demonstrates how to download a video from a tweet using the Twikit library. It shows how to access the video media, its streams, and then download a specific stream to a file. ```APIDOC ## Video Download This example demonstrates how to download a video from a tweet. ```python tweet = await client.get_tweet_by_id('00000000000') video = tweet.media[0] streams = video.streams await streams[0].download('output.mp4') ``` ``` -------------------------------- ### Retrieve Video Subtitles Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/media.html Example of how to get subtitles for a video. It fetches the tweet, accesses the video media, retrieves the subtitles, and then iterates through them to print start time, end time, and text. ```python tweet = await client.get_tweet_by_id('00000000000') video = tweet.media[0] subtitles = await video.get_subtitles() for l in subtitles: print(l.start) print(l.end) print(l.text) ``` -------------------------------- ### Download Video Stream Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/media.html Example of how to download a video from a tweet. It retrieves the tweet, accesses the first media object (expected to be a video), gets its available streams, and downloads the first stream. ```python tweet = await client.get_tweet_by_id('00000000000') video = tweet.media[0] streams = video.streams await streams[0].download('output.mp4') ``` -------------------------------- ### Get Bookmark Folders Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves all bookmark folders for the authenticated user. Supports pagination. ```python >>> folders = await client.get_bookmark_folders() >>> print(folders) [, ..., ] >>> more_folders = await folders.next() # Retrieve more folders ``` -------------------------------- ### Get Video Subtitles Source: https://twikit.readthedocs.io/en/latest/twikit.html This example shows how to retrieve subtitles for a video associated with a tweet. It iterates through the subtitles and prints their start time, end time, and text content. ```APIDOC ## Get Subtitles This example demonstrates how to retrieve and process subtitles for a video. ```python tweet = await client.get_tweet_by_id('00000000000') video = tweet.media[0] subtitles = await video.get_subtitles() for l in subtitles: print(l.start) print(l.end) print(l.text) ``` ``` -------------------------------- ### Upload Media - Basic Example Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Uploads a media file (e.g., image) using its file path. The media type is automatically detected. ```python media_id_1 = await client.upload_media( 'media1.jpg', ) ``` -------------------------------- ### UserString startswith Method Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Checks if the string starts with a specified prefix within a given range. Returns a boolean. ```python def startswith(self, prefix, start=0, end=_sys.maxsize): return self.data.startswith(prefix, start, end) ``` -------------------------------- ### Get Bookmark Folders Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves all bookmark folders created by the authenticated user. Supports pagination. ```APIDOC ## get_bookmark_folders ### Description Retrieves bookmark folders. ### Method `client.get_bookmark_folders(_cursor: str | None = None)` ### Parameters #### Path Parameters - **_cursor** (str | None) - Optional - Cursor for pagination. ### Response #### Success Response (200) - **Result[BookmarkFolder]** - Result object containing a list of bookmark folders. ### Request Example ```python folders = await client.get_bookmark_folders() print(folders) more_folders = await folders.next() # Retrieve more folders ``` ``` -------------------------------- ### Get Bookmarks Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves bookmarks for the authenticated user. Supports pagination and filtering by folder. ```python >>> bookmarks = await client.get_bookmarks() >>> for bookmark in bookmarks: ... print(bookmark) ``` ```python >>> # # To retrieve more bookmarks >>> more_bookmarks = await bookmarks.next() >>> for bookmark in more_bookmarks: ... print(bookmark) ``` -------------------------------- ### UserDict Get Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Retrieves an item by key, returning a default value if the key is not found. ```APIDOC ## UserDict Get ### Description Retrieves the value associated with the given key. If the key is not found, it returns the specified default value (or None if no default is provided). ### Method get ### Parameters - **key** - The key of the item to retrieve. - **default** (optional) - The value to return if the key is not found. Defaults to None. ### Returns - **any** - The value associated with the key, or the default value if the key is not found. ``` -------------------------------- ### Get User by Screen Name Source: https://twikit.readthedocs.io/en/latest/twikit.html Fetches user information by providing their screen name. This is useful for retrieving specific user details. ```python async get_user_by_screen_name(_screen_name : str_) → User[source] Fetches a user by screen name. ``` -------------------------------- ### Client Initialization Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Initializes the Client with optional language, proxy, and captcha solver. It sets up the asynchronous HTTP client and internal transaction management. ```APIDOC ## Client ### Description A client for interacting with the Twitter API. Methods must be executed using `await`. ### Parameters #### `language` (str, optional) - The language code to use in API requests. Defaults to 'en-US'. #### `proxy` (str, optional) - The proxy server URL to use for requests (e.g., 'http://0.0.0.0:0000'). #### `captcha_solver` (:class:`.Capsolver`, optional) - An instance of Capsolver for solving CAPTCHAs. #### `user_agent` (str, optional) - The User-Agent string to use for requests. ### Example ```python client = Client(language='en-US', proxy='http://user:pass@host:port') await client.login(auth_info_1='example_user', auth_info_2='email@example.com', password='00000000') ``` ``` -------------------------------- ### Create Bookmark Folder Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Creates a new bookmark folder with a given name. Returns the newly created bookmark folder object. ```python response, _ = await self.gql.create_bookmark_folder(name) return BookmarkFolder(self, response['data']['bookmark_collection_create']) ``` -------------------------------- ### Get Communities Timeline Example Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Fetches tweets from the main communities timeline. The returned result object allows for pagination to load more tweets using its `.next()` method. ```python >>> tweets = await client.get_communities_timeline() >>> for tweet in tweets: ... print(tweet) ... >>> more_tweets = await tweets.next() # Retrieve more tweets ``` -------------------------------- ### Flow Class for Onboarding Tasks Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/utils.html Manages the state and execution of onboarding tasks, including SSO initiation and task execution. ```python class Flow: def __init__(self, client: Client, guest_token: str) -> None: self._client = client self.guest_token = guest_token self.response = None async def execute_task(self, *subtask_inputs, **kwargs) -> None: response, _ = await self._client.v11.onboarding_task( self.guest_token, self.token, list(subtask_inputs), **kwargs ) self.response = response async def sso_init(self, provider: str) -> None: await self._client.v11.sso_init(provider, self.guest_token) @property def token(self) -> str | None: if self.response is None: return None return self.response.get('flow_token') @property def task_id(self) -> str | None: if self.response is None: return None if len(self.response['subtasks']) <= 0: return None return self.response['subtasks'][0]['subtask_id'] ``` -------------------------------- ### Get Community Tweets Example Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Retrieves tweets from a specified community. Use 'Latest' for recent tweets, 'Top' for relevant ones, or 'Media' for media content. The result object supports fetching more tweets using its `.next()` method. ```python >>> community_id = '...' >>> tweets = await client.get_community_tweets(community_id, 'Latest') >>> for tweet in tweets: ... print(tweet) ... >>> more_tweets = await tweets.next() # Retrieve more tweets ``` -------------------------------- ### HTTP GET Request Method Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Provides a simple wrapper for making GET requests to the Twitter API. It calls the internal request method with the 'GET' method. ```python async def get(self, url, **kwargs) -> tuple[dict | Any, Response]: ':meta private:' return await self.request('GET', url, **kwargs) ``` -------------------------------- ### Capsolver Initialization Source: https://twikit.readthedocs.io/en/latest/twikit.html Demonstrates how to initialize the Capsolver class and pass it to the Client for automatic captcha solving. ```APIDOC ## Capsolver class twikit._captcha.capsolver.Capsolver(_api_key : str_, _max_attempts : int = 3_, _get_result_interval : float = 1.0_, _use_blob_data : bool = False_)[source] You can automatically unlock the account by passing the captcha_solver argument when initialising the `Client`. First, visit https://capsolver.com and obtain your Capsolver API key. Next, pass the Capsolver instance to the client as shown in the example. ```python from twikit.twikit_async import Capsolver, Client solver = Capsolver( api_key='your_api_key', max_attempts=10 ) client = Client(captcha_solver=solver) ``` Parameters: * **api_key** (`str`) – Capsolver API key. * **max_attempts** (`int`, default=3) – The maximum number of attempts to solve the captcha. * **get_result_interval** (`float`, default=1.0) * **use_blob_data** (`bool`, default=False) ``` -------------------------------- ### Get User Tweets Source: https://twikit.readthedocs.io/en/latest/twikit.html Fetches tweets from a user's timeline, supporting different tweet types and pagination. Use `.next()` to get more tweets. ```python >>> user_id = '...' ``` ```python >>> screen_name = 'example_user' >>> user = client.get_user_by_screen_name(screen_name) >>> user_id = user.id ``` ```python >>> tweets = await client.get_user_tweets(user_id, 'Tweets', count=20) >>> for tweet in tweets: ... print(tweet) ... ... ``` ```python >>> more_tweets = await tweets.next() # Retrieve more tweets >>> for tweet in more_tweets: ... print(tweet) ... ... ``` ```python >>> # Retrieve previous tweets >>> previous_tweets = await tweets.previous() ``` -------------------------------- ### Create Bookmark Folder Source: https://twikit.readthedocs.io/en/latest/twikit.html Creates a new bookmark folder with a specified name. ```APIDOC ## create_bookmark_folder ### Description Creates a bookmark folder. ### Method `client.create_bookmark_folder(_name: str)` ### Parameters #### Path Parameters - **_name** (str) - Required - Name of the folder. ### Response #### Success Response (200) - **BookmarkFolder** - Newly created bookmark folder. ``` -------------------------------- ### Streaming API Example Source: https://twikit.readthedocs.io/en/latest/_sources/twikit.rst.txt Demonstrates how to use the streaming API to receive real-time events like tweet engagements, DM updates, and DM typings. Requires a client instance and defines topics to subscribe to. ```python from twikit.streaming import Topic topics = { Topic.tweet_engagement('1739617652'), # Stream tweet engagement Topic.dm_update('17544932482-174455537996'), # Stream DM update Topic.dm_typing('17544932482-174455537996') # Stream DM typing } session = client.get_streaming_session(topics) for topic, payload in session: if payload.dm_update: conversation_id = payload.dm_update.conversation_id user_id = payload.dm_update.user_id print(f'{conversation_id}: {user_id} sent a message') if payload.dm_typing: conversation_id = payload.dm_typing.conversation_id user_id = payload.dm_typing.user_id print(f'{conversation_id}: {user_id} is typing') if payload.tweet_engagement: like = payload.tweet_engagement.like_count retweet = payload.tweet_engagement.retweet_count view = payload.tweet_engagement.view_count print(f'Tweet engagement updated likes: {like} retweets: {retweet} views: {view}') ``` -------------------------------- ### Get Community Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a specific community by its unique ID. ```APIDOC ## async get_community(_community_id : str_) ### Description Retrieves community by ID. ### Parameters #### Path Parameters - **community_id** (str) - Required - The ID of the community to retrieve. ### Returns Community object. ### Return Type `Community` ``` -------------------------------- ### Capsolver Initialization Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/_captcha/capsolver.html Initialize the Capsolver solver with your API key and configure optional parameters like max attempts and result retrieval interval. ```APIDOC ## Capsolver ### Description You can automatically unlock the account by passing the `captcha_solver` argument when initialising the :class:`.Client`. First, visit https://capsolver.com and obtain your Capsolver API key. Next, pass the Capsolver instance to the client as shown in the example. ### Parameters - **api_key** (str) - Required - Capsolver API key. - **max_attempts** (int) - Optional - The maximum number of attempts to solve the captcha. Defaults to 3. - **get_result_interval** (float) - Optional - The interval in seconds to wait between checking for task results. Defaults to 1.0. - **use_blob_data** (bool) - Optional - Whether to use blob data for solving captchas. Defaults to False. ``` -------------------------------- ### UserDict Get Item Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Retrieves an item from the UserDict by its key. ```APIDOC ## UserDict Get Item ### Description Retrieves the value associated with the given key. If the key is not found and a `__missing__` method is defined, it will be called. ### Method __getitem__ ### Parameters - **key** - The key of the item to retrieve. ### Returns - **any** - The value associated with the key. ### Raises - **KeyError** - If the key is not found and no `__missing__` method is defined. ``` -------------------------------- ### Get Bookmarks with Twikit Client Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Retrieves bookmarks for the authenticated user. Supports specifying count, cursor, and folder ID. ```python >>> bookmarks = await client.get_bookmarks() >>> for bookmark in bookmarks: ... print(bookmark) ``` -------------------------------- ### Get Community Note Source: https://twikit.readthedocs.io/en/latest/twikit.html Fetches a community note by its unique identifier. ```APIDOC ## get_community_note ### Description Fetches a community note by its unique identifier. ### Method `async get_community_note(note_id: str)` ### Parameters #### Path Parameters - **note_id** (str) - Required - The ID of the community note. ### Response #### Success Response (200) - **CommunityNote** (CommunityNote) - A CommunityNote object representing the fetched community note. ### Request Example ```python note_id = '...' client.get_community_note(note_id) ``` ### Response Example ```python ``` ### Raises **TwitterException** – Invalid note ID. ``` -------------------------------- ### UserDict Initialization Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Initializes a UserDict, optionally with an existing dictionary or keyword arguments. ```APIDOC ## UserDict Initialization ### Description Initializes a new UserDict instance. It can be populated with data from an existing dictionary or keyword arguments. ### Method __init__ ### Parameters - **dict** (dict, optional) - An existing dictionary to populate the UserDict. - **kwargs** - Keyword arguments to populate the UserDict. ``` -------------------------------- ### Get Favoriters Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a list of users who have favorited a specific tweet. ```APIDOC ## get_favoriters ### Description Retrieve users who favorited a specific tweet. ### Parameters #### Path Parameters - **tweet_id** (str) - Required - The ID of the tweet. #### Query Parameters - **count** (int, default=40) - Optional - The maximum number of users to retrieve. - **cursor** (str | None, default=None) - Optional - A string indicating the position of the cursor for pagination. ### Returns A list of users who favorited the tweet. ### Return Type Result[`User`] ### Example ```python >>> tweet_id = '...' >>> favoriters = client.get_favoriters(tweet_id) >>> print(favoriters) [, , ..., ] ``` ``` -------------------------------- ### Creating and Using a namedtuple Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Demonstrates how to create a namedtuple subclass and access its elements using both positional indexing and named fields. Also shows instantiation with keyword arguments and conversion to a dictionary. ```python >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) ``` -------------------------------- ### Initialize Twitter Client Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Instantiate the Client class to create an interface for the Twitter API. Configure language, proxy, and optionally a captcha solver. The client automatically initializes necessary internal components like GQLClient and V11Client. ```python client = Client(language='en-US') ``` -------------------------------- ### Get Scheduled Tweets Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a list of all currently scheduled tweets. ```APIDOC ## get_scheduled_tweets ### Description Retrieves scheduled tweets. ### Returns List of ScheduledTweet objects representing the scheduled tweets. ### Return Type list[`ScheduledTweet`] ``` -------------------------------- ### Client Initialization Source: https://twikit.readthedocs.io/en/latest/twikit.html Initializes a new Client instance for interacting with the Twitter API. Methods of this client must be executed using await. ```APIDOC ## Client Initialization ### Description Initializes a new `Client` instance for interacting with the Twitter API. Methods of this client must be executed using `await`. ### Parameters * **language** (`str` | None, default=None) - The language code to use in API requests. * **proxy** (`str` | None, default=None) - The proxy server URL to use for requests (e.g., ‘http://0.0.0.0:0000’). * **captcha_solver** (`Capsolver` | None, default=None) - An instance of `Capsolver` for solving CAPTCHAs. ### Example ```python client = Client(language='en-US') ``` ``` -------------------------------- ### Get User Information Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves detailed information about the authenticated user. ```APIDOC ## Get User Information ### Description Retrieve detailed information about the authenticated user. ### Method `await client.user()` ### Response #### Success Response (200) Returns a `User` object containing detailed user information. ``` -------------------------------- ### create_bookmark_folder() Source: https://twikit.readthedocs.io/en/latest/genindex.html Creates a new folder for bookmarks. This method is part of the Client class. ```APIDOC ## create_bookmark_folder() ### Description Creates a new folder for bookmarks. ### Method (twikit.client.client.Client method) ``` -------------------------------- ### Get Retweeters Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/tweet.html Retrieves a list of users who have retweeted the specified tweet. ```APIDOC ## GET /tweet/retweeters ### Description Retrieve users who retweeted the tweet. ### Method GET ### Endpoint /tweet/{id}/retweeters ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the tweet whose retweeters are to be retrieved. #### Query Parameters - **count** (int) - Optional - The maximum number of users to retrieve. Defaults to 40. - **cursor** (str) - Optional - A string indicating the position of the cursor for pagination. ### Response #### Success Response (200) - **Result[User]** - A list of users who retweeted the tweet. ### Request Example ```python await tweet.get_retweeters() ``` ``` -------------------------------- ### Initialize Capsolver Client Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/_captcha/capsolver.html Instantiate the Capsolver solver with your API key and configure maximum attempts. This solver can then be passed to the twikit Client for automatic captcha resolution. ```python from twikit.twikit_async import Capsolver, Client solver = Capsolver( api_key='your_api_key', max_attempts=10 ) client = Client(captcha_solver=solver) ``` -------------------------------- ### Get Tweet by ID Source: https://twikit.readthedocs.io/en/latest/twikit.html Fetches a single tweet by its unique tweet ID. ```APIDOC ## get_tweet_by_id ### Description Fetches a tweet by tweet ID. ### Parameters #### Path Parameters - **tweet_id** (str) - Required - The ID of the tweet. #### Query Parameters - **cursor** (str | None) - Optional - A string indicating the position of the cursor for pagination. ### Returns A Tweet object representing the fetched tweet. ### Return Type `Tweet` ### Example ```python >>> target_tweet_id = '...' >>> tweet = client.get_tweet_by_id(target_tweet_id) >>> print(tweet) ``` ``` -------------------------------- ### Upload Media and Create Tweet with Metadata Source: https://twikit.readthedocs.io/en/latest/twikit.html Uploads a media file, sets its alt text and sensitive warnings, and then creates a tweet with the uploaded media. ```python >>> media_id = await client.upload_media('media.jpg') >>> await client.create_media_metadata( ... media_id, ... alt_text='This is a sample media', ... sensitive_warning=['other'] ... ) >>> await client.create_tweet(media_ids=[media_id]) ``` -------------------------------- ### Get User ID Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves the user ID of the currently authenticated account. ```APIDOC ## Get User ID ### Description Retrieves the user ID associated with the authenticated account. ### Method `await client.user_id()` ### Response #### Success Response (200) Returns the user ID as a string. ``` -------------------------------- ### Get Trends Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Retrieves trending topics on Twitter across various categories. ```APIDOC ## get_trends ### Description Retrieves trending topics on Twitter. ### Parameters #### Query Parameters - **category** (str) - Required - The category of trends to retrieve. Valid options include: 'trending', 'for-you', 'news', 'sports', 'entertainment'. - **count** (int) - Optional - The number of trends to retrieve. Defaults to 20. - **retry** (bool) - Optional - If no trends are fetched continuously retry to fetch trends. Defaults to True. - **additional_request_params** (dict) - Optional - Parameters to be added on top of the existing trends API parameters. Typically, it is used as `additional_request_params = {'candidate_source': 'trends'}` when this function doesn't work otherwise. ### Returns - list[:class:`Trend`] - A list of Trend objects representing the retrieved trends. ### Examples ```python trends = await client.get_trends('trending') for trend in trends: print(trend) ``` ### See Also - .follow_user - .unfollow_user ``` -------------------------------- ### Start a Streaming Session Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Initiates a streaming session to receive real-time data. Requires a list of topics to subscribe to. Automatically retrieves the session ID from the initial stream payload. ```python stream = self._stream(topics) session_id = (await anext(stream))[1].config.session_id return StreamingSession(self, session_id, stream, topics, auto_reconnect) ``` -------------------------------- ### UserString Initialization Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Initializes a UserString object. It can accept a string, another UserString object, or any object that can be converted to a string. ```APIDOC ## UserString.__init__ ### Description Initializes a new instance of the UserString class. ### Parameters - **seq**: The input sequence or string to initialize the UserString with. ``` -------------------------------- ### Get Authenticated User Information Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves detailed information about the authenticated user. ```python await client.user() ``` -------------------------------- ### Get Place by ID Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Retrieves a specific place using its unique ID. ```APIDOC ## get_place ### Description Retrieves a specific place using its unique ID. ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the place. ### Returns - .Place - A Place object representing the fetched place. ``` -------------------------------- ### UserString partition Method Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Partitions the string at the first occurrence of a separator. Returns a tuple of three strings. ```python def partition(self, sep): return self.data.partition(sep) ``` -------------------------------- ### UserDict Initialization Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Initializes a UserDict instance, optionally with an existing dictionary or keyword arguments. The data is stored internally. ```python def __init__(self, dict=None, /, **kwargs): self.data = {} if dict is not None: self.update(dict) if kwargs: self.update(kwargs) ``` -------------------------------- ### Get Community Moderators Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a list of moderators for a specific community. Supports pagination. ```APIDOC ## async get_community_moderators(_community_id : str_, _count : int = 20_, _cursor : str | None = None_) ### Description Retrieves moderators of a community. ### Parameters #### Path Parameters - **community_id** (str) - Required - The ID of the community. #### Query Parameters - **count** (int) - Optional - The number of moderators to retrieve. Defaults to 20. - **cursor** (str | None) - Optional - The cursor for pagination. ### Returns List of retrieved moderators. ### Return Type Result[`CommunityMember`] ``` -------------------------------- ### Flow Class Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/utils.html The Flow class manages onboarding tasks and interactions with the client. It holds guest tokens and provides methods to execute tasks and retrieve flow-related information like tokens and task IDs. ```APIDOC ## class Flow Methods ------- async def execute_task(*subtask_inputs, **kwargs) -> None Executes an onboarding task with the provided subtask inputs and keyword arguments. async def sso_init(provider: str) -> None Initiates the SSO process with the specified provider. Properties --------- token : str | None Returns the flow token from the response, or None if no response is available. task_id : str | None Returns the first subtask ID from the response, or None if no response or subtasks are available. ``` -------------------------------- ### Get Community Members Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a list of members for a specific community. Supports pagination. ```APIDOC ## async get_community_members(_community_id : str_, _count : int = 20_, _cursor : str | None = None_) ### Description Retrieves members of a community. ### Parameters #### Path Parameters - **community_id** (str) - Required - The ID of the community. #### Query Parameters - **count** (int) - Optional - The number of members to retrieve. Defaults to 20. - **cursor** (str | None) - Optional - The cursor for pagination. ### Returns List of retrieved members. ### Return Type Result[`CommunityMember`] ``` -------------------------------- ### create_list() Source: https://twikit.readthedocs.io/en/latest/genindex.html Creates a new list. This method is available on the Client class. ```APIDOC ## create_list() ### Description Creates a new list. ### Method (twikit.client.client.Client method) ``` -------------------------------- ### Get Community by ID with Twikit Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a specific community using its unique ID. ```python async get_community(_community_id : str_) → Community[source] Retrieves community by ID. Parameters: **list_id** (`str`) – The ID of the community to retrieve. Returns: Community object. Return type: `Community` ``` -------------------------------- ### UserString zfill Method Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Pads the string with leading zeros to a specified width. Returns a new UserString instance. ```python def zfill(self, width): return self.__class__(self.data.zfill(width)) ``` -------------------------------- ### Follow a User Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/user.html Initiates a follow action on a user. This is a convenience method that calls the underlying client's follow_user function. ```python >>> user = await client.get_user_by_screen_name('example_user') >>> response = await user.follow() >>> print(response.status_code) ``` -------------------------------- ### Get Authenticated User ID Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves the user ID of the currently authenticated account. ```python await client.user_id() ``` -------------------------------- ### join Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/community.html Allows a user to join a community. ```APIDOC ## join ### Description Join the community. ### Parameters None ### Returns Community Returns the updated community object after joining. ### Examples ```python await community.join() ``` ``` -------------------------------- ### Length and Indexing Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Provides methods to get the length of the UserString and access its elements by index. ```APIDOC ## UserString.__len__ ### Description Returns the length of the UserString. ### Returns The number of characters in the UserString. ``` ```APIDOC ## UserString.__getitem__ ### Description Retrieves a character or slice from the UserString by index. ### Parameters - **index**: The index or slice to access. ### Returns A new UserString object representing the character or slice. ``` -------------------------------- ### create_list Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Creates a new list with a specified name, description, and privacy setting. ```APIDOC ## create_list ### Description Creates a list. ### Parameters #### Path Parameters - **name** (str) - Required - The name of the list. - **description** (str) - Optional - The description of the list. Defaults to ''. - **is_private** (bool) - Optional - Indicates whether the list is private (True) or public (False). Defaults to False. ### Returns - **List** - The created list. ### Example ```python list = await client.create_list( 'list name', 'list description', is_private=True ) print(list) ``` ``` -------------------------------- ### client.login Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Logs into the account using the specified login information. It supports various authentication details and handles cookie management for persistent sessions. The `enable_ui_metrics` parameter can help reduce the risk of account suspension by executing obfuscated UI metrics. ```APIDOC ## login ### Description Logs into the account using the specified login information. `auth_info_1` and `password` are required parameters. `auth_info_2` is optional and can be omitted, but it is recommended to provide if available. The order in which you specify authentication information (auth_info_1 and auth_info_2) is flexible. ### Method Signature ```python async def login( auth_info_1: str, password: str, auth_info_2: str | None = None, totp_secret: str | None = None, cookies_file: str | None = None, enable_ui_metrics: bool = True ) -> dict: ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **auth_info_1** (str) - Required - The first piece of authentication information, which can be a username, email address, or phone number. - **auth_info_2** (str) - Optional - The second piece of authentication information, which is optional but recommended to provide. It can be a username, email address, or phone number. - **password** (str) - Required - The password associated with the account. - **totp_secret** (str) - Optional - The TOTP (Time-Based One-Time Password) secret key used for two-factor authentication (2FA). - **cookies_file** (str) - Optional - The file path used for storing and loading cookies. If the specified file exists, cookies will be loaded from it, potentially bypassing the login process. After a successful login, cookies will be saved to this file for future use. - **enable_ui_metrics** (bool) - Optional - If set to True, obfuscated ui_metrics function will be executed using js2py, and the result will be sent to the API. Enabling this may reduce the risk of account suspension. ### Request Example ```python await client.login( auth_info_1='example_user', auth_info_2='email@example.com', password='00000000' ) ``` ### Response #### Success Response (200) Returns a dictionary containing login-related information. The exact structure is not detailed in the source. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Counter Unique Elements Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Get a sorted list of all unique elements present in the Counter. ```python sorted(c) ``` -------------------------------- ### Community.join Source: https://twikit.readthedocs.io/en/latest/twikit.html Allows the current user to join the community. ```APIDOC ## Community.join ### Description Join the community. ### Method `async join() -> Community` ### Returns Community - The updated community object. ### Example ```python >>> updated_community = await community.join() ``` ``` -------------------------------- ### Get Favoriters Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/tweet.html Retrieves a list of users who have favorited a specific tweet. Supports pagination. ```APIDOC ## get_favoriters ### Description Retrieve users who favorited a specific tweet. ### Parameters #### Query Parameters - **count** (int, optional) - The maximum number of users to retrieve. Defaults to 40. - **cursor** (str, optional) - A string indicating the position of the cursor for pagination. ### Request Example ```python tweet_id = '...' favoriters = tweet.get_favoriters() print(favoriters) more_favoriters = favoriters.next() # Retrieve more favoriters. print(more_favoriters) ``` ### Response #### Success Response (200) - **Result[User]** - A list of users who favorited the tweet. ``` -------------------------------- ### Get Retweeters Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/tweet.html Retrieves a list of users who have retweeted a specific tweet. Supports pagination. ```APIDOC ## get_retweeters ### Description Retrieves users who retweeted a specific tweet. ### Parameters #### Query Parameters - **count** (int, optional) - The maximum number of users to retrieve. Defaults to 40. - **cursor** (str, optional) - A string indicating the position of the cursor for pagination. ### Request Example ```python tweet_id = '...' retweeters = tweet.get_retweeters() print(retweeters) more_retweeters = retweeters.next() # Retrieve more retweeters. print(more_retweeters) ``` ### Response #### Success Response (200) - **list[User]** - A list of User objects who retweeted the tweet. ``` -------------------------------- ### Community Class Initialization Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/community.html Initializes a Community object with data from a dictionary, extracting attributes like ID, name, member count, NSFW status, banner, and member facepile URLs. ```python [docs] class Community: """ Attributes ---------- id : :class:`str` The ID of the community. name : :class:`str` The name of the community. member_count : :class:`int` The count of members in the community. is_nsfw : :class:`bool` Indicates if the community is NSFW. members_facepile_results : list[:class:`str`] The profile image URLs of members. banner : :class:`dict` The banner information of the community. is_member : :class:`bool` Indicates if the user is a member of the community. role : :class:`str` The role of the user in the community. description : :class:`str` The description of the community. creator : :class:`User` | :class:`CommunityCreator` The creator of the community. admin : :class:`User` The admin of the community. join_policy : :class:`str` The join policy of the community. created_at : :class:`int` The timestamp of the community's creation. invites_policy : :class:`str` The invites policy of the community. is_pinned : :class:`bool` Indicates if the community is pinned. rules : list[:class:`CommunityRule`] The rules of the community. """ def __init__(self, client: Client, data: dict) -> None: self._client = client self.id: str = data['rest_id'] self.name: str = data['name'] self.member_count: int = data['member_count'] self.is_nsfw: bool = data['is_nsfw'] self.members_facepile_results: list[str] = [ i['result']['legacy']['profile_image_url_https'] for i in data['members_facepile_results'] ] self.banner: dict = data['default_banner_media']['media_info'] self.is_member: bool = data.get('is_member') self.role: str = data.get('role') self.description: str = data.get('description') if 'creator_results' in data: creator = data['creator_results']['result'] if 'rest_id' in creator: self.creator = User(client, creator) else: self.creator = CommunityCreator( b64_to_str(creator['id']).removeprefix('User:'), creator['legacy']['screen_name'], creator['legacy']['verified'] ) else: self.creator = None if 'admin_results' in data: admin = data['admin_results']['result'] self.admin = User(client, admin) else: self.admin = None self.join_policy: str = data.get('join_policy') self.created_at: int = data.get('created_at') self.invites_policy: str = data.get('invites_policy') self.is_pinned: bool = data.get('is_pinned') if 'rules' in data: self.rules: list = [ CommunityRule(i['rest_id'], i['name']) for i in data['rules'] ] else: self.rules = None ``` -------------------------------- ### Retrieve Bookmark Folders Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Fetches bookmark folders, allowing for pagination using the next cursor. Returns a Result object containing bookmark folders. ```python >>> folders = await client.get_bookmark_folders() >>> print(folders) [, ..., ] >>> more_folders = await folders.next() # Retrieve more folders ``` ```python response, _ = await self.gql.bookmark_folders_slice(cursor) slice = find_dict(response, 'bookmark_collections_slice', find_one=True)[0] results = [] for item in slice['items']: results.append(BookmarkFolder(self, item)) if 'next_cursor' in slice['slice_info']: next_cursor = slice['slice_info']['next_cursor'] fetch_next_result = partial(self.get_bookmark_folders, next_cursor) else: next_cursor = None fetch_next_result = None return Result( results, fetch_next_result, next_cursor ) ``` -------------------------------- ### Get Communities Timeline Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a timeline of tweets from communities the user is part of. Supports pagination. ```APIDOC ## async get_communities_timeline(_count : int = 20_, _cursor : str | None = None_) ### Description Retrieves tweets from communities timeline. ### Parameters #### Query Parameters - **count** (int) - Optional - The number of tweets to retrieve. Defaults to 20. - **cursor** (str | None) - Optional - The cursor for pagination. ### Returns List of retrieved tweets. ### Return Type Result[`Tweet`] ``` -------------------------------- ### Get Community Moderators with Twikit Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a list of moderators for a given community, with support for pagination. ```python async get_community_moderators(_community_id : str_, _count : int = 20_, _cursor : str | None = None_) → Result[CommunityMember][source] Retrieves moderators of a community. Parameters: * **community_id** (`str`) – The ID of the community. * **count** (`int`, default=20) – The number of moderators to retrieve. Returns: List of retrieved moderators. Return type: Result[`CommunityMember`] ``` -------------------------------- ### Upload Media - With Completion Wait Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Uploads a video file and waits for the upload process to complete. Requires `wait_for_completion=True`. ```python media_id_2 = await client.upload_media( 'media2.mp4', wait_for_completion=True ) ``` -------------------------------- ### ChainMap Initialization Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Initializes a ChainMap with the provided mappings. If no mappings are given, an empty dictionary is used. ```APIDOC ## ChainMap ### Description A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list accessible via the `maps` attribute. ### Method `__init__` ### Parameters * `*maps` (Mapping) - The mappings to group together. If none are provided, an empty dictionary is used. ### Example ```python from collections import ChainMap map1 = {'a': 1, 'b': 2} map2 = {'b': 3, 'c': 4} chain = ChainMap(map1, map2) print(chain) # Output: ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4}) ``` ``` -------------------------------- ### Get Community Members with Twikit Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves a list of members for a given community, with support for pagination. ```python async get_community_members(_community_id : str_, _count : int = 20_, _cursor : str | None = None_) → Result[CommunityMember][source] Retrieves members of a community. Parameters: * **community_id** (`str`) – The ID of the community. * **count** (`int`, default=20) – The number of members to retrieve. Returns: List of retrieved members. Return type: Result[`CommunityMember`] ``` -------------------------------- ### Execute Login Flow Tasks Source: https://twikit.readthedocs.io/en/latest/_modules/twikit/client/client.html Executes a series of tasks within the login flow, including initial guest token retrieval, flow execution with specific parameters, and SSO initialization. It also handles UI metrics collection and instrumentation if enabled. ```python await flow.execute_task(params={'flow_name': 'login'}, data={ 'input_flow_data': { 'flow_context': { 'debug_overrides': {}, 'start_location': { 'location': 'splash_screen' } } }, 'subtask_versions': { 'action_list': 2, 'alert_dialog': 1, 'app_download_cta': 1, 'check_logged_in_account': 1, 'choice_selection': 3, 'contacts_live_sync_permission_prompt': 0, 'cta': 7, 'email_verification': 2, 'end_flow': 1, 'enter_date': 1, 'enter_email': 2, 'enter_password': 5, 'enter_phone': 2, 'enter_recaptcha': 1, 'enter_text': 5, 'enter_username': 2, 'generic_urt': 3, 'in_app_notification': 1, 'interest_picker': 3, 'js_instrumentation': 1, 'menu_dialog': 1, 'notifications_permission_prompt': 2, 'open_account': 2, 'open_home_timeline': 1, 'open_link': 1, 'phone_verification': 4, 'privacy_options': 1, 'security_key': 3, 'select_avatar': 4, 'select_banner': 2, 'settings_list': 7, 'show_code': 1, 'sign_up': 2, 'sign_up_review': 4, 'tweet_selection_urt': 1, 'update_users': 1, 'upload_media': 1, 'user_recommendations_list': 4, 'user_recommendations_urt': 1, 'wait_spinner': 3, 'web_modal': 1 } }) ``` ```python await flow.sso_init('apple') ``` ```python ui_metrics_response = solve_ui_metrics( await self._ui_metrics() ) ``` ```python ui_metrics_response = '' ``` ```python await flow.execute_task({ 'subtask_id': 'LoginJsInstrumentationSubtask', 'js_instrumentation': { 'response': ui_metrics_response, 'link': 'next_link' } }) ``` ```python await flow.execute_task({ 'subtask_id': 'LoginEnterUserIdentifierSSO', 'settings_list': { 'setting_responses': [ { 'key': 'user_identifier', 'response_data': { 'text_data': {'result': auth_info_1} } } ] } }) ``` -------------------------------- ### Get Tweets by IDs Source: https://twikit.readthedocs.io/en/latest/twikit.html Retrieves multiple tweets efficiently using a list of tweet IDs. ```APIDOC ## get_tweets_by_ids ### Description Retrieve multiple tweets by IDs. ### Parameters #### Path Parameters - **ids** (list[str]) - Required - A list of tweet IDs to retrieve. ### Returns List of tweets. ### Return Type list[`Tweet`] ### Example ```python >>> tweet_ids = ['1111111111', '1111111112', '111111113'] >>> tweets = await client.get_tweets_by_ids(tweet_ids) >>> print(tweets) [, , ] ``` ``` -------------------------------- ### UserString rpartition Method Source: https://twikit.readthedocs.io/en/latest/_modules/collections.html Partitions the string at the last occurrence of a separator. Returns a tuple of three strings. ```python def rpartition(self, sep): return self.data.rpartition(sep) ```