Twitter is the world’s largest repository of short messages from people who have nothing to say, and now you too can contribute to this epic project with an automated Twitter bot powered by a Raspberry Pi. I’m kidding, of course — some people actually tweet interesting things. . Although I’m not one of them, I use mine to shamelessly promote a product in exchange for free stuff, entry into contests, and automatic posting of new episodes of our own Technophilia podcast. Anything — my followers love me!

Now I’m going to add to the usefulness of my personal Twitter thread as the Raspberry Pi automatically tweets the current CPU temperature every hour and the webcam image!

Beginning

This project uses Python; simple programming language, ideal for DIY projects. We’ll start by installing Twython on the Pi, a Python module for interacting with Twitter; setting up an «app» on Twitter to get an API key; then get busy creating Pi tweets on our behalf. It will be so much fun!

I’m doing this on Raspian — but in theory it should work on any Linux-based OS you use on the Pi If you haven’t already, make sure you set up SSH so we can log in remotely and execute console commands.

Installing Twython

It’s a good idea to run updates first. Copy and paste the following commands one at a time — most will require confirmation.

sudo apt-get update sudo apt-get upgrade sudo apt-get install python-setuptools sudo easy_install pip sudo pip install twython 

Registering the Twitter App

In order to use the Twitter API, i.e. the REST interface that we will use to post new tweets and general interaction with Twitter outside of the Twitter website, we need to register a new application. Do it by this link — you don’t need to provide a callback url, just create a website if you want.

new twitter app

When you’re done, you’ll see something that looks like this — these keys are unique to you.

twitter app

By default, the app is set to read-only, so we won’t be able to post tweets without changing it to » Reading and writing» . Go to the «Settings» tab and change application type .

read and write access

After saving, return to the » Details » and press the button below to create an OAuth access token — this will give your application access to your Twitter account. Refresh and leave the page open for later — we’ll need to copy and paste some of these keys in a minute.

access token

Create your Python project

Start by creating a new directory to house your Tweet project, then create a new file.

 mkdir SillyTweeter cd SillyTweeter sudo nano SillyTweeter.py 

You can call it whatever you want, obviously.

In the text editor that appears, copy and paste the following, replacing the consumer key with the appropriate key from the Twitter app page we left open earlier. Each key is enclosed in single quotes, so don’t skip them. note that ACCESS_KEY referred to as access token on the Twitter app page.

 #!/usr/bin/env python import sys from twython import Twython CONSUMER_KEY = '***************YOUR DATA*****************' CONSUMER_SECRET = '***************YOUR DATA*****************' ACCESS_KEY = '***************YOUR DATA*****************' ACCESS_SECRET = '***************YOUR DATA*****************' api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) api.update_status(status=sys.argv[1]) 

Press Ctrl-X and press Y to exit and save the file. Make it executable with the following command (replacing the Python filename if you chose something else)

 sudo chmod +x SillyTweeter.py 

You should now be able to test your ability to post tweets as follows:

 python SillyTweeter.py 'Hello Everyone, this is my Raspberry Pi tweeting you more nonsense' 

Tweet your CPU temperature

Now that you’re free to post any nonsense, let’s set up the app to display the current CPU temperature because I’ll be damned if the world doesn’t need to know about this every hour.

Start by adding another import for the os library:

 import os 

Then add the following lines, replacing the previous api.update_status from the example above.

 cmd = '/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip() temp = line.split('=')[1].split("'")[0] api.update_status(status="My current CPU temperature is "+temp+' C') 

I won’t explain this code too much because it doesn’t really matter — it runs a command that measures the temperature and then splits the output to extract the number and sends a tweet with the corresponding message. You can find the complete code example here.

Tweeting Webcam Pictures

Now let’s do something really useful; we’re going to tweet photos from the webcam. Luckily Twython supports the update_status_with_media API function which makes things pretty easy.

Connect a USB webcam to your device and check if it was recognized by the command:

 ls /dev/video* 

if you see video0 you’re lucky. I used a Playstation 3 PSEye camera and it worked just fine without any extra leg work.

We are also going to use libraries pygame, to take a picture; add the following lines right after the existing import statements:

 import pygame import pygame.camera from pygame.locals import * pygame.init() pygame.camera.init() cam = pygame.camera.Camera("/dev/video0",(640,480)) cam.start() image = cam.get_image() pygame.image.save(image,'webcam.jpg') 

In short, you’ve initialized the webcam with a specific resolution (you may need to adjust it, it’s a really old camera), take a picture, and save it as a jpg. We’re just going to overwrite the same webcam.jpg every time we run the app.

Finally, change the update_status line as follows:

 photo = open('webcam.jpg','rb') api.update_status_with_media(media=photo, status="My RPi be tweeting images now => ") 

Of course, you can change the status text to the current CPU temperature if you like. The complete code for this example is here.

Can you repeat it?

A Twitter bot is only useful if it runs multiple times automatically; You don’t want to sit here and run a command every hour. To achieve this, let’s use the Pi’s CRON scheduling feature (What is a CRON job?)

 sudo crontab -e 

Paste in this line to run every hour.

 */60 * * * * python /home/pi/SillyTweeter/SillyTweeter.py 

Change it to * * * * *, if you want it to run every minute and be prepared to lose followers faster than a twitter account that loses followers fast.

This is for today. I’m glad I contributed a lot to the vast amount of useless bytes on the internet, and I hope you do too! Show your appreciation for this lesson, writing it in Twitter and then let us know what your own Twitter bot has to say in the comments.

Image credit: adafruit/flickr

Похожие записи