Posting to Twitter with Python - Part Two - Posting Photos

Posting to Twitter with Python - Part Two: Posting Photos

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


If you just want the code, you can grab the code repo for this tutorial here:

Fork me on GitHub

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

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


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(
    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__":

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


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.
Ok, lets continue.