/
context.go
67 lines (56 loc) · 1.22 KB
/
context.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
67
package botbot
import (
"io"
"net/http"
"github.com/bwmarrin/discordgo"
"github.com/pkg/errors"
)
// Context of a message
type Context struct {
s *discordgo.Session
m *discordgo.MessageCreate
channelName string
args []string
app map[string]interface{}
}
// Channel name that is known to users
func (c *Context) Channel() string {
return c.channelName
}
// Arg in the message
func (c *Context) Arg(i int) string {
if len(c.args) < i+1 {
return ""
}
return c.args[i]
}
// Attachment reader of the message
func (c *Context) Attachment(i int) (io.ReadCloser, error) {
if len(c.m.Attachments) < i+1 {
return nil, errors.Errorf("no attachment at %d", i)
}
url := c.m.Attachments[i].URL
resp, err := http.Get(url)
if err != nil {
return nil, err
}
return resp.Body, nil
}
// Send a response to the same channel
func (c *Context) Send(msg string) error {
_, err := c.s.ChannelMessageSend(c.m.ChannelID, msg)
return err
}
// Value of a global context var
func (c *Context) Value(name string) interface{} {
return c.app[name]
}
func (c *Context) sub() *Context {
return &Context{
s: c.s,
m: c.m,
channelName: c.channelName,
args: c.args[1:],
app: c.app,
}
}