beanbot/bot/recent.go

48 lines
781 B
Go
Raw Normal View History

2023-09-26 21:42:14 +08:00
package bot
import (
"sort"
"time"
)
type recentCmd struct {
command string
t time.Time
}
var recentCmds []recentCmd
type recentCmdSort []recentCmd
func (r recentCmdSort) Len() int {
return len(r)
}
func (r recentCmdSort) Less(i, j int) bool {
return r[i].t.Before(r[j].t)
}
func (r recentCmdSort) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
func updateRecentCommand(command string) {
exists := false
2023-10-12 15:56:04 +08:00
for idx, v := range recentCmds {
2023-09-26 21:42:14 +08:00
if v.command == command {
2023-10-12 15:56:04 +08:00
recentCmds[idx].t = time.Now()
2023-09-26 21:42:14 +08:00
exists = true
break
}
}
if !exists {
recentCmds = append([]recentCmd{{command: command, t: time.Now()}}, recentCmds...)
if len(recentCmds) > 5 {
recentCmds = recentCmds[:5]
}
} else {
2023-09-28 14:47:55 +08:00
sort.Sort(sort.Reverse(recentCmdSort(recentCmds)))
2023-09-26 21:42:14 +08:00
}
}