Beispiel #1
0
func updateAction(a *models.Action, text string) {
	text = url.QueryEscape(text)

	a.Content = strings.Replace(a.Content, "{_text_}", text, -1)

	r, _ := regexp.Compile("(?i){_key\\((.+)\\)_}")
	matched := r.FindStringSubmatch(a.Content)
	if len(matched) >= 2 {
		keyVal := os.Getenv(matched[1] + "_key")
		a.Content = strings.Replace(a.Content, matched[0], keyVal, -1)
	}
}
Beispiel #2
0
func responseForMessage(message service.Message, bot models.Bot) (string, models.Action) {
	actions, _ := models.FetchActions(true)
	sort.Sort(models.ByPriority(actions))

	var (
		act    models.Action
		sMatch string
	)
	for _, a := range actions {
		regexString := strings.Replace(*a.Pattern, "{_botname_}", bot.BotName, -1)
		r, _ := regexp.Compile("(?i)" + regexString)
		matched := r.FindStringSubmatch(message.Text())
		if len(matched) > 1 && matched[1] != "" {
			sMatch = matched[1]
			act = a
			break
		}
	}

	var (
		postString string
		err        error
	)
	for {
		updateAction(&act, sMatch)
		if act.IsURLType() {
			postString, err = handleURLAction(act, bot)
		} else {
			postString = act.Content
		}

		if (err == nil && postString != "") || act.FallbackAction == nil {
			break
		} else {
			act, _ = models.FetchAction(*act.FallbackAction)
		}
	}

	return postString, act
}
Beispiel #3
0
func handleURLAction(a models.Action, b models.Bot) (string, error) {

	resp, err := http.Get(a.Content)
	defer resp.Body.Close()

	if err != nil {
		return "", err
	}

	content, _ := ioutil.ReadAll(resp.Body)
	pathString := *a.DataPath

	str := utility.ParseJSON(content, pathString)
	for i := 0; i < 3; i++ {
		if !utility.ValidateURL(str, a.IsImageType()) {
			fmt.Printf("Invalid URL: %v\n", str)
			str = utility.ParseJSON(content, pathString)
		} else {
			return str, nil
		}
	}

	return "", errors.New("Failed to handle URL action")
}