-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
66 lines (53 loc) · 1.39 KB
/
parser.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
package bot
import (
"regexp"
"strings"
)
var (
re = regexp.MustCompile("\\s+") // Matches one or more spaces
)
func parse(s string, channel string, nick string) *Cmd {
c := &Cmd{Raw: s}
s = strings.TrimSpace(s)
if !strings.HasPrefix(s, Config.Prefix) {
return nil
}
c.Channel = strings.TrimSpace(channel)
c.Nick = strings.TrimSpace(nick)
// Trim the prefix and extra spaces
c.Message = strings.TrimPrefix(s, Config.Prefix)
c.Message = strings.TrimSpace(c.Message)
// check if we have the command and not only the prefix
if c.Message == "" {
return nil
}
// get the command
pieces := strings.SplitN(c.Message, " ", 2)
c.Command = pieces[0]
if len(pieces) > 1 {
// get the arguments and remove extra spaces
c.FullArg = removeExtraSpaces(pieces[1])
c.Args = strings.Split(c.FullArg, " ")
}
return c
}
func removeExtraSpaces(args string) string {
return re.ReplaceAllString(strings.TrimSpace(args), " ")
}
func removeDuplicates(elements []string) []string {
// Use map to record duplicates as we find them.
encountered := map[string]bool{}
result := []string{}
for v := range elements {
if encountered[elements[v]] == true {
// Do not add duplicate.
} else {
// Record this element as an encountered element.
encountered[elements[v]] = true
// Append to result slice.
result = append(result, elements[v])
}
}
// Return the new slice.
return result
}