Files
trbot/mess.go
2025-02-11 22:19:51 +08:00

100 lines
2.8 KiB
Go

package main
import (
"log"
"reflect"
"strings"
)
func AnyContains(target any, candidates ...any) bool {
for _, candidate := range candidates {
if candidates == nil { continue }
// fmt.Println(reflect.ValueOf(target).Kind(), reflect.ValueOf(candidate).Kind(), reflect.Array, reflect.Slice)
targetKind := reflect.ValueOf(target).Kind()
candidateKind := reflect.ValueOf(candidate).Kind()
if targetKind != candidateKind && !AnyContains(candidateKind, reflect.Slice, reflect.Array) {
log.Printf("[Warn] (func)AnyContains: candidate(%v) not match target(%v)", candidateKind, targetKind)
}
switch c := candidate.(type) {
case string:
if targetKind == reflect.String && strings.Contains(c, target.(string)) {
return true
}
default:
if reflect.DeepEqual(target, c) {
return true
}
if reflect.ValueOf(c).Kind() == reflect.Slice || reflect.ValueOf(c).Kind() == reflect.Array {
if checkNested(target, reflect.ValueOf(c)) {
return true
}
}
}
}
return false
}
// 为 AnyContains 的递归函数
func checkNested(target any, value reflect.Value) bool {
// fmt.Println(reflect.ValueOf(value.Index(0).Interface()).Kind())
if reflect.TypeOf(target) != reflect.TypeOf(value.Index(0).Interface()) && !AnyContains(reflect.ValueOf(value.Index(0).Interface()).Kind(), reflect.Slice, reflect.Array) {
log.Printf("[Error] (func)AnyContains: candidates's subitem(%v) not match target(%v), skip this compare", reflect.TypeOf(value.Index(0).Interface()), reflect.TypeOf(target))
return false
}
for i := 0; i < value.Len(); i++ {
element := value.Index(i).Interface()
switch c := element.(type) {
case string:
if reflect.ValueOf(target).Kind() == reflect.String && strings.Contains(c, target.(string)) {
return true
}
default:
if reflect.DeepEqual(target, c) {
return true
}
// Check nested slices or arrays
elemValue := reflect.ValueOf(c)
if elemValue.Kind() == reflect.Slice || elemValue.Kind() == reflect.Array {
if checkNested(target, elemValue) {
return true
}
}
}
}
return false
}
func InlineQueryMatchMultKeyword(queryFields []string, Keyword []string, inSubCommand bool) bool {
var allkeywords int
if strings.HasPrefix(queryFields[len(queryFields)-1], InlinePaginationSymbol) {
queryFields = queryFields[:len(queryFields) -1]
} else {
allkeywords = len(queryFields)
}
if inSubCommand && len(queryFields) > 0 {
queryFields = queryFields[1:]
}
if allkeywords == 1 {
if AnyContains(queryFields[0], Keyword) {
return true
}
} else {
var allMatch bool = true
for _, n := range queryFields {
if AnyContains(n, Keyword) {
// 保持 current 内容,继续过滤
// continue
} else {
// 只要有一个关键词未匹配,返回 false
allMatch = false
}
}
if allMatch {
return true
}
}
return false
}