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¶
- defcreate_custom_profile
- defcreate_welcome_message
- defevent
- deffetch_message
- deffetch_space
- deffetch_space_by_title
- deffetch_tweet
- deffetch_user
- deffetch_user_by_name
- deffetch_welcome_message
- deffetch_welcome_message_rules
- defget_message
- defget_tweet
- defsearch_geo
- defstream
- deftweet
- 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 usefetch_user_by_namebecause it only requires the user’s username.- Returns
This method returns a
Userobject.- Return type
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
Userobject.- Return type
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
Tweetobject.- Return type
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
DirectMessageobject.- Return type
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.Filepoll (Optional[
Poll]) – The poll attachment.geo (Optional[Union[
Geo,str]]) – The geo attachment, you can put an object that is an instance ofGeoor 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 ofTweet, 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
Messageobject.- Return type
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 Messagetext (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.Filequick_reply (Optional[
QuickReply]) – The message’sQuickReplyattachments.
- Returns
This method returns
WelcomeMessageobject.- Return type
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
WelcomeMessageobject.- Return type
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
WelcomeMessageRuleobject.- Return type
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
Spaceobject.- Return type
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
Spaceobject.- Return type
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 countrymax_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
Geoobject.- Return type
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
DirectMessageobject.- Return type
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.
- create_custom_profile(name, file)¶
Create a custom profile
- Parameters
- Returns
This method returns a
CustomProfileobject.- Return type
- 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_streamevent. 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¶
- defblock
- deffetch_followers
- deffetch_following
- deffetch_pinned_tweet
- deffetch_timelines
- deffollow
- defmute
- defreport
- defsend
- deftrigger_typing
- defunblock
- defunfollow
- defunmute
- 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.Filecustom_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
DirectMessageobject.- Return type
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
RelationFollowobject.- Return type
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
RelationFollowobject.- Return type
New in version 1.1.0.
- block()¶
Make a POST Request to Block a User.
New in version 1.2.0.
- unblock()¶
Make a DELETE Request to unblock a User.
New in version 1.2.0.
- mute()¶
Make a POST Request to mute a User.
New in version 1.2.5.
- unmute()¶
Make a DELETE Request to unmute the User.
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.
- 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
Tweetobjects or an empty list if none founded.- Return type
Union[List[
Tweet], List]
New in version 1.3.5.
- property username¶
Return the user’s username, this usually start with ‘@’ follow by their username.
- Type
- property link¶
Return url where the user put links, return an empty string if there isn’t a url
- Type
- property private¶
An alias to
User.protected.- Type
- property created_at¶
Return datetime.datetime object with the user’s account date.
- Type
Optional[
datetime.datetime]
Tweet¶
- defdelete
- deffetch_liking_users
- deffetch_replied_user
- deffetch_retweeters
- defhide
- deflike
- defreply
- defretweet
- defunhide
- defunlike
- defunretweet
- 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
RelationLikeobject.- Return type
Optional[
RelationLike]
New in version 1.2.0.
- unlike()¶
Unlike the tweet.
- Returns
This method returns a
RelationLikeobject.- Return type
New in version 1.2.0.
- retweet()¶
Retweet the tweet.
- Returns
This method returns a
RelationRetweetobject.- Return type
New in version 1.2.0.
- unretweet()¶
Unretweet the tweet.
- Returns
This method returns a
RelationRetweetobject.- Return type
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
RelationHideobject.- Return type
RelationHide
New in version 1.2.5.
- unhide()¶
Unhide a hide reply.
- Returns
This method returns a
RelationHideobject.- Return type
RelationHide
New in version 1.2.5.
- fetch_retweeters()¶
Return users that retweeted the tweet.
- fetch_liking_users()¶
Return users that liked the tweet.
- 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.
- 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
- 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
- property raw_reply_setting¶
Return the raw reply setting value. If everyone can replied, this method return ‘Everyone’.
- Type
- property reply_setting¶
Return a
ReplySettingobject with the tweet’s reply setting. If everyone can reply, this method return ReplySetting.everyone.- Type
- 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
- property mentions¶
Return the mentioned user’s username.
New in version 1.1.3.
- Type
Optional[List[
str]]
- property embeds¶
Return a list of Embedded url from that tweet
New in version 1.1.3.
- Type
List[
Embed]
- 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¶
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
- property created_at¶
Returns the time when the Direct Message event was created.
New in version 1.2.0.
- Type
- 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]
WelcomeMessage¶
- class pytweet.WelcomeMessage(name=None, *, text, id, timestamp, http_client)¶
Represent a Welcome Message in a Direct Message.
- Parameters
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 textfile (Optional[
File]:) – Represent a single file attachment. It could be an image, gif, or video. It also have to be an instance of pytweet.Filequick_reply (Optional[
QuickReply]) – The message’sQuickReplyattachments.
- Returns
Returns your
WelcomeMessageinstance.- Return type
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
WelcomeMessageRule¶
- defdelete
- 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
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
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¶
- 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 created_at¶
Returns a datetime.datetime object with the CustomProfile created time.
New in version 1.3.5.
- Type
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 isMediaType.videoconsider usingMedia.preview_image_url.- Type
- property preview_image_url¶
Returns the video’s preview image url, This is only available when the media type is a
MediaType.videowhich is for video only.- Type
Space¶
- defis_ticketed
- class pytweet.Space(data)¶
-
- property state¶
The type of the space’s state.
New in version 1.3.5.
- Type
- property created_at¶
Returns a datetime.datetime object with the space’s created datetime.
New in version 1.3.5.
- Type
- 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]
Poll¶
- defadd_option
- 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
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.
- property options¶
Return a list of
PollOption.New in version 1.1.0.
- Type
List[
PollOption]
- 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
- property end_date¶
Return the end date in datetime.datetime object.
New in version 1.1.0.
- Type
Optional[
datetime.datetime]
PollOption¶
CTA¶
- defadd_button
- 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
CTAinstance.- Return type
New in version 1.3.5.
QuickReply¶
- defadd_option
- 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
QuickReplyinstance.- Return type
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 country_code¶
Returns the country’s code where the location is in.
New in version 1.3.5.
- Type
File¶
Option¶
- class pytweet.Option(label, description, metadata)¶
Represent an Option object. You can create an Option using
QuickReply.add_optionNew 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¶
- clsStream.sample_stream
- defadd_rule
- defclear
- defconnect
- deffetch_rules
- defset_rules
- 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
Streaminstance.- Return type
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
- 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
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
listofStreamRuleobjects.- Return type
Optional[List[
StreamRule]]
New in version 1.3.5.
StreamConnection¶
- 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.
- 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¶
RelationLike¶
RelationRetweet¶
Embeds¶
Embed¶
- class pytweet.Embed(data)¶
Represent the embedded urls in a tweet.
- property images¶
Return a list of Embed’s Images
New in version 1.1.3.
- Type
List[
EmbedsImages]
EmbedsImages¶
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_connectis 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_disconnectis an event trigger when the client disconnect from stream.- Parameters
connection (
StreamConnection) – The Stream connection.
- pytweet.on_stream(tweet, connection)¶
on_streamis 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
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
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
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 andpost_oauth_tokenposting 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/homewill behttp://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: 401New in version 1.0.0.
- exception pytweet.TooManyRequests(response=None, message=None)¶
HTTPException: Raised when ratelimit exceeded and a request return status code: 429New 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.