Posting to Twitter with Python - Part Two - Posting Photos

Posting to Twitter with Python - Part Two: Posting Photos

NOTE:

This is part two of my posting to Twitter with Python tutorial. If you haven't been through part one, it's here: Four Simple Steps To Post To Twitter Using Python

In this tutorial, we're going to write a quick script to post to twitter using the Python and the Tweepy package

TLDR;

If you just want the code, you can grab the code repo for this tutorial here: https://github.com/mattccrampton/post_to_twitter_using_python

Fork me on GitHub

First, fire up your editor of choice again and create a new file named post_tweet_with_image.py

> vim post_tweet_with_image.py

Paste in the following code, make sure to substitute your keys and tokens you copied down from the earlier steps above.

import tweepy

def main():
    twitter_auth_keys = {
        "consumer_key"        : "REPLACE_THIS_WITH_YOUR_CONSUMER_KEY",
        "consumer_secret"     : "REPLACE_THIS_WITH_YOUR_CONSUMER_SECRET",
        "access_token"        : "REPLACE_THIS_WITH_YOUR_ACCESS_TOKEN",
        "access_token_secret" : "REPLACE_THIS_WITH_YOUR_ACCESS_TOKEN_SECRET"
    }

    auth = tweepy.OAuthHandler(
            twitter_auth_keys['consumer_key'],
            twitter_auth_keys['consumer_secret']
            )
    auth.set_access_token(
            twitter_auth_keys['access_token'],
            twitter_auth_keys['access_token_secret']
            )
    api = tweepy.API(auth)

    # Upload image
    media = api.media_upload("william_gibson.jpg")

    # Post tweet with image
    tweet = "Great scifi author or greatest scifi author? #williamgibson"
    post_result = api.update_status(status=tweet, media_ids=[media.media_id])

if __name__ == "__main__":
    main()

You'll notice there is a few additonal lines there that wasn't in step 1. Those show how we're first uploading an image to twitter, getting a media object out, and then passing that media object to the api.update_status() call.

Note: the william_gibson.jpg image I'm using as an example is in the github repo for this tutorial

BTW: The original Tweetpy documentation incorrectly asked for a comma separated list of media ids instead of a native python list which failed when used. I filed a bug to correct the issue and the Tweepy folks put a fix in within an hour. Very cool.

Run the new script

Now we're ready to run our code, fire away

> python post_tweet_with_image.py

If everything went right, you should see your brand new tweet (with image) on your twitter profile page.

Thanks for reading, I hope you followed along and were able to get a version of this working for yourself. If you're having issues or want to chat, ping me on twitter at @mattccrampton

Pause reading for 5 seconds...
Join My Mailing List!
Note: I will never share your email with anyone else.
Awesome! Thanks so much.
Submitting...
Ok, lets continue.
Post A Twitter Response To This Blog Post

To: @mattccrampton

0