Operation Manual

Human-computer interfacing
115
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leinthe
# home directory of the current user
oauth_lename=os.path.join(os.path.expanduser('~'),
'.twitterdemo_oauth')
# get twitter account login info
if notos.path.exists(oauth_lename):
oauth_dance('Raspberry Pi Twitter Demo', CONSUMER_KEY,
CONSUMER_SECRET,oauth_lename)
(oauth_token,oauth_token_secret)=read_token_le(oauth_lename)
# log in to Twitter
auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY,
CONSUMER_SECRET)
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',t w e et['created_at'])
print(tw eet['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)!
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.