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 }
func HandleCalman(message service.Message, service service.Service, cache cache.QueryCache) { if message.UserType() != "user" { return } bot, _ := models.FetchBot(message.GroupID()) // Make sure the message has the bot's name with a preceeding character, and that it isn't escaped index := strings.Index(strings.ToLower(message.Text()), strings.ToLower(bot.BotName)) isEscaped := (index >= 2 && message.Text()[index-2] == '\\') if len(message.Text()) < 1 || index < 1 || isEscaped { return } var ( postString string act models.Action ) if cached := cache.CachedResponse(message.Text()); cached != nil { postString = *cached } else { postString, act = responseForMessage(message, bot) } postString = updatedPostText(act, postString) postString = utility.ProcessedString(postString) cacheID := cache.CacheQuery(message.Text(), postString) fmt.Printf("Query: %v\n", message.Text()) if postString != "" { fmt.Printf("Action: %v\n", act.Content) fmt.Printf("Posting: %v\n", postString) service.PostText(bot.Key, postString, cacheID, message) } }