-
Notifications
You must be signed in to change notification settings - Fork 0
/
vocechatbot.go
112 lines (104 loc) · 2.68 KB
/
vocechatbot.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
qq "qqNode"
"strconv"
)
type vocechatUser struct {
Name string `json:"name"`
Uid int `json:"uid"`
Gender int `json:"gender"`
IsBot bool `json:"is_bot"`
}
type vocechatDetail struct {
Content string `json:"content,omitempty"`
ContentType string `json:"content_type,omitempty"`
Type string `json:"type"`
}
type vocechatTarget struct {
Gid int `json:"gid,omitempty"`
Uid int `json:"uid,omitempty"`
}
type vocechatJSON struct {
Detail vocechatDetail `json:"detail"`
From int `json:"from_uid"`
Target vocechatTarget `json:"target"`
}
func voceChatBot(port int) {
listen(port)
}
func handleWebhook(w http.ResponseWriter, r *http.Request) {
// fmt.Printf("headers: %v\n", r.Header)
// fmt.Printf("body: %v\n", r.Body)
// bytes, _ := io.ReadAll(r.Header)
// fmt.Println(string(bytes))
// bytes, _ = io.ReadAll(r.Body)
// fmt.Println(string(bytes))
if r.Header.Get("Content-Type") != "application/json" {
return
}
decoder := json.NewDecoder(r.Body)
var vcJSON vocechatJSON
decoder.Decode(&vcJSON)
// 获取用户信息
getUser := func(v vocechatInstance) vocechatUser {
r, err := http.Get(v.Url + "/user/" + strconv.Itoa(vcJSON.From))
if err != nil {
// Error log
}
decoder := json.NewDecoder(r.Body)
var user vocechatUser
decoder.Decode(&user)
return user
}
// 判断是否是新消息
if vcJSON.Detail.Type == "normal" {
// 判断消息是否属于转发列表
for qqgroup, v := range qq2vcRouteMap {
if v.Gid == strconv.Itoa(vcJSON.Target.Gid) {
user := getUser(v)
// 判断消息是否是机器人发送
if user.IsBot {
return
}
// 转发消息至目的地
id, _ := strconv.ParseInt(qqgroup, 10, 64)
go qq.SendToQQGroup(user.Name+" 转发自 vocechat:\n"+vcJSON.Detail.Content, id)
}
}
for kookGid, v := range kook2vcRouteMap {
if v.Gid == strconv.Itoa(vcJSON.Target.Gid) {
user := getUser(v)
// 判断消息是否是机器人发送
if user.IsBot {
return
}
go vcMsgToKook(kookGid, user.Name, vcJSON.Detail.Content)
}
}
}
}
func vocechatSend(url string, gid int, secret string, content string) {
markdown := []byte(content)
r, err := http.NewRequest("POST", url+"/bot/send_to_group/"+strconv.Itoa(gid), bytes.NewBuffer(markdown))
if err != nil {
return
}
r.Header.Add("Content-Type", "text/markdown")
r.Header.Add("x-api-key", secret)
client := &http.Client{}
_, err = client.Do(r)
if err != nil {
// 发送失败
return
}
}
func listen(port int) {
fmt.Println("Listen on port:", port)
http.HandleFunc("/", handleWebhook)
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), nil))
}