Good News

My Raspberry Pi (and yours) can tweet again! He could do it before, using a web service from Supertweet. However as of January 2014 Supertweet was banned from using the Twitter API and therefore could no longer be used. I didn’t really bother trying to find another solution though, until I stubled upon a description of how to use the official Twitter API on the Raspberry Pi website. And now you can interface directly to the Twitter API, so there’s no need for a third party to be involved anymore.

Preparations

Before you can send tweets you’ll obviously need a Twitter account. Apart from that you’ll also need a set of API keys or tokens for your application. This allows your application to send tweets on your behalf, without knowing your Twitter password.
And finally you’ll need to install some additional software. Let’s start with that, because that is the easiest part.

sudo apt-get update
sudo apt-get install python3 python3-pip
sudo pip3 twython

That was easy enough I think. Now let’s generate some API keys, assuming you already have a Twitter account.

Creating a new Twitter App

First login to your Twitter account. Then go to apps.twitter.com. Then click the Create New App button. Fill in the mandatory boxes and don’t forget to tick the agreement box. B.T.W. the URL requires the https:// or https:// prefix. The Callback URL can be left blank.
Then click Create your twitter Application.

Creating a new Twitter Token

After creating an application like this make sure that your application is set to allow at least write access to your Twitter account, otherwise you won’t be able to send any tweets.
Now select the Keys and Access Tokens tab. Then, under Token Actions, click on the Create my access token button.

All settings complete

Now you’ve got all the information you need for twython. Please note that you’ll need the 4 strings of seemingly garbage. The Consumer Key (API Key), the Consumer Secret (API secret), the Access Token and the Access token Secret. Also note that the Access Token is split across two lines on the web page. You’ll need the entire token, including the part in front of the hyphen, which apparently is the same as the Owner ID.

B.T.W. don’t bother trying to send tweets on my behalf with these tokens. I have scrambled them a little.

The Script

Now create a new file in your ~/bin directory, name it twitter.py and copy/paste the code from the listing below into that file. Save the file and change its permissions with the command chmod 700 twitter.py. Why 700? Your Twitter tokens are to be included into this file and you don’t want just anybody to be able to read them.

You’ll have to change some variables to reflect your own Twitter API tokens. The comments in the listing will tell you what is needed. The example listing has place holders for 3 accounts. You can delete, create and name the accounts as you please. Don’t forget to define the default_id, which is to be used when you don’t specify the identity to be used on the command line.

#! /usr/bin/python3

"""
This script can send tweet messages from one of your Twitter accounts.
You'll have to setup a set of tokens for each of your accounts and
add them to the accounts library below. You can also set a default
account to tweet from.
Tokens can be generated at https://apps.twitter.com

Usage:
twitter.py [-i identity] -m "Message"

Requires twython package
    Install: sudo pip3 twython

Author  : San Bergmans
Website : www.sbprojects.net
"""

import argparse, sys
from twython import Twython

#======================================================================
# Begin of user defined variables
#======================================================================

# Define all accounts, as many as you like
#   'identity' : (consumer_key, consumer_secret,
#                 access_token, access_token_secret)
accounts = {
    'web_id'      : (
        'copy consumer key here',
        'copy consumer secret here',
        'copy access token here',
        'copy access token secret here'
    ) ,
    'company_id'  : (
        'copy consumer key here',
        'copy consumer secret here',
        'copy access token here',
        'copy access token secret here'
    ),
    'personal_id' : (
        'copy consumer key here',
        'copy consumer secret here',
        'copy access token here',
        'copy access token secret here'
    )
}

# Define the default ID in case no identity is specified
default_id = "personal_id"

#======================================================================
# End of user defined variables
#======================================================================

# Get the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-i", help="Specify Twitter identity")
parser.add_argument("-m", help="Specify Tweet message")
args = parser.parse_args()

# Set the defualt identity if identity argument is omitted
if args.i == None:
    identity = default_id
else:
    identity = args.i

# See if this identity exists. Exit with 1 if it doesn't.
if identity not in accounts:
    print ("Sorry, unknown identity.")
    sys.exit (1)

# See if a message is given. Exit with 2 if no message.
if args.m == None:
   print ("Sorry, no message given.")
   sys.exit (2)

# Get all the account details for this identity
consumer_key        = accounts[identity][0]
consumer_secret     = accounts[identity][1]
access_token        = accounts[identity][2]
access_token_secret = accounts[identity][3]

# The next code may fail if you've made some errors in your
#  tokens or if there is no internet connection for instance.
#  It also fails when your tweet is too long for instance.
# So let's be prepared for an error.
try:
    # Create twitter object
    twitter = Twython (
        consumer_key,
        consumer_secret,
        access_token,
        access_token_secret
)

    # Send tweet now
    twitter.update_status(status=args.m)
except:
    print ("An error occurred. Could not tweet.")
    sys.exit (3)

Sending A Tweet Message

Now you can send tweets with a command like this.

twitter.py -i web_id -m "Wow, my Raspberry Pi can send tweets again, thanks to the script found on https://goo.gl/QWa5Br"

Tweet example

Please remember that Tweets are limited to a maximum of 140 characters. The script will exit with an error if your string is too long. Calculating the maximum length is a bit complicated. Special international characters can count as multiple characters and URLs appear not to be counted against the limit.

Please remember that the script is called from a shell, which tries its best to make life difficult for you be interpreting special characters like white space, *, <, >, or $. Therefore you must use quotes to surround the message and you might have to escape other special characters with a \ symbol.

Room For Improvements

The script will simply exit with a general error when it can't send a tweet, for any reason. You may create a more specific error handler if you like.

The twython library also allows you to send pictures and videos in your tweets. It may be interesting to adopt the script to include these media.

One Final Remark

Twitter will skip duplicate tweets which are sent too quickly in succession. This means that you can't send a tweet with the same text over and over again. You can easily solve that by appending a time stamp to your message.