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.

Classes

These are all the public classes of pytweet.

Clients

Client

class pytweet.Client(bearer_token, *, consumer_key=None, consumer_key_secret=None, access_token=None, access_token_secret=None, stream=None)

Represent a client that connected to Twitter!

Parameters
  • bearer_token (Optional[str]) – The Bearer Token of the app. The most important one, because this makes most of the requests for Twitter’s api version 2.

  • consumer_key (Optional[str]) – The Consumer Key of the app.

  • consumer_key_secret (Optional[str]) – The Consumer Key Secret of the app.

  • access_token (Optional[str]) – The Access Token of the app.

  • access_token_secret (Optional[str]) – The Access Token Secret of the app.

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

http

Returns the HTTPClient, the HTTPClient is responsible for making most of the Requests.

Type

Optional[HTTPClient]

New in version 1.0.0.

property account

Returns the client’s account information. The callback is a User object.

New in version 1.2.0.

Type

Optional[User]

event(func)

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

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.

See also

Event Reference

See the Event Reference.

New in version 1.3.5.

fetch_user(user_id=None)

A method for fetching the user with the user’s id.

Warning

This method uses API call and might cause ratelimits if used often!

Parameters

user_id (Union[str, int]) – Represents the user ID that you wish to get info for. If you don’t have it you may use fetch_user_by_name 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_name(username)

A method for fetching the user with the user’s username.

Warning

This method uses API call and might cause ratelimits if used often!

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=None)

A method for fetching tweet with the tweet’s id.

Warning

This method uses API call and might cause ratelimits if used often! More recommended is to use get_tweet to get the client’s tweet.

Parameters

tweet_id (Union[str, int]) – Represents the tweet id that you wish to get info about.

Returns

This method returns a Tweet object.

Return type

Tweet

New in version 1.0.0.

fetch_message(event_id=None)

A method for fetching the message with the message’s event ID.

Warning

This method uses API call and might cause ratelimit if used often! It is more ecommended to use get_message() method, as it only retrieves the client’s message only.

Parameters

event_id (Union[str, int]) – Represents the event’s ID that you wish to fetch with.

Returns

This method returns a DirectMessage object.

Return type

DirectMessage

New in version 1.2.0.

tweet(text=None, *, file=None, poll=None, geo=None, quote_tweet=None, direct_message_deep_link=None, reply_setting=None, reply_tweet=None, exclude_reply_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]) – Represent a single file attachment. It could be an image, gif, or video. It also have to 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.

  • quote_tweet (Optional[Union[str, int]]) – The tweet ID you want to quote.

  • 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.

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

  • exclude_reply_users (Optional[List[Union[str, int]]]) – Exclude the users when replying to a tweet, 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.

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

Returns

This method returns a Message object.

Return type

Message

New in version 1.1.0.

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]:) – Represent 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.

fetch_welcome_message(welcome_message_id)

Fetches the welcome message with the given welcome message ID argument.

Parameters

welcome_message_id (Union[str, int]) – Represents the welcome message ID that you wish to fetch with.

Returns

This method returns WelcomeMessage object.

Return type

WelcomeMessage

New in version 1.3.5.

fetch_welcome_message_rules(welcome_message_rules_id)

A method for fetching a welcome message rules.

Parameters

welcome_message_rules_id (Union[str, int]) – Represents the welcome message rule ID that you wish to fetch with.

Returns

This method returns WelcomeMessageRule object.

Return type

WelcomeMessageRule

New in version 1.3.5.

fetch_space(space_id)

A method for fetching a space.

Parameters

space_id (Union[str, int]) – Represents the space ID that you wish to fetch with.

Returns

This method returns a Space object.

Return type

Space

New in version 1.3.5.

fetch_space_by_title(title, state=SpaceState.live)

Fetch a space using its title.

Parameters
  • title (Union[str, int]) – 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

Returns

This method returns a Space object.

Return type

Space

New in version 1.3.5.

search_geo(query, *, lat=None, long=None, ip=None, granularity='neighborhood', max_results=None)

Search a location 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.

  • 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 (Union[str, int]) – 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 ,ity ,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

  • max_results (Optional[Union[str, int]]) – 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

Returns

This method return a Geo object.

Return type

Geo

New in version 1.5.3.

get_message(event_id=None)

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

Note

Note that only the client’s tweet is going to be stored in the cache which means you can’t get someone’s message other then the client itself from the cache.

Parameters

event_id (Union[str, int]) – 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.

get_tweet(tweet_id=None)

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

Note

Note that, only the client’s tweet is going to be stored in the cache which mean you can’t get someone’s tweet other then the client itself from the cache.

Parameters

event_id (Union[str, int]) – 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

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

  • .. versionadded:: 1.2.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

stream(*, dry_run=False)

Stream realtime in twitter! Make sure to put stream kwarg in client. If you want the tweet data make sure to make an on_stream event. example:

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

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

New in version 1.3.5.

Twitter Models

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

User

class pytweet.User(data, http_client=None)

Represent 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.

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]) – Represent 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[custom_profile]) – 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()

Make a Request to follow a User.

Parameters

user_id (Union[str, int]) – The user’s id that you wish to follow.

Returns

This method return a RelationFollow object.

Return type

RelationFollow

New in version 1.1.0.

unfollow()

Make a DELETE Request to unfollow a User.

Parameters

user_id (Union[str, int]) – The user’s id that you wish to unfollow.

Returns

This method return a RelationFollow object.

Return type

RelationFollow

New in version 1.1.0.

block()

Make a POST Request to Block a User.

Parameters

user_id (Union[str, int]) – The user’s id that you wish to block.

New in version 1.2.0.

unblock()

Make a DELETE Request to unblock a User.

Parameters

user_id (Union[str, int]) – The user’s id that you wish to unblock.

New in version 1.2.0.

mute()

Make a POST Request to mute a User.

Parameters

user_id (Union[str, int]) – The user’s id that you wish to mute.

New in version 1.2.5.

unmute()

Make a DELETE Request to unmute the User.

Parameters

user_id (Union[str, int]) – The user’s id that you wish to unmute.

New in version 1.2.5.

trigger_typing()

Indicates that the client is typing in a user Dm.

New in version 1.3.5.

report(block=True)

Report the user as a spam account to twitter.

Parameters

block – Indicates that the client perform a block action to the user if set to True. Default to True.

New in version 1.3.5.

fetch_followers()

Fetch the user’s followers.

Note

This method will only returns 100 users unless you have an academic research access. Then it can returns more then 100 users.

New in version 1.3.5.

fetch_following()

Fetch the user’s following.

Note

This method will only returns 100 users unless you have an academic research access. Then it can returns more then 100 users.

New in version 1.3.5.

fetch_pinned_tweet()

Returns the user’s pinned tweet.

Returns

This method returns a Tweet object.

Return type

Optional[int]

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

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

Parameters
  • max_results (int) – Specified how many tweets should be return.

  • 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[Union[str, int]]) – 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[Union[str, int]]) – 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 list of Tweet objects or an empty list if none founded.

Return type

Union[List[Tweet], List]

New in version 1.3.5.

property name

Return the user’s name.

Type

str

property username

Return the user’s username, this usually start with ‘@’ follow by their username.

Type

str

property id

Return the user’s id.

Type

int

property bio

Return the user’s bio.

Type

str

property description

an alias to User.bio

Type

str

Return the user’s profile link

Type

str

Return url where the user put links, return an empty string if there isn’t a url

Type

str

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 profile_url

Return the user profile image.

Type

Optional[str]

property location

Return the user’s location

Type

str

property created_at

Return datetime.datetime object with the user’s account date.

Type

Optional[datetime.datetime]

property follower_count

Return total of followers that a user has.

Type

int

property following_count

Return total of following that a user has.

Type

int

property tweet_count

Return total of tweet that a user has.

Type

int

property listed_count

Return total of listed that a user has.

Type

int

Tweet

class pytweet.Tweet(data, **kwargs)

Represent a tweet message from Twitter. A Tweet is any message posted to Twitter which may contain photos, videos, links, and text.

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.

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)

Post a tweet to reply a specific tweet present by the tweet’s id.

Note

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

Parameters

text (str) – The reply tweet’s main text.

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.

unhide()

Unhide a hide reply.

Returns

This method returns a RelationHide object.

Return type

RelationHide

New in version 1.2.5.

fetch_retweeters()

Return users that retweeted the tweet.

Returns

  • Optional[List[User], List] – This method returns a list of User objects

  • .. versionadded:: 1.1.3

fetch_liking_users()

Return users that liked the tweet.

Returns

  • Optional[List[User], List] – This method returns a list of User objects

  • .. versionadded:: 1.1.3

fetch_replied_user()

Return the user that you reply with the tweet, a tweet count as reply tweet if the tweet startswith @Username or mention a user.

Returns

  • Optional[User] – This method returns a User object or NoneType

  • .. versionadded:: 1.1.3

property author

Return a user (object) who posted the tweet.

Type

Optional[User]

property possibly_sensitive

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

Type

class`bool`

property created_at

Return a datetime object with the tweet posted age.

Type

datetime.datetime

property source

Return 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 raw_reply_setting

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

Type

str

property reply_setting

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

Type

ReplySetting

property lang

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

Type

str

property conversation_id

All replied are bind to an id named conversation id. An alias to Tweet.id(), this set as an alias due to the api return it in the tweet data.

Type

int

Get the tweet’s link.

Type

str

property mentions

Return the mentioned user’s username.

New in version 1.1.3.

Type

Optional[List[str]]

property poll

Return a Poll object with the tweet’s poll.

New in version 1.1.0.

Type

Poll

property media

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

New in version 1.1.0.

Type

List[Media]

property embeds

Return a list of Embedded url from that tweet

New in version 1.1.3.

Type

List[Embed]

property like_count

Return the total of likes in a tweet.

Type

int

property retweet_count

Return the total of retweetes in a tweet.

Type

int

property reply_count

Return the total of replies in a tweet.

Type

int

property quote_count

Return the total of quotes in a tweet.

Type

int

property sensitive

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

Type

class`bool`

Messages

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

Message

Attributes
class pytweet.Message(text, id, type)

Represents the base Message of all Message types in Twitter.

Parameters
  • text (Optional[str]) – The messages’s text.

  • id (Union[str, int]) – The messages’s unique ID.

  • type (int.) – The message’s type in int form, it will get form to MessageTypeEnum.

New in version 1.2.0.

property text

Returns the message’s text.

New in version 1.3.5.

Type

str

property id

Returns the message’s id.

New in version 1.3.5.

Type

int

property type

Returns the message’s type.

New in version 1.3.5.

Type

MessageTypeEnum

DirectMessage

class pytweet.DirectMessage(data, *, http_client)

Represents a Direct Message in Twitter.

New in version 1.2.0.

delete()

Make a Request to delete the DirectMessage.

New in version 1.1.0.

mark_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 event_type

Returns the message event type.

New in version 1.2.0.

Type

MessageEventTypeEnum

property recipient

Returns the recipient that received the message.

New in version 1.2.0.

Type

User

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[Hashtags]

property symbols

Returns the messages’s hashtags.

New in version 1.2.0.

Type

List[Symbols]

property mentions

Returns the messages usermentions.

New in version 1.2.0.

Type

List[UserMentions]

property urls

Returns the message’s urls.

New in version 1.2.0.

Type

List[Urls]

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 cta

Returns the message’s cta.

New in version 1.3.5.

Type

Optional[CTA]

WelcomeMessage

Attributes
Methods
class pytweet.WelcomeMessage(name=None, *, text, id, timestamp, http_client)

Represent a Welcome Message in a Direct Message.

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

  • text (str) – The welcome message main text.

  • id (Union[str, int]) – The welcome message unique id.

  • timestamp (Optional[str]) – The welcome message timestamp.

  • http_client (HTTPClient) – The http client that make the request.

New in version 1.3.5.

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 (str) – The welcome message main text

  • file (Optional[File]:) – Represent 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 created_at

Returns the welcome message created date.

New in version 1.3.5.

Type

datetime.datetime

property name

Returns the welcome message’s name.

New in version 1.3.5.

Type

str

WelcomeMessageRule

Methods
class pytweet.WelcomeMessageRule(id, welcome_message_id, timestamp, *, http_client)

Represent 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.

Parameters
  • id (Union[str, int]) – The welcome message rule unique id.

  • welcome_message_id (Union[str, int]) – The welcome message unique id.

  • timestamp (Optional[str]) – The welcome message rule created timestamp.

  • http_client (HTTPClient) – The http client that make the request.

New in version 1.3.5.

delete()

Delete the Welcome Message Rule.

New in version 1.3.5.

property created_at

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

New in version 1.3.5.

Type

datetime.datetime

property welcome_message_id

Returns the welcome message’s id.

New in version 1.3.5.

Type

Union[str, int]

Attachments

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

CustomProfile

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

Represent 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

Media

class pytweet.Media(data)

Represent media in a message.

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 media_key

Returns the image’s media 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]

Space

class pytweet.Space(data)
property title

The space’s title.

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 id

The space’s unique id.

New in version 1.3.5.

Type

str

property lang

The space’s language.

New in version 1.3.5.

Type

str

property creator_id

Returns the creator’s id.

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 hosts_id

Returns a list of the hosts id.

New in version 1.3.5.

Type

Optional[List[int]]

property invited_users

Returns the a list of users id. 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.

New in version 1.3.5.

Type

Optional[List[int]]

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]

is_ticketed()

Returns a bool indicate if the space is ticketed.

Returns

  • bool – This method returns a bool object.

  • .. versionadded:: 1.3.5

Poll

class pytweet.Poll(duration, **kwargs)

Represent 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 in the poll.
Parameters
  • duration (int) – The poll duration in minutes.

  • id (Optional[Union[str, int]]) – 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

Return True if the poll is still open for voting, if its closed it return False.

New in version 1.1.0.

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]

PollOption

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

Represent an Option for Poll

CTA

Attributes
Methods
class pytweet.CTA

Represent call-to-action attachment(CTA) You can use this in a post_tweet method via direct_message_deep_link kwarg or use it in direct message 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

Attributes
Methods
class pytweet.QuickReply(type='options')

Represent a quick_reply attachment in Direct Message.

Parameters

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

options

The QuickReply’s options. An option must have a label, description and metadata, Maximum options is 20.

Type

List[Any, Any]

.. versionadded:: 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 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)

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

Parameters

data (Dict[str, Any]) – The Geo data in a dictionary.

New in version 1.3.5.

property name

Returns place’s name.

New in version 1.3.5.

Type

str

property id

Returns place’s unique id.

New in version 1.3.5.

Type

str

property fullname

Returns place’s fullname.

New in version 1.3.5.

Type

str

property type

Returns place’s type.

New in version 1.3.5.

Type

str

property country

Returns the country where the place is in.

New in version 1.3.5.

Type

str

property country_code

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

New in version 1.3.5.

Type

str

property centroid

Returns the place’s centroid.

New in version 1.3.5.

Type

str

property bounding_box_type

Returns the place’s bounding box type.

New in version 1.3.5.

Type

str

property coordinates

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

New in version 1.3.5.

Type

List[str]

File

class pytweet.File(path_to_filename, *, dm_only=False)

Represent a File attachment for messages.

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

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

property path

Returns the file’s path.

New in version 1.3.5.

Type

str

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

Button

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

Represent a Button object. Button are attachment that you can attach via CTA

New in version 1.3.5.

Option

class pytweet.Option(label, description, metadata)

Represent an Option object. You can create an Option using QuickReply.add_option

New in version 1.3.5.

Streaming

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

Stream

Attributes
class pytweet.Stream(backfill_minutes=0, reconnect_attempts=15)

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.

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()

Fetch 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.

Returns

This method returns None.

Return type

NoneType

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.

Returns

This method returns None.

Return type

NoneType

New in version 1.3.5.

StreamConnection

Attributes
Methods
class pytweet.StreamConnection(url, backfill_minutes=0, reconnect_attempts=0, http_client=None)

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

  • Optional[bool] – This method returns a bool object.

  • .. versionadded:: 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.

StreamRule

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

Represent a stream rule.

New in version 1.3.5.

Relations

RelationFollow

Attributes
class pytweet.RelationFollow(data)

Represent the 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

Attributes
class pytweet.RelationLike(data)

Represent the 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

Attributes
class pytweet.RelationRetweet(data)

Represent the retweet relations 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

Embeds

Embed

class pytweet.Embed(data)

Represent the embedded urls in a tweet.

property title

Return the embed’s title

Type

str

property description

Return the embed’s description

Type

str

property start

Return the embed’s url startpoint start

Type

int

property end

Return the embed’s url endpoint.

Type

int

property url

Return the embed’s url

Type

str

property expanded_url

Return the expanded url

Type

str

property display_url

Return the display url

Type

str

property unwound_url

Return the unwound url

Type

str

property images

Return a list of Embed’s Images

New in version 1.1.3.

Type

List[EmbedsImages]

property status_code

Return the embed’s url HTTP status code

Type

int

EmbedsImages

Attributes
class pytweet.EmbedsImages(data)

Represent the tweets embed images.

property width

Return the image’s width

Type

int

property height

Return the image’s height

Type

int

property url

Return the image’s url

Type

str

Event Reference

This section shows events listened to by Client

You can register an event using Client.event()

Example:

@client.event
def on_stream_connect(connection):
 print(connection)
pytweet.on_stream_connect(connection)

on_stream_connect is an event trigger 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 trigger when the client disconnect from stream.

Parameters

connection (StreamConnection) – The Stream connection.

pytweet.on_stream(tweet, connection)

on_stream is an event trigger 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

Enums

All these enums are a subclass of enum.Enum

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.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.

Oauth

Oauth is a way to authenticate a twitter user account. You can do this with the 3 legged authentication via OauthSession.with_oauth_flow(). This also required in every request you’ve made for identification!

OauthSession

class pytweet.OauthSession(consumer_key, consumer_secret, callback=None)

The OauthSession, this usually is uses for POST requests and requests that need Oauth1 Authorization.

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

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

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

New in version 1.2.0.

static invalidate_access_token(client)

A staticmethod to invalidate a pair of access token and access token secret!

Warning

This staticmethod will invalidate your access token and access token secret that you passed in your Client() argument.

Parameters
  • access_token (str) – The oauth1 access token to be invalidate.

  • access_token_secret (str) – The oauth1 access token secret to be invalidate.

  • client (Client) – An instance of your Client(), note that this staticmethod will invalidate the access token and access token secret in this Client().

New in version 1.3.5.

classmethod with_oauth_flow(client, *, callback='https://twitter.com')

Authorize a user using the 3 legged oauth flow classmethod! This let’s your application to do an action on behalf of a user. This will give you 2 new methods, OauthSession.generate_oauth_url() for generating an oauth url so a user can authorize and post_oauth_token posting oauth token and verifier for getting a pair of access token and secret.

Note

There are 3 steps for using 3 legged oauth flow:

  • Use OauthSession.generate_oauth_url()

method and generate an oauth link.

  • Click that link and press the authorize button, you should get redirect to the callback-url with an oauth token and verifier appended in that url, e.g http://twitter.com/home will be http://twitter.com/home?oauth_token=xxxxxxxxxxxxxxxxxx?oauth_verifier=xxxxxxxxxxxxxxxxxx, copy the oauth token & verifier and use it in the next step.

  • Use post_oauth_token method with the oauth token and verifier. It should return a pair of access token & secret, it also return the screen name and user id. Now use those access token & secret in access_token & access_token_secret arguments in pytweet.Client, and now you can use the client to do certain action!

property oauth1

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

New in version 1.2.0.

Type

Oauth1

set_access_token(key, secret)

Set the access token’s key and secret.

set_consumer_key(consumer_key, consumer_secret)

Set a the consumer key and secret

Errors

Error raised by pytweet.

exception pytweet.PytweetException(message=None)

Exception: This is the base class of all exceptions.

New in version 1.2.0.

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

PytweetException: Raised when an error is incurred during a request with HTTP Status code 200.

New in version 1.2.0.

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

PytweetException: A custom error that will be raised whenever a request returns an HTTP status code above 200.

New in version 1.2.0.

exception pytweet.Unauthorized(response, message=None)

HTTPException: Raised when the credentials you passed are invalid and a request returns status code: 401

New in version 1.0.0.

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

HTTPException: Raised when ratelimit exceeded and a request return status code: 429

New in version 1.1.0.

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

HTTPException: Raised when a request returns status code: 403.

New in version 1.2.0.

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

HTTPException: Raised when a request returns status code: 404.

New in version 1.2.0.