Create a gist now

Instantly share code, notes, and snippets.

@gbaman /README.md Secret
Created Sep 11, 2015

Tweeting Babbage example

Tweeting Babbage

Create some Python code that takes photos and sends tweets from the Raspberry Pi!

Connect to Twitter from Python

  1. Boot your Raspberry Pi to the desktop and launch LXTerminal.

  2. Because the Raspberry Pi doesn't have a real-time clock, you may need to start by setting the correct date and time on the system.
    First lets check the date/time with the command:

    date

    If the date looks wrong by more than a few hours, we can set it with this command:

    sudo date -s "2 OCT 2014 12:00:00"

This is important, as without the correct time we won't be able to connect to Twitter.

  1. Create a folder for your project with the following command:

    mkdir tweeting-babbage
  2. Enter this folder with cd tweeting-babbage and ask a volunteer for the NI Raspberry Jam test account authentication keys:

  3. Lets create the new Python file we will be using:

    touch babbage.py
  4. Launch these Python files in IDLE3 with root permissions (you'll need this for the GPIO) with the command:

    sudo idle3 *.py &
    
  5. In auth.py you will see the API keys. These are kind of like usernames and passwords, but are designed for computers as they are near impossible to remember:

    consumer_key        = 'ABCDEFGHIJKLKMNOPQRSTUVWXYZ'
    consumer_secret     = '1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ'
    access_token        = 'ZYXWVUTSRQPONMLKJIHFEDCBA'
    access_token_secret = '0987654321ZYXWVUTSRQPONMLKJIHFEDCBA'
  6. Now switch over to babbage.py. Import the twython library and the variables from auth.py:

    from twython import Twython
    from auth import (
        consumer_key,
        consumer_secret,
        access_token,
        access_token_secret
    )
  7. Make a connection with the Twitter API using this set of keys:

    twitter = Twython(
        consumer_key,
        consumer_secret,
        access_token,
        access_token_secret
    )
  8. Create a main() function which will be called when the script is run. Pick any random message so we can check that your connection to Twitter works:

    def main():
        message = "Put your own message in here"
        twitter.update_status(status=message)

    This uses the API's update_status() function to send a tweet containing the text "Hello world!".

  9. We'll also add an instruction at the end to run the main() method when the script is called directly:

    if __name__ == '__main__':
        main()

    Your code should now look like this:

    from twython import Twython
    from auth import (
        consumer_key,
        consumer_secret,
        access_token,
        access_token_secret
    )
    
    twitter = Twython(
        consumer_key,
        consumer_secret,
        access_token,
        access_token_secret
    )
    
    def main():
        message = "Put your own message in here"
        twitter.update_status(status=message)
        print("Tweeted: %s" % message)
    
    if __name__ == '__main__':
        main()
  10. Now save (Ctrl + S) and run with F5. You should see the message "Tweeted: Hello world!". Go to your Twitter profile in a web browser to verify it was sent! This will be at twitter.com/nijamdev, as we are using the @nijamdev test account.

Note that sending multiple tweets with the exact same text are classed as duplicates and rejected by Twitter. If you want to test it again, try tweeting a different message.

If you see an error, your API keys may be incorrect. Be sure to copy them exactly and check the spelling of the variables. You should also check that your Pi is online.

Tweet random messages

Now that we can send some text as a tweet, let's mix it up a bit.

  1. First, import the random module:

    import random

    This module contains a choice function which takes a list and returns a single entry at random.

  2. Now create a list of messages like so:

    messages = [
        "Hello world",
        "Hi there",
        "My name is Babbage",
        "What's up?",
        "How's it going?",
        "Have you been here before?",
        "Get a hair cut!",
    ]
  3. Replace message = "Hello world!" with message = random.choice(messages).

    This chooses a single item from the messages list at random.

  4. Run the code again two or more times to see different messages being tweeted at random.

Tweet a picture

Now that the Twitter connection has been tested, let's try to upload a picture. Rather than try to hook up the camera now, we'll test it independently.

  1. Find a picture, copy it to your Raspberry Pi or download it from the internet, and save it to your home folder. Make a note of its location (something like /home/pi/Downloads/image.jpg).

  2. Modify the main() function in the code accordingly:

    message = "Hello world - here's a picture!"
    with open('/home/pi/Downloads/image.jpg', 'rb') as photo:
        twitter.update_status_with_media(status=message, media=photo)

    Make sure to specify the full path to the image correctly.

    This opens the file and uses the update_status_with_media() function to upload the image, along with the tweet text.

  3. Run the code and see if it tweets the text and image together!

Take a picture with the Pi camera

Now that we know we can upload a given picture to Twitter, let's take one with the Pi camera.

  1. With the Pi switched off, connect a Raspberry Pi camera module to the camera port. You may want to ask a volunteer to help you do this.

  2. Boot the Pi and from the command line or LXTerminal test that it works with the command raspistill -k. If you see the camera's image on the screen, you know it's working. Press Ctrl + C to exit the preview.

  3. Now open a new Python window in IDLE3, save as camera.py and enter the following code:

    from picamera import PiCamera
    from time import sleep
    
    with PiCamera() as camera:
        camera.start_preview()
        sleep(3)
        camera.capture('/home/pi/image.jpg')
        camera.stop_preview()

    This is a test script to check we can take a picture from Python.

  4. Run with F5 and you should see a preview on the screen for 3 seconds before the camera takes the picture.

  5. Open the file manager and you should see image.jpg. Double-click the icon to open it up.

Tweet a picture from the Pi camera

Now we'll copy the picamera code we just used into the babbage.py file, so that it will tweet the photo taken by the Pi camera.

  1. First add the import lines at the top:

    from picamera import PiCamera
    from time import sleep

    Imports are best kept at the top of the code before anything else.

  2. Then add the picamera lines in the main() method:

    with PiCamera() as camera:
        camera.start_preview()
        sleep(3)
        camera.capture('/home/pi/image.jpg')
        camera.stop_preview()
    
        message = "Here's a Pi camera picture!"
        with open('/home/pi/image.jpg', 'rb') as photo:
            twitter.update_status_with_media(status=message, media=photo)
  3. Now run the code; it will save the photo to image.jpg in the home folder and upload it to Twitter.

  4. Check Twitter to see if it worked!

Use a timestamp

Now let's fix the hard-coded filename of image.jpg and use something more dynamic. It would be better to timestamp the filename so it will never get overwritten. It should also be stored in a folder inside our project.

  1. In the terminal window, create a new folder inside tweeting-babbage called photos with mkdir photos.

  2. Import the datetime function with from datetime import datetime.

  3. Save the timestamp as a variable before taking the picture, and pass this into the path string:

    timestamp = datetime.now().isoformat()
    photo_path = '/home/pi/tweeting-babbage/photos/%s.jpg' % timestamp
    camera.capture(photo_path)

    The timestamp is formatted in the ISO datetime format YYYY-MM-DDTHH:MM:SS.mmmmmm e.g. 2014-10-02T05:10:25.642155 (year, month, day, hours, minutes, seconds, microseconds).

  4. Now change the update_status_with_media() call to this new photo path:

    with open(photo_path, 'rb') as photo:
        twitter.update_status_with_media(status=message, media=photo)
  5. Run the code again; it should save the image in the tweeting-babbage/photos folder and tweet it as usual.

What next?

  • Try adding a text or image overlay to the picture before tweeting! See the picamera documentation http://picamera.readthedocs.org/
  • Could you try wiring up a button and using it to twigger a tweet?
  • Or even better, use a motion (PIR) sensor to detect movement, then tweet a picture? (might want to check out the parent detector activity for that).

Credits

This activity is heavily based off the excellent Tweeting Babbage activity by the Raspberry Pi Foundation, which is released under the Creative Commons Attribution 4.0 International Licence.
The Tweeting Babbage activity can be found at - https://www.raspberrypi.org/learning/tweeting-babbage/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment