| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "io/ioutil" |
| 7 | "net/http" |
| 8 | "os" |
| 9 | |
| 10 | "github.com/slack-go/slack" |
| 11 | "github.com/slack-go/slack/slackevents" |
| 12 | ) |
| 13 | |
| 14 | // You more than likely want your "Bot User OAuth Access Token" which starts with "xoxb-" |
| 15 | var api = slack.New("TOKEN") |
| 16 | |
| 17 | func main() { |
| 18 | signingSecret := os.Getenv("SLACK_SIGNING_SECRET") |
| 19 | |
| 20 | http.HandleFunc("/events-endpoint", func(w http.ResponseWriter, r *http.Request) { |
| 21 | body, err := ioutil.ReadAll(r.Body) |
| 22 | if err != nil { |
| 23 | w.WriteHeader(http.StatusBadRequest) |
| 24 | return |
| 25 | } |
| 26 | sv, err := slack.NewSecretsVerifier(r.Header, signingSecret) |
| 27 | if err != nil { |
| 28 | w.WriteHeader(http.StatusBadRequest) |
| 29 | return |
| 30 | } |
| 31 | if _, err := sv.Write(body); err != nil { |
| 32 | w.WriteHeader(http.StatusInternalServerError) |
| 33 | return |
| 34 | } |
| 35 | if err := sv.Ensure(); err != nil { |
| 36 | w.WriteHeader(http.StatusUnauthorized) |
| 37 | return |
| 38 | } |
| 39 | eventsAPIEvent, err := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionNoVerifyToken()) |
| 40 | if err != nil { |
| 41 | w.WriteHeader(http.StatusInternalServerError) |
| 42 | return |
| 43 | } |
| 44 | |
| 45 | if eventsAPIEvent.Type == slackevents.URLVerification { |
| 46 | var r *slackevents.ChallengeResponse |
| 47 | err := json.Unmarshal([]byte(body), &r) |
| 48 | if err != nil { |
| 49 | w.WriteHeader(http.StatusInternalServerError) |
| 50 | return |
| 51 | } |
| 52 | w.Header().Set("Content-Type", "text") |
| 53 | w.Write([]byte(r.Challenge)) |
| 54 | } |
| 55 | if eventsAPIEvent.Type == slackevents.CallbackEvent { |
| 56 | innerEvent := eventsAPIEvent.InnerEvent |
| 57 | switch ev := innerEvent.Data.(type) { |
| 58 | case *slackevents.AppMentionEvent: |
| 59 | api.PostMessage(ev.Channel, slack.MsgOptionText("Yes, hello.", false)) |
| 60 | } |
| 61 | } |
| 62 | }) |
| 63 | fmt.Println("[INFO] Server listening") |
| 64 | http.ListenAndServe(":3000", nil) |
| 65 | } |