Exemplo n.º 1
0
// Route from a telegram message channel to the respective handler
func (router *Routes) Route(message *telegram.Message) {
	var elements []string
	for _, item := range strings.Split(message.Text, " ") {
		if item == "" {
			continue
		}
		elements = append(elements, item)
	}

	count := len(elements)
	answer := telegram.NewAnswerBack(message, router.Bot.API)
	messageContext := MessageContext{map[string]string{}, answer}

	for _, handler := range router.handlers {
		if count != len(handler.elements) {
			continue
		}
		matched := true
		for index, item := range handler.elements {
			givenItem := elements[index]
			switch {
			case strings.Index(item, ":") == 0:
				messageContext.Params[item[1:]] = givenItem
			case item != givenItem:
				matched = false
			}
		}
		if !matched {
			continue
		}
		check := handler.actions.Check(&messageContext)

		switch {
		case check == RouteAccept:
			handler.actions.Handle(&messageContext)
			return
		case check == RouteStop:
			return
		}
	}
}
Exemplo n.º 2
0
func TestHandle(t *testing.T) {
	mover := &mockQuoteMover{}
	handler := moveHandler{storage: mover}

	message := &telegram.Message{Chat: telegram.Chat{ID: 2}, MessageID: 3}
	sender := &mockMessageSender{}
	answer := telegram.NewAnswerBack(message, sender)
	context := &bot.MessageContext{Params: make(map[string]string), Message: answer}
	context.Params["from"] = "1"
	context.Params["to"] = "2"

	handler.Handle(context)

	if mover.from != "1" || mover.to != "2" {
		t.Error("Wrong storage call", mover)
	}

	if sender.msg.Text != "Moved 100 quotes" {
		t.Error("Wrong message", sender.msg.Text)
	}
}