Beispiel #1
0
func (b *bot) loop(io input.Input) {
	log.Println("[bot][loop] starting", io.String())

	for {
		select {
		case <-b.exit:
			log.Println("[bot][loop] exiting", io.String())
			return
		default:
			if err := b.run(io); err != nil {
				log.Println("[bot][loop] error", err)
				time.Sleep(time.Second)
			}
		}
	}
}
Beispiel #2
0
func (b *bot) run(io input.Input) error {
	log.Println("[bot][loop] connecting to", io.String())

	c, err := io.Stream()
	if err != nil {
		return err
	}

	for {
		select {
		case <-b.exit:
			log.Println("[bot][loop] closing", io.String())
			return c.Close()
		default:
			var recvEv input.Event
			// receive input
			if err := c.Recv(&recvEv); err != nil {
				return err
			}

			// only process TextEvent
			if recvEv.Type != input.TextEvent {
				continue
			}

			// process command
			for pattern, cmd := range b.commands {
				// skip if it doesn't match
				if m, err := regexp.Match(pattern, recvEv.Data); err != nil || !m {
					continue
				}

				// matched, exec command
				args := strings.Split(string(recvEv.Data), " ")
				rsp, err := cmd.Exec(args...)
				if err != nil {
					rsp = []byte("error executing cmd: " + err.Error())
				}

				// send response
				if err := c.Send(&input.Event{
					Meta: recvEv.Meta,
					From: recvEv.To,
					To:   recvEv.From,
					Type: input.TextEvent,
					Data: rsp,
				}); err != nil {
					return err
				}

				// done
				break
			}
		}
	}
}