Skip to content

Commit

Permalink
WIP on README
Browse files Browse the repository at this point in the history
  • Loading branch information
boogheta committed Oct 29, 2021
1 parent a50ec37 commit 69e1112
Showing 1 changed file with 161 additions and 68 deletions.
229 changes: 161 additions & 68 deletions README
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
Python Twitter Tools
====================
# Python Twitter Tools

[![Tests](https://github.com/python-twitter-tools/twitter/workflows/Tests/badge.svg)](https://github.com/python-twitter-tools/twitter/actions)
[![Coverage Status](https://coveralls.io/repos/github/python-twitter-tools/twitter/badge.svg?branch=master)](https://coveralls.io/github/python-twitter-tools/twitter?branch=master)
Expand All @@ -12,17 +11,7 @@ For more information:
* import the `twitter` package and run `help()` on it


Programming with the Twitter API classes
========================================

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.


The `Twitter` class
-------------------
## Programming with the Twitter API classes

The minimalist yet fully featured Twitter API class.

Expand All @@ -37,6 +26,150 @@ The list of most accessible functions is listed at:

**[https://developer.twitter.com/en/docs/api-reference-index](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.

```python
from twitter import Twitter, Twitter2, TwitterStream, TwitterStream2
```

### Authenticating

Querying the Twitter API requires you to [authenticate](https://developer.twitter.com/en/docs/authentication/overview) using individual credentials.

In order to obtain these, visit first the [Twitter developer page](https://developer.twitter.com/)
and [apply for a developer acount](https://developer.twitter.com/en/apply-for-access)
(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](https://developer.twitter.com/en/portal/apps/new).

Once your app is configured, you can generate your API keys set:
- API `KEY` and `SECRET`
- Access `OAUTH_TOKEN` and `OAUTH_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` and
`OAUTH_TOKEN_SECRET`:

```python
from twitter import OAuth

auth = OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, KEY, SECRET)
```

- OAuth2 can be used directly with just the `BEARER_TOKEN`:

```python
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](#oauth-dance).


### Instantiating

Now that you have credentials allowing to use either OAuth or OAuth2
authentification, you can instantiate the Twitter classes like this:

```python
# 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](https://developer.twitter.com/en/docs/api-reference-index)
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`](https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent),
you can call it as such:

```python
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`](https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/api-reference/get-search-tweets):

```python
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`](https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-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`](https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets);

```python
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)

```python
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`](https://developer.twitter.com/en/docs/twitter-api/v1/tweets/curate-a-collection/api-reference/get-collections-show):

```python
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`](https://developer.twitter.com/en/docs/twitter-api/users/mutes/api-reference/get-users-muting) can be called with GET to collect a list of muted users, and with `POST` to add a user to this list:

```python
# 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:
+++++++++++++++++++++++++++++
Expand Down Expand Up @@ -295,29 +428,14 @@ attributes.
`httplib.HTTPHeaders` instance. Use `response.headers.get('h')`
to retrieve a header.

Authentication
--------------

You can authenticate with Twitter in three ways: NoAuth, OAuth, or
OAuth2 (app-only). Get `help()` on these classes to learn how to use them.

OAuth and OAuth2 are probably the most useful.


Working with OAuth
------------------

Visit the Twitter developer page and create a new application:
### OAuth Danse

**[https://dev.twitter.com/apps/new](https://dev.twitter.com/apps/new)**

This will get you a `CONSUMER_KEY` and `CONSUMER_SECRET`.

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.
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
Expand All @@ -331,50 +449,25 @@ Finally, you can use the `OAuth` authenticator to connect to Twitter. In
code it all goes like this:

```python
from twitter import *
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", CONSUMER_KEY, CONSUMER_SECRET,
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, CONSUMER_KEY, CONSUMER_SECRET))
twitter = Twitter(auth=OAuth(oauth_token, oauth_secret, KEY, SECRET))

# Now work with Twitter
twitter.statuses.update(status='Hello, world!')
```

Working with `OAuth2`
---------------------

Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.

To authenticate with OAuth2, visit the Twitter developer page and create a new
application:

**[https://dev.twitter.com/apps/new](https://dev.twitter.com/apps/new)**

This will get you a `CONSUMER_KEY` and `CONSUMER_SECRET`.

Exchange your `CONSUMER_KEY` and `CONSUMER_SECRET` for a bearer token using the
`oauth2_dance` function.

Finally, you can use the `OAuth2` authenticator and your bearer token to connect
to Twitter. In code it goes like this::

```python
twitter = Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN))

# Now work with Twitter
twitter.search.tweets(q='keyword')
```

License
=======
## License

Python Twitter Tools are released under an MIT License.
Python Twitter Tools and the Twitter API Python wrapper are released
under an MIT License.

0 comments on commit 69e1112

Please sign in to comment.