forked from SmoothieNoIce/Easy-hahamut-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
347 lines (279 loc) · 7.89 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
const (
//https://haha.gamer.com.tw/bot_detail.php?id=<YOUR-BOTID>
APP_SECRET = "<YOUR_APP_SECRET>"
ACCESS_TOKEN = "<YOUR_ACCESS_TOKEN>"
POST_URL = "https://us-central1-hahamut-8888.cloudfunctions.net/messagePush?access_token="
POST_IMAGE_URL = "https://us-central1-hahamut-8888.cloudfunctions.net/ImgMessagePush?access_token="
)
type Text struct {
Text string `json:"text"`
}
type Messaging struct {
SenderID string `json:"sender_id"`
Message Text `json:"message"`
}
type Message struct {
BotID string `json:"botid"`
Time int `json:"time"`
Messaging []Messaging `json:"messaging"`
}
type Recipient struct {
ID string `json:"id"`
}
type MessageingSend struct {
Type string `json:"type"`
Text string `json:"text"`
}
type MessageSend struct {
MyRecipient Recipient `json:"recipient"`
MyMessageingSend MessageingSend `json:"message"`
}
type StickerSend struct {
Type string `json:"type"`
StickerGroup string `json:"sticker_group"`
StickerID string `json:"sticker_id"`
}
type StickerMessageSend struct {
MyRecipient Recipient `json:"recipient"`
StickerSend StickerSend `json:"message"`
}
type VerifyError struct {
When time.Time
What string
}
func (e *VerifyError) Error() string {
fmt.Println("Error:", e.What)
return fmt.Sprintf("at %v, %s", e.When, e.What)
}
/*
http.HandleFunc的handler
*/
func handler(w http.ResponseWriter, r *http.Request) {
// Do: 結束後執行 關閉httpRequest
defer r.Body.Close()
// Do: Read body
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Do: 傳回200
request200(w)
// Do: 驗證簽章
err = verifyWebhook(r, b)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Do: Decode body 的東西
var msg Message
err = json.Unmarshal(b, &msg)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Do: 剩下靠自己
fmt.Println("bot_id=", msg.BotID)
fmt.Println("time=", msg.Time)
fmt.Println("senderid=", msg.Messaging[0].SenderID)
fmt.Println("text=", msg.Messaging[0].Message.Text)
handleMessage(w, msg.Messaging[0].Message.Text, msg.Messaging[0].SenderID)
}
/*
處理使用者傳入的訊息
*/
func handleMessage(w http.ResponseWriter, msg string, senderid string) {
switch msg {
case "打招呼":
sendMsg(w, senderid, "嗨嗨OwO")
case "發貼圖":
sendSticker(w, senderid, "28", "09")
case "發圖片":
sendImg(w, senderid, "src/img/ralsei.png")
default:
sendMsg(w, senderid, "我聽不懂==")
}
}
/*
發送文字訊息
*/
func sendMsg(w http.ResponseWriter, senderID string, msg string) {
// 包成json
r := Recipient{senderID}
m := MessageingSend{"text", msg}
ms := MessageSend{r, m}
json, err := json.Marshal(ms)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// 請求Post
req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", POST_URL, ACCESS_TOKEN), bytes.NewBuffer(json))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// 設置header
req.Header.Set("X-Custom-Header", "hahamut-hender")
req.Header.Set("Content-Type", "application/json")
// For control over HTTP client headers
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
//取得哈哈的伺服器取得狀態
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Headers:", resp.Header)
fmt.Println("Response Body:", string(body))
}
func sendSticker(w http.ResponseWriter, senderID string, stickerGroup string, stickerID string) {
r := Recipient{senderID}
s := StickerSend{"sticker", stickerGroup, stickerID}
sms := StickerMessageSend{r, s}
json, err := json.Marshal(sms)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// 請求Post
req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", POST_URL, ACCESS_TOKEN), bytes.NewBuffer(json))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// 設置header
req.Header.Set("X-Custom-Header", "hahamut-hender")
req.Header.Set("Content-Type", "application/json")
// For control over HTTP client headers
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
//取得哈哈的伺服器取得狀態
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Headers:", resp.Header)
fmt.Println("Response Body:", string(body))
}
func sendImg(w http.ResponseWriter, senderID string, img string) {
fullPath, _ := os.Getwd()
fullPath += "/" + img
fmt.Println("fullPath:" + fullPath)
extraParams := map[string]string{
"message": `{"type":"img"}`,
"recipient": fmt.Sprintf(`{"id":"%s"}`, senderID),
}
req, err := newfileUploadRequest(fmt.Sprintf("%s%s", POST_IMAGE_URL, ACCESS_TOKEN), extraParams, "filedata", img)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// For control over HTTP client headers
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), 500)
return
} else {
body, _ := ioutil.ReadAll(resp.Body)
//取得哈哈的伺服器取得狀態
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Headers:", resp.Header)
fmt.Println("Response Body:", string(body))
resp.Body.Close()
}
}
/*
-需要使用multipart/form-data格式的表單
-不能用golang默認的http.POST
-自行實現body參數邏輯
*/
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
//打開檔案
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close() //函式執行完關閉檔案
body := &bytes.Buffer{} //建立一個容納byte的緩衝器
writer := multipart.NewWriter(body) //建立一個新的writter
part, err := writer.CreateFormFile(paramName, filepath.Base(path)) //建立一個form 參數名稱是"filedata" ///檔案名稱是path
if err != nil {
return nil, err
}
//把file的數據複製到建立的form
_, err = io.Copy(part, file)
//key=i,val等於params參數map的數值
//寫入 message="type":"img"
//寫入"recipient"="senderID"
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
//把自己編好的body送出去
req, err := http.NewRequest("POST", uri, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, err
}
func request200(w http.ResponseWriter) {
w.WriteHeader(200)
}
func verifyWebhook(r *http.Request, body []byte) error {
//Note: 取得x-baha-data-signature開頭的Header
headerget := r.Header.Get("x-baha-data-signature")
key := []byte(headerget[5:])
fmt.Println("key=", key)
//Note: 使用HMAC-SHA1雜湊APP_SECRET和傳來的Body
mac := hmac.New(sha1.New, []byte(APP_SECRET))
mac.Write(body)
fmt.Printf("%x\n", mac.Sum(nil))
//轉為字串比較
str1 := string(key[:])
str2 := fmt.Sprintf("%x", mac.Sum(nil))
fmt.Println("str1=", str1)
fmt.Println("str2=", str2)
if str1 != str2 {
return &VerifyError{
time.Now(),
"Verify error",
}
} else {
return nil
}
}
func main() {
//開啟伺服器
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
address := ":" + port
log.Println("Starting server on address", address)
err := http.ListenAndServe(address, nil)
if err != nil {
panic(err)
}
}