From a4b478a3e4f443bfb4da51d2c9cff48e36016be6 Mon Sep 17 00:00:00 2001 From: Dmitry Ratnikov Date: Tue, 22 Mar 2011 23:32:50 -0400 Subject: [PATCH] Made the main use the more bot-like stuff. --- connection.go | 31 +++++++++++-------------------- main.go | 25 +++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/connection.go b/connection.go index 6e7dfef..80b66b8 100644 --- a/connection.go +++ b/connection.go @@ -11,9 +11,9 @@ import ( type Client struct { hostname string conn net.Conn + listeners listenerList } - func NewClient(hostname, user, password string) (client *Client, failure os.Error) { failure = nil defer func() { @@ -32,31 +32,22 @@ func NewClient(hostname, user, password string) (client *Client, failure os.Erro client.startTls() client.authenticate(NewAuth(user, password)) - client.Message("ratnikov@gmail.com", "Write me something and I will write back! (Please send 2 messages at first....)") + return client, nil +} - client.read() +func (client *Client) Subscribe(l Listener) { + client.listeners.subscribe(l) +} +func (client *Client) Loop() { for { - raw := client.read() - - var recipient, received string + msg := client.read() - if match := regexp.MustCompile("to=\"([^/\"]*)/").FindStringSubmatch(raw); len(match) > 1 { - recipient = match[1] + switch { + case regexp.MustCompile("^(.*)").FindStringSubmatch(raw); len(match) > 1 { - received = match[1] - } - - message := "You wrote: " + received - - fmt.Printf("Sending message %s to %s", message, recipient) - - client.Message(recipient, message) } - - return client, nil } func (client *Client) startTls() { diff --git a/main.go b/main.go index 85fd28a..9818812 100644 --- a/main.go +++ b/main.go @@ -5,12 +5,33 @@ import ( "xmpp" ) +type Bot struct { +} + +func (b *Bot) onMessage(message string) { + log("Bot received message: %s", message) +} + +func (b *Bot) onUnkown(msg string) { + log("Bot received unsupported message: %s", msg) +} + func main() { - client, err := xmpp.NewClient("talk.google.com", "ratnikov@gmail.com", "secret") + bot := Bot{} + + client, err := xmpp.NewClient("talk.google.com", "xmpp.chatterbox@gmail.com", "XXX") if err != nil { fmt.Printf("Failed due to: %s\n", err) + } else { + client.Subscribe(&bot) + + client.Message("ratnikov@gmail.com", "Hello world!") + + client.Loop() } +} - fmt.Printf("Client: %x\nError: %s\n", client, err) +func log(format string, args ...interface{}) { + fmt.Printf("MAIN LOG: " + format, args...) }