To develop a Jabber / Google Talk Bot, we first need to enable the XMPP inbound service for the application. Just add the lines:
1 2 |
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:
1 2 3 4 5 6 7 8 9 10 11 |
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”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#!/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() |