Access to the Twitter API from Python. Supports both Python 2 and 3.
There is also python-twitter, but basically you just send an HTTP Request and get JSON, so use the Twitter-only library. I thought it wasn't there, so I wrote it myself. Only OAuth authentication uses a separate library.
You need ** OAuth authentication ** to access Twitter. The authentication method is so complicated that ordinary people use libraries.
This time, I will use Requests-OAuthlib, which is self-identified as "OAuth for humans". I don't know what kind of creatures other libraries envision.
To access the Twitter API, you first need to register your application. When you finish this
Two keys are issued. In addition, for each user of the app
Two keys are issued. You need these four keys to access the Twitter API.
How to get it is [Konohen](http://website-planner.com/twitter%E3%82%A2%E3%83%97%E3%83%AA%E3%82%B1%E3%83%BC % E3% 82% B7% E3% 83% A7% E3% 83% B3% E3% 81% AE% E4% BD% 9C% E6% 88% 90% EF% BC% 88consumer-key% E3% 80% 81consumer -see secret% E3% 80% 81access-token% E3% 80% 81access-token-secret /).
The application registration itself is free, but it seems that it became necessary to register the mobile number from around February 2014. I don't know the details, so ggr.
Once you get the key, write the code right away.
Below, replace the CK, CS, AT, AS
parts with your own key as appropriate.
tweet.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
CK = 'XXXXXXXXXXXXXXXXXXXXXX' # Consumer Key
CS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Consumer Secret
AT = 'XXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Access Token
AS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Accesss Token Secert
#URL for posting tweets
url = "https://api.twitter.com/1.1/statuses/update.json"
#Tweet body
params = {"status": "Hello, World!"}
#Post by POST method with OAuth authentication
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.post(url, params = params)
#Check the response
if req.status_code == 200:
print ("OK")
else:
print ("Error: %d" % req.status_code)
The basics are like this. If you want to add an image, rewrite the posted part like this.
tweet_with_image.py
#Tweet body
files = {
"status": "Hello, World!",
"media[]": open("image.png ", "rb")
}
#Post by POST method with OAuth authentication
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.post(url, files = files)
** * Added on 2015/04/27 ** It seems that the specifications for posting images have changed. See here → Tweet with image in Python
There is no big difference except that the URL changes and POST becomes GET. The return value is JSON, and 20 tweets are in list format. Here, only the text is displayed, but it also includes a lot of meta information such as user information, tweet time, and number of favs.
timeline.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
import json
CK = 'XXXXXXXXXXXXXXXXXXXXXX' # Consumer Key
CS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Consumer Secret
AT = 'XXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Access Token
AS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Accesss Token Secert
#URL for getting the timeline
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
#There are no particular parameters
params = {}
#GET with OAuth
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.get(url, params = params)
if req.status_code == 200:
#Since the response is in JSON format, parse it
timeline = json.loads(req.text)
#Display the body of each tweet
for tweet in timeline:
print(tweet["text"])
else:
#In case of error
print ("Error: %d" % req.status_code)
There is no need for parameters, but you can set the range of tweet IDs to be acquired (assigned in chronological order) and the number of tweets (standard 20, maximum 200).
After that, you can do almost anything by rewriting the URL and params. Click here for a list of APIs provided. (English) https://dev.twitter.com/docs/api/1.1
The "unfollow" API is friendships / destroy
, which I've seen many times.
Twitter has a generous API, so it can be functionally almost the same as the official client. However, there is a limit to the number of requests. In particular, Home Timeline is so strict that ** up to 15 times in 15 minutes **, so it is not possible to update the timeline every few seconds.
The remaining API number and the time of the next update are stored in the request header.
#GET with OAuth
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.get(url, params = params)
if req.status_code == 200:
#API rest
limit = req.headers['x-rate-limit-remaining']
#API limit update time(UNIX time)
reset = req.headers['x-rate-limit-reset']
print ("API remain: " + limit)
print ("API reset: " + reset)
As a way to overcome API restrictions
There is such a thing.
The possibilities are endless.
Recommended Posts