Esempio n. 1
0
func CommandHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	hook := r.URL.Path == "/slack_hook"
	if err == nil {
		decoder := schema.NewDecoder()
		command := new(robots.SlashCommand)
		err := decoder.Decode(command, r.PostForm)
		if err != nil {
			log.Println("Couldn't parse post request:", err)
		}
		if hook {
			c := strings.Split(command.Text, " ")
			command.Command = c[1]
			command.Text = strings.Join(c[2:], " ")
		} else {
			command.Command = command.Command[1:]
		}
		robot := GetRobot(command.Command)
		w.WriteHeader(http.StatusOK)
		if robot != nil {
			if hook {
				JSONResp(w, robot.Run(command))
			} else {
				plainResp(w, robot.Run(command))
			}
		} else {
			r := "No robot for that command yet :("
			if hook {
				JSONResp(w, r)
			} else {
				plainResp(w, r)
			}
		}
	}
}
Esempio n. 2
0
File: main.go Progetto: mbp/slackbot
func slashCommandHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	d := schema.NewDecoder()
	command := new(robots.SlashCommand)
	err = d.Decode(command, r.PostForm)
	if err != nil {
		log.Println("Couldn't parse post request:", err)
	}
	if command.Command == "" || command.Token == "" {
		log.Printf("[DEBUG] Ignoring request from unidentified source: %s - %s", command.Token, r.Host)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	command.Robot = command.Command[1:]

	if token := os.Getenv(fmt.Sprintf("%s_SLACK_TOKEN", strings.ToUpper(command.Robot))); token != "" && token != command.Token {
		log.Printf("[DEBUG] Ignoring request from unidentified source: %s - %s", command.Token, r.Host)
		w.WriteHeader(http.StatusBadRequest)
	}
	robots := getRobots(command.Robot)
	if len(robots) == 0 {
		plainResp(w, "No robot for that command yet :(")
		return
	}
	resp := ""
	for _, robot := range robots {
		resp += fmt.Sprintf("\n%s", robot.Run(&command.Payload))
	}
	plainResp(w, strings.TrimSpace(resp))
}