Skip to main content

python-twitter

A simple Python wrapper for Twitter API v2 :sparkles: :cake: :sparkles:.

v2 Build Status Codecov PyPI

Introduction

Twitter has published new version Twitter API V2 for developer at Aug 13, 2020.

This library provides a service to easily use this new version Twitter API.

Documentation

You can get all API descriptions Twitter API v2 Documentation.

Docs for this library on here

Installing

You can install this library easily by pypi:

$ pip install python-twitter-v2

Code is hosted at https://github.com/sns-sdks/python-twitter.

Checkout latest development version with:

$ git clone https://github.com/sns-sdks/python-twitter.git
$ cd python-twitter

Install dependencies with:

$ make env

Run tests with:

$ make test

Run tests with coverage:

$ make cov-term
$ make cov-html

Using

The API is exposed via the pytwitter.Api class.

Now covers these features:

  • Tweets
    • Tweet lookup

    • Manage Tweets

    • Quote Tweets

    • Retweet Tweets

    • Timelines

    • Search Tweets

    • Tweet counts

    • Filtered stream

    • Volume streams

    • Retweets

    • Likes

    • Bookmarks

    • Hide replies

  • Users
    • User lookup

    • Follows

    • Blocks

    • Mutes

  • Usage
    • Tweets

  • Trends

  • Spaces
    • Spaces lookup

    • Search Spaces

  • Direct Messages
    • Direct Messages lookup

    • Manage Direct Messages

  • Lists
    • List lookup

    • Manage lists

    • List Tweets lookup

    • List members

    • List follows

    • Pinned Lists

  • Compliance
    • Batch compliance

  • Media Upload
    • Media Simple upload

    • Media Chunked upload

INSTANTIATE

You can initialize with an bearer token:

>>> from pytwitter import Api
>>> api = Api(bearer_token="Your bearer token")

With OAuth 1.0A user context token:

>>> api = Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="access token",
        access_secret="access secret"
    )

Or with authorization done by user:

>>> api = Api(consumer_key="consumer key",consumer_secret="consumer secret",oauth_flow=True)
# get url for user to authorize
>>> api.get_authorize_url()
# copy the response url
>>> api.generate_access_token("https://localhost/?oauth_token=oauth_token&oauth_verifier=oauth_verifier")
{'oauth_token': 'oauth_token',
 'oauth_token_secret': 'oauth_token_secret',
 'user_id': '123456',
 'screen_name': 'screen name'}

Twitter has announced OAuth 2.0 user authentication support with fine-grained scopes

Now if you have app with OAuth2.0 client ID. you can do authorize with OAuth2.

>>> api = Api(client_id="You client ID", oauth_flow=True)
# get the url and code verifier for user to authorize
>>> url, code_verifier, _ = api.get_oauth2_authorize_url()
# copy the response url
>>> api.generate_oauth2_access_token("https://localhost/?state=state&code=code", code_verifier)
{'token_type': 'bearer',
 'expires_in': 7200,
 'access_token': 'access_token',
 'scope': 'users.read tweet.read',
 'expires_at': 1631775928}

Users-lookup

You can get information about a user or group of users, specified by a user ID or a username.

Get group of users:

# By ids
>>> api.get_users(ids=["783214", "2244994945"])
Response(data=[User(id='2244994945', name='Twitter Dev', username='TwitterDev'), User(id='783214', name='Twitter', username='Twitter')])

# By username
>>> api.get_users(usernames="Twitter,TwitterDev")
Response(data=[User(id='2244994945', name='Twitter Dev', username='TwitterDev'), User(id='783214', name='Twitter', username='Twitter')])

Get single user:

# By id
>>> api.get_user(user_id="783214")
Response(data=User(id='783214', name='Twitter', username='Twitter'))

# By username
>>> api.get_user(username="Twitter")
Response(data=User(id='783214', name='Twitter', username='Twitter'))

Get user following:

>>> api.get_following(user_id="2244994945", max_results=5)
Response(data=[User(id='459860328', name='julie✨', username='JulieMendoza206'), User(id='273830767', name='🄿🅄🅂🄷', username='rahul_pushkarna')...])

Get user followers:

>>> api.get_followers(user_id="2244994945", max_results=5)
Response(data=[User(id='715131097332518912', name='Daniel', username='RGIDaniel'), User(id='1176323137757048832', name='Joyce Wang', username='joycew67')...])

You can follow or unfollow user if you have User context.

follow user:

>>> api.follow_user(user_id="123456", target_user_id="654321")
{'data': {'following': True, 'pending_follow': False}}

unfollow user:

>>> api.unfollow_user(user_id="123456", target_user_id="654321")
{'data': {'following': False}}

Tweets-lookup

You can get information about a tweet or group of tweets by tweet id(s).

Get single tweet:

>>> api.get_tweet("1354143047324299264", expansions=["attachments.media_keys"], media_fields=["type","duration_ms"])
Response(data=Tweet(id=1354143047324299264, text=Academics are one of the biggest groups using...))

Get group of tweets:

>>> api.get_tweets(["1261326399320715264","1278347468690915330"],expansions="author_id",tweet_fields=["created_at"], user_fields=["username","verified"])
Response(data=[Tweet(id=1261326399320715264, text=Tune in to the @MongoDB @Twitch stream...), Tweet(id=1278347468690915330, text=Good news and bad news: 2020 is half over)])

Streaming API

For Streaming, this provide StreamApi independent. Same as main Api, You need initialize it first.

>>> from pytwitter import StreamApi
>>> stream_api = StreamApi(bearer_token="bearer token")
# or use consumer key and secret
>>> stream_api = StreamApi(consumer_key="consumer key", consumer_secret="consumer secret")

For Sample Stream tweets, you can use the sample_stream function to build a connection.

>>> stream_api.sample_stream()

For Filtered Stream, you can create rules.

Get your current rules.

>>> stream_api.get_rules()
Response(data=[StreamRule(id='1369580714056843266', value='twitter api ')])

Delete your rules.

>>> stream_api.manage_rules(rules={"delete": {"ids": ["1369580714056843266"]}})
Response(data=[])

Add new rules. If you set dry_run to True, will only validate rules, and not create them.

>>> np = {
        "add": [
            {"value": "cat has:media", "tag": "cats with media"},
            {"value": "cat has:media -grumpy", "tag": "happy cats with media"}
        ]
     }
>>> stream_api.manage_rules(rules=np, dry_run=True)
Response(data=[StreamRule(id='1370406958721732610', value='cat has:media -grumpy'), StreamRule(id='1370406958721732609', value='cat has:media')])

Then you can use search_stream to get tweets matching your rules.

>>> stream_api.search_stream()

You can go to the Example folder for streaming examples.

TODO

  • More Api waiting twitter

Metadata

Release files for python-twitter-v2 0.9.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for python-twitter-v2 0.9.3
File Size Uploaded
python_twitter_v2-0.9.3.tar.gz 32.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for python-twitter-v2 0.9.3
File Interpreter ABI Platform
python_twitter_v2-0.9.3-py3-none-any.whl Python 3 none any Details

Total release size: 69.5 kB

Release files / python_twitter_v2-0.9.3.tar.gz

Download URL python_twitter_v2-0.9.3.tar.gz
Size 32.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e021943cb74f785452d68c87e63e02593ffca9316d6903c4f1799df965654f29
BLAKE2b-256 checksum
How to use checksums
aeab3e261c34ad1b833a0ee3d73fb6b874b107bb32dc72cc2318d7acba0a1116
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.13.1 Linux/6.11.0-1018-azure

Release files / python_twitter_v2-0.9.3-py3-none-any.whl

Download URL python_twitter_v2-0.9.3-py3-none-any.whl
Size 37.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e8317f0bc61d107b44bbafe4c6372231c6edd58a044a324145c898d0b2094759
BLAKE2b-256 checksum
How to use checksums
9f5a54fcdf62c28b7afccde8cc9aa620c5e9d06192979bed158292d8cc5f6bbd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.13.1 Linux/6.11.0-1018-azure

Release history Release notifications | RSS feed

This release

0.9.3 This release

2 release files

0.9.2

2 release files

0.9.1

2 release files

0.9.0

2 release files

0.8.1

2 release files

0.8.0

2 release files

0.7.9

2 release files

0.7.8

2 release files

0.7.7

2 release files

0.7.6

2 release files

0.7.5

2 release files

0.7.4

2 release files

0.7.3

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.2

2 release files

0.3.5

2 release files

0.3.4

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

0.0.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page