summaryrefslogtreecommitdiff
path: root/command.go
blob: e4ee147a6f461b0d57d621b633ca9494d73e26bf (plain)
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
package main

import (
	"fmt"
	"log"
	"strings"
	"time"

	irc "github.com/fluffle/goirc/client"
)

type Commander interface {
	irc.Handler
	fmt.Stringer
	Timeout(string) bool
	WithArgs(int) bool
}

type Command struct {
	Help string
	Arg  string
	Last map[string]time.Time
}

var commands = make(map[string]Commander)

func Register(cmd string, f Commander) {
	commands[cmd] = f
}

func (v Command) String() string { return v.Help }
func (v *Command) Timeout(nick string) bool {
	defer func() { v.Last[nick] = time.Now() }()
	if v.Last == nil {
		v.Last = make(map[string]time.Time)
	}
	if last, ok := v.Last[nick]; ok {
		if to := time.Since(last); to < 5*time.Second {
			log.Println(nick, "timeout", to)
			return true
		}
	}
	return false
}
func (_ Command) WithArgs(n int) bool { return n == 1 }

func Dispatch(conn *irc.Conn, line *irc.Line) {
	if f := strings.Fields(line.Text()); len(f) > 0 {
		cmd := strings.ToLower(f[0])
		if c, ok := commands[cmd]; ok {
			if line.Public() && c.Timeout(line.Nick) {
				log.Println("timeout", line.Nick)
				conn.Kick(*room, line.Nick, "timeout")
				return
			}
			if c.WithArgs(len(f)) {
				log.Println(line.Nick, f)
				c.Handle(conn, line)
			}
		}
	}
}