Skip to content

Commit

Permalink
Made the main use the more bot-like stuff.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmitry Ratnikov committed Apr 12, 2011
1 parent 5bd2fd5 commit a4b478a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 22 deletions.
31 changes: 11 additions & 20 deletions connection.go
Expand Up @@ -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() {
Expand All @@ -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("^<message").MatchString(msg): client.listeners.fireOnMessage(msg)
default: client.listeners.fireOnUnknown(msg)
}

if match := regexp.MustCompile("<body>(.*)</body>").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() {
Expand Down
25 changes: 23 additions & 2 deletions main.go
Expand Up @@ -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...)
}

0 comments on commit a4b478a

Please sign in to comment.