Google Talk now comes with translation bots. While translation is fun, even more fun is to build your own bot! And with the Smack library, it's also easy.
As an example, here's a simple echo bot implementation in 40 lines:
public class EchoBot {
private final XMPPConnection conn;
// Simple bot that echoes incoming messages.
private EchoBot() throws XMPPException {
// Login as my-bot@gmail.com with password "my-password".
conn = new XMPPConnection("gmail.com");
conn.connect();
conn.login("my-bot", "my-password");
// Become available.
conn.sendPacket(new Presence(Presence.Type.available));
// Auto-accept all friend requests.
conn.getRoster().setSubscriptionMode(SubscriptionMode.accept_all);
// Echo incoming messages.
final MessageListener messageListener = new MessageListener() {
public void processMessage(Chat chat, Message message) {
if ((message.getType() == Message.Type.chat
|| message.getType() == Message.Type.normal)
&& message.getBody()!= null) {
try {
chat.sendMessage(message.getBody());
} catch(XMPPException e) {
e.printStackTrace();
}
}
}
};
conn.getChatManager().addChatListener(
new ChatManagerListener() {
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(messageListener);
}
});
}
}
Feel free to re-use the code and go build something awesome!

No comments:
Post a Comment