Skip to main content

A simple Python wrapper for Twitter API v2 ✨ 🍰 ✨

Project description

python-twitter

A simple Python wrapper around 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 description and update at Twitter API v2: Early Access.

Library docs site 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 cover features:

  • Tweets
    • Tweet lookup

    • Manage Tweets

    • Timelines

    • Search Tweets

    • Tweet counts

    • Filtered stream

    • Volume streams

    • Retweets

    • Likes

    • Hide replies

  • Users
    • User lookup

    • Follows

    • Blocks

    • Mutes

  • Spaces
    • Spaces lookup

    • Search Spaces

  • Compliance
    • Batch compliance

  • Lists
    • List lookup

    • Manage lists

    • List Tweets lookup

    • List members

    • List follows

    • Pinned Lists

INSTANTIATE

You can initialize with an bearer token:

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

With user context token:

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

Or with authorize 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 announcing OAuth 2.0 beta

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 OAuth 1.0a 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 initial 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 sample_stream function to build a connection.

>>> stream_api.sample_stream()

For Search Stream, You can point your rules.

Get your current rules.

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

Delete You 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 match your rules.

>>> stream_api.search_stream()

You can go to the Example folder for streaming examples.

TODO

  • More Api waiting twitter

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python-twitter-v2-0.7.4.tar.gz (27.8 kB view details)

Uploaded Source

Built Distribution

python_twitter_v2-0.7.4-py3-none-any.whl (30.1 kB view details)

Uploaded Python 3

File details

Details for the file python-twitter-v2-0.7.4.tar.gz.

File metadata

  • Download URL: python-twitter-v2-0.7.4.tar.gz
  • Upload date:
  • Size: 27.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.13 CPython/3.8.2 Linux/5.11.0-1028-azure

File hashes

Hashes for python-twitter-v2-0.7.4.tar.gz
Algorithm Hash digest
SHA256 cf8ced6151f4203b7d2530d533252c7bf85cf4a2e4c2185a72b04177019ec9bb
MD5 220f2a699dd27a5ee4eb5c885404fb1a
BLAKE2b-256 5d012ca01eefa457c63bb264fa807cee5e46fa7cdedf86ba38a466cd1ca84eb7

See more details on using hashes here.

File details

Details for the file python_twitter_v2-0.7.4-py3-none-any.whl.

File metadata

  • Download URL: python_twitter_v2-0.7.4-py3-none-any.whl
  • Upload date:
  • Size: 30.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.13 CPython/3.8.2 Linux/5.11.0-1028-azure

File hashes

Hashes for python_twitter_v2-0.7.4-py3-none-any.whl
Algorithm Hash digest
SHA256 c161cdf06c2d7f8796f87d75ccca675312a43931110d96340b9071768a8b092d
MD5 8740e1756a66a2e8faf7e7d020fd9cf0
BLAKE2b-256 4802899c3dec0d890b7732c9ea9b216699bab3bb3c783e770d2539463540da21

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page