Try hitting the Twitter API quickly and easily with Python

Introduction

Since I have more opportunities to use Python personally, this time I will try to tweet and get the timeline with just a simple library. Please refer to other sites until you register the application and obtain the authentication key. I don't think you'll stumble too much. (Please note that you need to link your phone number to your Twitter account.)

As a preliminary preparation, it is a good idea to copy and paste various authentication keys and save them as config.py.

config.py


CONSUMER_KEY = "**************"
CONSUMER_SECRET = "**************"
ACCESS_TOKEN = "**************"
ACCESS_TOKEN_SECRET = "**************"

Now let's write some simple scripts and play with Twitter.

# -*- coding:utf-8 -*-
import json, config
from requests_oauthlib import OAuth1Session

CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET
twitter = OAuth1Session(CK, CS, AT, ATS)

I used request-oauthlib for the Oauth authentication library.

Try to get your own timeline

timeline.py


url = "https://api.twitter.com/1.1/statuses/user_timeline.json"

params ={'count' : 5}
req = twitter.get(url, params = params)

if req.status_code == 200:
    timeline = json.loads(req.text)
    for tweet in timeline:
        print(tweet['user']['name']+'::'+tweet['text'])
        print(tweet['created_at'])
        print('----------------------------------------------------')
else:
    print("ERROR: %d" % req.status_code)

Tearon :: Yesterday's "Broadcast Ban" seems to be amazing, but it seems to have a bad reputation, and above all, it's hard to see because it's a horror or something like that. Tue Jan 03 13:38:22 +0000 2017 ---------------------------------------------------- Tearon::MINAMI KOIKE https://t.co/vFmSRLs89X Tue Jan 03 13:29:53 +0000 2017 ---------------------------------------------------- Tearon :: Overwhelming lack of time due to too much radio that I wanted to listen to during the New Year holidays Tue Jan 03 13:12:42 +0000 2017 ---------------------------------------------------- Tearon :: Then listen "Linda Linda" at The Blue Hearts Tue Jan 03 11:46:17 +0000 2017 ---------------------------------------------------- Tearon :: Boasting "I won with a slingshot!", It seems that the tension is quite high, but I want you to notice this one with the eyes of a rat. Tue Jan 03 11:45:53 +0000 2017 ----------------------------------------------------

Try searching by keyword

search.py


url = "https://api.twitter.com/1.1/search/tweets.json"

print("What to look for?")
keyword = input('>> ')
print('----------------------------------------------------')


params = {'q' : keyword, 'count' : 5}

req = twitter.get(url, params = params)

if req.status_code == 200:
    search_timeline = json.loads(req.text)
    for tweet in search_timeline['statuses']:
        print(tweet['user']['name'] + '::' + tweet['text'])
        print(tweet['created_at'])
        print('----------------------------------------------------')
else:
    print("ERROR: %d" % req.status_code)

What to look for?

#Alpy dcg

----------------------------------------------------

Galileo's ankle :: Alpy ANN is too strong wwwwwwwww #Alpy dcg Tue Jan 03 15:21:09 +0000 2017 ---------------------------------------------------- Always nice everyone's festival :: "This is ... amazing" www #Alpy dcg Tue Jan 03 15:21:08 +0000 2017 ---------------------------------------------------- Cheering song fan :: Don't be spoiled by music w #Alpy dcg Tue Jan 03 15:21:07 +0000 2017 ---------------------------------------------------- New York Nyanchus :: The power of music is amazing ...!

#Alpy dcg Tue Jan 03 15:21:07 +0000 2017 ---------------------------------------------------- Shoo :: How to use Dean Fujioka when you say sugoroku www #Alpy dcg Tue Jan 03 15:21:07 +0000 2017 ----------------------------------------------------

Try to tweet something

tweet.py


url = "https://api.twitter.com/1.1/statuses/update.json"

print("What do you tweet?")
tweet = input('>> ')
print('----------------------------------------------------')

params = {"status" : tweet}

req = twitter.post(url, params = params)

if req.status_code == 200:
    print("Succeed!")
else:
    print("ERROR : %d"% req.status_code)

What do you tweet?

The radio that I wanted to listen to during the New Year holidays is too much and I don't have enough time

----------------------------------------------------
Succeed!

image.png

Post with an image

tweet_media.py


url_media = "https://upload.twitter.com/1.1/media/upload.json"
url_text = "https://api.twitter.com/1.1/statuses/update.json"

print("Enter the name of the attached image(jpg format only)")
media_name = input('>> ')
print('-----------------------------------')

files = {"media" : open(media_name+".jpg ", 'rb')}
req_media = twitter.post(url_media, files = files)

if req_media.status_code != 200:
    print("MEDIA UPLOAD FAILED... %s", req_media.text)
    exit()

media_id = json.loads(req_media.text)['media_id']
print("MEDIA ID: %d" % media_id)

print("What do you tweet?")
tweet = input('>> ')
print('-----------------------------------')

params = {"status" : tweet, "media_ids" : [media_id]}
req_media = twitter.post(url_text, params = params)

if req_media.status_code != 200:
    print("TEXT UPLOAD FAILED... %s", req_text.text)
    exit()

print("SUCCEED!")

Enter the name of the attached image (jpg format only) >> asuka ----------------------------------- MEDIA ID: 816275347591208960 What do you tweet? >> ASUKA SAITO ----------------------------------- SUCCEED!

image.png

in conclusion

It's easy, but I was impressed that the Twitter API was easier to use than I expected. Actually, I was thinking of implementing it using Tweepy, which I had heard before, but it seems that it has not been maintained for a long time, so I stopped it. Next time, I would like to talk about Twitter BOT made using this knowledge.

I was allowed to reference

Get tweets with Twitter API tweepy is no longer maintained Search keywords from Twitter to get images I tried Twitter with Python Access the Twitter API with Python

Recommended Posts

Try hitting the Twitter API quickly and easily with Python
Try hitting the YouTube API in Python
Second half of the first day of studying Python Try hitting the Twitter API with Bottle
Use Twitter API with Python
Try using the Twitter API
Try using the Twitter API
Call the API with python3.
Crawling with Python and Twitter API 1-Simple search function
I tried hitting the API with echonest's python client
A note about hitting the Facebook API with the Python SDK
Specifying the date with the Twitter API
I tried follow management with Twitter API and Python (easy)
Hit the Etherpad-lite API with Python
Streamline information gathering with the Twitter API and Slack bots
Easily post to twitter with Python 3
Access the Twitter API in Python
Quickly install OpenCV 2.4 (+ python) on OS X and try the sample
Crawling with Python and Twitter API 2-Implementation of user search function
Collecting information from Twitter with Python (Twitter API)
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Tweet using the Twitter API in Python
Quickly try Microsoft's Face API in Python
[Python] Quickly create an API with Flask
Easily download mp3 / mp4 with python and youtube-dl!
Try hitting the Spotify API in Django.
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Get the number of articles accessed and likes with Qiita API + Python
Tweet regularly with the Go language Twitter API
Try running Google Chrome with Python and Selenium
Try to solve the man-machine chart with Python
Try using the BitFlyer Ligntning API in Python
Tips for hitting the ATND API in Python
Solving the Lorenz 96 model with Julia and Python
Archive and compress the entire directory with python
Get Gmail subject and body with Python and Gmail API
Try accessing the YQL API directly from Python 3
Try using ChatWork API and Qiita API in Python
Create an API server quickly with Python + Falcon
Try using the DropBox Core API in Python
I tried to automate internal operations with Docker, Python and Twitter API + bonus
Try out the touch of data-driven testing with Selenium Python Bindings and py.test
Try scraping with Python.
Easily beep with python
Try to solve the programming challenge book with python3
[First API] Try to get Qiita articles with Python
[Cloudian # 8] Try setting the bucket versioning with Python (boto3)
Try translating with Python while maintaining the PDF layout
Hit the Twitter API after Oauth authentication with Django
Easily try Amazon EMR / Cloud Dataproc with Python [mrjob]
Try to solve the internship assignment problem with Python
Try touching the micro: bit with VS Code + Python
Install selenium on Mac and try it with python
Try to operate DB with Python and visualize with d3
Visualize the range of interpolation and extrapolation with python
Crawl the URL contained in the twitter tweet with python
Automatic follow on Twitter with python and selenium! (RPA)
Send and receive Gmail via the Gmail API using Python
Book registration easily with Google Books API and Rails
PHP and Python samples that hit the ChatWork API