An API and command-line toolset for Twitter (twitter.com)
Project description
Python Twitter Tools
The Minimalist Twitter API for Python is a Python port for Twitter's API.
For more information:
- install the package
pip install twitter
- import the
twitter
package and runhelp()
on it
Programming with the Twitter API classes
The minimalist yet fully featured Twitter API class.
Get RESTful data by accessing members of this class. The result is decoded python objects (lists and dicts).
The Twitter API is documented at:
https://developer.twitter.com/en/docs
The list of most accessible functions is listed at:
https://developer.twitter.com/en/docs/api-reference-index
The Twitter
and TwitterStream
classes are the key to building your own
Twitter-enabled applications.
The Twitter2
and TwitterStream2
classes are helpers preconfigured to
handle the specificities of Twitter API v2.
from twitter import Twitter, Twitter2, TwitterStream, TwitterStream2
Authenticating
Querying the Twitter API requires you to authenticate using individual credentials.
In order to obtain these, visit first the Twitter developer page and apply for a developer acount (which now requires you to provide a cellphone number in your account settings and to fill a form describing your intentions in using the Twitter API), then create an app.
Once your app is configured, you can generate your API keys set:
- API
KEY
andSECRET
- Access
OAUTH_TOKEN
andOAUTH_TOKEN_SECRET
- OAuth2
BEARER_TOKEN
You can authenticate with Twitter in three ways: NoAuth, OAuth, or
OAuth2 (app-only and API v2). Get help()
on these classes to learn how to use them.
OAuth and OAuth2 are probably the most useful.
- OAuth requires a complete set of
KEY
,SECRET
,OAUTH_TOKEN
andOAUTH_TOKEN_SECRET
:
from twitter import OAuth
auth = OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, KEY, SECRET)
- OAuth2 can be used directly with just the
BEARER_TOKEN
:
from twitter import OAuth2
auth2 = OAuth2(bearer_token=BEARER_TOKEN)
Note also that you can configure your app to enable "3-legged OAuth" if you want to allow other users to interact with Twitter through your app. In this case, only your KEY and SECRET will be required and your application will need to be authorized by the user by performing the "OAuth Dance" (see dedicated documentation below.
Instantiating
Now that you have credentials allowing to use either OAuth or OAuth2 authentification, you can instantiate the Twitter classes like this:
# For the API v1.1:
tw = Twitter(auth=auth)
# and
tw_app = Twitter(auth=auth2)
# And for the v2:
tw2 = Twitter2(auth=auth)
tw2_app = Twitter2(auth=auth2)
# (which are actually the same as:)
tw2 = Twitter(auth=auth, api_version = "2", format="")
tw2_app = Twitter(auth=auth2, api_version = "2", format="")
Note that the different API routes proposed can sometimes require always OAuth2 while certain will only work with regular OAuth and other will accept both (but potentially with different rate limits). Please read the official documentation to know which authentication to use for which routes.
Querying the API
The philosophy of this wrapper is to be as flexible as possible and allow users to call any new routes added by Twitter without requiring to add specific code for each route within the library first. One only needs to know the url of an API route to call it as if it were an attribute of the Twitter classes.
Hence, for instance, to use the v2 search tweets route
https://api.twitter.com/2/tweets/search/recent
,
you can call it as such:
tw2_app.tweets.search.recent(query="python", max_results=50)
Identically with the v1.1 search route
https://api.twitter.com/1.1/search/tweets.json
:
tw.search.tweets(q="python", result_type="recent", count=50)
API routes sometimes include an argument within them. In such cases the
positionnal argument should be prefixed with an underscore and reused as
such in the function's arguments. For instance, to get a user's id when
knowing only its screen_name, one can use https://api.twitter.com/2/users/by/username/:username
:
res = tw2.users.by.username._username(_username="PythonTwitTools")
user_id = res["data"]["id"]
Similarly, to collect all recent tweets of this account (his "timeline"), using https://api.twitter.com/2/users/:id/tweets
;
tw2.users._id.tweets(_id=user_id, exclude="retweets")
Some routes also require an id
to be given at the end of the route url. In those cases, one can directly use the 'id argument without prefixing it with an underscore and it will magically be added at the end of the route. For instance to get more metadata on the previous user, thanks to the route [
https://api.twitter.com/2/users/:id`](https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-id)
tw2.users(id=user_id)
# which is identical to
tw2.users._id(_id=user_id)
Consequently, when calling one of the rare routes raking an argument named "id" but that is not supposed to appear within the route url, it needs to be renamed as _id
within the function's argument. For instance, to call https://api.twitter.com/1.1/collections/show.json
:
tw.collections.show(_id="custom-388061495298244609")
# instead of the following which will return a 404 error:
tw.collections.show(id="custom-388061495298244609")
Finally, some routes require to force the HTTP method used to call them (GET
, POST
, DELETE
, etc.). The library uses GET by default and tries to guess most other cases, but it required sometimes to be forced, wghich can be done by using the extra _method
argument. For instance, the route https://api.twitter.com/2/users/:id/muting
can be called with GET to collect a list of muted users, and with POST
to add a user to this list:
# To see the list of all users muted by our previous user:
tw2.users._id.muting(_id=user_id)
# And instead to mute this specific user:
tw2.users._id.muting(_id=user_id, _method="POST")
Examples with Twitter API v2: +++++++++++++++++++++++++++++
from twitter import *
# First instantiate the class by authenticating with OAuth:
t = Twitter2(
auth=OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET))
# Or with OAuth2 using a bearer token:
t = Twitter2(auth=OAuth2(bearer_token=BEARER_TOKEN))
# Note Twitter2 is only a wrapper for the regular Twitter class with presets,
# so the above are equivalent to the following:
t = Twitter(
auth=OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET),
api_version="2",
format="")
t = Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN), api_version="2", format="")
# Then use it to query the API. For instance grab a specific tweet:
t.tweets(id=1293595870563381249)
# Twitter v2 API does not return automatically all fields like v1.1 was
# One needs to specify which expansions and fields are desired as listed in
# the [official documentation](https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id).
# For instance, to get everything available on the previous tweet:
t.tweets(
id=1293595870563381249,
expansions="author_id,referenced_tweets.id,referenced_tweets.id.author_id,entities.mentions.username,attachments.poll_ids,attachments.media_keys,in_reply_to_user_id,geo.place_id",
params={
"tweet.fields": "attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,public_metrics,possibly_sensitive,referenced_tweets,reply_settings,source,text,withheld",
"user.fields": "created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld",
"media.fields": "duration_ms,height,media_key,preview_image_url,type,url,width,public_metrics",
"place.fields": "contained_within,country,country_code,full_name,geo,id,name,place_type",
"poll.fields": "duration_minutes,end_datetime,id,options,voting_status"
})
# The Stream also has its own wrapper:
ts = TwitterStream2(auth=OAuth2(bearer_token=BEARER_TOKEN))
# Then calling it behaves like python generators. For instance the sample stream:
for tweet in ts.tweets.sample.stream():
print(tweet)
# The same applies to the regular filter stream:
for tweet in ts.tweets.search.stream():
print(tweet)
# Although it does not anymore take any filter argument and needs to be
# controlled separately using the regular Twitter class.
# To know which rules apply, just call:
t.tweets.search.stream.rules()
# And to add new rules, send POST json queries to the same route:
t.tweets.search.stream.rules(_json={"add": [{"value": "python"}]})
# Then call the stream as described above:
for tweet in ts.tweets.search.stream():
print(tweet)
# Get more details on rules possibilities and syntax in the officiel documentation:
# https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/post-tweets-search-stream-rules
Examples with Twitter API Standard v1.1: ++++++++++++++++++++++++++++++++++++++++
from twitter import *
t = Twitter(auth=OAuth(token, token_secret, consumer_key, consumer_secret))
# Get your "home" timeline
t.statuses.home_timeline()
# Get a particular friend's timeline
t.statuses.user_timeline(screen_name="boogheta")
# to pass in GET/POST parameters, such as `count`
t.statuses.home_timeline(count=5)
# to pass in the GET/POST parameter `id` you need to use `_id`
t.statuses.show(_id=1234567890)
# Update your status
t.statuses.update(
status="Using @boogheta's sweet Python Twitter Tools.")
# Send a direct message
t.direct_messages.events.new(
_json={
"event": {
"type": "message_create",
"message_create": {
"target": {
"recipient_id": t.users.show(screen_name="boogheta")["id"]},
"message_data": {
"text": "I think yer swell!"}}}})
# Get the members of maxmunnecke's list "network analysis tools" (grab the list_id within the url) https://twitter.com/i/lists/1130857490764091392
t.lists.members(owner_screen_name="maxmunnecke", list_id="1130857490764091392")
# Favorite/like a status
status = t.statuses.home_timeline()[0]
if not status['favorited']:
t.favorites.create(_id=status['id'])
# An *optional* `_timeout` parameter can also be used for API
# calls which take much more time than normal or twitter stops
# responding for some reason:
t.users.lookup(
screen_name=','.join(A_LIST_OF_100_SCREEN_NAMES), _timeout=1)
# Overriding Method: GET/POST
# you should not need to use this method as this library properly
# detects whether GET or POST should be used, Nevertheless
# to force a particular method, use `_method`
t.statuses.oembed(_id=1234567890, _method='GET')
# Send images along with your tweets:
# - first just read images from the web or from files the regular way:
with open("example.png", "rb") as imagefile:
imagedata = imagefile.read()
# - then upload medias one by one on Twitter's dedicated server
# and collect each one's id:
t_upload = Twitter(domain='upload.twitter.com',
auth=OAuth(token, token_secret, consumer_key, consumer_secret))
id_img1 = t_upload.media.upload(media=imagedata)["media_id_string"]
id_img2 = t_upload.media.upload(media=imagedata)["media_id_string"]
# - finally send your tweet with the list of media ids:
t.statuses.update(status="PTT ★", media_ids=",".join([id_img1, id_img2]))
# Or send a tweet with an image (or set a logo/banner similarly)
# using the old deprecated method that will probably disappear some day
params = {"media[]": imagedata, "status": "PTT ★"}
# Or for an image encoded as base64:
params = {"media[]": base64_image, "status": "PTT ★", "_base64": True}
t.statuses.update_with_media(**params)
# Attach text metadata to medias sent, using the upload.twitter.com route
# using the _json workaround to send json arguments as POST body
# (warning: to be done before attaching the media to a tweet)
t_upload.media.metadata.create(_json={
"media_id": id_img1,
"alt_text": { "text": "metadata generated via PTT!" }
})
# or with the shortcut arguments ("alt_text" and "text" work):
t_upload.media.metadata.create(media_id=id_img1, text="metadata generated via PTT!")
Searching Twitter:
# Search for the latest tweets about #pycon
t.search.tweets(q="#pycon")
# Search for the latest tweets about #pycon, using [extended mode](https://developer.twitter.com/en/docs/tweets/tweet-updates)
t.search.tweets(q="#pycon", tweet_mode='extended')
Retrying after reaching the API rate limit
Simply create the Twitter
instance with the argument retry=True
, then the
HTTP error codes 429
, 502
, 503
, and 504
will cause a retry of the last
request.
If retry
is an integer, it defines the maximum number of retry attempts.
Using the data returned
Twitter API calls return decoded JSON. This is converted into a bunch of Python lists, dicts, ints, and strings. For example:
x = twitter.statuses.home_timeline()
# The first 'tweet' in the timeline
x[0]
# The screen name of the user who wrote the first 'tweet'
x[0]['user']['screen_name']
Getting raw XML data
If you prefer to get your Twitter data in XML format, pass
format="xml"
to the Twitter
object when you instantiate it:
twitter = Twitter(format="xml")
The output will not be parsed in any way. It will be a raw string of XML.
The TwitterStream
class
The TwitterStream
object is an interface to the Twitter Stream
API. This can be used pretty much the same as the Twitter
class,
except the result of calling a method will be an iterator that
yields objects decoded from the stream. For example::
twitter_stream = TwitterStream(auth=OAuth(...))
iterator = twitter_stream.statuses.sample()
for tweet in iterator:
...do something with this tweet...
Per default the TwitterStream
object uses
public streams.
If you want to use one of the other
streaming APIs, specify the URL
manually.
The iterator will yield
until the TCP connection breaks. When the
connection breaks, the iterator yields {'hangup': True}
(and
raises StopIteration
if iterated again).
Similarly, if the stream does not produce heartbeats for more than
90 seconds, the iterator yields {'hangup': True, 'heartbeat_timeout': True}
(and raises StopIteration
if
iterated again).
The timeout
parameter controls the maximum time between
yields. If it is nonzero, then the iterator will yield either
stream data or {'timeout': True}
within the timeout period. This
is useful if you want your program to do other stuff in between
waiting for tweets.
The block
parameter sets the stream to be fully non-blocking.
In this mode, the iterator always yields immediately. It returns
stream data, or None
.
Note that timeout
supercedes this argument, so it should also be
set None
to use this mode, and non-blocking can potentially lead
to 100% CPU usage.
Twitter Response
Objects
Response from a Twitter request. Behaves like a list or a string (depending on requested format), but it has a few other interesting attributes.
headers
gives you access to the response headers as an
httplib.HTTPHeaders
instance. Use response.headers.get('h')
to retrieve a header.
OAuth Danse
When users run your application they have to authenticate your app with their Twitter account. A few HTTP calls to Twitter are required to do this. Please see the twitter.oauth_dance module to see how this is done. If you are making a command-line app, you can use the oauth_dance() function directly.
Performing the "oauth dance" gets you an oauth token and oauth secret that authenticate the user with Twitter. You should save these for later, so that the user doesn't have to do the oauth dance again.
read_token_file
and write_token_file
are utility methods to read and
write OAuth token
and secret
key values. The values are stored as
strings in the file. Not terribly exciting.
Finally, you can use the OAuth
authenticator to connect to Twitter. In
code it all goes like this:
import os
from twitter import oauth_dance, read_token_file, Twitter, OAuth
KEY = "xxxxxxxx"
SECRET = "xxxxxxxx"
MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
oauth_dance("My App Name", KEY, SECRET, MY_TWITTER_CREDS)
oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)
twitter = Twitter(auth=OAuth(oauth_token, oauth_secret, KEY, SECRET))
# Now work with Twitter
twitter.statuses.update(status='Hello, world!')
License
Python Twitter Tools and the Twitter API Python wrapper are released under an MIT License.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file twitter-2.0a0.tar.gz
.
File metadata
- Download URL: twitter-2.0a0.tar.gz
- Upload date:
- Size: 52.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a2349289e17d93afa8dd9cc0ad397f63c2e715d1ca510217c2c3a7d22856321a |
|
MD5 | 16e9ce941245d622b2545e8a634206cd |
|
BLAKE2b-256 | 5e66c0f670e288f13d48f915e2ff085298aca21759f0d511a426a664da9d1b33 |
Provenance
File details
Details for the file twitter-2.0a0-py2.py3-none-any.whl
.
File metadata
- Download URL: twitter-2.0a0-py2.py3-none-any.whl
- Upload date:
- Size: 52.6 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 92838a8b419ef880de45978a9f81216cee39cb2fe75c181b6a52727a68270ead |
|
MD5 | 0563378c3dc45c4921527e2e97fc0281 |
|
BLAKE2b-256 | e4c6b0de715d2087d81964e655b722383d75b07a2fdf1605d42e3708c3b7afa2 |