Manipulate the Twitter API from Python Post a tweet to your account!
By the way, the Python Twitter Tools used this time is a package that can not only post, but also get Twitter search results and send direct messages.
MacBook Air (13-inch, Mid 2011) Processor: 1.8 GHz Intel Core i7 Memory: 4 GB 1333 MHz DDR3 OS version: 10.11.5 Python: 3.5.2
This time we will use Python Twitter Tools.
There seems to be a way to install it with pip, but I downloaded the file from here and installed it.
https://pypi.python.org/pypi/twitter
After downloading, move to the unzipped folder and install. (Since the version is written in the folder, please enter it according to the DL.)
$cd twitter-x.xx.x
$python setup.py install
$pip install twitter
Register the Twitter application from the following page to use the API. Use the same account that you normally post.
https://apps.twitter.com/
After registering, select the "Keys and Access Tokens" tab and select Get API key, API secret, Access token, Access token secret.
Now, let's put various Tokens in the following code and execute it.
post.py
from twitter import Twitter, OAuth
access_token = "Fill in your own"
access_token_secret = "Fill in your own"
api_key = "Fill in your own"
api_secret = "Fill in your own"
t = Twitter(auth = OAuth(access_token, access_token_secret, api_key, api_secret))
text = 'I tweeted using Python.'
statusUpdate = t.statuses.update(status=text)
#Output of raw post data
print(statusUpdate)
#Output of post data with narrowed down elements
print(statusUpdate['user']['screen_name'])
print(statusUpdate['user']['name'])
print(statusUpdate['text'])
When you run it, it first prints a very long string, which is all the data contained in one post.
It's hard to tell what kind of content was tweeted, so it looks like this. In the last 3 lines, the screen name, user name, and post body are extracted and output.
post.py
#Output of post data with narrowed down elements
print(statusUpdate['user']['screen_name'])
print(statusUpdate['user']['name'])
print(statusUpdate['text'])
I think you should edit the inside of [] according to the data you want to extract. For example, you can get a profile introduction by typing ['description'].
It was a handy introduction to Python Twitter Tools that you can post and extract.
Recommended Posts