Advertisement
SH1NU11b1

rpibot.txt

Nov 29th, 2016
156
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. geekybodhi@jabber.hot-chilli.net
  88. fi
  89. Listing 2: pitalk.py
  90. import os, subprocess, yowsup, logging
  91. from wasend import YowsupSendStack
  92. from wareceive import YowsupReceiveStack, MessageReceived
  93. def credential():
  94. return
  95. “447712345678”,“jK0zdPJ9zz0BBC3CwmnLqmxuhBk=”
  96. def Answer(risp):
  97. try:
  98. stack=YowsupSendStack(credential(), [([“447668139981”,
  99. risp])])
  100. stack.start()
  101. except: pass
  102. return
  103. def Refresh():
  104. Answer(“Refreshing the repos.”)
  105. os.system(“sudo apt-get -y update”)
  106. Answer(“Repos updated.”)
  107. return
  108. def Restart():
  109. Answer(“Rebooting”)
  110. os.system(“sudo reboot”)
  111. return
  112. def Temp():
  113. t=float(subprocess.check_output([“/opt/vc/bin/vcgencmd
  114. measure_temp | cut -c6-9”], shell=True)[:-1])
  115. ts=str(t)
  116. Answer(“My temperature is “+ts+” C”)
  117. return
  118. def Disk():
  119. result=subprocess.check_output(“df -h .”, shell=True)
  120. output=result.split()
  121. Answer(“Disk space:\nTotal: “+output[8]+”\nUsed:
  122. “+output[9]+” (“+output[11]+”)\nFree: “+output[10])
  123. return
  124. while True:
  125. try:
  126. stack=YowsupReceiveStack(credential())
  127. stack.start()
  128. except MessageReceived as rcvd:
  129. received=rcvd.value.lower()
  130. if received[:len(“447668139981”)]==“447668139981”:
  131. received=received[len(“447668139981”):]
  132. if received[:4]==“hiya”: Answer(“Hi chap!”)
  133. elif received[:7]==“restart” or received[:6]==“reboot”: Restart()
  134. elif “disk” in received: Disk()
  135. elif “hot” in received: Temp()
  136. elif “refresh” in received: Refresh()
  137. else: Answer(“Eh? What was that?”)
  138. else: #message from wrong sender
  139. with open(“/home/pi/whatsapp.log”,”a”) as mf:
  140. mf.write(“Unauthorised access from: “+received[:len(“91996813
  141. 9981”)]+”\n”)
  142. account. Make sure you edit both the parameters in this
  143. function. The Answer() function specifies the WhatsApp
  144. number our Pi communicates with. This is important because
  145. we don’t want just anybody to control our Pi.
  146. Then we define the functions that do the actual task we
  147. query the Pi for via the WhatsApp messages. For example, the
  148. Refresh() function refreshes the repository list and Restart()
  149. reboots the Pi. The Temp() and Disk() functions are a little
  150. more complex. The former fetches and truncates the
  151. temperature information, as illustrated earlier in the tutorial.
  152. Similarly, Disk() formats and rearranges the output of the df
  153. -h command for easier reading.
  154. In the main part of the program (the while loop), the script
  155. waits for a message, and when it gets one, it raises a
  156. MessageReceived exception. The received message begins
  157. with a phone number followed by a message, such as
  158. “449876543210Message”.
  159. When it raises the exception, the script first converts the
  160. whole string to lowercase with the value.lower() method. It
  161. then checks whether the message is from the number it’s
  162. supposed to respond to. If it isn’t, the script appends it to a
  163. log file and doesn’t respond.
  164. If, however, the phone number is correct, the script then
  165. strips the number from the message and just leaves the
  166. textual bit. The If conditions then parse the message to
  167. decide how to respond. We’ve used different types of
  168. matching to give you an idea of what’s possible. The first two
  169. look for matching characters at the start of the text. For
  170. example, if received[:4]==“hiya”: Answer(“Hi chap!”) is
  171. triggered if the first four characters of the message are h, i, y
  172. and a, and responds with “Hi chap!” This condition is met
  173. even if the message it receives is, “Hiya Raspberry Pi, are you
  174. online?” The second also looks for matching characters at the
  175. beginning of the message but is triggered if it finds either of
  176. the two strings (restart or reboot).
  177. The next three do a different kind of matching. They’re
  178. triggered if their corresponding text is in any part of the
  179. message and not just at the beginning. So if you send a
  180. “What’s the status of your disk?” message, the script picks up
  181. the “disk” keyword and triggers the Disk() function. Similarly,
  182. if you send a “You’re not running too hot, are you?” message,
  183. the script picks up the “hot” keyword and responds with a
  184. readout from its temperature sensor. If it fails to pick up any
  185. keywords, the scripts just responds with the “Eh? What was
  186. that?” message.
  187. You can extend this script for a whole variety of home
  188. automation tasks. You can even hook up the Pi camera
  189. module and use the Python Picam library to take pictures or
  190. videos and send them to you via a WhatsApp message.
  191. Check the Yowsup library’s wiki page (https://github.com/
  192. tgalal/yowsup/wiki) for some examples of rolling the script
  193. into usable apps.
  194. WorldMags.net
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement