Ok, file this one under the “What were you thinking” category, but I’ve written a little service to sent New Comment notifications via Google Talk.
All of the heavy lifting is done via the Smack API, since Google Talk runs on XMPP (the same protocol as Jabber). You can find some (dated but good) background here. Anyways, here’s my beast in action:
To get this going in your own app, we’ll make thing configurable via a few entries in Config.groovy:
chat { serviceName = "gmail.com" host = "talk.google.com" port = 5222 username = "yourid@gmail.com" password = "your_password" }
Then we’ll add ourselves a simple GoogleNotificationService…
import org.codehaus.groovy.grails.commons.ConfigurationHolder import org.jivesoftware.smack.Chat import org.jivesoftware.smack.ConnectionConfiguration import org.jivesoftware.smack.Roster import org.jivesoftware.smack.XMPPConnection import org.jivesoftware.smack.packet.Message /** * All these ideas courtesy of chase@osdev.org from a discussion at: * http://www.igniterealtime.org/community/message/147918 */ class GoogleTalkService { boolean transactional = false def sendChat(String to, String msg) { log.debug "Sending notification to: [${to}]" ConnectionConfiguration cc = new ConnectionConfiguration( ConfigurationHolder.config.chat.host, ConfigurationHolder.config.chat.port, ConfigurationHolder.config.chat.serviceName) XMPPConnection connection = new XMPPConnection(cc) try { connection.connect() connection.login(ConfigurationHolder.config.chat.username, ConfigurationHolder.config.chat.password) def chatmanager = connection.getChatManager() // we talk, but don't listen, how rude Chat chat = chatmanager.createChat(to, null) // google bounces back the default message types, you must use chat def msgObj = new Message(to, Message.Type.chat) msgObj.setBody(msg) chat.sendMessage(msgObj) } catch (Exception e) { log.error("Failed to send message") } // and close down connection.disconnect() } }
You can’t seem to send messages to yourself… So I had to setup a second Gmail account just to test things out! There’s probably a better way, but it’s already pretty late.
Anyways, probably not that useful, but I’ve been wanting to learn a little XMPP for a while, and have finally had the chance!
Happy Grails Chat botting!