Building a Jabber Bot (Google Talk) with Python and Google App Engine

To develop a Jabber / Google Talk Bot, we first need to enable the XMPP inbound service for the application. Just add the lines:

inbound_services:
- xmpp_message

to your app.yaml file. That would activate the service for our application. Have a look at my application’s app.yaml file:

 
application: masnun-test
version: 3
runtime: python
api_version: 1
 
handlers:
- url: .*
  script: masnun.py
 
inbound_services:
- xmpp_message

Now, we have the app configured, we need to do the actual coding. Every GAE app has it’s own IM id: [application_id]@appspot.com :) There are other extensive IDs also available but for this task we will use this format. So, my app has the ID: masnun-test@appspot.com as it’s Jabber / Google Talk ID. If the user adds this ID to his/her contact list, it’ll auto accept the friend invitation and appear online. Now when he/she sends a message, the message is sent as a POST request to the url: /_ah/xmpp/message/chat/ . This URL is not publicly accessible without admin rights. Our app can handle this URL like any other URL. So we need to setup a request handler for any POST request to this URL.

GAE has a nice API for it’s XMPP service which lets us build a Message object directly from the POSTed data. We will do that. Extract the message parts and send a response back. Here is source code for “masnun.py”:

#!/usr/bin/env python
 
import cgi
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
 
class XMPPHandler(webapp.RequestHandler):
    def post(self):
        message = xmpp.Message(self.request.POST)
        sender = cgi.escape(self.request.get('from')).split("/")[0]
        body = message.body
        message.reply("Hello, " + sender + "!, you sent: " + message.body)
 
application = webapp.WSGIApplication([('/_ah/xmpp/message/chat/', XMPPHandler)],
                                     debug=True)
 
def main():
    run_wsgi_app(application)
 
if __name__ == "__main__":
    main()
This entry was posted in Blog Post and tagged . Bookmark the permalink.

2 Responses to Building a Jabber Bot (Google Talk) with Python and Google App Engine

  1. Pingback: Tweets that mention Building a Jabber Bot (Google Talk) with Python and Google App Engine « maSnun.com -- Topsy.com

  2. That’s a nice use of API.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">