mtfosbot/module/message-command/message-command.go

118 lines
2.3 KiB
Go
Raw Permalink Normal View History

2018-09-14 16:01:36 +00:00
package msgcmd
import (
"regexp"
"strings"
"git.trj.tw/golang/mtfosbot/model"
"git.trj.tw/golang/mtfosbot/module/apis/line"
lineobj "git.trj.tw/golang/mtfosbot/module/line-message/line-object"
)
func parseCMD(in string) (c [][]string) {
re, err := regexp.Compile("{{(.+?)}}")
if err != nil {
return
}
c = re.FindAllStringSubmatch(in, -1)
return
}
// ParseLineMsg -
func ParseLineMsg(txt, replyToken string, source *lineobj.SourceObject) {
if source.Type != "group" {
return
}
strs := strings.Split(strings.Trim(txt, " "), " ")
2018-09-20 17:16:17 +00:00
2018-09-14 16:01:36 +00:00
// skip empty string
if len(strs[0]) == 0 {
return
}
2018-10-09 16:52:40 +00:00
firstNum := []rune(strs[0])[0]
2018-10-09 16:59:24 +00:00
2018-10-09 16:52:40 +00:00
if firstNum == 33 || firstNum == 65281 {
2018-09-14 16:01:36 +00:00
// nor cmd
2018-10-09 16:59:24 +00:00
cmd := ""
if firstNum == 65281 {
cmd = strs[0][3:]
} else {
cmd = strs[0][1:]
}
2018-09-14 16:01:36 +00:00
if len(cmd) == 0 {
return
}
2018-09-20 17:14:08 +00:00
c, err := model.GetGroupCommand(strings.ToLower(cmd), source.GroupID)
2018-09-14 16:01:36 +00:00
if err != nil || c == nil {
return
}
str := runCMD(strings.Join(strs[1:], " "), c.Message, source)
m := parseResult(str)
line.ReplyMessage(replyToken, m)
} else {
// key cmd
2018-09-20 17:14:08 +00:00
c, err := model.GetGroupKeyCommand(strings.ToLower(strs[0]), source.GroupID)
2018-09-14 16:01:36 +00:00
if err != nil || c == nil {
return
}
str := runCMD(strings.Join(strs[1:], " "), c.Message, source)
m := parseResult(str)
line.ReplyMessage(replyToken, m)
}
}
func parseResult(str string) interface{} {
var m interface{}
if strings.HasPrefix(str, "$image$") {
str = strings.Replace(str, "$image$", "", 1)
strs := strings.Split(str, ";")
2018-12-18 09:14:08 +00:00
m = line.ImageMessage{
2018-09-14 16:01:36 +00:00
OriginalContentURL: strs[0],
PreviewImageURL: strs[1],
}
2018-12-18 08:50:38 +00:00
} else if strings.HasPrefix(str, "$video$") {
str = strings.Replace(str, "$video$", "", 1)
strs := strings.Split(str, ";")
2018-12-18 09:14:08 +00:00
m = line.VideoMessage{
2018-12-18 08:50:38 +00:00
OriginalContentURL: strs[0],
PreviewImageURL: strs[1],
}
2018-09-14 16:01:36 +00:00
} else {
2018-12-18 09:14:08 +00:00
m = line.TextMessage{
2018-09-14 16:01:36 +00:00
Text: str,
}
}
return m
}
func runCMD(txt, c string, s *lineobj.SourceObject) (res string) {
cmdAct := parseCMD(c)
if len(cmdAct) == 0 {
return c
}
res = c
for _, v := range cmdAct {
if len(v) > 1 {
// run cmd
m := strings.Split(v[1], "=")
sub := ""
if len(m) > 1 {
sub = strings.Join(m[1:], " ")
}
cmdRes := selectAct(m[0], sub, txt, s)
2018-09-20 17:14:08 +00:00
res = strings.Replace(res, v[0], cmdRes, 1)
2018-09-14 16:01:36 +00:00
}
}
return
}