Tweepy

An easy-to-use Python library for accessing the Twitter API.

http://www.tweepy.org/

Installing

pip install tweepy

Twitter App

https://apps.twitter.com/

Create an app and save:

  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret

Store Secrets Securely

Don't commit them to a public repo!

I set them via environment variables and then access via os.environ.


In [ ]:
# Load keys, secrets, settings

import os

ENV = os.environ
CONSUMER_KEY = ENV.get('IOTX_CONSUMER_KEY')
CONSUMER_SECRET = ENV.get('IOTX_CONSUMER_SECRET')
ACCESS_TOKEN = ENV.get('IOTX_ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = ENV.get('IOTX_ACCESS_TOKEN_SECRET')
USERNAME = ENV.get('IOTX_USERNAME')
USER_ID = ENV.get('IOTX_USER_ID')

print(USERNAME)

Twitter APIs

REST vs Streaming

https://dev.twitter.com/docs

Twitter REST API

  • Search
  • Tweet
  • Get information

https://dev.twitter.com/rest/public


In [ ]:
import tweepy

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)

public_tweets = api.home_timeline(count=3) 
for tweet in public_tweets:
    print(tweet.text)

In [ ]:
# Models

user = api.get_user('clepy')
print(user.screen_name)
print(dir(user))

In [ ]:
# Tweet!
status = api.update_status("I'm at @CLEPY!")
print(status.id)
print(status.text)

Streaming API

Real-time streaming of:

  • Searches
  • Mentions
  • Lists
  • Timeline

https://dev.twitter.com/streaming/public


In [ ]:
# Subclass StreamListener and define on_status method

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        print("@{0}: {1}".format(status.author.screen_name, status.text))

In [ ]:
myStream = tweepy.Stream(auth = api.auth, listener=MyStreamListener())

In [ ]:
try:
    myStream.filter(track=['#clepy'])
except KeyboardInterrupt:
    print('Interrupted...')
except tweepy.error.TweepError:
    myStream.disconnect()
    print('Disconnected. Try again!')

See also:

"Small Batch Artisanal Bots: Let's Make Friends" by Elizabeth Uselton at PyCon & PyOhio

https://www.youtube.com/watch?v=pDS_LWgjMgg


In [ ]: