-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
utils.go
239 lines (220 loc) · 5.33 KB
/
utils.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
package utils
import (
"encoding/json"
"errors"
"fmt"
"github.com/Logiase/MiraiGo-Template/bot"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Sora233/requests"
"github.com/davecgh/go-spew/spew"
"github.com/sirupsen/logrus"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
var ErrGoCvNotSetUp = errors.New("gocv not setup")
func FilePathWalkDir(root string) ([]string, error) {
var files []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
if ImageSuffix(info.Name()) {
files = append(files, path)
}
} else if path != root {
subfiles, err := FilePathWalkDir(path)
if err != nil {
return err
}
for _, f := range subfiles {
files = append(files, f)
}
}
return nil
})
return files, err
}
func toMap(data interface{}) (map[string]string, error) {
params := make(map[string]string)
rg := reflect.ValueOf(data)
if rg.Type().Kind() == reflect.Ptr {
rg = rg.Elem()
}
if rg.Type().Kind() != reflect.Struct {
return nil, errors.New("can only convert struct type")
}
for i := 0; ; i++ {
if i >= rg.Type().NumField() {
break
}
field := rg.Type().Field(i)
fillname, found := field.Tag.Lookup("json")
if !found {
fillname = toCamel(field.Name)
} else {
if pos := strings.Index(fillname, ","); pos != -1 {
fillname = fillname[:pos]
}
}
switch field.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
params[fillname] = strconv.FormatInt(rg.Field(i).Int(), 10)
case reflect.String:
params[fillname] = rg.Field(i).String()
case reflect.Bool:
params[fillname] = strconv.FormatBool(rg.Field(i).Bool())
default:
return nil, fmt.Errorf("not support type %v", field.Type.Kind().String())
}
}
return params, nil
}
func ToParams(get interface{}) (requests.Params, error) {
return toMap(get)
}
func ToDatas(data interface{}) (requests.Datas, error) {
return toMap(data)
}
func toCamel(name string) string {
if len(name) == 0 {
return ""
}
sb := strings.Builder{}
sb.WriteString(strings.ToLower(name[:1]))
for _, c := range name[1:] {
if c >= 'A' && c <= 'Z' {
sb.WriteRune('_')
sb.WriteRune(c - 'A' + 'a')
} else {
sb.WriteRune(c)
}
}
return sb.String()
}
func FuncName() string {
pc := make([]uintptr, 15)
n := runtime.Callers(2, pc)
frames := runtime.CallersFrames(pc[:n])
frame, _ := frames.Next()
return frame.Function
}
func PrefixMatch(opts []string, target string) (string, bool) {
if len(opts) == 0 {
return "", false
}
var (
found = false
result = ""
)
for _, opt := range opts {
if strings.HasPrefix(opt, target) {
if found == true {
return "", false
}
found = true
result = opt
}
}
return result, found
}
func UnquoteString(s string) (string, error) {
return strconv.Unquote(fmt.Sprintf(`"%s"`, strings.Trim(s, `"`)))
}
func TimestampFormat(ts int64) string {
t := time.Unix(ts, 0)
return t.Format("2006-01-02 15:04:05")
}
func Retry(count int, interval time.Duration, f func() bool) bool {
for retry := 0; retry < count; retry++ {
if f() {
return true
}
time.Sleep(interval)
}
return false
}
func ArgSplit(str string) (result []string) {
r := regexp.MustCompile(`[^\s"]+|"([^"]*)"`)
match := r.FindAllString(str, -1)
for _, s := range match {
result = append(result, strings.Trim(strings.TrimSpace(s), `" `))
}
return
}
func GroupLogFields(groupCode int64) logrus.Fields {
var fields = make(logrus.Fields)
fields["GroupCode"] = groupCode
if bot.Instance == nil {
return fields
}
if groupInfo := bot.Instance.FindGroup(groupCode); groupInfo != nil {
fields["GroupName"] = groupInfo.Name
}
return fields
}
func MsgToString(elements []message.IMessageElement) (res string) {
for _, elem := range elements {
if elem == nil {
continue
}
switch e := elem.(type) {
case *message.TextElement:
res += e.Content
case *message.ImageElement:
res += "[Image]"
case *message.FaceElement:
res += "[" + e.Name + "]"
case *message.GroupImageElement:
res += "[Image]"
case *message.GroupFlashImgElement:
res += "[Flash Image]"
case *message.AtElement:
res += e.Display
case *message.RedBagElement:
res += "[RedBag:" + e.Title + "]"
case *message.ReplyElement:
res += "[Reply:" + strconv.FormatInt(int64(e.ReplySeq), 10) + "]"
case *message.GroupFileElement:
res += "[File]" + e.Name
case *message.ShortVideoElement:
res += "[Video]"
case *message.ForwardElement:
res += "[Forward]"
case *message.MusicShareElement:
res += "[Music]"
case *message.LightAppElement:
res += "[LightApp]" + e.Content
case *message.ServiceElement:
res += "[Service]" + e.Content
case *message.VoiceElement, *message.PrivateVoiceElement, *message.GroupVoiceElement:
res += "[Voice]"
default:
logger.WithField("content", spew.Sdump(elem)).Debug("found new element")
}
}
return
}
// CompareId 用_id的类型信息去转换number类型,并尝试比较
func CompareId(number json.Number, _id interface{}) bool {
idType := reflect.TypeOf(_id)
switch idType.Kind() {
case reflect.Int64:
jid, err := number.Int64()
if err != nil {
panic(err)
}
return jid == _id.(int64)
case reflect.String:
jid := number.String()
return jid == _id.(string)
default:
return false
}
}
func Switch2Bool(_s string) bool {
return _s == "on"
}