How to control a Raspberry Pi using WhatsApp
Build a PiBot monitor
WhatsApp is one of the most popular messaging apps and you can use it with the Raspberry Pi. The Yowsup Python library enables you to use your WhatsApp account to exchange messages with your contacts.
After the novelty of messaging your friends from the Raspberry Pi wears off, you can use the Yowsup library to monitor and control the Pi by sending messages via WhatsApp.
Before you can install the Yowsup library, fetch its dependencies with:
$ sudo apt-get install git python-dev libncurses5-dev
Then use:
$ git clone git://github.com/tgalal/yowsup.git
to download the library under the current directory, and install it with:
Are you a pro? Subscribe to our newsletter
Sign up to the TechRadar Pro newsletter to get all the top news, opinion, features and guidance your business needs to succeed!
$ cd yowsup
$ sudo python setup.py install
Once the library has been installed, it's time to register your mobile number with WhatsApp. In the yowsup directory, create a file called mydetails with the following:
$ nano mydetails
cc=44
phone=447712345678
The cc option points to the country code, which is 44 in the UK. Replace it and the phone number with your particulars. Make sure you don't enter the + symbol. Then save the file and use the following to ask WhatsApp for a registration code:
$ python yowsup-cli registration --config mydetails
--requestcode sms
After a few seconds, you should receive an SMS on the phone with the SIM card for the number you've entered in the mydetails file. The message contains a six-digit code. Use this to register the phone number with WhatsApp:
$ python yowsup-cli registration --config mydetails --register
xxx-xxx
Replace xxx-xxx with your code. After a second or two, you'll receive a response from WhatsApp on the Pi that will look something like this:
status: ok
kind: free
pw: jK0zdPJ9zz0BBC3CwmnLqmxuhBk=
price: 0.89
price_expiration: 1434674993
currency: EUR
cost: 0.89
expiration: 1463544490
login: 448375972334
type: new
The only bit of information we're interested in is the password mentioned with the pw variable. Copy it and paste it in the mydetails file, which should now read:
cc=44
phone=447712345678
password=jK0zdPJ9zz0M8G3CwmnLqmxuhBk=
That's all there's to it. The Yowsup library includes a demo application, which you can use to send and receive messages. Bring it up with:
$ yowsup-cli demos --yowsup --config mydetails
This brings up the Yowsup command line client. Type /help to see all the available commands. The [offline] prompt indicates that you aren't connected to the WhatsApp servers. Use the /L command, which picks up the authentication information from the mydetails file and connects to the server.
The prompt now changes to [connected].
You can now send messages to other WhatsApp users. To send a message to 449988776655 enter:
/message send 449988776655 "Hiya mate, I'm sending this from the Raspberry Pi!"
If the recipient responds with a message, it is displayed on the console on the Raspberry Pi. To end the session, use the /disconnect command to quit.
What's up Pi!
The real advantage of the Yowsup library is that it can be used to invoke actions on the Raspberry Pi, so for example you can send a WhatsApp message to check certain details on the Raspberry Pi, such as its disk space or temperature, then maybe update it or shut it down.
You can also use it to influence the GPIO pins and control any connected peripherals – a door, for example. You can use the Python script in Listing 1 to interact with the Raspberry Pi. The script listens to messages from a certain predefined number, recognises certain keywords and responds accordingly.
So if you send something like 'Hiya Pi', it greets you back. If it receives a message that begins with 'memory', the Raspberry Pi executes the df -h . command and messages you the results.
The script uses classes created by Italian blogger Carlo Mascellani. They are housed with two files, named wasend.py and warecieve,py, which you can download with:
$ wget http://www.mascal.it/public/wasend.py
$ wget http://www.mascal.it/public/wareceive.py
In the same directory, create a file called pitalk.py with the contents of Listing 2 (which again can be found here). Now create a shell script called talktome.sh that calls the pitalk.py Python script:
$ nano talktome.sh
#!/bin/bash
while :
do
sudo python /home/pi/yowsup/pitalk.py
done
Now make it executable with chmod +x talktome.sh and make sure it runs automatically whenever the Pi boots up by pointing to it in the /etc/rc.local file:
$ sudo nano /etc/rc.local
/home/pi/yowsup/talktome.sh
Save the file and reboot the Raspberry Pi, and the script starts automatically. Let's break down the script to understand it better. The credential() function at the top helps connect the script to the WhatsApp server by using the credentials for your account.
Make sure you edit both the parameters in this function. The Answer() function specifies the WhatsApp number our Raspberry Pi communicates with. This is important because we don't want just anybody to control our Raspberry Pi.
Parsing the script
Then we define the functions that do the actual task we query the Raspberry Pi for via the WhatsApp messages, eg the Refresh() function refreshes the repository list and Restart() reboots the Raspberry Pi. The Temp() and Disk() functions are a little more complex.
The former fetches and truncates the temperature information, as illustrated earlier in the tutorial. Similarly, Disk() formats and rearranges the output of the df -h command for easier reading.
In the main part of the program (the while loop), the script waits for a message, and when it gets one, it raises a MessageReceived exception. The received message begins with a phone number followed by a message, such as "449876543210Message".
When it raises the exception, the script first converts the whole string to lowercase with the value.lower() method. It then checks whether the message is from the number it's supposed to respond to. If it isn't, the script appends it to a log file and doesn't respond.
If, however, the phone number is correct, the script then strips the number from the message and just leaves the textual bit. The If conditions then parse the message to decide how to respond. We've used different types of matching to give you an idea of what's possible.
The first two look for matching characters at the start of the text, eg if received[:4]=="hiya": Answer("Hi chap!") is triggered if the first four characters of the message are h, i, y and a, and responds with 'Hi chap!' . This condition is met even if the message it receives is, 'Hiya Raspberry Pi, are you online?'
The second also looks for matching characters at the beginning of the message but is triggered if it finds either of the two strings (restart or reboot). The next three do a different kind of matching. They're triggered if their corresponding text is in any part of the message and not just at the beginning.
So if you send a "What's the status of your disk?" message, the script picks up the "disk" keyword and triggers the Disk() function. Similarly, if you send a 'You're not running too hot, are you?' message, the script picks up the 'hot' keyword and responds with a readout from its temperature sensor.
If it fails to pick up any keywords, the scripts just responds with the "Eh? What was that?" message. You can extend this script for a whole variety of home automation tasks. You can even hook up the Raspberry Pi camera module and use the Python Picam library to take pictures or videos and send them to you via a WhatsApp message.
Check the Yowsup library's wiki page for some examples of rolling the script into usable applications.
- Enjoyed this article? Expand your knowledge of Linux, get more from your code, and discover the latest open source developments inside Linux Format. Read our sampler today and take advantage of the offer inside.
With almost two decades of writing and reporting on Linux, Mayank Sharma would like everyone to think he’s TechRadar Pro’s expert on the topic. Of course, he’s just as interested in other computing topics, particularly cybersecurity, cloud, containers, and coding.