topamax once a day

Raspberry Pi Google Talk Robot

Google Talk/Chat/Messenger is normally used by humans to interact with other humans. However, its underlying technology can also be used as a mechanism to implement software robots.  Internet bots, also known as web robots, WWW robots or simply ‘bots’ can also utilize the technology to perform automated functions over the web.  There are many such bots in existence, offering a diverse spectrum of services from jokes ([email protected]) to URL Shortening using bit.ly ([email protected]), even mathematical calculation ([email protected]).  Using such bots is quick and easy to configure, all that must be done is to add the bot as a contact to your messaging account.  Then, whenever you desire data from the service, simply text the command to the bot and it will respond with the respective message.

The Raspi Bot is essentially the same as any other automated Internet robot.  To configure it, it must first have its own e-mail address associated with a Google talk account.  This e-mail address must also be added as a contact with the account that wishes to communicate to the bot.  Then, whenever the script is running on the remote machine, it will log into Google chat and appear as a friend in your contact list.

The software itself is essentially just a Python daemon script that is a wrapper around the XMPP protocol.  When executed, the script will sign in to Google talk using its own username and password.  The Python script is derived from the open source project pygtalkrobot: An open source python gtalk(google talk) bot framework using XMPPPY and PyDNS libraries, that also references the source code of python-jabberbot.

Software

The Raspi Bot requires several additional Python modules for use.  The easiest way to install these is with the python pip package manager. If you don’t have it installed, you can install them using apt-get:

sudo apt-get install python-pip git-core python2.7-dev

Then update the easy_install index:

sudo easy_install -U distribute

And install the GPIO, xmpppy, and pydns modules:

sudo pip install RPi.GPIO xmpppy pydns

Then clone my repo for the Raspi Gtalk robot:

git clone https://github.com/mitchtech/raspi_gtalk_robot.git

Now change into the newly created directory:

cd raspi_gtalk_robot

Finally, you will need  to configure the Raspi Bot’s Gtalk username and password.  This is done by editing the fields BOT_GTALK_USER, BOT_GTALK_PASS, and BOT_ADMIN, on lines 31-33 in the raspiBot.py file.  It is recommended, though not required, to give the Raspi Bot its own Gmail account. Since access to the Raspberry Pi GPIO pins is restricted, the script needs to be run with sudo:

sudo python ./raspiBot.py

This basic sample script supports the following commands:

  • [pinon|pon|on|high] [pin] : turns on the specified GPIO pin
  • [pinoff|poff|off|low] [pin] : turns off the specified GPIO pin
  • [write|w] [pin] [state] : writes specified state to the specified GPIO pin
  • [read|r] [pin]: reads the value of the specified GPIO pin
  • [available|online|busy|dnd|away|idle|out|xa] [arg1] : set gtalk state and status message to specified argument
  • [shell|bash] [arg1] : executes the specified shell command argument after ‘shell’ or ‘bash’

For example, sending the message “pinon 10” will turn on GPIO pin #10, “read 8” will read the current state of GPIO pin 8, or “bash ps” to execute the shell command ‘ps’.

 

Hardware

The video demonstration uses a slide switch connected to GPIO pin 8 and an LED connected to GPIO pin 10.  Here is a diagram of how this is wired   (created with Fritzing):

raspi_gtalk_robot

 

Use case #1: Home automation

One of the most obvious usages of this technology is for home automation purposes. The Raspi Bot can be accessed anywhere with Google talk, which to my understanding, is nearly every system in existence.  Send the Raspi Bot messages to turn on and off lights and other electrical appliances.

This is also useful to provide immediate notification in the event of intrusion detection. The Raspi Bot can be supplemented with additional security sensors, including infrared motion, and ultrasonic distance sensors. If any pre-programmed sensor violates any predefined condition, you can be immediately notified via message from the Raspi Bot.

 

Use case #2: Remote shell

The Raspi Bot can be used essentially as a remote shell.  In this configuration, every message sent to the Raspi Bot will be interpreted as a shell command with the output piped back to the user in the form of a response message.  Obviously, this could raise some security concerns. To protect against misuse, the Raspi Bot will only respond to Google chat messages from the Google user designated as the administrator of the bot.  By default, messages from any other user will simply be ignored.

The following is a small subset of the relatively benign commands possible to be run remotely via the Raspi Bot:

  • vmstat – system activity, hardware and information
  • uptime – how long the system has been running
  • w – logged in users and their process activity
  • ps – reports a snapshot of the current processes
  • free – physical and swap memory usage
  • iostat – average CPU load, disk activity

Arguably, disclosure of any amount of information about system can be considered a security issue such as that reported by some of the above tools.  For users more concerned about convenience over security exposure, much more elaborate commands can be run, such as executing additional scripts or accessing private data.

 

Use case #3: Remote Reboot

Another problem that can be solved by the Raspi Bot is frozen remote machines. We’ve all been there before, attempting to access a remote machine only to find it to be completely non-responsive to any form of remote login.  These cases, we (or maybe a system administrator somewhere) would usually have to make a trip to the physical location of the server and push ‘the big red button’ to reboot the affected machine.  The situation can be eliminated completely by deputizing a Raspi Bot as a remote reboot agent. This can be done by adding bot controlled relay(s) to the power supplies of the machines.  In the event any of the machines controlled by the Raspi Bot becomes non-responsive, simply send the appropriate Google talk message to flip the respective relay, and reboot the affected machine.  Here’s a diagram of how this would look:

raspi_remote_reboot

 

 

 

  • Impressive! Amazing! Linked in my website If you don’t mind 🙂

    • Thanks… Glad to hear you found it useful!

  • Pingback: Google Talk bot running on Raspberry Pi()

  • Pingback: Google Talk bot running on Raspberry Pi | Daily IT News on it news..it news..()

  • Pingback: Google Discuss rogrinding leveling pvp android working in Raspberry Pi | Make, Electronics projects, electronic Circuits, DIY projects, Microcontroller Projects - makeelectronic.com()

  • Pingback: Raspberry Pi Google Talk Robot #piday #raspberrypi @Raspberry_Pi « adafruit industries blog()

  • Pingback: ใช้ GPIO ของ Raspberry Pi ผ่านทาง Google Talk | Raspberry Pi Thailand()

  • Thanks a lot, this is great.
    I’m having a small problem though – I can get everything to work except the GPIO pins. When I go pon 8, pin 8 doesn’t turn on (although it gives me all the messages saying it is). I looked at the code and saw that it was pretty much the same as here: http://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/

    When I do it like on that page it works fine, I can’t figure out what’s different here. Any ideas?
    Thanks again,
    Alex

    • Hi Alex,

      It looks like your problem might be the pin mode of the GPIO. There are two GPIO numbering modes for the Raspberry Pi: board and BCM. My bot script uses GPIO.setmode(GPIO.BOARD) and the example in your link uses GPIO.setmode(GPIO.BCM). So pin 8 is likely actually turning on and off, just not necessarily the pin 8 that you think.

  • Hello Alex, Thanks for putting this together. It is very awesome!!! So, Your user case #1 is very interesting, however, how do you trigger the gtalkrobot to send a new message? Say if you push a button and wanting gtalkrobot to send a message to a user. i can’t quiet figure out how to do that, and I hope you can help.

    Min

    • Stu

      I was wondering the same thing – I found this site http://xmpppy.sourceforge.net/basic.html that describes how to do exactly this (minus the GPIO part).

      • Cool… I will check it out. Thanks for the find and reply!!! I will let you know how it goes.

        • Thomas

          Hello Min-Hsao. were you successful with the “case #1” ?
          I want to do the same thing – but I don´t know how….

          I want to get a message from the raspi, if one GPIO goes from 0 to 1 (low to high level).

  • thanks a lot for your wonderful work.
    having a minor problem. my gtalkbot goes offline after 2/3 minutes, everythingworks perfect within that time. so i decided to assign a crontab task to run the script every 2 minutes. hope you can help. thanks again.

    • I had the same issue, would also be interested in a solution 🙂

  • Juha Maanselkä

    Hi.

    Small problem here. I got the Bot working on Raspberry Pi. I can send commands to it but it won’t reply to my Talk.

    I get error “Warning: unable to estabilish secure connection – TLS failed!” on startup, the bot flashes green on my on talk and turns offline right away.

    Hope someone has had same problem and solved it 😉

    Juha

    • Juha Maanselkä

      Now got it working, or atleast it stopped whine about TLS, by changing port number to 5222(if I remember correctly).

      But as being noob with code my next question is:

      Can this system send messages by itself? I have 1-wire reading temps around and say I like GtalkBot to send message if outside temp drops below zero.

      Juha

      • Tony

        Hi, I got the same error, could you tell me what is the port and how should I change it? Thank you very much!

        • Himanshu

          For port, in “PyGtalkRobot.py” look for server_port=…
          It wasn’t replying to my commands also, but when i reverted back to Gtalk(from Hangout) i started receiving replies.

  • Pingback: Raspberry Pi Google Talk Robot #piday #raspberrypi @Raspberry_Pi « adafruit industries blog()

  • Pingback: Raspberry Pi: Gtalk Shell Bot | deepred()

  • Pingback: Raspberry PI Google Talk Robot | Robofun Blog()

  • Matt Jones

    Have you managed to solve the timeout issue at all? I have something very similar for interacting with my home server, based on PyGtalkRobot. However, after a period of inactivity the client program disconnects. I cant figure out where the disconnection is happening.

  • conres=self.conn.connect( server=(self.server_host, self.server_port),secure=0 )
    will solve the problem..
    Put ,secure=0
    i had the timeout problem, and this fixed it

    • i put conres=self.conn.connect( server=(self.server_host, self.server_port),secure=0 ) in pygtalkrobot.py file then its failing to connect. unable to authorize gmail.com please check your username/password.

      • Tarcas

        Mine is now failing to connect whether or not I put ,secure=0 in there. Did Google change the protocol and break something?

  • Paul

    Thanks for the tutorial. I managed to get it to work but it will only output the results to the terminal session and not back to my chat session. If i run “shell ls” it outputs correctly on pi session but does not return anything in the chat window. Any one having this issue?

  • Kevin

    Hi Michael!, thanks for this post!… I followed your instructions and got it working on my raspberry pi, but the problem is that the program gets disconnected with Google Talk in 2 mins… I changed the port 5222 but still the issue is not getting resolved!… please help!

    • Matt

      I had this same issue, I fixed it by creating a separate thread to send an empty packet every 300 seconds (5 mins). This kept my bot alive and well.

      • Paul

        Do you have an example of how you did it? Thanks

      • Kevin

        Hi Matt!, can you please tell me on how to do it?..

        • Matt

          No problems:

          Import the thread module into the main .py file. and under the start() function, before self.GoOn() I use the line:

          thread.start_new_thread(self.keepAlive, ())

          Hope this helps.

          • Hi Matt, can you post/email whole file with keepalive? 🙂 Also, ihave you managed to run Bot at rebbot, there’s no help with rc.local or crontab. Thank!

          • Sure thing. Get in touch google.com/+MattJones210585. Happy to share code and help with your init 🙂

  • jim

    this is awesome, but for a remote control system, it’s essential to be able to run raspiBot.py on boot-up. Do you have any suggestions how this is done ? I ask because so far all the help i’ve had does not work.
    Appreciate any help you can give.
    Jim

    • Tarcas

      I found that by starting it with init.d, it started too soon and couldn’t contact the server, and would just fail. I start and stop mine from a script in /etc/network/if-up.d and /if-down.d. All scripts in these folders are run in alphabetical order after the interface is brought up and before it is brought down, respectively, which is the perfect time to start and stop a network-based daemon.

  • Please is there any *.py example how to send message when GPIO IN trigered????? temperature is below/higher from DS18B20 ?
    I can read with read 17 but i would like to triger and send to gtalk thanks
    MANY THANKS for example of code or part of code to paste!!!
    I wrote some app to feed sen.se i could send invite to…
    THANKS for big HELP!!

    • Tarcas

      I created a separate script that does that for my home automation project. You can strip out the original bot script yourself too. Leave only the login and replyMessage sections, plus anything else that you think you’ll need. login once, wait for your gpio pin to change state, and then to send a message, you just reply. I’m guessing you’ll be putting the wait and the reply in a loop so that it sends one message when it goes high and another when it goes low, but you could just as easily exit the program after it changes once.

  • Click to my name to view created Raspberry feed on sen.se

    • lostpacket

      does anyone know how to get this to work with hangouts on Android 4.x and higher? connecting with pidgin ans xmpp it works fine. but not on the hangouts app 🙁

      • def replyMessage(self, user, message):
        senderMSG = xmpp.Message(user, message);
        senderMSG.setAttr(‘type’, ‘chat’)
        self.conn.send(senderMSG)

        • Seb

          Hey, can you explain that please ?

          • Tarcas

            What he means is to replace the replyMessage function definition in the PyGtalkRobot.py file, but I got a syntax error on the 3rd line of code. Apparently this message board replaces straight single quotes with angled ones, so to fix it, you’ll have to replace them with straight ones. After about 60-90 minutes of research, I got it working, and it does now send to both hangouts on my phone and gmail on my laptop. 🙂

  • SchumyAlex

    I have a problem, I can send commands to Raspberry but it won’t reply to my GTalk. Why?

    • Paul

      I had same problem and was not able to find a solution.

      • Fernando

        Same problem here, some infos?

    • Tarcas

      If you’re using Hangouts instead of gtalk, see the solution from Reinaldo above. That worked for me (after the fix to the posted fix that I responded with.) If it really is GTalk, I’m not sure what would cause this. Mine worked fine until I upgraded Android, which replaced GTalk with Hangouts. 🙁

  • Ace

    Thanks a lot for this, very very cool!

    A question tho,

    —–
    How to run a bash script without specifying its location?
    —–

    For example, I have a simple bash script ‘script1.sh’
    I have created an alias for it (‘myScript’) in .bashrc

    To run from terminal all I have to do is type ‘myScript’
    However to run from google talk, I have to type ‘/my/directory/script1.sh’

    How to fix this??

    What I hope to have are simple phrases like ‘hello’ that people can talk (to trigger some action).

    • Ace

      Turns out just gotta add script to /usr/bin (vs. another directory).
      =p

      • Tarcas

        That, or you can add the directory that contains your scripts to the path. Or specify the path when you call the script (i.e. if I receive “hello” then run “~/raspi_gtalk_robot/scripts/hello.py”) Linux almost always has lots of ways to do what you want.

  • Pingback: RFPiD – Raspberry Pi RFID door access system « NESIT Hackerspace()

  • dngrhm

    Any thoughts on alleviating some of the security consequences by opening up a door (as root) to your raspi? I can easily run ‘bash mkdir abc’ and ‘bash rmdir abc’ I haven’t tried but I assume I could run ‘bash rm -rf /*’

    • dngrhm

      The bot will respond to anyone who sends messages to it.

      You may want to restrict the bash command or disable it by default.

      ‘bash top’ (and likely any command requiring input) makes the bot non-responsive.

  • Lightnyng

    Hi, i have try to change the code for understand and if i send the message “hi” the raspberry should send “hello” but message don’t send. he appears in line command

    • Tarcas

      If you are using Hangouts, see the fix above given by Reinaldo Araújo. I responded to it to clarify how to implement it. That worked for me. Before the fix, it worked in the Gmail web interface, but not from Hangouts on my phone. After the fix, it works with both.

  • Wajid Naeem Malik

    i have followed all the steps and all were executed successfully but i am unable to run the last command for script

    sudo python ./raspiBot.py

    python: can’t open file ‘./raspiBot.py’: [Errno 2] No such file or directory

    I am doing this on RasPBX — asterisk in Raspberry Pi

    What could be the issue?

    • Wajid Naeem Malik

      yes i did it , i needed to use python ./raspi_gtalk_bot/raspiBot.py

      but now i am not getting way how can i chat with my server from gtalk, when i send message uptime it doesnt give response but if i ssh to my asterisk then there its showing as

      Testing [uptime] against regex [(available|online|busy|dnd|away|idle|out|xa)( +(.*))?$(?i)]

      Testing [uptime] against regex [(pinoff|poff|off|low)( +(.*))?$(?i)]

      Testing [uptime] against regex [(pinon|pon|on|high)( +(.*))?$(?i)]

      Testing [uptime] against regex [(read|r)( +(.*))?$(?i)]

      Testing [uptime] against regex [(shell|bash)( +(.*))?$(?i)]

      Testing [uptime] against regex [(write|w)( +(.*))?$(?i)]

      Testing [uptime] against regex [.*?(?s)(?m)]

      Can anyone explain what are these arguments and what do they mean?

      Regards

      Wajid Naeem Malik

      • Tarcas

        If you are using Hangouts, see the fix above given by Reinaldo Araújo. I responded to it to clarify how to implement it. That worked for me. Before the fix, it worked in the Gmail web interface, but not from Hangouts on my phone. After the fix, it works with both.

        The “Testing” lines are the bot checking what it just received against the various regular expressions (regex for short) that it was defined with. If it matches, it will run the code for that block. If it doesn’t match, it moves on to check the next regex.

  • Wajid Naeem Malik

    i think i have not used any LED or switch etc with my raspberry hardware so few commands are not working but some commands like shell uptime and bash ps are working. its telling me processes and uptime etc but the issue i am facing is that its showing the results in asterisk CLI not in gtalk chat

    • Tarcas

      If you are using Hangouts, see the fix above given by Reinaldo Araújo. I responded to it to clarify how to implement it. That worked for me. Before the fix, it worked in the Gmail web interface, but not from Hangouts on my phone. After the fix, it works with both.

  • Hi all, I collected all the solutions suggested by you in order to solve the issue with SSL and Hangout support. You just need to clone my repository
    — git clone https://github.com/UlisesGascon/raspi_gtalk_robot.git and follow the same steps as in the blog entry.

    • Ulises, I don’t suppose you’d be willing to help out a noob with a very similar project to this. I’ve been fighting through github the past few days and think I keep falling further down the hole lol.

  • Pingback: Raspberry Pi y Google Hangouts | Ulises Gascon()

  • Thomas

    thank you very much for that tutorial. After I did the steps above, it works ! 🙂 … but could you please explain me, whats the “BOT_ADMIN, in the raspiBot.py file” for ? It looks like there must be a eMail adress…. ?!?

    • Tarcas

      That’s the gTalk account that is permitted to run certain commands. It’s a security mechanism to make sure that only the account defined can do certain things like setting the bot’s state (such as online, busy, away, etc.) Look through the code for places where it compares “if jid == BOT_ADMIN:” and you’ll see what it can do that other users cannot. (jid is the user who sent the message that the bot is currently reacting to.)

      • Thomas

        thank you for your reply. I will look through the code 🙂
        another short question. The “BOT_ADMIN” account is actually not set. When I try to switch GPIO7 on or off, the raspberry answers, that it was done correctly, but it is not.
        Is the “bot_admin” the problem, because it is not set ?

        #sorryformybadenglish 🙂

        • Tarcas

          Thomas, your English is fine.
          I’m guessing you’re using a different numbering scheme than the code and therefore looking at the wrong pin. Take a look at the post above from “Alex” on January 20, 2013 for more info.

          • Thomas

            thank you again for the answer ! I’m sure the problem here will be the same as described above. I will check that as soon as possible.

  • Rich

    This is exactly what I have been looking for. -but- I can not get it to login, with the correct user / pass. Did something change with gtalk & the xmpp protocol?

    • Tarcas

      No, mine logs in fine, but if you’re using hangouts, it won’t communicate correctly unless you follow the directions in the post from Reinaldo Araújo on May 12, 2014. He explains how to fix that issue, which gtalk did change.

      • Rich

        This code was correct in what was installed.

        ef replyMessage(self, user, message):
        senderMSG = xmpp.Message(user, message);
        senderMSG.setAttr(‘type’, ‘chat’)
        self.conn.send(senderMSG)

        There were no angled quotes. It was not copied from the web page.

        The error is:

        Unable to authorize on gmail.com – Plsese check your name/password.

  • Karthik Fbk

    Hi, Is it possible to upload files from raspberry Pi via the google talk chat using this chatbot program or by tweaking the code?

  • Zelphar Oloxys

    So cute baby ginseng.Hope update soon
    d.657FW.CO/a5708ZT