-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhandler.go
89 lines (74 loc) · 2.17 KB
/
handler.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package function
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
)
// Handle a serverless request
func Handle(req []byte) string {
currentTweet := tweet{}
if err := json.Unmarshal(req, ¤tTweet); err != nil {
return fmt.Sprintf("Unable to unmarshal event: %s", err.Error())
}
if strings.Contains(currentTweet.Text, "RT") ||
currentTweet.Text == "alexellisuk_bot" ||
currentTweet.Username == "colorisebot" ||
currentTweet.Username == "scmsFaAS" ||
currentTweet.Username == "openfaas" {
return "filtered the tweet out"
}
discordURL := readSecret("twitter-discord-webhook-url")
discordMsg := discordMessage{
Content: "@" + currentTweet.Username + ": " + currentTweet.Text + " (via " + currentTweet.Link + ")",
Username: "@" + currentTweet.Username,
}
bodyBytes, _ := json.Marshal(discordMsg)
httpReq, err := http.NewRequest(http.MethodPost, discordURL, bytes.NewReader(bodyBytes))
if err != nil {
if err != nil {
fmt.Fprintf(os.Stderr, "resErr: %s", err)
os.Exit(1)
}
}
httpReq.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(httpReq)
if err != nil {
fmt.Fprintf(os.Stderr, "resErr: %s", err)
os.Exit(1)
}
if res.Body != nil {
defer res.Body.Close()
}
bodyRes, _ := ioutil.ReadAll(res.Body)
if res.StatusCode != http.StatusAccepted &&
res.StatusCode != http.StatusOK &&
res.StatusCode != http.StatusNoContent {
fmt.Fprintf(os.Stderr, "unexpected status code: %d, body: %s", res.StatusCode, string(bodyRes))
os.Exit(1)
}
return fmt.Sprintf("tweet forwarded [%d]", res.StatusCode)
}
// tweet in following format from IFTTT:
// { "text": "<<<{{Text}}>>>", "username": "<<<{{UserName}}>>>", "link": "<<<{{LinkToTweet}}>>>" }
type tweet struct {
Text string `json:"text"`
Username string `json:"username"`
Link string `json:"link"`
}
type discordMessage struct {
Content string `json:"content"`
Username string `json:"username"`
}
func readSecret(name string) string {
res, err := ioutil.ReadFile(path.Join("/var/openfaas/secrets/", name))
if err != nil {
os.Stderr.Write([]byte(err.Error()))
os.Exit(1)
}
return strings.TrimSpace(string(res))
}