Compare commits

..

5 Commits

Author SHA1 Message Date
4c5849daae Merge pull request 'Add a command router' (#2) from add-command-router into develop
Some checks failed
continuous-integration/drone/push Build is failing
Reviewed-on: chill9/bb#2
2022-09-06 12:49:18 +00:00
c59c95c47a
Refactor commands to use the router
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-09-06 00:02:24 -05:00
0345b1cba1
Add a command router
This will only required one handler for all of the commands
2022-09-06 00:02:24 -05:00
a1d612abc0
Add time zone database to container
Some checks failed
continuous-integration/drone/push Build is failing
2022-09-06 00:02:04 -05:00
0f25b75fe4
Add forgotten imports
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-09-05 15:14:42 -05:00
16 changed files with 256 additions and 325 deletions

View File

@ -6,4 +6,6 @@ RUN CGO_ENABLED=0 go build ./cmd/bb
FROM scratch AS bin FROM scratch AS bin
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /src/bb / COPY --from=build /src/bb /
ADD https://raw.githubusercontent.com/golang/go/master/lib/time/zoneinfo.zip /zoneinfo.zip
ENV ZONEINFO /zoneinfo.zip
ENTRYPOINT ["/bb"] ENTRYPOINT ["/bb"]

87
bot/command.go Normal file
View File

@ -0,0 +1,87 @@
package bot
import (
"fmt"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
var (
DefaultCommander *Commander
)
type (
Commander struct {
commands map[string]*Command
}
Command struct {
Name string
Config Config
Func func(cmd *Command, args []string) error
Session *discordgo.Session
Message *discordgo.MessageCreate
}
)
func init() {
DefaultCommander = NewCommander()
}
func NewCommander() *Commander {
cmdr := new(Commander)
cmdr.commands = make(map[string]*Command)
return cmdr
}
func (cmdr *Commander) AddCommand(cmd *Command) {
cmdr.commands[cmd.Name] = cmd
}
func (cmdr *Commander) GetCommand(name string) (*Command, bool) {
cmd, ok := cmdr.commands[name]
return cmd, ok
}
func AddCommand(cmd *Command) {
DefaultCommander.AddCommand(cmd)
}
func GetCommand(name string) (*Command, bool) {
cmd, ok := DefaultCommander.GetCommand(name)
return cmd, ok
}
func NewCommandHandler(config Config) func(s *discordgo.Session, m *discordgo.MessageCreate) {
return func(s *discordgo.Session, m *discordgo.MessageCreate) {
var cmd *Command
if m.Author.ID == s.State.User.ID {
return
}
if !lib.HasCommand(m.Content, config.Prefix) {
return
}
cmdName, args := lib.SplitCommandAndArgs(m.Content, config.Prefix)
cmd, ok := GetCommand(cmdName)
if ok {
cmd.Config = config
cmd.Name = cmdName
cmd.Session = s
cmd.Message = m
log.Debugf("command: %+v, args: %+v", cmd.Name, args)
cmd.Func(cmd, args)
return
}
log.Warnf("unknown command: %+v, args: %+v", cmdName, args)
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("unknown command: %s", cmdName))
}
}

29
bot/commands/coin.go Normal file
View File

@ -0,0 +1,29 @@
package commands
import (
"git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib"
)
type Coin bool
func (c *Coin) Flip() bool {
*c = Coin(lib.Itob(lib.RandInt(0, 1)))
return bool(*c)
}
func CoinCommand(cmd *bot.Command, args []string) error {
var (
c Coin
msg string
)
if c.Flip() {
msg = "heads"
} else {
msg = "tails"
}
cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, msg)
return nil
}

View File

@ -1,4 +1,4 @@
package handler package commands
import ( import (
"errors" "errors"
@ -8,8 +8,6 @@ import (
"strings" "strings"
"git.kill0.net/chill9/beepboop/bot" "git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -52,36 +50,16 @@ func (d *Deck) Deal(n int) ([]Card, error) {
return hand, err return hand, err
} }
func NewDealHandler(s string) *DealHandler { func DealCommand(cmd *bot.Command, args []string) error {
h := new(DealHandler)
h.Name = s
return h
}
func (h *DealHandler) SetConfig(config bot.Config) {
h.config = config
}
func (h *DealHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
if !lib.ContainsCommand(m.Content, h.config.Prefix, h.Name) {
return
}
rand.Shuffle(len(deck), func(i, j int) { rand.Shuffle(len(deck), func(i, j int) {
deck[i], deck[j] = deck[j], deck[i] deck[i], deck[j] = deck[j], deck[i]
}) })
log.Debugf("%+v", deck) log.Debugf("%+v", deck)
_, args := lib.SplitCommandAndArgs(m.Content, h.config.Prefix)
if len(args) != 1 { if len(args) != 1 {
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("help: `!%s <n>`", h.Name)) cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, fmt.Sprintf("help: `!%s <n>`", cmd.Name))
return return nil
} }
n, err := strconv.Atoi(args[0]) n, err := strconv.Atoi(args[0])
@ -91,11 +69,12 @@ func (h *DealHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
hand, err := deck.Deal(n) hand, err := deck.Deal(n)
if err != nil { if err != nil {
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("error: %s\n", err)) cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, fmt.Sprintf("error: %s\n", err))
return return nil
} }
s.ChannelMessageSend(m.ChannelID, JoinCards(hand, " ")) cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, JoinCards(hand, " "))
return nil
} }
func JoinCards(h []Card, sep string) string { func JoinCards(h []Card, sep string) string {

View File

@ -1,4 +1,4 @@
package handler package commands
import ( import (
"errors" "errors"
@ -9,7 +9,6 @@ import (
"git.kill0.net/chill9/beepboop/bot" "git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib" "git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -25,11 +24,6 @@ type (
Rolls []int Rolls []int
S string S string
} }
RollHandler struct {
config bot.Config
Name string
}
) )
func NewRoll(n, d int) *Roll { func NewRoll(n, d int) *Roll {
@ -84,42 +78,19 @@ func (r *Roll) RollDice() {
} }
} }
func NewRollHandler(s string) *RollHandler { func RollCommand(cmd *bot.Command, args []string) error {
return &RollHandler{Name: s}
}
func (h *RollHandler) SetConfig(config bot.Config) {
h.config = config
}
func (h *RollHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
var ( var (
err error err error
msg, roll string msg, roll string
r *Roll r *Roll
) )
if m.Author.ID == s.State.User.ID { roll = args[0]
return
}
if !lib.ContainsCommand(m.Content, h.config.Prefix, h.Name) {
return
}
x := strings.Split(m.Content, " ")
if len(x) != 2 {
s.ChannelMessageSend(m.ChannelID, "help: `!roll <n>d<s>`")
return
}
roll = x[1]
r, err = ParseRoll(roll) r, err = ParseRoll(roll)
if err != nil { if err != nil {
s.ChannelMessageSend(m.ChannelID, err.Error()) cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, err.Error())
return return nil
} }
r.RollDice() r.RollDice()
@ -127,5 +98,6 @@ func (h *RollHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
msg = fmt.Sprintf("🎲 %s = %d", lib.JoinInt(r.Rolls, " + "), r.Sum) msg = fmt.Sprintf("🎲 %s = %d", lib.JoinInt(r.Rolls, " + "), r.Sum)
s.ChannelMessageSend(m.ChannelID, msg) cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, msg)
return nil
} }

10
bot/commands/ping.go Normal file
View File

@ -0,0 +1,10 @@
package commands
import (
"git.kill0.net/chill9/beepboop/bot"
)
func PingCommand(cmd *bot.Command, args []string) error {
cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, "pong")
return nil
}

View File

@ -1,11 +1,8 @@
package handler package commands
import ( import (
"strings"
"git.kill0.net/chill9/beepboop/bot" "git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib" "git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -21,11 +18,6 @@ type (
C [6]bool C [6]bool
N int N int
} }
RouletteHandler struct {
config bot.Config
Name string
}
) )
var ( var (
@ -74,23 +66,7 @@ func (g *Gun) IsEmpty() bool {
return true return true
} }
func NewRouletteHandler(s string) *RouletteHandler { func RouletteCommand(cmd *bot.Command, args []string) error {
return &RouletteHandler{Name: s}
}
func (h *RouletteHandler) SetConfig(config bot.Config) {
h.config = config
}
func (h *RouletteHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
if !strings.HasPrefix(m.Content, "!roulette") {
return
}
if gun.IsEmpty() { if gun.IsEmpty() {
gun.Load(Bullets) gun.Load(Bullets)
log.Debugf("reloading gun: %+v\n", gun) log.Debugf("reloading gun: %+v\n", gun)
@ -98,8 +74,9 @@ func (h *RouletteHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreat
log.Debugf("firing gun: %+v\n", gun) log.Debugf("firing gun: %+v\n", gun)
if gun.Fire() { if gun.Fire() {
s.ChannelMessageSend(m.ChannelID, GunFireMessage) cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, GunFireMessage)
} else { } else {
s.ChannelMessageSend(m.ChannelID, GunClickMessage) cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, GunClickMessage)
} }
return nil
} }

34
bot/commands/time.go Normal file
View File

@ -0,0 +1,34 @@
package commands
import (
"fmt"
"time"
"git.kill0.net/chill9/beepboop/bot"
log "github.com/sirupsen/logrus"
)
func TimeCommand(cmd *bot.Command, args []string) error {
var (
t time.Time
tz string
)
now := time.Now()
if len(args) == 1 {
tz = args[0]
loc, err := time.LoadLocation(tz)
if err != nil {
log.Warnf("failed to load location: %s", err)
cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, err.Error())
return nil
}
t = now.In(loc)
} else {
t = now
}
cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, fmt.Sprint(t))
return nil
}

23
bot/commands/version.go Normal file
View File

@ -0,0 +1,23 @@
package commands
import (
"fmt"
"runtime"
"git.kill0.net/chill9/beepboop/bot"
)
const (
SourceURI = "https://git.kill0.net/chill9/bb"
)
func VersionCommand(cmd *bot.Command, args []string) error {
cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, fmt.Sprintf(
"go version: %s\nplatform: %s\nos: %s\nsource: %s\n",
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
SourceURI,
))
return nil
}

View File

@ -1,12 +1,10 @@
package handler package commands
import ( import (
"fmt" "fmt"
"strings"
"git.kill0.net/chill9/beepboop/bot" "git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib/weather" "git.kill0.net/chill9/beepboop/lib/weather"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -24,48 +22,38 @@ func (h *WeatherHandler) SetConfig(config bot.Config) {
h.Config = config h.Config = config
} }
func (h *WeatherHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) { func WeatherCommand(cmd *bot.Command, args []string) error {
var ( var (
err error err error
loc string loc string
w weather.Weather w weather.Weather
) )
if m.Author.ID == s.State.User.ID { if len(args) != 1 {
return cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, "help: `!weather <CITY>,<STATE>,<COUNTRY>`")
return nil
} }
if !strings.HasPrefix(m.Content, "!weather") { loc = args[0]
return
}
x := strings.SplitN(m.Content, " ", 2) if cmd.Config.OpenWeatherMapToken == "" {
if len(x) != 2 {
s.ChannelMessageSend(m.ChannelID, "help: `!weather <CITY>,<STATE>,<COUNTRY>`")
return
}
loc = x[1]
if h.Config.OpenWeatherMapToken == "" {
log.Error("OpenWeather token is not set") log.Error("OpenWeather token is not set")
return return nil
} }
wc := weather.NewClient(h.Config.OpenWeatherMapToken) wc := weather.NewClient(cmd.Config.OpenWeatherMapToken)
log.Debugf("weather requested for '%s'", loc) log.Debugf("weather requested for '%s'", loc)
w, err = wc.Get(loc) w, err = wc.Get(loc)
if err != nil { if err != nil {
log.Errorf("weather client error: %v", err) log.Errorf("weather client error: %v", err)
return return nil
} }
log.Debugf("weather returned for '%s': %+v", loc, w) log.Debugf("weather returned for '%s': %+v", loc, w)
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf( cmd.Session.ChannelMessageSend(cmd.Message.ChannelID, fmt.Sprintf(
"%s (%.1f, %.1f) — C:%.1f F:%.1f K:%.1f", "%s (%.1f, %.1f) — C:%.1f F:%.1f K:%.1f",
loc, loc,
w.Coord.Lat, w.Coord.Lat,
@ -74,4 +62,6 @@ func (h *WeatherHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate
w.Main.Temp.Fahrenheit(), w.Main.Temp.Fahrenheit(),
w.Main.Temp.Kelvin(), w.Main.Temp.Kelvin(),
)) ))
return nil
} }

View File

@ -1,52 +0,0 @@
package handler
import (
"git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
)
type (
Coin bool
CoinHandler struct {
config bot.Config
Name string
}
)
func (c *Coin) Flip() bool {
*c = Coin(lib.Itob(lib.RandInt(0, 1)))
return bool(*c)
}
func NewCoinHandler(s string) *CoinHandler {
return &CoinHandler{Name: s}
}
func (h *CoinHandler) SetConfig(config bot.Config) {
h.config = config
}
func (h *CoinHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
var (
c Coin
msg string
)
if m.Author.ID == s.State.User.ID {
return
}
if !lib.ContainsCommand(m.Content, h.config.Prefix, h.Name) {
return
}
if c.Flip() {
msg = "heads"
} else {
msg = "tails"
}
s.ChannelMessageSend(m.ChannelID, msg)
}

View File

@ -1,37 +0,0 @@
package handler
import (
"git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
type (
PingHandler struct {
config bot.Config
Name string
}
)
func NewPingHandler(s string) *PingHandler {
return &PingHandler{Name: s}
}
func (h *PingHandler) SetConfig(config bot.Config) {
h.config = config
}
func (h *PingHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
if !lib.ContainsCommand(m.Content, h.config.Prefix, h.Name) {
return
}
log.Debug("received ping")
s.ChannelMessageSend(m.ChannelID, "pong")
}

View File

@ -1,65 +0,0 @@
package handler
import (
"fmt"
"strings"
"time"
"git.kill0.net/chill9/beepboop/bot"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
type (
TimeHandler struct {
config bot.Config
Name string
}
)
func NewTimeHandler(s string) *TimeHandler {
return &TimeHandler{Name: s}
}
func (h *TimeHandler) SetConfig(config bot.Config) {
h.config = config
}
func (h *TimeHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
var (
t time.Time
tz string
)
if m.Author.ID == s.State.User.ID {
return
}
if !strings.HasPrefix(m.Content, "!time") {
return
}
x := strings.SplitN(m.Content, " ", 2)
if len(x) > 2 {
s.ChannelMessageSend(m.ChannelID, "help: `!time TIMEZONE`")
return
}
now := time.Now()
if len(x) == 2 {
tz = x[1]
loc, err := time.LoadLocation(tz)
if err != nil {
log.Warnf("failed to load location: %s", err)
s.ChannelMessageSend(m.ChannelID, err.Error())
return
}
t = now.In(loc)
} else {
t = now
}
s.ChannelMessageSend(m.ChannelID, fmt.Sprint(t))
}

View File

@ -1,47 +0,0 @@
package handler
import (
"fmt"
"runtime"
"git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
)
const (
SourceURI = "https://git.kill0.net/chill9/bb"
)
type (
VersionHandler struct {
config bot.Config
Name string
}
)
func NewVersionHandler(s string) *VersionHandler {
return &VersionHandler{Name: s}
}
func (h *VersionHandler) SetConfig(config bot.Config) {
h.config = config
}
func (h *VersionHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
if !lib.ContainsCommand(m.Content, h.config.Prefix, h.Name) {
return
}
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf(
"go version: %s\nplatform: %s\nos: %s\nsource: %s\n",
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
SourceURI,
))
}

View File

@ -11,6 +11,7 @@ import (
"syscall" "syscall"
"git.kill0.net/chill9/beepboop/bot" "git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/bot/commands"
"git.kill0.net/chill9/beepboop/bot/handler" "git.kill0.net/chill9/beepboop/bot/handler"
"git.kill0.net/chill9/beepboop/lib" "git.kill0.net/chill9/beepboop/lib"
@ -24,18 +25,41 @@ var (
C bot.Config C bot.Config
handlers []bot.MessageCreateHandler = []bot.MessageCreateHandler{ handlers []bot.MessageCreateHandler = []bot.MessageCreateHandler{
handler.NewCoinHandler("coin"),
handler.NewPingHandler("ping"),
handler.NewRollHandler("roll"),
handler.NewRouletteHandler("roulette"),
handler.NewTimeHandler("time"),
handler.NewVersionHandler("version"),
handler.NewWeatherHandler("weather"),
handler.NewReactionHandler(), handler.NewReactionHandler(),
handler.NewDealHandler("deal"),
} }
) )
func init() {
bot.AddCommand(&bot.Command{
Name: "coin",
Func: commands.CoinCommand,
})
bot.AddCommand(&bot.Command{
Name: "deal",
Func: commands.DealCommand,
})
bot.AddCommand(&bot.Command{
Name: "ping",
Func: commands.PingCommand,
})
bot.AddCommand(&bot.Command{
Name: "roll",
Func: commands.RollCommand,
})
bot.AddCommand(&bot.Command{
Name: "time",
Func: commands.TimeCommand,
})
bot.AddCommand(&bot.Command{
Name: "version",
Func: commands.VersionCommand,
})
bot.AddCommand(&bot.Command{
Name: "weather",
Func: commands.WeatherCommand,
})
}
func main() { func main() {
setupConfig() setupConfig()
@ -55,6 +79,8 @@ func main() {
dg.AddHandler(h.Handle) dg.AddHandler(h.Handle)
} }
dg.AddHandler(bot.NewCommandHandler(C))
dg.Identify.Intents = discordgo.IntentsGuildMessages | discordgo.IntentsDirectMessages dg.Identify.Intents = discordgo.IntentsGuildMessages | discordgo.IntentsDirectMessages
err = dg.Open() err = dg.Open()

View File

@ -1,6 +1,9 @@
package lib package lib
import "testing" import (
"reflect"
"testing"
)
func TestContainsCommand(t *testing.T) { func TestContainsCommand(t *testing.T) {
tables := []struct { tables := []struct {