«

»

Apr
28

Tweepy – Python Twitter Library

It‘s pretty awesome and easy to use.  The whole oauth circle is a nice thing to know, but it’s major headache the first time around.  Tweepy hides a lot of the not so fun parts and sets up a simple interface.  So, I’ll assume we can forward past the whole registering a Twitter account in order to get a consumer and secret key and move on.  So in order to hook up your user to their Twitter account for a web app, it’s just these easy steps (note, the code is chopped from some prod code, so a few things have been pseudo-coded for generic reasons):

1) Get the auth url:


def get_authorization_url(user_id):
    auth = tweepy.OAuthHandler(consumer_key, secret_key)
    url = auth.get_authorization_url()
    return url #or redirect to it, or whatever you want

2) Receive their token and verifier, then store for later use:


def authorize(user_id, token, verifier):
    auth = tweepy.OAuthHandler(consumer_key, secret_key)
    try:
        auth.set_request_token(token, secret_key)
        token = auth.get_access_token(verifier=verifier)
        attach_token_to_user(user_id, token.to_string())
        return WHATEVERYOUWANT
    except tweepy.error.TweepError as e:
        log.exception("some exception")
        raise InvalidAuthorizationError() #my custom error

3) Use later:


def post_to_my_feed(user_id, twitter_username, tweet):
    try:
        token_string = get_auth_token_for_user(user_id)
        if not token_string:
            raise AccountNotLinkedError()
        token = tweepy.oauth.OAuthToken.from_string(token_string)
        auth = tweepy.OAuthHandler(consumer_key, secret_key)
        auth.set_access_token(token.key, token.secret)
        api = tweepy.API(auth)
        api.update_status(tweet)
        return WHATEVERYOUWANT
    except tweepy.error.TweepError as e:
        log.exception('Something went wrong: appropriate error message')
        raise SomethingWentWrongException("some good message")

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>