API Reference

The following section outlines the API of pytweet.

Note

This module uses the Python logging module to log to tell you what you are doing wrong, See Logging for more info.

Clients

Client

class pytweet.Client(bearer_token, *, consumer_key=None, consumer_secret=None, access_token=None, access_token_secret=None, stream=None, callback_url=None, client_id=None, client_secret=None, use_bearer_only=False, sleep_after_ratelimit=False, verify_credentials=False)

Represents a twitter-api client for twitter api version 1.1 and 2 interface.

Parameters
  • bearer_token (Optional[str]) – The Bearer Token of the app. Uses for twitter version 2 endpoints.

  • consumer_key (Optional[str]) – The Consumer Key of the app. Users for twitter version 1.1 endpoints.

  • consumer_secret (Optional[str]) – The Consumer Key Secret of the app. Users for twitter version 1.1 endpoints.

  • access_token (Optional[str]) – The Access Token of the app. Users for twitter version 1.1 endpoints.

  • access_token_secret (Optional[str]) – The Access Token Secret of the app. Users for twitter version 1.1 endpoints.

  • stream (Optional[Stream]) – The client’s stream. Must be an instance of Stream.

  • callback_url (Optional[str]) – The oauth callback url, default to None. Makes sure the callback url is the same as the one in your application auth-settings or else it can’t create and interact with oauth related methods.

  • client_id (Optional[str]) – The client’s OAuth 2.0 Client ID from keys and tokens page.

  • client_secret (Optional[str]) – The client’s OAuth 2.0 Client Secret from keys and tokens page.

  • use_bearer_only (bool) – Indicates to only use bearer token for all methods. This mean the client is now a twitter-api-client v2 interface. Some methods are unavailable to use such as fetching trends and location, environment fetching methods, and features such as events. Some methods can be recover with OAuth 2 authorization code flow with PKCE with the correct scopes or permissions. Like users.read scope for reading users info which some methods provide a way like Client.fetch_user().

  • sleep_after_ratelimit (bool) – Indicates to sleep when your client is ratelimited, If set to True it won’t raise TooManyRequests error but it would print a message indicating to sleep, then it sleeps for how many seconds it needs to sleep, after that it continue to restart the request.

  • verify_credentials (bool) – Indicates to verify the credentials you specified, this includes consumer_key, consumer_secret, access_token, access_token_secret. make sure to specified all of them in your client, you cannot specified only one of them.

webhook

Returns the client’s main webhook, Returns None if not found.

Type

Optional[Webhook]

environment

Returns the client’s main Environment, Returns None if not found.

Type

Optional[Environment]

webhook_url_path

Returns the webhook url path, Returns None if not found.

Type

Optional[str]

New in version 1.0.0.

account(*, update=False)

Returns ClientAccount object which hold the client’s informations as a twitter user.

Parameters

update (bool) –

Indicates to update the client’s account information, setting update to True would make a request to the api and returns a new and updated data everytime. If sets to False, it will either make a request (if used the first time) or use the previous data stored in an instance variable.

New in version 1.5.0.

Returns

This method returns a ClientAccount object.

Return type

Optional[ClientAccount]

New in version 1.2.0.

me(*, update=False)

An alias to Client.account().

Parameters

update (bool) –

Indicates to update the client’s account information, setting update to True would make a request to the api and returns a new and updated data everytime. If sets to False, it will either make a request (if used the first time) or use the previous data stored in an instance variable.

New in version 1.5.0.

Returns

This method returns a ClientAccount object.

Return type

Optional[ClientAccount]

New in version 1.2.0.

event(func)

A decorator for making an event, the event will be register in the client’s internal cache.

See the Event Reference for the currently documented events.

Parameters

func (typing.Callable) – The function that execute when the event is trigger. The event must be a synchronous function. You must also put the right event name in the function’s name, See event reference for full events name.

Raises

TypeError – The function passed is a coroutine function.

New in version 1.3.5.

fetch_user(user_id)

Fetches a twitter user.

Warning

This method uses API call and might cause ratelimits if used often! There is always an alternative like Client.get_user() from the client’s internal cache.

Parameters

user_id (ID) – Represents the user ID that you wish to get info with. If you don’t have it you may use fetch_user_by_username because it only requires the user’s username.

Returns

This method returns a User object.

Return type

User

New in version 1.0.0.

fetch_user_by_username(username)

Fetches a twitter user by the user’s username.

Warning

This method uses API call and might cause ratelimits if used often! There is always an alternative like Client.get_user() from the client’s internal cache.

Parameters

username (str) – Represents the user’s username that you wish to get info. A Username usually starts with ‘@’ before any letters. If a username named @Jack, then the username argument must be ‘Jack’.

Returns

This method returns a User object.

Return type

User

New in version 1.0.0.

fetch_tweet(tweet_id, *, organic_metrics=False, promoted_metrics=False)

Fetches a tweet.

Warning

This method uses API call and might cause ratelimits if used often! There is always an alternative like Client.get_tweet() from the client’s internal cache.

Parameters
  • tweet_id (ID) – Represents the tweet ID that you wish to get info with.

  • organic_metrics (bool) –

    Whether to return an organic metrics data. Grouping of public and non-public metrics attributed to an organic context (posted and viewed in a regular manner). Requires OAuth 1.0a User Context authentication.

    versionadded:: 1.5.0

  • promoted_metrics (bool) –

    Whether to return a promoted metrics data. Grouping of public and non-public metrics attributed to a promoted context (posted or viewed as part of an Ads campaign).

    Requires OAuth 1.0a User Context authentication and that the Tweet was promoted in an Ad. Promoted metrics are not included in these counts when a Twitter user is using their own Ads account to promote another Twitter user’s Tweets.

    Promoted metrics are included in these counts when: * a Twitter user promotes their own Tweets. * in an Ads account for a specific handle, the admin for that account may add another Twitter user as an account user so this second account user can promote Tweets for the handle

    versionadded:: 1.5.0

Raises
  • ResourceNotFound – The tweet was not found

  • DisallowedResource: – Examples of why this error raises are: * If the tweet is older than 30 days and you fetch it with organic_metrics parameter. * When you set promoted_metrics to True but the tweet has not been promoted.

Returns

This method returns a Tweet object.

Return type

Tweet

New in version 1.0.0.

fetch_direct_message(event_id)

Fetches a direct message.

Warning

This method uses API call and might cause ratelimits if used often! There is always an alternative like Client.fetch_direct_message() from the client’s internal cache.

Parameters

event_id (ID) – Represents the event’s ID that you wish to get info with.

Returns

This method returns a DirectMessage object.

Return type

DirectMessage

New in version 1.2.0.

fetch_welcome_message(welcome_message_id)

Fetches a welcome message.

Parameters

welcome_message_id (ID) – Represents the welcome message ID that you wish to get info with.

Returns

This method returns WelcomeMessage object.

Return type

WelcomeMessage

New in version 1.3.5.

fetch_welcome_message_rule(welcome_message_rule_id)

Fetches a welcome message rule.

Parameters

welcome_message_rule_id (ID) – Represents the welcome message rule ID that you wish to get info with.

Returns

This method returns WelcomeMessageRule object.

Return type

WelcomeMessageRule

New in version 1.3.5.

fetch_space(space_id, *, space_host=False)

Fetches a space.

Parameters
  • space_id (ID) – Represents the space ID that you wish to get info with.

  • space_host (bool) –

    Indicates if the client is the host of the requested space. This is very useful to returns a Space object with the ‘subscriber_count’ data, if sets to False the ‘subscriber_count’ will returns None. Default to False.

    Changed in version 1.5.0.

Returns

This method returns a Space object.

Return type

Space

New in version 1.3.5.

fetch_spaces_by_title(title, state=SpaceState.live, *, space_host=False)

Fetches spaces using its title.

Parameters
  • title (ID) – The space title that you are going use for fetching the space.

  • state (SpaceState) – The type of state the space has. There are only 2 types: SpaceState.live indicates that the space is live and SpaceState.scheduled indicates the space is not live and scheduled by the host. Default to SpaceState.live,

  • space_host (bool) –

    Indicates if the client is the host of the requested space. This is very useful to returns a space with the ‘subscriber_count’ data, if sets to False the ‘subscriber_count’ will returns None. Default to False.

    Changed in version 1.5.0.

Returns

This method returns a list of Space objects.

Return type

Optional[List[Space]]

New in version 1.3.5.

fetch_list(id)

Fetches a twitter list using its id

Returns

This method returns a List object.

Return type

List

New in version 1.5.0.

fetch_all_environments()

Fetches all the client’s environments.

Returns

Returns a list of Environment objects.

Return type

Optional[List[Environment]]

New in version 1.5.0.

fetch_message_history()

Returns all Direct Messages (both sent and received) within the last 30 days. Sorted in chronological order.

Returns

This method returns a MessagePagination object.

Return type

Optional[MessagePagination]

New in version 1.5.0.

fetch_job(id)

Fetches a job.

Parameters

user_id (ID) – Represents the job’s ID that you wish to get info with.

New in version 1.5.0.

fetch_jobs(type=JobType.users, status=None)

Fetches jobs and minimize the results with the correct JobType or JobStatus.

Parameters
  • type (JobType) – The job’s type, this parameter minimize the results to only return jobs with the type you specified. Default to JobType.users().

  • status (Jobstatus) – The job’s status, this parameter minimize the results to only return jobs with the status you specified. Default to None.

New in version 1.5.0.

tweet(text=None, *, file=None, files=None, poll=None, geo=None, direct_message_deep_link=None, reply_setting=None, quote_tweet=None, reply_tweet=None, exclude_reply_users=None, media_tagged_users=None, super_followers_only=False)

Posts a tweet directly to twitter from the given parameters.

Parameters
  • text (str) – The tweet’s text, it will show up as the main text in a tweet.

  • file (Optional[File]) – Represents a single file attachment. It could be an image, gif, or video. Must be an instance of pytweet.File

  • files (Optional[List[File]]) – Represents multiple file attachments in a list. It could be an image, gif, or video. the item in the list must also be an instance of pytweet.File

  • poll (Optional[Poll]) – The poll attachment.

  • geo (Optional[Union[Geo, str]]) – The geo attachment, you can put an object that is an instance of Geo or the place ID in a string.

  • direct_message_deep_link (Optional[str]) – The direct message deep link, It will showup as a CTA(call-to-action) with button attachment.

  • reply_setting (Optional[Union[ReplySetting, str]]) – The reply setting that you can set to minimize users that can reply. If None is specified, the default is set to ‘everyone’ can reply.

  • quote_tweet (Optional[ID]) – The tweet or tweet ID you want to quote.

  • reply_tweet (Optional[Tweet, ID]) – The tweet or tweet ID you want to reply. If you have an instance of Tweet, you can use the Tweet.reply() method rather then using this method.

  • exclude_reply_users (Optional[List[User, ID]]) – A list of users or user ids to be excluded from the reply Tweet thus removing a user from a thread, if you dont want to mention a reply with 3 mentions, You can use this argument and provide the user id you don’t want to mention.

  • media_tagged_users (Optional[List[User, ID]]) – A list of users or user ids being tagged in the Tweet with Media. If the user you’re tagging doesn’t have photo-tagging enabled, their names won’t show up in the list of tagged users even though the Tweet is successfully created.

  • super_followers_only (bool) – Allows you to tweet exclusively for super followers.

Returns

This method returns a Tweet object.

Return type

Tweet

New in version 1.1.0.

Changed in version 1.5.0: Added files and media_tagged_users arguments.

create_welcome_message(*, name=None, text=None, file=None, quick_reply=None, cta=None)

Create a welcome message which you can set with WelcomeMessage.set_rule().

Parameters
  • name (Optional[str]) – A human readable name for the Welcome Message

  • text (Optional[str]) – The welcome message’s text. Please do not make this empty if you don’t want the text to be blank.

  • file (Optional[File]:) – Represents a single file attachment. It could be an image, gif, or video. It also have to be an instance of pytweet.File

  • quick_reply (Optional[QuickReply]) – The message’s QuickReply attachments.

  • cta (Optional[CTA]) – The message’s CTA attachment.

Returns

This method returns WelcomeMessage object.

Return type

WelcomeMessage

New in version 1.3.5.

create_list(name, *, description='', private=False)

Creates a new list.

Parameters
  • name (str) – The name of the List you wish to create.

  • description (str) – Description of the List.

  • private (bool) – Determine whether the List should be private, default to False.

Returns

This method returns a List object.

Return type

Optional[List]

New in version 1.5.0.

create_job(type, *, name=None, resumable=False)

Creates a Job Compliance.

Parameters
  • type (JobType) – The type of the job. There’s only 2 types of job, JobType.tweets' and :class:`JobType.users(). You can upload tweet ids if use JobType.tweets() otherwise you can use user ids. You cannot mix tweet ids with user ids!

  • name (str) – The human readable name for the Job, default to None.

  • resumable (bool) – Specifies whether to enable the upload URL with support for resumable uploads. If true, this endpoint will return a pre-signed URL with resumable uploads enabled. Default to False

Returns

This method returns Job object

Return type

Optional[Job]

New in version 1.5.0.

create_custom_profile(name, file)

Create a custom profile

Parameters
  • name (str) – The author’s custom name.

  • file (File) – The media file that’s associate with the profile.

Returns

This method returns a CustomProfile object.

Return type

CustomProfile

search_geos(query, max_result=None, *, lat=None, long=None, ip=None, granularity=Granularity.neighborhood)

Search geo-locations with the given arguments.

Parameters
  • query (str) – Free-form text to match against while executing a geo-based query, best suited for finding nearby locations by name. Remember to URL encode the query.

  • max_results (Optional[ID]) – A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many “nearby” results to return. Ideally, only pass in the number of places you intend to display to the user here.

  • lat (int) – The latitude to search around. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn’t a corresponding long parameter.

  • long (int) – The longitude to search around. The valid ranges for longitude are -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is turned off, or if there is not a corresponding lat parameter.

  • ip (ID) – An IP address. Used when attempting to fix geolocation based off of the user’s IP address.

  • granularity (str) – This is the minimal granularity of place types to return and must be one of: neighborhood, city, admin or country. If no granularity is provided for the request neighborhood is assumed. Setting this to city, for example, will find places which have a type of city, admin or country.

Returns

This method return a list of Geo objects.

Return type

List[Geo]

New in version 1.3.5.

search_trend_with_place(woeid, exclude=None)

Search trends with woeid.

Note

You can find woeid information through Location.woeid() with Client.search_trend_locations() or Client.search_trend_closest().

Parameters
  • woeid (ID) – “where on earth identifier” or WOEID, which is a legacy identifier created by Yahoo and has been deprecated. Twitter API v1.1 still uses the numeric value to identify town and country trend locations. Example WOEID locations include: Worldwide: 1 UK: 23424975 Brazil: 23424768 Germany: 23424829 Mexico: 23424900 Canada: 23424775 United States: 23424977 New York: 2459115.

  • exclude (Optional[str]) – Setting this equal to hashtags will remove all hashtags from the trends list.

Returns

This method returns a list of Trend objects.

Return type

Optional[List[Trend]]

New in version 1.5.0.

search_trend_locations()

Search locations that Twitter has trending topic information.

Returns

This method returns a list of Location objects.

Return type

Optional[List[Location]]

New in version 1.5.0.

search_trend_closest(lat, long)

Search the rend closest to the lat and long.

Parameters
  • lat (int) – If provided with a long parameter the available trend locations will be sorted by distance, nearest to furthest, to the coordinate pair. The valid ranges for longitude is -180.0 to +180.0 (West is negative, East is positive) inclusive.

  • long (int) – If provided with a lat parameter the available trend locations will be sorted by distance, nearest to furthest, to the coordinate pair. The valid ranges for longitude is -180.0 to +180.0 (West is negative, East is positive) inclusive -122.400612831116

Returns

This method returns a list of Location objects.

Return type

Optional[List[Location]]

New in version 1.5.0.

search_recent_tweet(query, *, max_results=10, start_time=None, end_time=None, since_id=None, until_id=None, sort_by_relevancy=False)

Searches tweet from the last seven days that match a search query.

Parameters
  • query (str) – One query for matching Tweets.

  • max_results (int) – The maximum number of search results to be returned by a request. A number between 10 and 100. By default, the method will returns 10 results.

  • start_time (Optional[datetime.datetime]) – This will make sure the tweets created datetime is after that specific time.

  • end_time (Optional[datetime.datetime]) – This will make sure the tweets created datetime is before that specific time.

  • since_id (Optional[ID]) – Returns results with a Tweet ID greater than (that is, more recent than) the specified ‘since’ Tweet ID. Only the 3200 most recent Tweets are available. The result will exclude the since_id. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available.

  • until_id (Optional[ID]) – Returns results with a Tweet ID less less than (that is, older than) the specified ‘until’ Tweet ID. Only the 3200 most recent Tweets are available. The result will exclude the until_id. If the limit of Tweets has occurred since the until_id, the until_id will be forced to the most recent ID available.

  • sort_by_relevancy (bool) – This parameter is used to specify the order in which you want the Tweets returned. If sets to True, tweets will be order by relevancy, else it sets to recency. Default to False.

Returns

This method returns a list of Tweet objects.

Return type

Union[TweetPagination, list]

New in version 1.5.0.

search_all_tweet(query, *, max_results=10, start_time=None, end_time=None, since_id=None, until_id=None, sort_by_relevancy=False)

Searches all tweet from the complete history of public Tweets matching a search query; since the first Tweet was created March 26, 2006. Only available to those users who have been approved for Academic Research access.

Parameters
  • query (str) – One query for matching Tweets.

  • max_results (int) – The maximum number of search results to be returned by a request. A number between 10 and 100. By default, the method will returns 10 results.

  • start_time (Optional[datetime.datetime]) – This will make sure the tweets created datetime is after that specific time.

  • end_time (Optional[datetime.datetime]) – This will make sure the tweets created datetime is before that specific time.

  • since_id (Optional[ID]) – Returns results with a Tweet ID greater than (that is, more recent than) the specified ‘since’ Tweet ID. Only the 3200 most recent Tweets are available. The result will exclude the since_id. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available.

  • until_id (Optional[ID]) – Returns results with a Tweet ID less less than (that is, older than) the specified ‘until’ Tweet ID. Only the 3200 most recent Tweets are available. The result will exclude the until_id. If the limit of Tweets has occurred since the until_id, the until_id will be forced to the most recent ID available.

  • sort_by_relevancy (bool) – This parameter is used to specify the order in which you want the Tweets returned. If sets to True, tweets will be order by relevancy, else it sets to recency. Default to False.

Returns

This method returns a list of Tweet objects.

Return type

Union[TweetPagination, list]

New in version 1.5.0.

get_user(user_id)

Gets a user through the client internal user cache. Return None if the user is not in the cache.

Note

Users will get cache with several conditions:
  • Users return from a method such as Client.fetch_user().

  • The client interacts with other users such as sending a message to another user through User.send() and many more

  • The subscription users interact with other users such as sending message from the subscription user to another user (This condition only applies if you use Client.listen() at the very end of the file)

Parameters

user_id (ID) – The ID of a user that you want to get.

Raises

ValueError: – Raised when the user_id argument is not an integer or a string of digits.

Returns

This method returns a User object or None if the user was not found.

Return type

User

New in version 1.5.0.

get_tweet(tweet_id)

Gets a tweet through the client internal tweet cache. Return None if the tweet is not in the cache.

Note

Tweets will get cache with several conditions:
  • Tweets send by the client.

  • Tweets send by the subscription users (This condition only applies if you use Client.listen() at the very end of the file).

  • Tweets return from a method such as: Client.fetch_tweet()

Parameters

tweet_id (ID) – The ID of a tweet that you want to get.

Raises

ValueError: – Raised when the tweet_id argument is not an integer or a string of digits.

Returns

This method returns a Tweet object or None if the tweet was not found.

Return type

Tweet

New in version 1.2.0.

get_direct_message(event_id)

Get a direct message through the client message cache. Returns None if the message is not in the cache.

Note

Messages will get cache with several conditions:
  • Messages send by the client.

  • Messages return from a method such as: Client.fetch_direct_message()

  • The subscription users interact with other users such as sending message from the subscription user to another user (This condition only applies if you use Client.listen() at the very end of the file).

Parameters

event_id (ID) – The event ID of the Direct Message event that you want to get.

Returns

This method returns a DirectMessage object.

Return type

DirectMessage

New in version 1.2.0.

stream(*, dry_run=False)

Stream realtime in twitter for tweets! This method use the stream argument in request.get() for streaming in one of the stream endpoint that twitter api provides. If you want to use this method, make sure to provides the stream kwarg in your Client instance and make an on_stream event to get the stream’s tweet data and connection, example:

import pytweet

stream = pytweet.Stream()
stream.add_rule("pytweet") #this make sure to only return tweets that has pytweet keyword in it.

client = pytweet.Client(
    ...
    stream=stream
)

@client.event
def on_stream(tweet, connection):
    ... #Do what you want with tweet and stream connection you got.

client.stream()

You can also add rules and specified which tweets must be retrieve via the tweet’s characteristic features.

Parameters

dry_run (bool) – Indicates if you want to debug your rule’s operator syntax.

New in version 1.3.5.

listen(app, *, url, env_label, sleep_for=0.5, ngrok=False, **kwargs)

Listen to upcoming account activity events send by twitter to your flask’s url. You can use the rest of Flask arguments like port or host via the kwargs argument.

Note

For the time being, we only support Flask for the app argument! If you want to use your own web application url, consider using Client.listen_to().

Parameters
  • app (flask.Flask) – Your flask application.

  • url (str) – a kwarg that the webhook url aka your flask’s web application url. This completely up to you, e.g https://your-website.domain/webhook/twitter.

  • env_label (str) – a kwarg that the environment’s label.

  • sleep_for (Union[int, float]) – a kwarg that ensure the flask application is running before triggering a CRC by sleeping after starting a thread. Default to 0.50.

  • ngrok (bool) – a kwarg that indicates to use ngrok for tunneling your localhost. This usually uses for users that use localhost url.

  • disabled_log (bool) – A kwarg that indicates to disable flask’s log so it does not print the request process in your terminal, this also will disable werkzeug log.

  • make_new (bool) – A kwarg indicates to make a new webhook url when the api can’t find the url passed. Default to True.

New in version 1.5.0.

listen_to(url, *, env_label, ngrok=False, make_new=True)

Listen to upcoming account activity events send by twitter to a web application url. This method differ from Client.listen(), this method doesn’t use the flask’s web application url, rather your web application url. This is good for people that want to implement their web application outside flask.

Warning

With this method, you have to make your own CRC and event handlers in your web application. For the time being, the documentation doesn’t provides information for the handlers, either go to twitter documentation about account activity api or wait until we write the documentation.

Parameters
  • url (str) – The webhook url. This completely up to you, e.g https://your-website.domain/webhook/twitter.

  • env_label (str) – The environment’s label.

  • ngrok (bool) – indicates to use ngrok for tunneling your localhost. This is usually use for users that use localhost url.

  • make_new (bool) – A kwarg indicates to make a new webhook url when the api can’t find the url passed. Default to True.

New in version 1.5.0.

Environment

Environment

class pytweet.Environment

Represents a dev environment to use one of the subscription APIs (Account Activity API or events etc)

New in version 1.5.0.

property name

The environment name/label.

New in version 1.5.0.

Type

str

property label

An alias to Environment.name()

New in version 1.5.0.

Type

str

property webhooks

Returns a list of webhooks.

New in version 1.5.0.

Type

List[Webhook]

add_user_subscription(client)

Add a new user subscription to the environment, which is the client (that you passed in the argument) itself.

Note

If you want to add other user subscription, use OauthSession.create_oauth_url() to generate an oauth url and get the oauth token and verifier, then use OauthSession.post_oauth_token() to post the oauth token.

New in version 1.5.0.

add_my_subscription()

Add a new user subscription to the environment, which is the client WHO made the environment request. Use add_user_subscription() to add other user subscription. This method only add the client WHO made the fetch environment request.

New in version 1.5.0.

register_webhook(url)

Register your WebHook with your WebApp’s url that you develop. Before this, you need to develop, deploy and host a WebApp that will receive Twitter webhook events. You also need to perform a Twitter Challenge Response Check (CRC) GET request and responds with a properly formatted JSON response.

Parameters

url (str) – Your WebApp url that you want to register as the WebHook url. Twitter will send account events to this url as an http post request.’

Returns

This method returns a Webhook object.

Return type

Webhook

New in version 1.5.0.

fetch_all_subscriptions()

Returns a list of the the current users subscriptions from the environment.

Returns

This method returns a list of int object.

Return type

List[int]

New in version 1.5.0.

Webhook

class pytweet.Webhook

Represents a webhook for an environment. This webhook belongs to an environment and have a webhook url for sending account activity events.

New in version 1.5.0.

property id

Returns the webhook unique id.

New in version 1.5.0.

Type

int

property url

Returns the webhook url.

New in version 1.5.0.

Type

str

property valid

Returns True if the webhook is valid else False.

New in version 1.5.0.

Type

bool

property environment

Returns an environment where the webhook belongs to.

New in version 1.5.0.

Type

Environment

property env

An alias to Webhook.environment()

New in version 1.5.0.

Type

Environment

property created_at

Returns a datetime.datetime object with the webhook’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

delete()

Delete the webhook.

Returns

Returns the webhook object with the valid set to False.

Return type

Webhook

New in version 1.5.0.

trigger_crc()

Trigger a challenge-response-checks to enable Twitter to confirm the ownership of the WebApp receiving webhook events. Will return True if its successful else False.

Returns

This method returns a bool object.

Return type

bool

New in version 1.5.0.

Twitter Objects

These following objects are not meant to be create as an instance rather its for knowledge of what you can do with them.

User

class pytweet.User

Represents a user in Twitter. User is an identity in twitter, its very interactive. Can send message, post a tweet, and even send messages to other user through Dms.

x == y

Check if one user id is equal to another.

x != y

Check if one user id is not equal to another.

str(x)

Get the user’s name.

property name

Return the user’s name.

Type

str

property username

Return the user’s username.

Type

str

property id

Return the user’s id.

Type

int

property description

Return the user’s description.

Type

str

property bio

an alias to User.description().

Type

str

property mention

Return the user mention format.

Type

str

property pinned_tweet

Returns the user’s pinned tweet. Returns None if the user dont have one.

New in version 1.5.0.

Type

Optional[Tweet]

property url

Return url that associated with the user profile.

Type

str

property profile_url

Return the user’s profile url.

Type

str

property profile_image_url

Optional[str] Return the user profile image url.

property verified

Return True if the user is verified account, else False.

Type

bool

property protected

Return True if the user is protected, else False.

Type

bool

property private

An alias to User.protected().

Type

bool

property location

Return the user’s location.

Type

str

property created_at

Returns a datetime.datetime object with the user’s account date.

Type

Optional[datetime.datetime]

property follower_count

Returns total of followers that the user has.

Type

Optional[int]

property following_count

Returns total of following that the user has.

Type

Optional[int]

property tweet_count

Returns total of tweet that the user has.

Type

Optional[int]

property listed_count

Returns total of listed that the user has.

Type

Optional[int]

send(text, *, file=None, custom_profile=None, quick_reply=None, cta=None)

Send a message to the user.

Parameters
  • text (str) – The text that will be send to that user.

  • file (Optional[File]) – Represents a single file attachment. It could be an image, gif, or video. It also have to be an instance of pytweet.File.

  • custom_profile (Optional[CustomProfile]) – The custom profile attachment.

  • quick_reply (Optional[QuickReply]) – The QuickReply attachment that will be send to a user.

  • cta (Optional[CTA]) – cta or call-to-actions is use to make an action whenever a user ‘call’ something, a quick example is buttons.

Returns

This method return a DirectMessage object.

Return type

DirectMessage

New in version 1.1.0.

follow()

Follows the User.

Returns

This method return a RelationFollow object.

Return type

RelationFollow

New in version 1.1.0.

unfollow()

Unfollows the User.

Returns

This method return a RelationFollow object.

Return type

RelationFollow

New in version 1.1.0.

block()

Blocks the user.

New in version 1.2.0.

unblock()

Unblocks the user.

New in version 1.2.0.

mute()

Mutes the user.

New in version 1.2.5.

unmute()

Unmutes the user.

New in version 1.2.5.

report(*, block=True)

Reports the user as a spam account to twitter.

Parameters

block (bool) – Indicates to perform a block action to the user if set to True. Default to True.

New in version 1.3.5.

trigger_typing()

Trigger the typing animation in the user’s dm. W ill stop when the client decide to send a message when the typing animation is playing or in couple of seconds.

New in version 1.3.5.

fetch_followers()

Fetches users from the user’s followers list then paginate it .

Returns

This method returns a UserPagination object.

Return type

Optional[UserPagination]

New in version 1.3.5.

fetch_following()

Fetches users from the user’s following list then paginate it.

Returns

This method returns a UserPagination object.

Return type

Optional[UserPagination]

New in version 1.3.5.

fetch_blockers()

Fetches users from the user’s block list then paginate it.

Returns

This method returns a UserPagination object.

Return type

Optional[UserPagination]

New in version 1.5.0.

fetch_muters()

Fetches users from the user’s mute list then paginate it.

Returns

This method returns a UserPagination object.

Return type

Optional[UserPagination]

New in version 1.5.0.

fetch_timelines(*, start_time=None, end_time=None, since_id=None, until_id=None, mentioned=False, exclude=None)

Fetches the user timelines, this can be timelines where the user got mention or a normal tweet timelines.

Parameters
  • start_time (Optional[datetime.datetime]) – This will make sure the tweets created datetime is after that specific time.

  • end_time (Optional[datetime.datetime]) – This will make sure the tweets created datetime is before that specific time.

  • since_id (Optional[ID]) – Returns results with a Tweet ID greater than (that is, more recent than) the specified ‘since’ Tweet ID. Only the 3200 most recent Tweets are available. The result will exclude the since_id. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available.

  • until_id (Optional[ID]) – Returns results with a Tweet ID less less than (that is, older than) the specified ‘until’ Tweet ID. Only the 3200 most recent Tweets are available. The result will exclude the until_id. If the limit of Tweets has occurred since the until_id, the until_id will be forced to the most recent ID available.

  • mentioned (bool) – Indicates if only mentioned timelines return if set to True, else it will returns a normal tweet timelines. Default to False.

  • exclude (str) – Specified which tweet type should not be returns, you can set it to:’retweets,replies’ or ‘retweets’ or ‘replies’.

Returns

This method returns a TweetPagination objects or an empty list if none founded.

Return type

Union[TweetPagination, list]

New in version 1.3.5.

fetch_liked_tweets()

Fetches tweets that’s been liked by the user.

New in version 1.5.0.

fetch_pinned_tweet()

Fetches the user’s pinned tweet, consider using this method if User.pinned_tweet() returns None.

Returns

This method returns a Tweet object.

Return type

Optional[Tweet]

fetch_lists()

Fetches the user’s lists

Returns

This method returns a list of List objects.

Return type

Optional[List[List]]

New in version 1.5.0.

fetch_pinned_lists()

Fetches the user’s pinned lists, returns an empty list if not found

Returns

This method returns a list of List objects.

Return type

Optional[List[List]]

New in version 1.5.0.

fetch_list_memberships()

Fetches all lists the user is a member of.

Returns

This method returns a list of List objects.

Return type

Optional[List[List]]

New in version 1.5.0.

fetch_followed_lists()

Fetches the user’s followed lists.

New in version 1.5.0.

Tweet

class pytweet.Tweet

Represents a tweet message from Twitter. A Tweet is any message posted to Twitter which may contain photos, videos, links, and text. This class inherits Message,

x == y

Check if one tweet id is equal to another.

x != y

Check if one tweet id is not equal to another.

str(x)

Get the Tweet’s text.

New in version 1.0.0.

property author

Returns a user (object) who posted the tweet.

Type

Optional[User]

property possibly_sensitive

Returns True if the tweet is possible sensitive to some users, else False.

Type

bool

property sensitive

An alias to Tweet.possibly_sensitive().

Type

bool

property created_at

Returns a datetime.datetime object when the tweet was created.

Type

datetime.datetime

property deleted_at

Returns a datetime.datetime object when the tweet was deleted. Returns None when the tweet is not deleted.

Note

This property can only returns datetime.datetime object through a tweet object from on_tweet_delete event.

Type

Optional[datetime.datetime]

property source

Returns the source of the tweet. e.g if you post a tweet from a website, the source is gonna be ‘Twitter Web App’

Type

str

property reply_setting

Returns a ReplySetting object with the tweet’s reply setting. If everyone can reply, this method return ReplySetting.everyone.

Type

ReplySetting

property raw_reply_setting

Returns the raw reply setting value. If everyone can replied, this method return ‘Everyone’.

Type

str

property lang

Returns the tweet’s lang, if its english it return en.

Type

str

property conversation_id

All replies are bind to the original tweet, this property returns the tweet’s id if the tweet is a reply tweet else it returns None.

Type

Optional[int]

property url

Get the tweet’s url.

New in version 1.1.0.

Changed in version 1.5.0: Returns None if the author is invalid or the tweet doesn’t have id.

Type

Optional[str]

property mentions

Returns a list of User objects that were mentioned in the tweet or an empty list / [] if no users were mentioned.

New in version 1.1.3.

Changed in version 1.5.0: Now returns a list of User objects rather then a list of str objects.

Type

Optional[List[User]]

property poll

Returns a Poll object with the tweet’s poll.

New in version 1.1.0.

Type

Poll

property medias

Returns a list of media(s) in a tweet.

New in version 1.1.0.

Type

Optional[List[Media]]

property reference_user

Returns the referenced user. This can means:

The tweet is a retweet, which means the method returns the retweeted tweet’s author. The tweet is a quote tweet(retweet with comments), which means the method returns the quoted tweet’s author. The tweet is a reply tweet, which means the method returns the replied tweet’s author.

New in version 1.5.0.

Type

Optional[User]

property reference_tweet

Returns the tweet’s parent tweet or the referenced tweet. This can mean the parent tweet of the requested tweet is:

A retweeted tweet (The child Tweet is a Retweet), A quoted tweet (The child Tweet is a Retweet with comment, also known as Quoted Tweet), A replied tweet (The child Tweet is a reply tweet).

New in version 1.5.0.

Type

Optional[Tweet]

property embeds

Returns a list of Embedded urls from the tweet

New in version 1.1.3.

Type

List[Embed]

property like_count

Returns the total of likes in the tweet.

Type

Optional[int]

property retweet_count

Returns the total of retweetes in the tweet.

Type

Optional[int]

property reply_count

Returns the total of replies in the tweet.

Type

Optional[int]

property quote_count

Returns the total of quotes in the tweet.

Type

Optional[int]

property non_public_metrics

The tweet’s metrics that are not available for anyone to view on Twitter, such as impressions_count and video view quartiles.

New in version 1.5.0.

Type

Optional[OrganicTweetMetrics]

property organic_metrics

The tweet’s metrics in organic context (posted and viewed in a regular manner), such as impression_count, user_profile_clicks and url_link_clicks.

New in version 1.5.0.

Type

Optional[OrganicTweetMetrics]

property promoted_metrics

The tweet’s metrics in promoted context (posted or viewed as part of an Ads campaign), such as impression_count, user_profile_clicks and url_link_clicks.

New in version 1.5.0.

Type

Optional[PromotedTweetMetrics]

like()

Like the tweet.

Returns

This method returns a RelationLike object.

Return type

Optional[RelationLike]

New in version 1.2.0.

unlike()

Unlike the tweet.

Returns

This method returns a RelationLike object.

Return type

RelationLike

New in version 1.2.0.

retweet()

Retweet the tweet.

Returns

This method returns a RelationRetweet object.

Return type

RelationRetweet

New in version 1.2.0.

unretweet()

Unretweet the tweet.

Returns

This method returns a RelationRetweet object.

Return type

RelationRetweet

New in version 1.2.0.

delete()

Delete the client’s tweet.

Note

You can only delete the client’s tweet.

New in version 1.2.0.

reply(text=None, *, file=None, files=None, geo=None, direct_message_deep_link=None, reply_setting=None, exclude_reply_users=None, media_tagged_users=None)

Post a tweet to reply to the tweet present by the tweet’s id. Returns a Tweet object or Message if the tweet is not found in the cache.

Note

Note that if the tweet is a retweet you cannot reply to that tweet, it might not raise an error but it will post the tweet has a normal tweet rather then a reply tweet and it ping the Tweet.author.

Parameters
  • text (str) – The tweet’s text, it will show up as the main text in a tweet.

  • file (Optional[File]) – Represents a single file attachment. It could be an image, gif, or video. It also have to be an instance of pytweet.File

  • files (Optional[List[File]]) – Represents multiple file attachments in a list. It could be an image, gif, or video. the item in the list must also be an instance of pytweet.File

  • geo (Optional[Union[Geo, str]]) – The geo attachment, you can put an object that is an instance of Geo or the place ID in a string.

  • direct_message_deep_link (Optional[str]) – The direct message deep link, It will showup as a CTA(call-to-action) with button attachment. Example of direct message deep link:

  • reply_setting (Optional[Union[ReplySetting, str]]) – The reply setting that you can set to minimize users that can reply. If None is specified, the default is set to ‘everyone’ can reply.

  • exclude_reply_users (Optional[List[User]]) – A list of users or user ids to be excluded from the reply Tweet thus removing a user from a thread, if you dont want to mention a reply with 3 mentions, You can use this argument and provide the user id you don’t want to mention.

  • media_tagged_users (Optional[List[User]]) – A list of users or user ids being tagged in the Tweet with Media. If the user you’re tagging doesn’t have photo-tagging enabled, their names won’t show up in the list of tagged users even though the Tweet is successfully created.

Returns

Returns a Tweet object or Message object if the tweet is not found in the cache.

Return type

Union[Tweet, Message]

New in version 1.2.5.

hide()

Hide a reply tweet.

Returns

This method returns a RelationHide object.

Return type

RelationHide

New in version 1.2.5.

property id

Returns the message’s id, or if its a direct message it returns an event id.

New in version 1.2.0.

Type

int

property text

Returns the message’s text.

New in version 1.2.0.

Type

str

property type

Returns the message’s type.

New in version 1.2.0.

Type

MessageTypeEnum

unhide()

Unhide a hide reply.

Returns

This method returns a RelationHide object.

Return type

RelationHide

New in version 1.2.5.

fetch_retweeters()

Returns a pagination object with the users that retweeted the tweet.

Returns

This method returns a UserPagination object.

Return type

Optional[UserPagination]

New in version 1.1.3.

fetch_likers()

Returns a pagination object with the users that liked the tweet.

Returns

This method returns a UserPagination object.

Return type

Optional[UserPagination]

New in version 1.1.3.

fetch_quoted_tweets()

Returns a pagination object for tweets that quoted the tweet

Returns

This method returns TweetPagination or an empty list if the tweet does not contain any quoted tweets.

Return type

Optional[TweetPagination]

New in version 1.5.0.

Space

class pytweet.Space

Represents a twitter space.

New in version 1.3.5.

property title

The space’s title.

New in version 1.3.5.

Type

str

property id

The space’s unique id.

New in version 1.3.5.

Type

str

property raw_state

The raw space’s state in a string.

New in version 1.3.5.

Type

str

property state

The type of the space’s state.

New in version 1.3.5.

Type

SpaceState

property lang

The space’s language.

New in version 1.3.5.

Type

str

property created_at

Returns a datetime.datetime object with the space’s created datetime.

New in version 1.3.5.

Type

datetime.datetime

property started_at

Returns a datetime.datetime object with the space’s started time. Only available if the space has started.

New in version 1.3.5.

Type

Optional[datetime.datetime]

property updated_at

Returns a datetime.datetime object with the space’s last update to any of this Space’s metadata, such as the title or scheduled time. Only available if the space has started.

New in version 1.3.5.

Type

Optional[datetime.datetime]

property ticketed

Returns a bool indicate if the space is ticketed.

Returns

This method returns a bool object.

Return type

bool

New in version 1.5.0.

property topics

Returns a list of the space’s topics, returns None if the space has no topic

New in version 1.5.0.

Type

Optional[List[Topic]]

property participant_count

Returns the current number of users in the Space, including Hosts and Speakers.

New in version 1.5.0.

Type

int

property subscriber_count

Returns the number of people who set a remainder to this Space. This requires you to authenticate the request using the Access Token of the creator of the requested Space aka using OAuth 2.0 Authorization Code with PKCE.

New in version 1.5.0.

Type

Optional[int]

fetch_creator()

Fetches the creator’s using the id.

Returns

This method returns a User object.

Return type

User

New in version 1.3.5.

Changed in version 1.5.0: Made as a function that returns User.

fetch_invited_users()

Fetches the invited users. Usually, users in this list are invited to speak via the Invite user option and have a Speaker role when the Space starts. Returns None if there isn’t invited users.

Returns

This method returns a list of users or an empty list if not found.

Return type

Optional[List[User]]

New in version 1.3.5.

Changed in version 1.5.0: Made as a function that returns a list of User.

fetch_hosts()

Fetches the space’s hosts.

Returns

Returns a list of User.

Return type

Optional[List[User]]

New in version 1.3.5.

Changed in version 1.5.0: Made as a function that returns a list of User.

fetch_tweets()

Fetches users who purchased a ticket to the space. This requires you to authenticate the request using the Access Token of the creator of the requested Space aka using OAuth 2.0 Authorization Code with PKCE.

Returns

This method returns a list of Tweet objects or an empty list.

Return type

Optional[List[Tweet]]

New in version 1.5.0.

fetch_buyers()

Fetches users who purchased a ticket to the space. This requires you to authenticate the request using the Access Token of the creator of the requested Space aka using OAuth 2.0 Authorization Code with PKCE.

Returns

This method returns a list of users.

Return type

Union[List[User], list]

New in version 1.5.0.

is_ticketed()

An alias to Space.ticketed().

Returns

This method returns a bool object.

Return type

bool

New in version 1.3.5.

Changed in version 1.5.0: Made as an alias to Space.ticketed().

List

pytweet.List

alias of List

Job

class pytweet.Job

Represents a job compliance.

New in version 1.5.0.

property name

Returns the job’s name

New in version 1.5.0.

Type

str

property id

Returns the job’s id

New in version 1.5.0.

Type

id

property resumable

Returns True if the job is esumable otherwise False.

New in version 1.5.0.

Type

bool

property download_url

Returns the job’s download url.

New in version 1.5.0.

Type

str

property upload_url

Returns the job’s upload url.

New in version 1.5.0.

Type

str

property type

Returns JobType with the job’s type.

New in version 1.5.0.

Type

JobType

property status

Returns JobStatus with the job’s status.

New in version 1.5.0.

Type

JobStatus

property created_at

Returns a datetime.datetime object with the job’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property download_expires_at

Returns a datetime.datetime object which the download URL will be available (usually seven days from the request time).

New in version 1.5.0.

Type

datetime.datetime

property upload_expires_at

Returns a datetime.datetime object which the upload URL will be available (usually seven days from the request time).

New in version 1.5.0.

Type

datetime.datetime

upload_file(path_to_filename)

Upload a txt file to Job.upload_url().

Parameters

path_to_filename (str) – Path to the filename that you want to upload.

New in version 1.5.0.

get_download_result()

Get the download result of the job. You can only get the result if the job has a complete status, check Job.status() to check the job’s status.

Returns

This method returns a list of JobResult objects.

Return type

Optional[List[JobResult]]

New in version 1.5.0.

ClientAccount

class pytweet.ClientAccount

Represents the client’s account. This inherits User object. This class unlocks methods that you can only use for the authenticated user (the client).

New in version 1.5.0.

update_settings(*, lang=None, enabled_sleep_time=None, start_sleep_time=None, end_sleep_time=None, timezone=None, location=None)

Updates the user settings.

Parameters
  • lang (Optional[str]) – The new language replacing the old one.

  • enabled_sleep_time (Optional[bool]) – Indicates to enabled sleep time.

  • start_sleep_time (Optional[int]) – The hour that sleep time should begin if it is enabled. Must be an instance of datetime.datetime.

  • end_sleep_time (Optional[int]) – The hour that sleep time should end if it is enabled. Must be an instance of datetime.datetime.

  • timezone (Optional[Timezone]) – The new timezone replacing the old one. Must be an instance of Timezone (e.g Timezone.jakarta or Timezone.paris)

  • location (Optional[Location, int]) – The Yahoo! Where On Earth ID to use as the user’s default trend location. Global information is available by using 1 as the WOEID. Must be an instance of Location or the woeid in int.

New in version 1.5.0.

fetch_settings()

Fetches the user settings.

New in version 1.5.0.

update_profile(*, name=None, description=None, image=None, location=None, profile_url=None, profile_link_color=None)

Updates the client profile information from the given arguments.

Parameters
  • name (Optional[str]) – The new name replacing the client’s oldname. Note that this isn’t going to update the username.

  • description (Optional[str]) – The new description that you want to replace with the old version.

  • image (Optional[File]) – The new profile image that you want to replace with the old version. Must be an instance of File.

  • location (Optional[Geo]) – The new location you want to replace with the old version. Must be an instance of Geo or the fullname of geo. You use Geo.fullname() to get the fullname.

  • profile_url (Optional[str]) – URL associated with the profile. Will be prepended with http:// if not present.

  • profile_link_color (Optional[str]) – Sets a hex value that controls the color scheme of links used on the authenticating user’s profile page on twitter.com. This must be a valid hexadecimal value, and may be either three or six characters (ex: F00 or FF0000 in string). If you specified integer instead of string, the process will use hex() function to change the int value to a hex value.

Returns

Returns a updated client’s account object.

Return type

ClientAccount

New in version 1.5.0.

update_profile_banner(*, banner, width=0, height=0, offset_left=0, offset_top=0)

Updates the profile banner.

Parameters
  • banner (File) – The new banner to replace the old one. Must be an instance of File.

  • width (int) – The width of the preferred section of the image being uploaded in pixels. Use with height , offset_left , and offset_top to select the desired region of the image to use.

  • height (int) – The height of the preferred section of the image being uploaded in pixels. Use with width , offset_left , and offset_top to select the desired region of the image to use.

  • offset_left (int) – The number of pixels by which to offset the uploaded image from the left. Use with height , width , and offset_top to select the desired region of the image to use.

  • offset_top (int) – The number of pixels by which to offset the uploaded image from the top. Use with height , width , and offset_left to select the desired region of the image to use.

New in version 1.5.0.

remove_profile_banner()

Remove the user profile banner.

New in version 1.5.0.

Message

class pytweet.Message

Represents the base Message of all Message types in Twitter.

New in version 1.2.0.

property text

Returns the message’s text.

New in version 1.2.0.

Type

str

property id

Returns the message’s id, or if its a direct message it returns an event id.

New in version 1.2.0.

Type

int

property type

Returns the message’s type.

New in version 1.2.0.

Type

MessageTypeEnum

DirectMessage

class pytweet.DirectMessage

Represents a Direct Message in Twitter. This class inherits Message.

New in version 1.2.0.

property event_type

Returns the message event type.

New in version 1.2.0.

Type

MessageEventTypeEnum

property recipient

Returns the user that received the direct message.

New in version 1.2.0.

Type

User

property sender

Returns the user that sent the direct message.

New in version 1.5.0.

Type

User

property author

An alias to DirectMessage.sender()

New in version 1.5.0.

Type

User

property application_info

Returns the direct messages’s source application info if there is, else it return None.

New in version 1.5.0.

Type

ApplicationInfo

property created_at

Returns the time when the Direct Message event was created.

New in version 1.2.0.

Type

datetime.datetime

property hashtags

Returns the messages’s hashtags.

New in version 1.2.0.

Type

List[Hashtag]

property symbols

Returns the messages’s symbols.

New in version 1.2.0.

Type

List[Symbol]

property mentions

Returns the messages mentioned users.

New in version 1.2.0.

Type

List[UserMention]

property urls

Returns the message’s urls.

New in version 1.2.0.

Type

List[Url]

property quick_reply

Returns the quick reply attachment in a message, if none found it return None.

New in version 1.3.5.

Type

Optional[QuickReply]

property quick_reply_response

Returns the metadata of the quick reply option that the author clicked.

New in version 1.5.0.

Type

Optional[str]

property cta

Returns the message’s cta attachment.

New in version 1.3.5.

Type

Optional[CTA]

property initiated_via

Returns InitiatedVia object which provides a way to track how a conversation starts. For example, if a welcome message was used then InitiatedVia.welcome_message_id() would returns the welcome message id that was used in that conversation.

New in version 1.5.0.

Type

Optional[InitiatedVia]

delete()

Delete the direct message.

New in version 1.1.0.

mark_as_read()

Mark the DirectMessage as read, it also mark other messages before the DirectMessage was sent as read.

New in version 1.3.5.

property id

Returns the message’s id, or if its a direct message it returns an event id.

New in version 1.2.0.

Type

int

property text

Returns the message’s text.

New in version 1.2.0.

Type

str

property type

Returns the message’s type.

New in version 1.2.0.

Type

MessageTypeEnum

WelcomeMessage

class pytweet.WelcomeMessage

Represents a Welcome Message in a Direct Message. This class inherits Message.

New in version 1.3.5.

property name

Returns the welcome message’s name.

New in version 1.3.5.

Type

str

property created_at

Returns the welcome message created date.

New in version 1.3.5.

Type

datetime.datetime

set_rule()

Set a new Welcome Message Rule that determines which Welcome Message will be shown in a given conversation. Returns the created rule if successful.

New in version 1.3.5.

update(*, text=None, file=None, quick_reply=None, cta=None)

Updates the Welcome Message, you dont need to use set_rule again since this update your default welcome message.

Parameters
  • text (Optional[str]) – The welcome message main text

  • file (Optional[File]:) – Represents a single file attachment. It could be an image, gif, or video. It also have to be an instance of pytweet.File

  • quick_reply (Optional[QuickReply]) – The message’s QuickReply attachments.

  • cta (Optional[CTA]) – The message’s CTA attachment.

Returns

Returns your WelcomeMessage instance.

Return type

WelcomeMessage

New in version 1.3.5.

delete()

Delete the Welcome Message.

New in version 1.3.5.

property id

Returns the message’s id, or if its a direct message it returns an event id.

New in version 1.2.0.

Type

int

property text

Returns the message’s text.

New in version 1.2.0.

Type

str

property type

Returns the message’s type.

New in version 1.2.0.

Type

MessageTypeEnum

WelcomeMessageRule

class pytweet.WelcomeMessageRule

Represents a Welcome Message Rule in a Direct Message. This object is returns by WelcomeMessage.set_rule or client.fetch_welcome_message_rules, it determines which Welcome Message will be shown in a given conversation. This class inherits Message.

New in version 1.3.5.

property welcome_message_id

Returns the welcome message’s id.

New in version 1.3.5.

Type

clasD`

property created_at

Returns a datetime.datetime object with the WelcomeMessageRule created time.

New in version 1.3.5.

Type

datetime.datetime

delete()

Delete the Welcome Message Rule.

New in version 1.3.5.

fetch_welcome_message()

A method for fetching the welcome message rule’s welcome message. An equivalent to Client.fetch_welcome_message().

Returns

This method returns a WelcomeMessage object.

Return type

Optional[WelcomeMessage]

New in version 1.5.0.

Twitter Dataclass

These following section documented objects derive from dataclass folder and use dataclasses.dataclass decorator. The following objects are not meant to be create as an instance rather its for knowledge of what you can do with them.

ApplicationInfo

class pytweet.ApplicationInfo(name, id, url)

Represents an application’s info.

New in version 1.5.0.

Attachments Objects

class pytweet.PollOption(label, position=0, votes=0)

Represents an Option for Poll. You can add an option to a poll using Poll.add_option().

New in version 1.3.5.

class pytweet.Option(label, description, metadata)

Represents an Option object for QuickReply. You can add an Option using QuickReply.add_option().

New in version 1.3.5.

class pytweet.Button(label, type, url, tco_url=None)

Represents a Button object. Button is an attachment that you can attach via CTA.add_button().

New in version 1.3.5.

Locations Objects

class pytweet.Location(country, country_code, name, parent_id, place_type, url, woeid)

Represents a Location that Twitter has trending topic information for.

New in version 1.5.0.

class pytweet.Trend(name, url, promoted_content, query, tweet_volume)

Represents a twitter’s trending topics display as Trend.

New in version 1.5.0.

class pytweet.PlaceType(code, name)

Represents a place type consist of the code and name for Location.

New in version 1.5.0.

class pytweet.TimezoneInfo(name, name_info, utc_offset)

Represents a TimezoneInfo for the user’s setting.

New in version 1.5.0.

Setting Objects

class pytweet.UserSettings(always_use_https, geo_enabled, sleep_time_setting, use_cookie_personalization, language, discoverable_by_email, discoverable_by_mobile_phone, display_sensitive_media, allow_contributor_request, allow_dms_from, allow_dm_groups_from, protected, translator_type, screen_name, show_all_inline_media=None, location=None, timezone=None)

Represents a user setting.

New in version 1.5.0.

class pytweet.SleepTimeSettings(enabled, end_time, start_time)

Represents a setting for sleep time from a user setting.

New in version 1.5.0.

Space Objects

class pytweet.Topic(id, name, description)

Represents a space topic.

New in version 1.5.0.

Embed Objects

class pytweet.Embed(title=None, description=None, start=None, end=None, url=None, expanded_url=None, display_url=None, unwound_url=None, status_code=None, images=None)

Represents a dataclass for embedded urls in a tweet.

class pytweet.EmbedImage(url, width, height)

Represents a dataclass for an embed image.

Stream Objects

class pytweet.StreamRule(value, tag=None, id=None)

Represents a stream rule.

New in version 1.3.5.

Compliance Objects

class pytweet.JobResult(id, action, reason, created_at, redacted_at=None)

Represents a download result from a job.

New in version 1.5.0.

Message Object

class pytweet.InitiatedVia(tweet_id, welcome_message_id)

Represents an object that stores ‘initiated_via’ key from direct message event data.

New in version 1.5.0.

Metrics Objects

class pytweet.PublicTweetMetrics(like_count, retweet_count, quote_count, reply_count)

A public metrics for Tweet

The following properties return an object from the metrics.

New in version 1.5.0.

class pytweet.NonPublicTweetMetrics(impression_count, user_profile_clicks, url_link_clicks=None)

A non public metrics for Tweet

To get the metrics you can use Tweet.non_public_metrics.

New in version 1.5.0.

class pytweet.OrganicTweetMetrics(like_count, retweet_count, reply_count, impression_count, user_profile_clicks, url_link_clicks=None)

An organic metrics for Tweet

To get the metrics you can use Tweet.organic_metrics.

New in version 1.5.0.

class pytweet.PromotedTweetMetrics(like_count, retweet_count, reply_count, impression_count, user_profile_clicks, url_link_clicks=None)

A promoted metrics for Tweet

To get the metrics you can use Tweet.promoted_metrics.

New in version 1.5.0.

class pytweet.NonPublicMediaMetrics(playback_0_count, playback_100_count, playback_25_count, playback_50_count, playback_75_count)

A non public metrics for Media

To get the metrics you can use Media.non_public_metrics.

New in version 1.5.0.

class pytweet.OrganicMediaMetrics(playback_0_count, playback_100_count, playback_25_count, playback_50_count, playback_75_count, view_count=None)

An organic metrics for Media

To get the metrics you can use Media.organic_metrics.

New in version 1.5.0.

class pytweet.PromotedMediaMetrics(playback_0_count, playback_100_count, playback_25_count, playback_50_count, playback_75_count, view_count=None)

A promoted metrics for Media

To get the metrics you can use Media.promoted_metrics.

New in version 1.5.0.

Attachments

Attachments is a way to attach additional part to a message, this include tweet and direct message. You may contruct the following objects except CustomProfile and Geo. Consider using Client.create_custom_profile for making a custom profile attachment and Client.search_geo for searching a geo-location.

Media

class pytweet.Media(data, *, http_client)

Represents a media attachment in a message.

Note that this object is different than File. While you need File to send attachment (this includes .png, .jpeg, .gif and .mp4) to a message, Media is like the final result of that File (after you initialize it through upload endpoints).

property url

Returns the image’s url, this method is only available if the media type is MediaType.photo. If the media type is MediaType.video consider using Media.preview_image_url.

Type

str

property preview_image_url

Returns the video’s preview image url, This is only available when the media type is a MediaType.video which is for video only.

Type

str

property key

Returns the media’s key

Type

str

property type

Returns the image’s type in a MediaType() object.

Type

str

property width

Returns the image’s width

Type

Optional[int]

property height

Returns the image’s height

Type

Optional[int]

property view_count

Returns the media’s view_count if the media count as a video type.

New in version 1.5.0.

Type

Optional[int]

property non_public_metrics

The media’s metrics that are not available for anyone to view on Twitter, such as video view quartiles.

New in version 1.5.0.

Type

Optional[NonPublicMediaMetrics]

property organic_metrics

The media’s metrics in organic context (posted and viewed in a regular manner), such as video view quartiles.

New in version 1.5.0.

Type

Optional[OrganicMediaMetrics]

property promoted_metrics

The tweet’s metrics in promoted context (posted or viewed as part of an Ads campaign), such as video view quartiles.

New in version 1.5.0.

Type

Optional[PromotedMediaMetrics]

CustomProfile

class pytweet.CustomProfile(name, id, timestamp, media)

Represents a CustomProfile attachments that allow a Direct Message author to present a different identity than that of the Twitter account being used.

New in version 1.3.5.

property name

The author’s custom name.

New in version 1.3.5.

Type

str

property id

The custom profile unique ID.

New in version 1.3.5.

Type

int

property created_at

Returns a datetime.datetime object with the CustomProfile created time.

New in version 1.3.5.

Type

datetime.datetime

property media

Returns the media object.

New in version 1.3.5.

Type

Media

Poll

class pytweet.Poll

Represents a Poll attachment in a tweet.

x == y

Check if one Poll’s id is equal to another.

x != y

Check if one Poll’s id is not equal to another.

len(x)

returns how many options the poll have.

Parameters
  • duration (int) – The poll duration in minutes.

  • id (Optional[ID]) – The poll’s unique ID.

  • voting_status (Optional[str]) – The poll’s voting status.

  • end_date (Optional[str]) – The poll’s end date.

New in version 1.1.0.

add_option(*, label, **kwargs)

Add option to your Poll instance.

Note

For attaching a poll object you should use the label argument and only label as the api only need labels to make poll.

Parameters
  • label (str) – The option’s label.

  • position (int) – The option’s position.

  • votes (int) – The option’s votes.

Returns

This method return your Poll instance.

Return type

Poll

property id

Return the poll’s unique ID.

New in version 1.1.0.

Type

Optional[int]

property options

Return a list of PollOption.

New in version 1.1.0.

Type

List[PollOption]

property raw_options

Return a list of raw poll option.

New in version 1.3.5.

Type

List[dict]

property voting_status

Returns the current voting status of the poll.

New in version 1.1.0.

Changed in version 1.3.7.

Type

str

property is_open

Return True if the poll is still open for voting, if it’s closed it will returns False.

New in version 1.3.7.

Type

bool

property is_closed

Returns False if the poll is still open for voting, if it’s closed it returns True.

New in version 1.3.7.

Type

bool

property duration

Return the poll duration in minutes.

New in version 1.3.5.

Type

int

property end_date

Return the end date in datetime.datetime object.

New in version 1.1.0.

Type

Optional[datetime.datetime]

CTA

class pytweet.CTA

Represents call-to-action attachment(CTA) You can use it in User.send() via CTA kwarg. CTA will perform and action whenever a user “call” something, an example of this is buttons.

New in version 1.3.5.

add_button(*, label, url, type=ButtonType.web_url, tco_url=None)

Add a button in your CTA instance.

Parameters
  • label (str) – The button’s label, will be shown in the main text.

  • url (str) – A url that specified where to take you when you click the button, e.g you can take a user to someone’s dm, a tweet, etc.

  • type (ButtonType) – The button’s type, For now twitter only use web_url, if none specified the default type is ButtonType.web_url.

  • tco_url (Optional[str]) – The url in tco style.

Returns

Returns your CTA instance.

Return type

CTA

New in version 1.3.5.

property buttons

Returns a list of pre-made buttons object.

New in version 1.3.5.

Type

List[Button]

property raw_buttons

Returns the list of dictionaries filled with raw buttons.

New in version 1.3.5.

Type

List[dict]

QuickReply

class pytweet.QuickReply

Represents a quick_reply attachment in Direct Message.

Parameters

type (str) – The quick_reply’s types, it must be and only ‘options’

New in version 1.2.0.

add_option(*, label, description=None, metadata=None)

Method for adding an option in your quick reply instance.

Parameters
  • label (str) – The option’s label. Label text is returned as the user’s message response, Must be less then 36 characters.

  • description (str) – The option’s description. Description text displayed under label text. All options must have this property defined if property is present in any option. Text is auto-wrapped and will display on a max of two lines and supports n for controlling line breaks, Must be less then 72 characters.

  • metadata (str) – The option’s metadata. Metadata that will be sent back in the webhook request, must be less then 1000 characters.

Returns

This method return your QuickReply instance.

Return type

QuickReply

New in version 1.2.0.

property type

Returns the QuickReply type.

New in version 1.5.0.

Type

str

property options

Returns a list of pre-made Option objects.

New in version 1.3.5.

Type

List[Option]

property raw_options

Returns the raw options.

New in version 1.2.0.

Type

List[dict]

Geo

class pytweet.Geo(data)

Represents the Geo location in twitter. You can use this as attachment in a tweet or for searching a location

New in version 1.3.5.

property name

Returns the geo’s name.

New in version 1.3.5.

Type

str

property id

Returns the geo’s unique id.

New in version 1.3.5.

Type

str

property fullname

Returns the geo’s fullname.

New in version 1.3.5.

Type

str

property type

Returns the geo’s type.

New in version 1.3.5.

Type

str

property country

Returns the country where the geo is in.

New in version 1.3.5.

Type

str

property country_code

Returns the country’s code where the geo is in.

New in version 1.3.5.

Type

str

property centroid

Returns the geo’s centroid.

New in version 1.3.5.

Type

str

property bounding_box_type

Returns the geo’s bounding box type.

New in version 1.3.5.

Type

str

property coordinates

Returns a list of coordinates where the geo’s located.

New in version 1.3.5.

Type

List[str]

Files

class pytweet.File

Represents a File attachment for messages.

Parameters
  • path (str) – The file’s path.

  • dm_only (bool) – Indicates if the file is use in dm only. Default to False.

  • alt_text (Optional[str]) – The image’s alt text, if None specified the image won’t have an alt text. Default to None.

  • subtitle_language_code (str) – The language code should be a BCP47 code (e.g. “en”).

  • subfile (SubFile) – The subtitle’s source file. Must be a .srt file with the correct formats.

New in version 1.3.5.

property path

Returns the file’s path.

New in version 1.3.5.

Type

str

property media_id

Returns the file’s media id. Returns None if the file was never uploaded.

New in version 1.5.0.

Type

Optional[int]

property subfile_media_id

Returns the file’s subtitle file’s media id. Returns None if the subfile was never uploaded.

New in version 1.5.0.

Type

Optional[int]

property mimetype

Returns the file’s mimetype.

New in version 1.3.5.

Type

str

property filename

Returns the file’s basename.

New in version 1.3.5.

Type

str

property total_bytes

Returns an integer value that represents the size of the specified path in bytes.

New in version 1.3.5.

Type

int

property media_category

Returns the file’s media category. e.g If its more tweet messages it can be TWEET_IMAGE if its in direct messages it will be dm_image.

New in version 1.3.5.

Type

str

property subfile

Returns the file’s subfile.

New in version 1.5.0.

Type

Optional[SubFile]

property subfiles

Returns a list of the file’s subfiles.

New in version 1.5.0.

Type

Optional[List[SubFile]]

SubFile

class pytweet.SubFile

Represents a subtitle File for File. You can attach one subfile in File via subfile arguments. This method inherits File. Always remembers that twitter only supports srt extension file with the correct timestamps.

New in version 1.5.0.

property filename

Returns the SubFile’s filename.

New in version 1.5.0.

Type

str

property path

Returns the SubFile’s path.

New in version 1.3.5.

Type

str

property language

Returns the SubFile’s language.

New in version 1.5.0.

Type

str

property language_code

Returns the SubFile’s language code.

New in version 1.5.0.

Type

str

property media_id

Returns the SubFile’s media id. Returns None if the file was never uploaded.

New in version 1.5.0.

Type

Optional[int]

property total_bytes

Returns an integer value that represents the size of the specified path in bytes.

New in version 1.5.0.

Type

int

property mimetype

Returns the subfile’s media category. This always returns ‘text/srt’

New in version 1.5.0.

Type

str

property media_category

Returns the subfile’s media category. This always returns ‘Subtitles’.

New in version 1.5.0.

Type

str

Streaming

Streaming is a way to stream in twitter for tweets! This differ with on_tweet_create, Stream can detech global tweets while on_tweet_create only detech tweets from subscription users.

Stream

class pytweet.Stream

Represent a stream object that stream over twitter for tweets.

Parameters
  • backfill_minutes (int) – This feature will deliver duplicate Tweets, meaning that if you were disconnected for 90 seconds, and you requested two minutes of backfill, you will receive 30 seconds worth of duplicate Tweets. Due to this, you should make sure your system is tolerant of duplicate data. This feature is currently only available to the Academic Research product track.

  • reconnect_attempts (int) – Decide how many attempts for a reconnect to perform, if the client reconnected more then this argument, it would break the loop.

New in version 1.3.5.

classmethod sample_stream(backfill_minutes=0, reconnect_attempts=15)

A class method that change the stream connection to a sample one, this would mean you dont have to set any stream rules. This would not recommended because it can make the progress of tweet cap much faster, if its out of limit you would not be able to stream.

Parameters
  • backfill_minutes (int) – This feature will deliver duplicate Tweets, meaning that if you were disconnected for 90 seconds, and you requested two minutes of backfill, you will receive 30 seconds worth of duplicate Tweets. Due to this, you should make sure your system is tolerant of duplicate data. This feature is currently only available to the Academic Research product track.

  • reconnect_attempts (int) – Decide how many attempts for a reconnect to perform, if the client reconnected more then this argument, it would break the loop.

Returns

This classmethod returns your Stream instance.

Return type

Stream

New in version 1.3.5.

property rules

Returns the stream’s rules, if its a sample stream it would returns None.

New in version 1.3.5.

Type

dict

add_rule(value, tag=None)

Add a rule to your stream to match with tweets that the stream return. You can use an operator to do this, check https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/build-a-query for more information about the operator. You can add multiple rules depending your access level, 5 for essential access, 25 for elevated access and 100 for academic research access.

Parameters
  • value (str) – The rule text. If you are using a Standard Project at the Basic access level, you can use the basic set of operators, can submit up to 25 concurrent rules, and can submit rules up to 512 characters long. If you are using an Academic Research Project at the Basic access level, you can use all available operators, can submit up to 1,000 concurrent rules, and can submit rules up to 1,024 characters long.

  • tag (Optional[str]) – The tag label. This is a free-form text you can use to identify the rules that matched a specific Tweet in the streaming response. Tags can be the same across rules.

Returns

Returns the stream’s rules, if its a sample stream it would returns None.

Return type

Stream

New in version 1.3.5.

clear()

Clear stream before attempting to connect with the stream connection, this would delete all previous rules in your stream.

Returns

This method returns None.

Return type

NoneType

New in version 1.3.5.

fetch_rules()

Fetches the stream’s rules.

Returns

This method returns a list of StreamRule objects.

Return type

Optional[List[StreamRule]]

New in version 1.3.5.

set_rules(dry_run)

Create and set rules to your stream.

Parameters

dry_run (bool) – Indicates if you want to debug your rule’s operator syntax.

New in version 1.3.5.

connect(*, dry_run=False)

Connect with the stream connection.

Parameters

dry_run (bool) – Indicates if you want to debug your rule’s operator syntax. Default to None.

New in version 1.3.5.

StreamConnection

class pytweet.StreamConnection

Represent the twitter api stream connection. This will handle the stream connection.

New in version 1.3.5.

property closed

Returns True if the connection is closed, else False.

New in version 1.3.5.

Type

Optional[bool]

is_close()

An alias to StreamConnection.closed.

Returns

This method returns a bool object.

Return type

Optional[bool]

New in version 1.3.5.

close()

Close the stream connection.

Returns

This method returns None.

Return type

NoneType

New in version 1.3.5.

connect()

Connect to the current stream connection.

New in version 1.3.5.

Oauth

Oauth is a way to authenticate a twitter user account. You can do this with 3 legged authentication via OauthSession.create_oauth_url() to create an oauth url and OauthSession.post_oauth_token() to post an oauth token and verifier. This also required in every request you’ve made for identification! This section will show you what you can do with oauth, You can use Client.http.oauth_session to get the client’s OauthSession.

OauthSession

class pytweet.OauthSession(consumer_key, consumer_secret, *, access_token, access_token_secret, http_client, callback_url=None, client_id=None, client_secret=None)

Represents an OauthSession for OAuth1 and OAuth2 Authorization.

Parameters
  • consumer_key (Optional[str]) – The application’s consumer key.

  • consumer_secret (Optional[str]) – The application’s consumer secret.

  • access_token (Optional[str]) – The application’s access token.

  • access_token_secret (Optional[str]) – The application’s access token secret.

  • http_client (:class:`HTTPClient) – The HTTPClient for making requests.

  • callback_url (Optional[str]) – The callback url, the user will get redirect to the callback url after they authorize. Default to None.

  • client_id (Optional[str]) – The client’s OAuth 2.0 Client ID from keys and tokens page.

  • client_secret (Optional[str]) – The client’s OAuth 2.0 Client Secret from keys and tokens page.

New in version 1.2.0.

property oauth1

Wrap the credentials in a function that return Oauth1. Usually Uses for Authorization.

New in version 1.2.0.

Type

Oauth1

property basic_auth

The decoded base64 encoded client id and secret.

New in version 1.5.0.

Type

str

invalidate_access_token()

Invalidate the access token and access token secret of yout client.

Warning

This staticmethod will invalidate your access token and access token secret of your client.

New in version 1.3.5.

verify_credentials(*, raise_error=True)

Verify the credentials are correct. Returns a boolean whether its succesful or not if raise_error turns to False. Default to True

Parameters

raise_error (bool) – Indicates whether to raise if the credentials are wrong. If sets to False, the method will returns a boolean, True for succesful and False for error.

Raises

Forbidden – Raised if the credentials are wrong.

New in version 1.5.0.

generate_request_tokens(access_type=None)

Generates request tokens with an access_type. This method returns a dictionary with the credentials, example return object:

Parameters

access_type (str) – Must be either read, write, direct_messages. read for reading twitter info only, write will have the same as read and also write permission this includes but not limited to post & delete a Tweet, and direct_messages is for read & write and sending & deleting

Returns

Returns the request_tokens data.

Return type

dict

New in version 1.3.5.

create_oauth_url(access_type=None, *, signin_with_twitter=False)

Creates an oauth url with an access type. This is the 1st step of making a request on behalf of other users through oauth1.1 usercontext.

The callback after pressing authorize button is your callback url that you passed in your Client. The oauth_token and oauth_verifier will automatically appended in the callback url. If you are setting up a sign up button in your website to lookup the user’s profile information, You have to setup a system where if the oauth_token or oauth_verifier is present in the url then, it will use OauthSession.post_oauth_token() to post an oauth token and verifier to exchange with the user’s access token and secret. If its for personal uses then just copy the result and passed in OauthSession.post_oauth_token().

Parameters
  • access_type (str) – Must be either read, write, direct_messages. read for reading twitter info only, write will have the same as read and also write permission this includes but not limited to post & delete a Tweet, and direct_messages is for read & write and sending & deleting DirectMessages.

  • signin_with_twitter (bool) – Register a user account in as little as one click. This works on websites, iOS, mobile, and desktop applications.

Returns

Returns an oauth url.

Return type

str

New in version 1.3.5.

post_oauth_token(oauth_token, oauth_verifier)

Posts the oauth token & verifier. This is the 2nd step(and the last step) of making a request on behalf of other users through oauth1.1 usercontext. Returns a pair of access token & secret also the user’s username(present as screen_name) and id e.g (“access_token=xxxxxxxxxxxxx”, “access_token_secret=xxxxxxxxxxxxx”, “screen_name=TheGenocides”, “user_id=1382006704171196419”). Uses the access token and secret to make request on behalf of users! You can use the raw api or construct another client with the access token and secret.

Parameters
  • oauth_token (str) – The Oauth token.

  • oauth_verifier (str) – The Oauth verifier.

Returns

Returns a tuple object with the credentials in.

Return type

tuple

New in version 1.3.5.

create_oauth2_url(scope, *, code_challenge_method='plain', state=None)

Creates an oauth 2 url. This is The 1st step of using OAuth 2.0 Authorization Code Flow with PKCE. The callback after pressing authorize button is your callback url that you passed in your Client.

Parameters
  • scope (Scope) – The scope permissions. Must be an instance of Scope.

  • code_challenge_method (str) – The code challenge method, must be tiher plain or s256. Default to plain.

  • state (Optional[str]) – A random string you provide to verify against CSRF attacks. If none specified, the method will generates one.

New in version 1.5.0.

post_auth_code(code, code_challenge)

Posts the authorize code and code challenge. This is The 2nd step of using OAuth 2.0 Authorization Code Flow with PKCE. In this method, the client will make a request and create a new bearer token. With this, you can make request on behalf of users.

Parameters
  • code (str) – The authorize code.

  • code_challenge (str) – The code challenge.

New in version 1.5.0.

request_new_token(refresh_token)

Request a new access token with the refresh token, to obtain a refresh token make sure to use OauthSession.create_oauth2_url() with offline_access permission sets to True in the scope parameter.

Parameters

refresh_token (str) – Refresh tokens allow an application to obtain a new access token without prompting the user via the refresh token flow.

Returns

This method returns a dict object with the new request token in that dict.

Return type

Optional[dict]

New in version 1.5.0.

Scope

class pytweet.Scope(*, tweet_read=False, tweet_write=False, tweet_moderate_write=False, users_read=False, follows_read=False, follows_write=False, offline_access=False, space_read=False, mute_read=False, mute_write=False, like_read=False, like_write=False, list_read=False, list_write=False, block_read=False, block_write=False)

Scopes allow you to set granular access for your App so that your App only has the permissions that it needs. Here are the full documented scopes!

Scopes

Scope

Description

tweet.read

All the Tweets you can view, including Tweets from protected accounts.

tweet.write

Tweet and Retweet for you.

tweet.moderate.write

Hide and unhide replies to your Tweets.

users.read

Any account you can view, including protected accounts.

follows.read

People who follow you and people who you follow.

follows.write

Follow and unfollow people for you.

offline.access

Stay connected to your account until you revoke access.

space.read

All the Spaces you can view.

mute.read

Accounts you’ve muted.

mute.write

Mute and unmute accounts for you.

like.read

Tweets you’ve liked and likes you can view.

like.write

Like and un-like Tweets for you.

list.read

Lists, list members, and list followers of lists you’ve created or are a member of, including private lists..

list.write

Create and manage Lists for you..

block.read

Accounts you’ve blocked.

block.write

Block and unblock accounts for you.

New in version 1.5.0.

classmethod read_only(*, offline_access=False)

A classmethod that enables only read scopes. offline_access scope is optional, you can set it true or not. Defaults to False.

Parameters

offline_access (bool) – Indicates to stay connected to your account until you revoke access.

New in version 1.5.0.

classmethod write_only(*, offline_access=False)

A classmethod that enables only write scopes. This includes tweet_moderate_write scope. offline_access scope is optional, you can set it true or not. Defaults to False.

Parameters

offline_access (bool) – Indicates to stay connected to your account until you revoke access.

New in version 1.5.0.

classmethod all(*, offline_access=False)

A classmethod that enables all scopes. offline_access scope is optional, you can set it true or not. Defaults to False.

Parameters

offline_access (bool) – Indicates to stay connected to your account until you revoke access.

New in version 1.5.0.

property values

Returns the scope url encoded value. Example:

import pytweet

scope = pytweet.Scope(tweet_read=True, tweet_write=True)
print(scope.value) # --> 'tweet.read%20tweet.write'

New in version 1.5.0.

Type

str

Paginations

Some endpoints returns more objects but limits it to some pages. Using pagination classes like UserPagination and TweetPagination, you can change page and manage objects easily. Example:

pagination = client.account().fetch_following()
print("Page 1, object 1:", pagination.content[0])
pagination.next_page() #Change page to the next page
print("Page 2, object 2:", pagination.content[1])
pagination.previous_page() #Change page to the previous page
print("Page 1, object 3:", pagination.content[2])

#Pagination object stores page's content in a cache everytime you turn a page. You can use the pages property to get the zipped page number and the page content:
for page_number, page_content in pagination.pages:
    print(f"Page {page_number}, content: 1: {page_content[0]}")

Pagination

class pytweet.Pagination(data, *, item_type, endpoint_request, http_client, **kwargs)

Represents the base class of all pagination objects.

New in version 1.5.0.

property content

Returns a list of objects from the current page’s content.

New in version 1.5.0.

Type

list

property paginate_over

Returns how many times you change page over the pagination.

New in version 1.5.0.

Type

int

property current_page_number

Returns the current page number.

New in version 1.5.0.

Type

int

property pages

Returns the zipped pages with the page number and content from a cache. If you never been into the page you want, it might not be returns in this property. example to use:

for page_number, page_content in pagination.pages:
    ... #do something

New in version 1.5.0.

Type

List[Tuple[int, list]]

get_page_content(page_number)

Gets the page content from the pagination pages cache. If you never been into the page you want, it might not be returns.

Note

Note that, if the page_number is 0 it automatically would returns None. Specify number 1 or above.

Returns

This method returns a list of objects.

Return type

Optional[list]

New in version 1.5.0.

UserPagination

class pytweet.UserPagination(data, **kwargs)

Represents a pagination that handles users object. This inherits Pagination. These following methods return this object:

New in version 1.5.0.

next_page()

Change content property to the next page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

previous_page()

Change content property to the previous page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

property content

Returns a list of objects from the current page’s content.

New in version 1.5.0.

Type

list

property current_page_number

Returns the current page number.

New in version 1.5.0.

Type

int

get_page_content(page_number)

Gets the page content from the pagination pages cache. If you never been into the page you want, it might not be returns.

Note

Note that, if the page_number is 0 it automatically would returns None. Specify number 1 or above.

Returns

This method returns a list of objects.

Return type

Optional[list]

New in version 1.5.0.

property pages

Returns the zipped pages with the page number and content from a cache. If you never been into the page you want, it might not be returns in this property. example to use:

for page_number, page_content in pagination.pages:
    ... #do something

New in version 1.5.0.

Type

List[Tuple[int, list]]

property paginate_over

Returns how many times you change page over the pagination.

New in version 1.5.0.

Type

int

TweetPagination

class pytweet.TweetPagination(data, **kwargs)

Represents a pagination that handles tweets object. This inherits Pagination. These following methods return this object:

New in version 1.5.0.

property content

Returns a list of objects from the current page’s content.

New in version 1.5.0.

Type

list

next_page()

Change content property to the next page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

previous_page()

Change content property to the previous page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

property current_page_number

Returns the current page number.

New in version 1.5.0.

Type

int

get_page_content(page_number)

Gets the page content from the pagination pages cache. If you never been into the page you want, it might not be returns.

Note

Note that, if the page_number is 0 it automatically would returns None. Specify number 1 or above.

Returns

This method returns a list of objects.

Return type

Optional[list]

New in version 1.5.0.

property pages

Returns the zipped pages with the page number and content from a cache. If you never been into the page you want, it might not be returns in this property. example to use:

for page_number, page_content in pagination.pages:
    ... #do something

New in version 1.5.0.

Type

List[Tuple[int, list]]

property paginate_over

Returns how many times you change page over the pagination.

New in version 1.5.0.

Type

int

ListPagination

class pytweet.ListPagination(data, **kwargs)

Represents a pagination that handles list objects. This inherits Pagination. These following methods return this object:

New in version 1.5.0.

property content

Returns a list of objects from the current page’s content.

New in version 1.5.0.

Type

list

next_page()

Change content property to the next page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

previous_page()

Change content property to the previous page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

property current_page_number

Returns the current page number.

New in version 1.5.0.

Type

int

get_page_content(page_number)

Gets the page content from the pagination pages cache. If you never been into the page you want, it might not be returns.

Note

Note that, if the page_number is 0 it automatically would returns None. Specify number 1 or above.

Returns

This method returns a list of objects.

Return type

Optional[list]

New in version 1.5.0.

property pages

Returns the zipped pages with the page number and content from a cache. If you never been into the page you want, it might not be returns in this property. example to use:

for page_number, page_content in pagination.pages:
    ... #do something

New in version 1.5.0.

Type

List[Tuple[int, list]]

property paginate_over

Returns how many times you change page over the pagination.

New in version 1.5.0.

Type

int

MessagePagination

class pytweet.MessagePagination(data, **kwargs)

“Represents a pagination for message objects. These methods returns this pagination object:

New in version 1.5.0.

property content

Returns a list of objects from the current page’s content.

New in version 1.5.0.

Type

list

property current_page_number

Returns the current page number.

New in version 1.5.0.

Type

int

get_page_content(page_number)

Gets the page content from the pagination pages cache. If you never been into the page you want, it might not be returns.

Note

Note that, if the page_number is 0 it automatically would returns None. Specify number 1 or above.

Returns

This method returns a list of objects.

Return type

Optional[list]

New in version 1.5.0.

next_page()

Change content property to the next page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

property pages

Returns the zipped pages with the page number and content from a cache. If you never been into the page you want, it might not be returns in this property. example to use:

for page_number, page_content in pagination.pages:
    ... #do something

New in version 1.5.0.

Type

List[Tuple[int, list]]

property paginate_over

Returns how many times you change page over the pagination.

New in version 1.5.0.

Type

int

previous_page()

Change content property to the previous page’s contents..

Raises

NoPageAvailable – Raises when you reached the end of the pagination.

New in version 1.5.0.

Relations

Relations is an object that returns from a user action or a tweet action. This include but not limited to: Tweet.like, Tweet.retweet, Tweet.hide, and User.follow.

RelationFollow

class pytweet.RelationFollow

Represents a follow relation from a follow & unfollow request.

New in version 1.2.0.

property pending

Check if the relation is pending.

New in version 1.2.0.

Type

bool

property following

Check if the relation is following.

New in version 1.2.0.

Type

bool

RelationLike

class pytweet.RelationLike

Represents a like relation from a like & unlike request.

New in version 1.2.0.

property liked

Return True if user liked the tweet else False.

New in version 1.2.0.

Type

bool

RelationRetweet

class pytweet.RelationRetweet

Represents a retweet relation from a retweet & unretweet request.

New in version 1.2.0.

property retweeted

Return True if user retweeted the tweet else False.

New in version 1.2.0.

Type

bool

RelationHide

class pytweet.RelationHide

Represents a hide relation from a hide & unhide request.

New in version 1.2.0.

property hidden

Return True if a tweet is hidden else False

New in version 1.2.0.

Type

bool

Entities

Objects derives from entities.py

Hashtag

class pytweet.Hashtag

Represents a hashtag in a message.

property text

Returns the hashtag’s text.

Type

Optional[str]

property points

Returns a tuple with the hashtag’s startpoint and endpoint.

Type

Optional[Tuple]

UserMention

class pytweet.UserMention

Represents a user mention in a message.

property name

Returns the mention user’s name.

Type

str

property username

Returns the mention user’s username.

Type

str

property id

Returns the mention user’s id.

Type

id

property points

Returns a tuple with the mention’s startpoint and endpoint.

Type

Optional[Tuple]

Url

class pytweet.Url

Represents Url in a message.

property url

Returns the message’s url.

Type

str

property display_url

Returns the message’s display url

Type

str

property expanded_url

Returns the message’s expanded url

Type

str

property points

Returns a tuple with the url’s startpoint and endpoint.

Type

Optional[Tuple]

Symbol

class pytweet.Symbol

Represents a Symbol in a message.

property text

Returns the symbol’s text.

Type

str

property points

Returns a tuple with the url’s startpoint and endpoint.

Type

Optional[Tuple]

Event Objects

Event objects are objects returned by an event filled with the event data.

Event Type

class pytweet.Event

The base class of all event, this provides a type property that the event belongs to.

New in version 1.5.0.

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

property payload

Returns the event payload.

New in version 1.5.0.

class pytweet.DirectMessageEvent
property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property recipient

Returns the user that DirectMessageEvent.sender() interacted.

New in version 1.5.0.

Type

User

property sender

Returns the user that trigger the event.

New in version 1.5.0.

Type

User

property payload

Returns the event payload.

New in version 1.5.0.

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserActionEvent

Represents a user action event, this could be but not limited to: follow or unfollow. This is also a parent class to all UserAction events, this class inherits Event.

New in version 1.5.0.

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property target

Returns the user that was targeted by the source.

New in version 1.5.0.

Type

User

property source

Returns a user object that trigger this event.

New in version 1.5.0.

Type

User

property author

An alias to source.

New in version 1.5.0.

Type

User

property payload

Returns the event payload.

New in version 1.5.0.

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

Direct Message Events

Event objects thats related with direct message events.

class pytweet.DirectMessageTypingEvent

Represents a typing event object for on_typing event, this inherits DirectMessageEvent. This object contains the event information that twitter posts through the webhook url.

New in version 1.5.0.

property typer

An alias to DirectMessageEvent.sender().

New in version 1.5.0.

Type

User

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property payload

Returns the event payload.

New in version 1.5.0.

property recipient

Returns the user that DirectMessageEvent.sender() interacted.

New in version 1.5.0.

Type

User

property sender

Returns the user that trigger the event.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.DirectMessageReadEvent

Represents a direct message read event object for on_direct_message_read event, this inherits DirectMessageEvent. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property reader

An alias to DirectMessageEvent.sender().

New in version 1.5.0.

Type

User

property last_read_message

Returns the last message that got read, returns the event id if none found.

New in version 1.5.0.

Type

Optional[int]

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property payload

Returns the event payload.

New in version 1.5.0.

property recipient

Returns the user that DirectMessageEvent.sender() interacted.

New in version 1.5.0.

Type

User

property sender

Returns the user that trigger the event.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

Action Events

Action events are events trigger by or from a user

class pytweet.TweetFavoriteActionEvent

Represents a tweet favorite event object for on_tweet_favorite event, this inherits Event. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property id

Returns the action’s unique ID.

New in version 1.5.0.

Type

str

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property favorited_tweet

Returns the favorited tweet.

New in version 1.5.0.

Type

Tweet

property liker

Returns the user who favorited the tweet.

New in version 1.5.0.

Type

User

property payload

Returns the event payload.

New in version 1.5.0.

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserRevokeEvent

Represents a revoke access event by the subcription user, this inherits Event. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property revoked_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property app_id

Returns an application id who the user revoked from.

New in version 1.5.0.

Type

int

property user_id

Returns a user id who revoked the access.

New in version 1.5.0.

Type

int

property payload

Returns the event payload.

New in version 1.5.0.

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserFollowActionEvent

Represents a follow action event by user or of user, This inherits UserActionEvent. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property follower

An alias to UserActionEvent.source(). The user who followed/unfollowed the target.

New in version 1.5.0.

Type

User

property author

An alias to source.

New in version 1.5.0.

Type

User

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property payload

Returns the event payload.

New in version 1.5.0.

property source

Returns a user object that trigger this event.

New in version 1.5.0.

Type

User

property target

Returns the user that was targeted by the source.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserUnfollowActionEvent

Represents an unfollow action event by user, This inherits UserFollowActionEvent. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property author

An alias to source.

New in version 1.5.0.

Type

User

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property follower

An alias to UserActionEvent.source(). The user who followed/unfollowed the target.

New in version 1.5.0.

Type

User

property payload

Returns the event payload.

New in version 1.5.0.

property source

Returns a user object that trigger this event.

New in version 1.5.0.

Type

User

property target

Returns the user that was targeted by the source.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserBlockActionEvent

Represents a block action event by user, This inherits UserActionEvent. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property blocker

An alias to UserActionEvent.source(). The user who blocked/unblocked the target.

New in version 1.5.0.

Type

User

property author

An alias to source.

New in version 1.5.0.

Type

User

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property payload

Returns the event payload.

New in version 1.5.0.

property source

Returns a user object that trigger this event.

New in version 1.5.0.

Type

User

property target

Returns the user that was targeted by the source.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserUnblockActionEvent

Represents an unblock action event by user, This inherits UserBlockActionEvent. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property author

An alias to source.

New in version 1.5.0.

Type

User

property blocker

An alias to UserActionEvent.source(). The user who blocked/unblocked the target.

New in version 1.5.0.

Type

User

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property payload

Returns the event payload.

New in version 1.5.0.

property source

Returns a user object that trigger this event.

New in version 1.5.0.

Type

User

property target

Returns the user that was targeted by the source.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserMuteActionEvent

Represents a mute action event by user, This inherits UserActionEvent. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property muter

An alias to UserActionEvent.source(). The user who muted/unmuted the target.

New in version 1.5.0.

Type

User

property author

An alias to source.

New in version 1.5.0.

Type

User

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property payload

Returns the event payload.

New in version 1.5.0.

property source

Returns a user object that trigger this event.

New in version 1.5.0.

Type

User

property target

Returns the user that was targeted by the source.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

class pytweet.UserUnmuteActionEvent

Represents an unmute action event by user, This inherits UserMuteActionEvent. This object contains information that twitter posts through the webhook url.

New in version 1.5.0.

property author

An alias to source.

New in version 1.5.0.

Type

User

property created_at

Returns a datetime.datetime object with the action’s created timestamp.

New in version 1.5.0.

Type

datetime.datetime

property muter

An alias to UserActionEvent.source(). The user who muted/unmuted the target.

New in version 1.5.0.

Type

User

property payload

Returns the event payload.

New in version 1.5.0.

property source

Returns a user object that trigger this event.

New in version 1.5.0.

Type

User

property target

Returns the user that was targeted by the source.

New in version 1.5.0.

Type

User

property type

Returns the event’s action type.

New in version 1.5.0.

Type

Union[UserActionEventType, ActionEventType]

Event Reference

This section shows events listened to by Client. You can register an event using Client.event()

Example:

@client.event
def on_tweet_create(tweet):
    print(f"Someone posted a tweet: {tweet}")
pytweet.on_stream_connect(connection)

on_stream_connect is an event triggers when the client succesfuly connect to stream, this might trigger multiple times as a reconnect logic would trigger this event too.

Parameters

connection (StreamConnection) – The Stream connection.

pytweet.on_stream_disconnect(connection)

on_stream_disconnect is an event triggers when the client disconnect from stream.

Parameters

connection (StreamConnection) – The Stream connection.

pytweet.on_stream(tweet, connection)

on_stream is an event triggers when a stream return a tweet data.

Parameters
  • tweet (Tweet) – The data that’s going to be returns from the stream.

  • connection (StreamConnection) – The stream connection

pytweet.on_tweet_create(tweet)

on_tweet_create is an event triggers when a subscription user created a tweet.

Parameters

tweet (Tweet) – The Tweet that created by a subscription user.

pytweet.on_tweet_delete(tweet)

on_tweet_delete is an event triggers when a subscription user deleted a tweet.

Parameters

tweet (Tweet) – The Tweet that deleted by a subscription user.

pytweet.on_tweet_favorite(action)

on_tweet_favorite is an event triggers when someone likes/favorites the subscription user’s tweet.

Parameters

action (TweetFavoriteActionEvent) – The event action object information.

pytweet.on_user_revoke(action)

on_user_revoke is an event triggers when someone revoke the application access.

Parameters

action (UserRevokeEvent) – The event action object information.

pytweet.on_user_follow(action)

on_user_follow is an event triggers when someone follows the subscription user or the subscription user follows someone.

Parameters

action (UserFollowActionEvent) – The event action object information.

pytweet.on_user_unfollow(action)

on_user_unfollow is an event triggers when someone unfollows the subscription user.

Parameters

action (UserUnfollowActionEvent) – The event action object information.

pytweet.on_user_block(action)

on_user_block is an event triggers when someone blocks the subscription user.

Parameters

action (UserBlockActionEvent) – The event action object information.

pytweet.on_user_unblock(action)

on_user_unblock is an event triggers when someone unblocks the subscription user.

Parameters

action (UserUnblockActionEvent) – The event action object information.

pytweet.on_user_mute(action)

on_user_mute is an event triggers when someone mutes the subscription user.

Parameters

action (UserMuteActionEvent) – The event action object information.

pytweet.on_user_unmute(action)

on_user_unmute is an event triggers when someone unmutes the subscription user.

Parameters

action (UserUnmuteActionEvent) – The event action object information.

pytweet.on_direct_message(message)

on_direct_message is an event triggers when someone send a message to the subscription user or from the the subscription user.

Parameters

message (DirectMessage) – The DirectMessage that the subscription user sent or from the the subscription user.

pytweet.on_direct_message_read(action)

on_direct_message_read is an event triggers when someone read messages in the subscription user’s dm.

Parameters

action (DirectMessageReadEvent) – The event action object information.

pytweet.on_typing(action)

on_typing is an event triggers when someone trigger a typing animation in the subscription user dm.

Parameters

action (DirectMessageTypingEvent) – The event action object information.

Enums

All of these enums are a subclass of enum.Enum

class pytweet.MessageTypeEnum
DIRECT_MESSAGE

A direct message in twitter.

MESSAGE_TWEET

A public tweet.

MESSAGE_WELCOME_MESSAGE

A welcome message in a direct message.

MESSAGE_WELCOME_MESSAGE_RULE

A welcome message rule in a direct message.

class pytweet.SpaceState
live

indicates the space is live

scheduled

indicates the space is scheduled

class pytweet.ReplySetting
everyone

Everyone can reply.

mention_users

Only users who are mentioned in the tweet can reply.

following

Only people who are following the author of the tweet can reply.

class pytweet.ButtonType
web_url

A button type for opening a url.

class pytweet.ActionEventType
direct_message_read

A direct message read action event, this action event type returns by on_direct_message_read through the Event.type() attribute.

direct_message_typing

A direct message typing action event, this action event type returns by on_typing.

class pytweet.UserActionEventType
follow

A user follow action type returns by on_user_follow and on_user_unfollow.

block

A user block action type returns by on_user_block and on_user_unblock.

mute

A user mute action type returns by on_user_mute and on_user_unmute.

class pytweet.JobType
tweets

Indicates the job only support tweets id.

users

Indicates the job only support users id.

class pytweet.JobResultAction
delete

Indicates if the Job’s status is created.

null

For None value.

class pytweet.JobStatus
created

Indicates if the Job is created.

in_progress

Indicates if the Job is in_progress.

failed

Indicates if the Job is failed.

complete

Indicates if the Job is complete.

expired

Indicates if the Job is expired.

class pytweet.MediaType
photo

Indicates if the media is a photo.

video

Indicates if the media is a video.

gif

Indicates if the media is a gif.

class pytweet.Timezone
international_dateline_west

A timezone for Etc/GMT.

midway_island

A timezone for Pacific/Midway.

american_samoa

A timezone for Pacific/Pago_Pago.

hawaii

A timezone for Pacific/Honolulu.

alaska

A timezone for America/Juneau.

pacific_time

A timezone for America/Los_Angeles.

tijuana

A timezone for America/Tijuana.

mountain_time

A timezone for America/Denver.

arizona

A timezone for America/Phoenix.

chihuahua

A timezone for America/Chihuahua.

mazatlan

A timezone for America/Mazatlan.

central_time

A timezone for America/Chicago.

saskatchewan

A timezone for America/Regina.

guadalajara

A timezone for America/Mexico_City.

mexicoCity

A timezone for America/Mexico_City.

monterrey

A timezone for America/Monterrey.

central_america

A timezone for America/Guatemala.

eastern_time

A timezone for America/New_York.

indiana

A timezone for America/Indiana.

bogota

A timezone for America/Bogota.

lima

A timezone for America/Lima.

quito

A timezone for America/Lima.

atlantic_time

A timezone for America/Halifax.

caracas

A timezone for America/Caracas.

lapaz

A timezone for America/La_Paz.

santiago

A timezone for America/Santiago.

newfoundland

A timezone for America/St_Johns.

brasilia

A timezone for America/Sao_Paulo.

buenos_aires

A timezone for America/Argentina.

montevideo

A timezone for America/Montevideo.

georgetown

A timezone for America/Guyana.

puerto_rico

A timezone for America/Puerto_Rico.

greenland

A timezone for America/Godthab.

mid_atlantic

A timezone for Atlantic/South_Georgia.

azores

A timezone for Atlantic/Azores.

cape_verde

A timezone for Atlantic/Cape_Verde.

dublin

A timezone for Europe/Dublin.

edinburgh

A timezone for Europe/London.

lisbon

A timezone for Europe/Lisbon.

london

A timezone for Europe/London.

casablanca

A timezone for Africa/Casablanca.

monrovia

A timezone for Africa/Monrovia.

utc

A timezone for Etc/UTC.

belgrade

A timezone for Europe/Belgrade.

bratislava

A timezone for Europe/Bratislava.

budapest

A timezone for Europe/Budapest.

ljubljana

A timezone for Europe/Ljubljana.

prague

A timezone for Europe/Prague.

sarajevo

A timezone for Europe/Sarajevo.

skopje

A timezone for Europe/Skopje.

warsaw

A timezone for Europe/Warsaw.

zagreb

A timezone for Europe/Zagreb.

brussels

A timezone for Europe/Brussels.

copenhagen

A timezone for Europe/Copenhagen.

madrid

A timezone for Europe/Madrid.

paris

A timezone for Europe/Paris.

amsterdam

A timezone for Europe/Amsterdam.

berlin

A timezone for Europe/Berlin.

bern

A timezone for Europe/Zurich.

zurich

A timezone for Europe/Zurich.

rome

A timezone for Europe/Rome.

stockholm

A timezone for Europe/Stockholm.

vienna

A timezone for Europe/Vienna.

westCentralAfrica

A timezone for Africa/Algiers.

bucharest

A timezone for Europe/Bucharest.

cairo

A timezone for Africa/Cairo.

helsinki

A timezone for Europe/Helsinki.

kyiv

A timezone for Europe/Kiev.

riga

A timezone for Europe/Riga.

sofia

A timezone for Europe/Sofia.

tallinn

A timezone for Europe/Tallinn.

vilnius

A timezone for Europe/Vilnius.

athens

A timezone for Europe/Athens.

istanbul

A timezone for Europe/Istanbul.

minsk

A timezone for Europe/Minsk.

jerusalem

A timezone for Asia/Jerusalem.

harare

A timezone for Africa/Harare.

pretoria

A timezone for Africa/Johannesburg.

kaliningrad

A timezone for Europe/Kaliningrad.

moscow

A timezone for Europe/Moscow.

StPetersburg

A timezone for Europe/Moscow.

volgograd

A timezone for Europe/Volgograd.

samara

A timezone for Europe/Samara.

kuwait

A timezone for Asia/Kuwait.

riyadh

A timezone for Asia/Riyadh.

nairobi

A timezone for Africa/Nairobi.

baghdad

A timezone for Asia/Baghdad.

tehran

A timezone for Asia/Tehran.

abuDhabi

A timezone for Asia/Muscat.

muscat

A timezone for Asia/Muscat.

baku

A timezone for Asia/Baku.

tbilisi

A timezone for Asia/Tbilisi.

yerevan

A timezone for Asia/Yerevan.

kabul

A timezone for Asia/Kabul.

ekaterinburg

A timezone for Asia/Yekaterinburg.

islamabad

A timezone for Asia/Karachi.

karachi

A timezone for Asia/Karachi.

tashkent

A timezone for Asia/Tashkent.

chennai

A timezone for Asia/Kolkata.

kolkata

A timezone for Asia/Kolkata.

mumbai

A timezone for Asia/Kolkata.

newDelhi

A timezone for Asia/Kolkata.

kathmandu

A timezone for Asia/Kathmandu.

astana

A timezone for Asia/Dhaka.

dhaka

A timezone for Asia/Dhaka.

sriJayawardenepura

A timezone for Asia/Colombo.

almaty

A timezone for Asia/Almaty.

novosibirsk

A timezone for Asia/Novosibirsk.

rangoon

A timezone for Asia/Rangoon.

bangkok

A timezone for Asia/Bangkok.

hanoi

A timezone for Asia/Bangkok.

jakarta

A timezone for Asia/Jakarta.

krasnoyarsk

A timezone for Asia/Krasnoyarsk.

beijing

A timezone for Asia/Shanghai.

chongqing

A timezone for Asia/Chongqing.

hongKong

A timezone for Asia/Hong_Kong.

urumqi

A timezone for Asia/Urumqi.

kualaLumpur

A timezone for Asia/Kuala_Lumpur.

singapore

A timezone for Asia/Singapore.

taipei

A timezone for Asia/Taipei.

perth

A timezone for Australia/Perth.

irkutsk

A timezone for Asia/Irkutsk.

ulaanbaatar

A timezone for Asia/Ulaanbaatar.

seoul

A timezone for Asia/Seoul.

osaka

A timezone for Asia/Tokyo.

sapporo

A timezone for Asia/Tokyo.

tokyo

A timezone for Asia/Tokyo.

yakutsk

A timezone for Asia/Yakutsk.

darwin

A timezone for Australia/Darwin.

adelaide

A timezone for Australia/Adelaide.

canberra

A timezone for Australia/Melbourne.

melbourne

A timezone for Australia/Melbourne.

sydney

A timezone for Australia/Sydney.

brisbane

A timezone for Australia/Brisbane.

hobart

A timezone for Australia/Hobart.

vladivostok

A timezone for Asia/Vladivostok.

guam

A timezone for Pacific/Guam.

portMoresby

A timezone for Pacific/Port_Moresby.

magadan

A timezone for Asia/Magadan.

srednekolymsk

A timezone for Asia/Srednekolymsk.

solomon

A timezone for Pacific/Guadalcanal.

newCaledonia

A timezone for Pacific/Noumea.

fiji

A timezone for Pacific/Fiji.

kamchatka

A timezone for Asia/Kamchatka.

marshall

A timezone for Pacific/Majuro.

auckland

A timezone for Pacific/Auckland.

wellington

A timezone for Pacific/Auckland.

nukualofa

A timezone for Pacific/Tongatapu.

tokelau

A timezone for Pacific/Fakaofo.

chatham

A timezone for Pacific/Chatham.

samoa

A timezone for Pacific/Apia.

Errors

Error raised by pytweet.

exception pytweet.PytweetException(message=None)

This is the base class of all exceptions Raise by PyTweet. This inherits Exception.

New in version 1.2.0.

exception pytweet.APIException(response=None, message='No Error Message Provided')

A custom error that will be Raise whenever a request returns an HTTP status code 200. This inherits PytweetException.

New in version 1.2.0.

exception pytweet.HTTPException(response=None, message=None)

A custom error that will be Raise whenever a request returns an HTTP status code above 200. This inherits PytweetException.

New in version 1.2.0.

exception pytweet.Unauthorized(response=None, message=None)

This class inherits HTTPException. Raise when the credentials you passed are invalid and a request returns status code: 401

New in version 1.0.0.

exception pytweet.BadRequests(response=None, message=None)

This class inherits HTTPException. Raise when a request return status code: 400.

New in version 1.2.0.

exception pytweet.TooManyRequests(response=None, message=None)

This class inherits HTTPException. Raise when ratelimit exceeded and a request return status code 429.

New in version 1.1.0.

exception pytweet.Forbidden(response=None, message=None)

This class inherits HTTPException. Raises when a request returns status code: 403.

New in version 1.2.0.

exception pytweet.Conflict(response=None, message=None)

This error class inherits HTTPException. This error is Raise when a request return 409 status code.

exception pytweet.ConnectionException(response=None, message=None)

This error class inherits HTTPException. This error is Raise when a stream connection throw an error.

New in version 1.3.5.

exception pytweet.FieldsTooLarge(response=None, message=None)

“This class inherits HTTPException. Raises when a request returns status code: 431

exception pytweet.NotFound(response=None, message=None)

This class inherits HTTPException. Raise when a request returns status code: 404.

New in version 1.2.0.

exception pytweet.UnKnownSpaceState(given_state)

This error class inherits APIException. This error is Raise when a user specified an invalid space state.

New in version 1.5.0.

exception pytweet.NoPageAvailable

This error class inherits APIException. This error is Raise when a user try to lookup a new page in a pagination object that does not exist. These following methods can Raise this error:

New in version 1.5.0.