-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
main.go
280 lines (271 loc) · 8.43 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
package main
import (
"bufio"
"crypto/md5"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/Mrs4s/go-cqhttp/server"
"io"
"io/ioutil"
"os"
"os/signal"
"path"
"strconv"
"time"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus"
"github.com/t-tomalak/logrus-easy-formatter"
)
func init() {
log.SetFormatter(&easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "[%time%] [%lvl%]: %msg% \n",
})
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotatelogs.WithRotationTime(time.Hour*24))
if err == nil {
log.SetOutput(io.MultiWriter(os.Stderr, w))
}
if !global.PathExists(global.IMAGE_PATH) {
if err := os.MkdirAll(global.IMAGE_PATH, 0755); err != nil {
log.Fatalf("创建图片缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VOICE_PATH) {
if err := os.MkdirAll(global.VOICE_PATH, 0755); err != nil {
log.Fatalf("创建语音缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VIDEO_PATH) {
if err := os.MkdirAll(global.VIDEO_PATH, 0755); err != nil {
log.Fatalf("创建视频缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.CACHE_PATH) {
if err := os.MkdirAll(global.CACHE_PATH, 0755); err != nil {
log.Fatalf("创建发送图片缓存文件夹失败: %v", err)
}
}
if global.PathExists("cqhttp.json") {
log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.")
log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.json 文件.")
time.Sleep(time.Second * 5)
conf := global.CQHttpApiConfig{}
if err := json.Unmarshal([]byte(global.ReadAllText("cqhttp.json")), &conf); err != nil {
log.Fatalf("读取文件 cqhttp.json 失败: %v", err)
}
goConf := global.DefaultConfig()
goConf.AccessToken = conf.AccessToken
goConf.HttpConfig.Host = conf.Host
goConf.HttpConfig.Port = conf.Port
goConf.WSConfig.Host = conf.WSHost
goConf.WSConfig.Port = conf.WSPort
if conf.PostUrl != "" {
goConf.HttpConfig.PostUrls[conf.PostUrl] = conf.Secret
}
if conf.UseWsReverse {
goConf.ReverseServers[0].Enabled = true
goConf.ReverseServers[0].ReverseUrl = conf.WSReverseUrl
goConf.ReverseServers[0].ReverseApiUrl = conf.WSReverseApiUrl
goConf.ReverseServers[0].ReverseEventUrl = conf.WSReverseEventUrl
goConf.ReverseServers[0].ReverseReconnectInterval = conf.WSReverseReconnectInterval
}
if err := goConf.Save("config.json"); err != nil {
log.Fatalf("保存 config.json 时出现错误: %v", err)
}
_ = os.Remove("cqhttp.json")
}
}
func main() {
console := bufio.NewReader(os.Stdin)
var conf *global.JsonConfig
if global.PathExists("config.json") || os.Getenv("UIN") == "" {
conf = global.Load("config.json")
} else if os.Getenv("UIN") != "" {
log.Infof("将从环境变量加载配置.")
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
pwd := os.Getenv("PASS")
post := os.Getenv("HTTP_POST")
conf = &global.JsonConfig{
Uin: uin,
Password: pwd,
HttpConfig: &global.GoCQHttpConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 5700,
PostUrls: map[string]string{},
},
WSConfig: &global.GoCQWebsocketConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 6700,
},
PostMessageFormat: "string",
Debug: os.Getenv("DEBUG") == "true",
}
if post != "" {
conf.HttpConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
}
}
if conf == nil {
err := global.DefaultConfig().Save("config.json")
if err != nil {
log.Fatalf("创建默认配置文件时出现错误: %v", err)
return
}
log.Infof("默认配置文件已生成, 请编辑 config.json 后重启程序.")
time.Sleep(time.Second * 5)
return
}
if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") {
log.Warnf("请修改 config.json 以添加账号密码.")
time.Sleep(time.Second * 5)
return
}
// log classified by level
// Collect all records up to the specified level (default level: warn)
logLevel := conf.LogLevel
if logLevel != "" {
date := time.Now().Format("2006-01-02")
var logPathMap lfshook.PathMap
switch conf.LogLevel {
case "warn":
logPathMap = lfshook.PathMap{
log.WarnLevel: path.Join("logs", date+"-warn.log"),
log.ErrorLevel: path.Join("logs", date+"-warn.log"),
log.FatalLevel: path.Join("logs", date+"-warn.log"),
log.PanicLevel: path.Join("logs", date+"-warn.log"),
}
case "error":
logPathMap = lfshook.PathMap{
log.ErrorLevel: path.Join("logs", date+"-error.log"),
log.FatalLevel: path.Join("logs", date+"-error.log"),
log.PanicLevel: path.Join("logs", date+"-error.log"),
}
default:
logPathMap = lfshook.PathMap{
log.WarnLevel: path.Join("logs", date+"-warn.log"),
log.ErrorLevel: path.Join("logs", date+"-warn.log"),
log.FatalLevel: path.Join("logs", date+"-warn.log"),
log.PanicLevel: path.Join("logs", date+"-warn.log"),
}
}
log.AddHook(lfshook.NewHook(
logPathMap,
&easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "[%time%] [%lvl%]: %msg% \n",
},
))
}
log.Info("当前版本:", coolq.Version)
if conf.Debug {
log.SetLevel(log.DebugLevel)
log.Warnf("已开启Debug模式.")
log.Debugf("开发交流群: 192548878")
}
if !global.PathExists("device.json") {
log.Warn("虚拟设备信息不存在, 将自动生成随机设备.")
client.GenRandomDevice()
_ = ioutil.WriteFile("device.json", client.SystemDeviceInfo.ToJson(), 0644)
log.Info("已生成设备信息并保存到 device.json 文件.")
} else {
log.Info("将使用 device.json 内的设备信息运行Bot.")
if err := client.SystemDeviceInfo.ReadJson([]byte(global.ReadAllText("device.json"))); err != nil {
log.Fatalf("加载设备信息失败: %v", err)
}
}
if conf.EncryptPassword && conf.PasswordEncrypted == "" {
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
strKey, _ := console.ReadString('\n')
key := md5.Sum([]byte(strKey))
if encrypted := EncryptPwd(conf.Password, key[:]); encrypted != "" {
conf.Password = ""
conf.PasswordEncrypted = encrypted
_ = conf.Save("config.json")
} else {
log.Warnf("加密时出现问题.")
}
}
if conf.PasswordEncrypted != "" {
log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)")
strKey, _ := console.ReadString('\n')
key := md5.Sum([]byte(strKey))
conf.Password = DecryptPwd(conf.PasswordEncrypted, key[:])
}
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
time.Sleep(time.Second * 5)
log.Info("开始尝试登录并同步消息...")
log.Infof("使用协议: %v", func() string {
switch client.SystemDeviceInfo.Protocol {
case client.AndroidPad:
return "Android Pad"
case client.AndroidPhone:
return "Android Phone"
case client.AndroidWatch:
return "Android Watch"
}
return "未知"
}())
cli := client.NewClient(conf.Uin, conf.Password)
cli.OnLog(func(c *client.QQClient, e *client.LogEvent) {
switch e.Type {
case "INFO":
log.Info("Protocol -> " + e.Message)
case "ERROR":
log.Error("Protocol -> " + e.Message)
case "DEBUG":
log.Debug("Protocol -> " + e.Message)
}
})
cli.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) {
log.Infof("收到服务器地址更新通知, 将在下一次重连时应用. ")
})
if conf.WebUi == nil {
conf.WebUi = &global.GoCqWebUi{
Enabled: true,
WebInput: false,
WebUiPort: 9999,
}
}
if conf.WebUi.WebUiPort <= 0 {
conf.WebUi.WebUiPort = 9999
}
confErr := conf.Save("config.json")
if confErr != nil {
log.Error("保存配置文件失败")
}
b := server.WebServer.Run(fmt.Sprintf("%s:%d", "0.0.0.0", conf.WebUi.WebUiPort), cli)
c := server.Console
signal.Notify(c, os.Interrupt, os.Kill)
<-c
b.Release()
}
func EncryptPwd(pwd string, key []byte) string {
tea := binary.NewTeaCipher(key)
if tea == nil {
return ""
}
return base64.StdEncoding.EncodeToString(tea.Encrypt([]byte(pwd)))
}
func DecryptPwd(ePwd string, key []byte) string {
defer func() {
if pan := recover(); pan != nil {
log.Fatalf("密码解密失败: %v", pan)
}
}()
encrypted, err := base64.StdEncoding.DecodeString(ePwd)
if err != nil {
panic(err)
}
tea := binary.NewTeaCipher(key)
if tea == nil {
panic("密钥错误")
}
return string(tea.Decrypt(encrypted))
}