SH1NU11b1

rpibot.txt

Nov 29th, 2016
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.00 KB | None | 0 0
  1. second or two, you
  2. receive a response from WhatsApp on the Pi that looks
  3. something like this:
  4. status: ok
  5. kind: free
  6. pw: jK0zdPJ9zz0BBC3CwmnLqmxuhBk=
  7. price: 0.89
  8. price_expiration: 1434674993
  9. currency: EUR
  10. cost: 0.89
  11. expiration: 1463544490
  12. login: 448375972334
  13. type: new
  14. The only bit of information we’re interested in is the
  15. password mentioned with the pw variable. Copy it and paste
  16. it in the mydetails file, which should now read:
  17. cc=44
  18. phone=447712345678
  19. password=jK0zdPJ9zz0M8G3CwmnLqmxuhBk=
  20. That’s all there’s to it. The Yowsup library includes a demo
  21. app, which you can use to send and receive messages. Bring
  22. it up with:
  23. $ yowsup-cli demos --yowsup --config mydetails
  24. This brings up the Yowsup CLI client. Type /help to see all
  25. the available commands. The [offline] prompt indicates that
  26. you aren’t connected to the WhatsApp servers. Use the /L
  27. command, which picks up the authentication information
  28. from the mydetails file and connects to the server. The
  29. prompt now changes to [connected].
  30. You can now send messages to other WhatsApp users. To
  31. send a message to 449988776655 enter:
  32. /message send 449988776655 “Hiya mate, I’m sending this
  33. from the Raspberry Pi!”
  34. If the recipient responds with a message, it is displayed on
  35. the console on the Raspberry Pi. To end the session, use the /
  36. disconnect command to quit.
  37. What’s up Pi!
  38. The real advantage of the Yowsup library is that it can be used
  39. to invoke actions on the Pi. For example, you can send a
  40. WhatsApp message to check certain details on the Pi, such
  41. as its disk space or temperature, then maybe update it or
  42. shut it down. You can also use it to influence the GPIO pins
  43. and control any connected peripherals – a door, for example.
  44. You can use the Python script in Listing 1 (opposite) to
  45. interact with the Pi. The script listens to messages from a
  46. certain predefined number, recognises certain keywords and
  47. responds accordingly. So if you send something like “Hiya Pi”,
  48. it greets you back. If it receives a message that begins with
  49. “memory”, the Pi executes the df -h . command and
  50. messages you the results.
  51. The script uses classes created by Italian blogger Carlo
  52. Mascellani. They are housed with two files, named wasend.py
  53. and warecieve,py, which you can download with:
  54. $ wget http://www.mascal.it/public/wasend.py
  55. $ wget http://www.mascal.it/public/wareceive.py
  56. In the same directory, create a file called pitalk.py with the
  57. contents of Listing 2 (opposite). Now create a shell script
  58. called talktome.sh that calls the pitalk.oy Python script:
  59. $ nano talktome.sh
  60. #!/bin/bash
  61. while :
  62. do
  63. sudo python /home/pi/yowsup/pitalk.py
  64. done
  65. Now make it executable with chmod +x talktome.sh and
  66. make sure it runs automatically whenever the Pi boots up by
  67. pointing to it in the /etc/rc.local file:
  68. $ sudo nano /etc/rc.local
  69. /home/pi/yowsup/talktome.sh
  70. Save the file and reboot the Raspberry Pi, and the script
  71. starts automatically.
  72. Parsing the script
  73. Let’s break down the script to understand it better. The
  74. credential() function at the top helps connect the script to
  75. the WhatsApp server by using the credentials for your
  76. WorldMags.net
  77. WorldMags.net
  78. Projects
  79. Raspberry Pi Projects | 43
  80. Listings
  81. Listing 1: status.sh
  82. #!/bin/bash
  83. temp=$(/opt/vc/bin/vcgencmd measure_temp | cut -c6-7)
  84. if [ “$temp” -gt 40 ]; then
  85. echo Whoa! My temperature is up to $(/opt/vc/bin/vcgencmd
  86. measure_temp). Power me down for a bit! | sendxmpp -t
  87. fi
  88. Listing 2: pitalk.py
  89. import os, subprocess, yowsup, logging
  90. from wasend import YowsupSendStack
  91. from wareceive import YowsupReceiveStack, MessageReceived
  92. def credential():
  93. return
  94. “447712345678”,“jK0zdPJ9zz0BBC3CwmnLqmxuhBk=”
  95. def Answer(risp):
  96. try:
  97. stack=YowsupSendStack(credential(), [([“447668139981”,
  98. risp])])
  99. stack.start()
  100. except: pass
  101. return
  102. def Refresh():
  103. Answer(“Refreshing the repos.”)
  104. os.system(“sudo apt-get -y update”)
  105. Answer(“Repos updated.”)
  106. return
  107. def Restart():
  108. Answer(“Rebooting”)
  109. os.system(“sudo reboot”)
  110. return
  111. def Temp():
  112. t=float(subprocess.check_output([“/opt/vc/bin/vcgencmd
  113. measure_temp | cut -c6-9”], shell=True)[:-1])
  114. ts=str(t)
  115. Answer(“My temperature is “+ts+” C”)
  116. return
  117. def Disk():
  118. result=subprocess.check_output(“df -h .”, shell=True)
  119. output=result.split()
  120. Answer(“Disk space:\nTotal: “+output[8]+”\nUsed:
  121. “+output[9]+” (“+output[11]+”)\nFree: “+output[10])
  122. return
  123. while True:
  124. try:
  125. stack=YowsupReceiveStack(credential())
  126. stack.start()
  127. except MessageReceived as rcvd:
  128. received=rcvd.value.lower()
  129. if received[:len(“447668139981”)]==“447668139981”:
  130. received=received[len(“447668139981”):]
  131. if received[:4]==“hiya”: Answer(“Hi chap!”)
  132. elif received[:7]==“restart” or received[:6]==“reboot”: Restart()
  133. elif “disk” in received: Disk()
  134. elif “hot” in received: Temp()
  135. elif “refresh” in received: Refresh()
  136. else: Answer(“Eh? What was that?”)
  137. else: #message from wrong sender
  138. with open(“/home/pi/whatsapp.log”,”a”) as mf:
  139. mf.write(“Unauthorised access from: “+received[:len(“91996813
  140. 9981”)]+”\n”)
  141. account. Make sure you edit both the parameters in this
  142. function. The Answer() function specifies the WhatsApp
  143. number our Pi communicates with. This is important because
  144. we don’t want just anybody to control our Pi.
  145. Then we define the functions that do the actual task we
  146. query the Pi for via the WhatsApp messages. For example, the
  147. Refresh() function refreshes the repository list and Restart()
  148. reboots the Pi. The Temp() and Disk() functions are a little
  149. more complex. The former fetches and truncates the
  150. temperature information, as illustrated earlier in the tutorial.
  151. Similarly, Disk() formats and rearranges the output of the df
  152. -h command for easier reading.
  153. In the main part of the program (the while loop), the script
  154. waits for a message, and when it gets one, it raises a
  155. MessageReceived exception. The received message begins
  156. with a phone number followed by a message, such as
  157. “449876543210Message”.
  158. When it raises the exception, the script first converts the
  159. whole string to lowercase with the value.lower() method. It
  160. then checks whether the message is from the number it’s
  161. supposed to respond to. If it isn’t, the script appends it to a
  162. log file and doesn’t respond.
  163. If, however, the phone number is correct, the script then
  164. strips the number from the message and just leaves the
  165. textual bit. The If conditions then parse the message to
  166. decide how to respond. We’ve used different types of
  167. matching to give you an idea of what’s possible. The first two
  168. look for matching characters at the start of the text. For
  169. example, if received[:4]==“hiya”: Answer(“Hi chap!”) is
  170. triggered if the first four characters of the message are h, i, y
  171. and a, and responds with “Hi chap!” This condition is met
  172. even if the message it receives is, “Hiya Raspberry Pi, are you
  173. online?” The second also looks for matching characters at the
  174. beginning of the message but is triggered if it finds either of
  175. the two strings (restart or reboot).
  176. The next three do a different kind of matching. They’re
  177. triggered if their corresponding text is in any part of the
  178. message and not just at the beginning. So if you send a
  179. “What’s the status of your disk?” message, the script picks up
  180. the “disk” keyword and triggers the Disk() function. Similarly,
  181. if you send a “You’re not running too hot, are you?” message,
  182. the script picks up the “hot” keyword and responds with a
  183. readout from its temperature sensor. If it fails to pick up any
  184. keywords, the scripts just responds with the “Eh? What was
  185. that?” message.
  186. You can extend this script for a whole variety of home
  187. automation tasks. You can even hook up the Pi camera
  188. module and use the Python Picam library to take pictures or
  189. videos and send them to you via a WhatsApp message.
  190. Check the Yowsup library’s wiki page (https://github.com/
  191. tgalal/yowsup/wiki) for some examples of rolling the script
  192. into usable apps.
  193. WorldMags.net
Advertisement
Add Comment
Please, Sign In to add comment