-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
120 lines (105 loc) · 2.47 KB
/
main.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"ninjin/util/cls"
"ninjin/util/discord"
"ninjin/util/mdb"
slacktool "ninjin/util/slack"
"os"
"github.com/go-yaml/yaml"
_ "github.com/lib/pq"
)
type SlackEvent struct {
Type string `json:"type"`
Channel string `json:"channel"`
User string `json:"user"`
Text string `json:"text"`
}
func main() {
config_buf, err := os.ReadFile("./config.yaml")
if err != nil {
fmt.Println(err)
return
}
var config_data map[string]string
err = yaml.Unmarshal(config_buf, &config_data)
if err != nil {
fmt.Println(err)
return
}
var (
SLACK_VERIFY_TOKEN = config_data["SLACK_VERIFY_TOKEN"]
)
dr := discord.Router {
DISCORD_API_TOKEN: config_data["DISCORD_API_TOKEN"],
SERVER_ID: config_data["DISCORD_SERVER_ID"],
}
err = dr.Setup()
if err != nil {
return
}
slack := slacktool.SlackUtil {
SLACK_API_TOKEN: config_data["SLACK_API_TOKEN"],
}
SlackEventsEndPoint := "/slack/events"
db, err := mdb.Setup()
if err != nil {
return
}
defer db.Data.Close()
http.HandleFunc(SlackEventsEndPoint, func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
var event SlackEvent
err = json.Unmarshal(body, &event)
if err != nil {
http.Error(w, "Failed to parse request body", http.StatusBadRequest)
return
}
var jsonbody map[string]interface{}
err = json.Unmarshal(body, &jsonbody)
if err != nil {
http.Error(w, "Failed to parse json", http.StatusBadRequest)
return
}
switch event.Type {
case "url_verification":
slack.Verify(w, r, body, SLACK_VERIFY_TOKEN)
case "event_callback":
jsonbody2, ok := jsonbody["event"].(map[string]interface{})
if !ok {
http.Error(w, "Failed to parse json", http.StatusBadRequest)
return
}
if jsonbody2["type"] == "message" {
user := slacktool.User {
UserID: jsonbody2["user"].(string),
}
msg := cls.Message{}
slack.AttachUserInfo(&user)
slack.AttachMessageInfo(&msg, jsonbody2)
if err != nil {
http.Error(w, "Failed to get user info", http.StatusInternalServerError)
return
}
dr.EventMassage(&user, &msg, &db)
db.Insert(&msg)
}
}
w.WriteHeader(http.StatusOK)
})
go func() {
err := http.ListenAndServe(":3000", nil)
if err != nil {
fmt.Println("Error stargting HTTP server:", err)
}
}()
defer dr.Bot.Close()
select {}
}