Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- second or two, you
- receive a response from WhatsApp on the Pi that looks
- 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
- app, which you can use to send and receive messages. Bring
- it up with:
- $ yowsup-cli demos --yowsup --config mydetails
- This brings up the Yowsup CLI 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 Pi. For example, you can send a
- WhatsApp message to check certain details on the 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 (opposite) to
- interact with the 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 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 (opposite). Now create a shell script
- called talktome.sh that calls the pitalk.oy 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.
- Parsing the script
- 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
- WorldMags.net
- WorldMags.net
- Projects
- Raspberry Pi Projects | 43
- Listings
- Listing 1: status.sh
- #!/bin/bash
- temp=$(/opt/vc/bin/vcgencmd measure_temp | cut -c6-7)
- if [ “$temp” -gt 40 ]; then
- echo Whoa! My temperature is up to $(/opt/vc/bin/vcgencmd
- measure_temp). Power me down for a bit! | sendxmpp -t
- geekybodhi@jabber.hot-chilli.net
- fi
- Listing 2: pitalk.py
- import os, subprocess, yowsup, logging
- from wasend import YowsupSendStack
- from wareceive import YowsupReceiveStack, MessageReceived
- def credential():
- return
- “447712345678”,“jK0zdPJ9zz0BBC3CwmnLqmxuhBk=”
- def Answer(risp):
- try:
- stack=YowsupSendStack(credential(), [([“447668139981”,
- risp])])
- stack.start()
- except: pass
- return
- def Refresh():
- Answer(“Refreshing the repos.”)
- os.system(“sudo apt-get -y update”)
- Answer(“Repos updated.”)
- return
- def Restart():
- Answer(“Rebooting”)
- os.system(“sudo reboot”)
- return
- def Temp():
- t=float(subprocess.check_output([“/opt/vc/bin/vcgencmd
- measure_temp | cut -c6-9”], shell=True)[:-1])
- ts=str(t)
- Answer(“My temperature is “+ts+” C”)
- return
- def Disk():
- result=subprocess.check_output(“df -h .”, shell=True)
- output=result.split()
- Answer(“Disk space:\nTotal: “+output[8]+”\nUsed:
- “+output[9]+” (“+output[11]+”)\nFree: “+output[10])
- return
- while True:
- try:
- stack=YowsupReceiveStack(credential())
- stack.start()
- except MessageReceived as rcvd:
- received=rcvd.value.lower()
- if received[:len(“447668139981”)]==“447668139981”:
- received=received[len(“447668139981”):]
- if received[:4]==“hiya”: Answer(“Hi chap!”)
- elif received[:7]==“restart” or received[:6]==“reboot”: Restart()
- elif “disk” in received: Disk()
- elif “hot” in received: Temp()
- elif “refresh” in received: Refresh()
- else: Answer(“Eh? What was that?”)
- else: #message from wrong sender
- with open(“/home/pi/whatsapp.log”,”a”) as mf:
- mf.write(“Unauthorised access from: “+received[:len(“91996813
- 9981”)]+”\n”)
- account. Make sure you edit both the parameters in this
- function. The Answer() function specifies the WhatsApp
- number our Pi communicates with. This is important because
- we don’t want just anybody to control our Pi.
- Then we define the functions that do the actual task we
- query the Pi for via the WhatsApp messages. For example, the
- Refresh() function refreshes the repository list and Restart()
- reboots the 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. For
- example, 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 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 (https://github.com/
- tgalal/yowsup/wiki) for some examples of rolling the script
- into usable apps.
- WorldMags.net
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement