Raspberry_Pi_Education_Manual

Notes:

Lesson 4.1: Twitter

To complete this exercise you will need to install the Python Twitter Tools. You can either download these from http://pypi.python.org/pypi/twitter/ or install them from the SD card that came with your Raspberry Pi. The following Python script will tweet the message “Hello, World!” from your Raspberry Pi. It then displays a list of all your personal tweets. No web browser in sight! This example shows how simple this type of application can be, using Python.

import os from twitter import * # go to https://dev.twitter.com/apps/new to create your own # CONSUMER_KEY and CONSUMER_SECRET # Note that you need to set the access level to read and write # for this script to work (Found in the settings tab once you # have created a new application) CONSUMER_KEY = '9HvofZMpvHo0KGZyg9ckg' CONSUMER_SECRET = 'S75MwXN2H0h2qIYszc51WtHTbpbouhDkr6CCTBPzA' # get full pathname of .twitterdemo_oauth file in the # home directory of the current user oauth_filename = os.path.join(os.path.expanduser( '~' ), '.twitterdemo_oauth' ) # get twitter account login info if not os.path.exists(oauth_filename): oauth_dance( 'Raspberry Pi Twitter Demo' , CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) (oauth_token, oauth_token_secret) = read_token_file(oauth_filename) # log in to Twitter auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)

Tip...

As in the previous chapter, we sometimes have more code to write than fits on one line. When you see a line of code that goes onto a new line, don’t press Return to start a new line, just let it word wrap and Python will work it out for you.

twitter = Twitter(auth=auth) # Tweet a new status update twitter.statuses.update(status= "Hello, World!" ) # Display all my tweets for tweet in twitter.statuses.user_timeline(): print ( 'Created at' ,tweet[ 'created_at' ]) print (tweet[ 'text' ]) print ( '-' *80)

Over to you

Try to think of other ways in which you could use this mechanism. For instance, take an input from somewhere, process it and tweet the result. You could detect the weather outside and tweet the result. You could even make a tweet from your mobile phone and have your Raspberry Pi read and react to it (by playing some music, for example)!

Human-computer interfacing

115

Made with FlippingBook flipbook maker