Python/Twitter: Posting tweets (with images)

There are a few services out there that'll post your RSS feed to multiple societ networks, but sometimes you want that little extra configurability which just won't happen unless you do it yourself.

There are a few ways of skinning this cat, but today I'll only be writing up about the easiest one.

What you'll need

  • Twython (v3.0.0 at time of writing)
  • A Twitter account (API v1.1 at time of writing)

Download and install Twython from the site or via "pip install twython".

Setting up twitter

What you'll need for this to work is a twitter "app" associated with your account. For the purpose of this tutorial, I'll show you how to set up your own account with your own app for testing purposes.

  • Hit up https://dev.twitter.com and sign in with your twitter account.
  • Go to "My Applications" (via top/right dropdown menu where your account image is).
  • Create a new app by entering the name, description, website
  • Go to "Settings" and see "Application Type"
  • Change it to "read and write" and save.
  • Back in the "Details" tab, click on "Create my access token" (it may take a few minutes so periodically refresh the page and until your access token appears)
  • Click on the "OAuth tool" tab to make sure it's all filled in
  • Copy all 4 values (Consumer and Access token key/secret) somewhere because you'll be needing them soon.

Looking at your normal twitter page, check out https://twitter.com/settings/applications and it should list your app with "Permissions: read and write".

Now that's twitter done.

Python setup

Now for the fun bits, coding!

Just a tweet:

import twython

twitter = twython.Twython(
"CONSUMER_KEY",
"CONSUMER_SECRET",
"ACCESS_TOKEN",
"ACCESS_TOKEN_SECRET"
)

# Tweeting textually
twitter.update_status(status = "Testing tweet from Twig's Tech Tips")

And a tweet containing images:

# Update with image
# f = open("weather_sunny.png", 'rb')
# or
# f = urlopen("http://www.weather.com/sunny.jpg")

twitter.update_status_with_media(
status = "Testing tweet from Twig's Tech Tips... with imagery!",
media = f
)

There you have it, consider your cat is now skinned.

FUR-ITS-MURDER-e1297066919608

This setup can also be used for stuff like fetching/searching tweets using the twitter API, but just read the docs to find examples of that. Just be aware of the limitations which the twitter API impose before conjuring anything on a grand scale.

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog