~handlerug/handlebot

ref: e2138e35984f582b50a481b58c332afae2841b1f handlebot/handler.go -rw-r--r-- 3.6 KiB
e2138e35Umar Getagazov urlpreview: Parse Content-Disposition 3 months ago
                                                                                
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"strings"

	"git.sr.ht/~handlerug/girc"
)

type PublicError interface {
	Public()
}

type HandlerFunc func(ctx context.Context, req HandlerRequest) (string, error)

type Handlers struct {
	client     *girc.Client
	cmdPrefix  string
	serverHost string

	cmdNames []string
	cmds     map[string]command
}

type HandlersOpts struct {
	Client     *girc.Client
	ServerHost string
	CmdPrefix  string
}

type HandlerRequest struct {
	Client     *girc.Client
	Event      girc.Event
	ServerHost string
	Args       string
}

type command struct {
	name    string
	aliases []string
	handler HandlerFunc
	help    string
}

func NewHandlers(opts HandlersOpts) Handlers {
	return Handlers{
		client:     opts.Client,
		cmdPrefix:  opts.CmdPrefix,
		serverHost: opts.ServerHost,
		cmdNames:   make([]string, 0),
		cmds:       make(map[string]command),
	}
}

func (h *Handlers) Add(name string, aliases []string, handler HandlerFunc, help string) {
	cmd := command{
		name:    name,
		aliases: aliases,
		handler: handler,
		help:    help,
	}
	if help != "" {
		h.cmdNames = append(h.cmdNames, name)
	}
	h.cmds[name] = cmd
	for _, alias := range aliases {
		h.cmds[alias] = cmd
	}
}

func (h *Handlers) Handle(ctx context.Context, e girc.Event) bool {
	text := strings.TrimSpace(e.Last())
	if strings.HasPrefix(text, h.cmdPrefix) {
		var cmdName, args string
		parts := strings.SplitN(text[len(h.cmdPrefix):], " ", 2)
		if len(parts) >= 1 {
			cmdName = parts[0]
		}
		if len(parts) >= 2 {
			args = strings.TrimSpace(parts[1])
		}

		req := HandlerRequest{
			Client:     h.client,
			Event:      e,
			ServerHost: h.serverHost,
			Args:       args,
		}
		if cmdName == "help" {
			h.helpHandler(ctx, req)
			return true
		}
		if cmd, ok := h.cmds[cmdName]; ok {
			resp, err := cmd.handler(ctx, req)
			resp = handleError(resp, err)
			if resp != "" {
				h.client.Cmd.Reply(e, resp)
			}
			return true
		}
	}

	return false
}

func (h *Handlers) helpHandler(ctx context.Context, req HandlerRequest) {
	resp := h.getHelp(req.Args)
	for len(resp) > 0 {
		var line string
		if idx := strings.Index(resp, "\n"); idx >= 0 {
			line = resp[:idx]
			resp = resp[len(line)+1:]
		} else {
			line = resp
			resp = resp[:0]
		}
		line = strings.TrimSpace(line)
		req.Client.Cmd.Reply(req.Event, fmt.Sprintf("%s: %s", BotName, line))
	}
}

func (h *Handlers) getHelp(args string) string {
	if args == "" {
		var b strings.Builder
		for i, name := range h.cmdNames {
			if i > 0 {
				b.WriteString(", ")
			}
			b.WriteString(h.cmdPrefix + name)
		}
		fmt.Fprintf(&b, "\nRequest help for a specific command "+
			"using %shelp <command>", h.cmdPrefix)
		return b.String()
	}
	args = strings.TrimPrefix(args, h.cmdPrefix)
	cmd, ok := h.cmds[args]
	if !ok {
		// We don't have this command, but there's a chance it was
		// addressed to another bot, so don't complain loudly
		return ""
	}

	var b strings.Builder
	fmt.Fprintf(&b, "Help for command %s%s", h.cmdPrefix, cmd.name)
	for _, alias := range cmd.aliases {
		fmt.Fprintf(&b, ", %s%s", h.cmdPrefix, alias)
	}
	b.WriteString(":\n")
	b.WriteString(strings.TrimSpace(cmd.help))
	return b.String()
}

func handleError(resp string, err error) string {
	if err != nil {
		if resp == "" {
			if errors.Is(err, context.DeadlineExceeded) {
				resp = errorMsg("Command timed out", nil)
			} else {
				resp = errorMsg("An error occured during handler execution", err)
			}
		}
		log.Println(err)
	}
	return resp
}

func errorMsg(msg string, err error) string {
	if _, ok := err.(PublicError); ok {
		return fmt.Sprintf("%s: %v", msg, err)
	}
	return fmt.Sprintf("%s; check the logs for more info.", msg)
}