forked from grantmd/slack-markov
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
58 lines (50 loc) · 1.42 KB
/
web.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
// Slack outgoing webhooks are handled here. Requests come in and are run through
// the markov chain to generate a response, which is sent back to Slack.
//
// Create an outgoing webhook in your Slack here:
// https://my.slack.com/services/new/outgoing-webhook
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
type WebhookResponse struct {
Username string `json:"username"`
Text string `json:"text"`
}
func init() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
incomingText := r.PostFormValue("text")
if incomingText != "" && r.PostFormValue("user_id") != "" && r.PostFormValue("user_id") != botUsername {
log.Printf("Handling incoming request: %s", incomingText)
markovChain.Write(incomingText)
go func() {
markovChain.Save(stateFile)
}()
if rand.Intn(100) <= responseChance || strings.HasPrefix(incomingText, botUsername) {
var response WebhookResponse
response.Username = botUsername
response.Text = markovChain.Generate(numWords)
log.Printf("Sending response: %s", response.Text)
b, err := json.Marshal(response)
if err != nil {
log.Fatal(err)
}
//time.Sleep(5 * time.Second)
w.Write(b)
}
}
})
}
func StartServer(port int) {
log.Printf("Starting HTTP server on %d", port)
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}