-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdicebae.go
70 lines (61 loc) · 1.89 KB
/
dicebae.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
68
69
70
// Package dicebae implements the baepi DiceBae interface. It essentially wraps
// a discordgo session to provide a more bae-focused experience. Specifically,
// it defines a bot centered around responding to hotwords spoken in discord
// channels with simple, easy-to-write handlers.
package dicebae
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"dicebae/baepi"
"github.com/bwmarrin/discordgo"
)
// Baergs contains arguments for the creation of the bae.
type Baergs struct {
APIKey string // Required.
PlayerIDs []int
LogDir string
}
// diceBae implements the DiceBae interface defined in the baepi.
type diceBae struct {
session *discordgo.Session
logFile *os.File
logger *log.Logger
history []*baepi.BaeHistoryEntry
}
// NewBae returns a hot, fresh bae with validated and initialized handlers.
func NewBae(args *Baergs) (baepi.DiceBae, error) {
dg, err := discordgo.New("Bot " + args.APIKey)
if err != nil {
return nil, fmt.Errorf("Error: %v", err)
}
db := &diceBae{
session: dg,
history: make([]*baepi.BaeHistoryEntry, 0, 1024),
}
if err := db.initLogger(args.LogDir); err != nil {
return nil, fmt.Errorf("bae failed to init logger: %v", err)
}
if err := db.initHandlers(args); err != nil {
return nil, fmt.Errorf("bae failed to init handlers: %v", err)
}
return db, nil
}
// LetsRoll initializes a discordgo session and will attempt to serve responses
// from each dicebae handler until killed.
func (db *diceBae) LetsRoll() error {
if err := db.session.Open(); err != nil {
return fmt.Errorf("failed to open Discord session: %v", err)
}
defer db.session.Close()
defer db.logFile.Close()
db.LogInfo("I have no dice, but I must roll. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
// Block on this channel until we get a termination signal.
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
db.LogInfo("Later dopes.")
return nil
}