Compare commits

...

11 Commits

29 changed files with 719 additions and 437 deletions

View File

@ -1,11 +1,15 @@
package bot
import (
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"git.kill0.net/chill9/beepboop/command"
"git.kill0.net/chill9/beepboop/config"
"git.kill0.net/chill9/beepboop/handler"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
@ -13,14 +17,23 @@ import (
"github.com/spf13/viper"
)
var C Config
var C *config.Config
type (
Bot struct {
Session *discordgo.Session
Config Config
config *config.Config
session *discordgo.Session
commands map[string]*Command
}
Command struct {
Name string
Func CommandFunc
NArgs int
}
CommandFunc func(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error
MessageHandler func(s *discordgo.Session, m *discordgo.MessageCreate)
)
@ -31,50 +44,110 @@ func init() {
viper.BindPFlags(pflag.CommandLine)
}
func NewBot(s *discordgo.Session, config Config) *Bot {
return &Bot{Session: s, Config: config}
func NewBot(config *config.Config, s *discordgo.Session) *Bot {
return &Bot{
session: s,
commands: make(map[string]*Command),
}
}
func (b *Bot) RegisterCommands() {
AddCommand(&Command{
func (b *Bot) AddHandler(handler interface{}) func() {
return b.session.AddHandler(handler)
}
func (b *Bot) AddCommand(cmd *Command) {
b.commands[cmd.Name] = cmd
}
func (b *Bot) GetCommand(name string) (*Command, bool) {
cmd, ok := b.commands[name]
return cmd, ok
}
func (b *Bot) CommandHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
if !lib.HasCommand(m.Content, b.config.Prefix) {
return
}
cmdName, arg := lib.SplitCommandAndArg(m.Content, b.config.Prefix)
cmd, ok := b.GetCommand(cmdName)
if !ok {
return
}
args := lib.SplitArgs(arg, cmd.NArgs)
if ok {
log.Debugf("command: %v, args: %v, nargs: %d", cmd.Name, args, len(args))
if err := cmd.Func(args, s, m); err != nil {
log.Errorf("failed to execute command: %s", err)
}
return
}
log.Warnf("unknown command: %v, args: %v, nargs: %d", cmdName, args, len(args))
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("unknown command: %s", cmdName))
}
func (b *Bot) Init(h *handler.Handlers, ch *command.Handlers) {
// Register handlers
b.AddHandler(h.Reaction)
// Register commands
b.AddCommand(&Command{
Name: "coin",
Func: b.CoinCommand(),
Func: ch.Coin,
})
AddCommand(&Command{
b.AddCommand(&Command{
Name: "deal",
Func: b.DealCommand(),
Func: ch.Deal,
NArgs: 1,
})
AddCommand(&Command{
b.AddCommand(&Command{
Name: "ping",
Func: b.PingCommand(),
Func: ch.Ping,
})
AddCommand(&Command{
b.AddCommand(&Command{
Name: "roll",
Func: b.RollCommand(),
Func: ch.Roll,
NArgs: 1,
})
AddCommand(&Command{
b.AddCommand(&Command{
Name: "roulette",
Func: ch.Roulette,
})
b.AddCommand(&Command{
Name: "rps",
Func: ch.Rps,
NArgs: 1,
})
b.AddCommand(&Command{
Name: "rpsls",
Func: ch.Rpsls,
NArgs: 1,
})
b.AddCommand(&Command{
Name: "time",
Func: b.TimeCommand(),
Func: ch.Time,
NArgs: 1,
})
AddCommand(&Command{
b.AddCommand(&Command{
Name: "version",
Func: b.VersionCommand(),
Func: ch.Version,
})
AddCommand(&Command{
b.AddCommand(&Command{
Name: "weather",
Func: b.WeatherCommand(),
Func: ch.Weather,
NArgs: 1,
})
}
func (b *Bot) RegisterHandlers() {
b.Session.AddHandler(b.CommandHandler())
b.Session.AddHandler(b.ReactionHandler())
}
func Run() error {
initConfig()
go reloadConfig()
@ -84,22 +157,21 @@ func Run() error {
}
if C.DiscordToken == "" {
log.Fatalf("Discord token is not set")
return errors.New("discord token not set")
}
dg, err := discordgo.New(fmt.Sprintf("Bot %s", C.DiscordToken))
if err != nil {
log.Fatalf("error creating Discord session: %v\n", err)
return fmt.Errorf("error creating discord session: %v", err)
}
b := NewBot(dg, C)
b.RegisterHandlers()
b.RegisterCommands()
b := NewBot(C, dg)
b.Init(handler.NewHandlers(C), command.NewHandlers(C))
dg.Identify.Intents = discordgo.IntentsGuildMessages | discordgo.IntentsDirectMessages
if err = dg.Open(); err != nil {
log.Fatalf("error opening connection: %v\n", err)
return fmt.Errorf("error opening connection: %v", err)
}
log.Info("The bot is now running. Press CTRL-C to exit.")
@ -116,7 +188,7 @@ func Run() error {
}
func initConfig() {
C = NewConfig()
C = config.NewConfig()
viper.SetEnvPrefix("BEEPBOOP")
viper.AutomaticEnv()

View File

@ -1,31 +0,0 @@
package bot
import (
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
)
type Coin bool
func (c *Coin) Flip() bool {
*c = Coin(lib.Itob(lib.RandInt(0, 1)))
return bool(*c)
}
func (b *Bot) CoinCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) error {
var (
c Coin
msg string
)
if c.Flip() {
msg = "heads"
} else {
msg = "tails"
}
b.Session.ChannelMessageSend(m.ChannelID, msg)
return nil
}
}

View File

@ -1,90 +0,0 @@
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 CommandFunc
NArgs int
}
CommandFunc func(args []string, m *discordgo.MessageCreate) error
)
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 (b *Bot) CommandHandler() func(*discordgo.Session, *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, b.Config.Prefix) {
return
}
cmdName, arg := lib.SplitCommandAndArg(m.Content, b.Config.Prefix)
cmd, ok := GetCommand(cmdName)
args := lib.SplitArgs(arg, cmd.NArgs)
if ok {
cmd.Config = b.Config
log.Debugf("command: %v, args: %v, nargs: %d", cmd.Name, args, len(args))
if err := cmd.Func(args, m); err != nil {
log.Errorf("failed to execute command: %s", err)
}
return
}
log.Warnf("unknown command: %v, args: %v, nargs: %d", cmdName, args, len(args))
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("unknown command: %s", cmdName))
}
}

View File

@ -1,37 +0,0 @@
package bot
const (
defaultPrefix = "!"
)
var (
defaultReactions []string = []string{"👍", "🌶️", "🤣", "😂", "🍆", "🍑", "❤️", "💦", "😍", "💩", "🔥", "🍒", "🎉", "🥳", "🎊"}
)
type (
Config struct {
Debug bool `mapstructure:"debug"`
Handler HandlerConfig `mapstructure:"handler"`
Prefix string `mapstructure:"prefix"`
DiscordToken string `mapstructure:"discord_token"`
OpenWeatherMapToken string `mapstructure:"open_weather_map_token"`
}
HandlerConfig struct {
Reaction ReactionConfig `mapstructure:"reaction"`
}
ReactionConfig struct {
Emojis []string
Channels []string
}
)
func NewConfig() Config {
var c Config
c.Prefix = defaultPrefix
c.Handler.Reaction.Emojis = defaultReactions
return c
}

View File

@ -1,12 +0,0 @@
package bot
import (
"github.com/bwmarrin/discordgo"
)
func (b *Bot) PingCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) error {
b.Session.ChannelMessageSend(m.ChannelID, "pong")
return nil
}
}

View File

@ -1,52 +0,0 @@
package bot
import (
"math/rand"
"strings"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
func (b *Bot) ReactionHandler() func(*discordgo.Session, *discordgo.MessageCreate) {
return func(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
emojis := b.Config.Handler.Reaction.Emojis
channels := b.Config.Handler.Reaction.Channels
if len(emojis) == 0 {
log.Warning("emoji list is empty")
return
}
channel, err := s.Channel(m.ChannelID)
if err != nil {
log.Fatalf("unable to get channel name: %v", err)
}
if len(channels) > 0 && !lib.Contains(channels, channel.Name) {
return
}
for _, a := range m.Attachments {
if strings.HasPrefix(a.ContentType, "image/") {
for i := 1; i <= lib.RandInt(1, len(emojis)); i++ {
r := emojis[rand.Intn(len(emojis))]
s.MessageReactionAdd(m.ChannelID, m.ID, r)
}
}
}
for range m.Embeds {
for i := 1; i <= lib.RandInt(1, len(emojis)); i++ {
r := emojis[rand.Intn(len(emojis))]
s.MessageReactionAdd(m.ChannelID, m.ID, r)
}
}
}
}

View File

@ -1,36 +0,0 @@
package bot
import (
"fmt"
"time"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
func (b *Bot) TimeCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) 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)
b.Session.ChannelMessageSend(m.ChannelID, err.Error())
return nil
}
t = now.In(loc)
} else {
t = now
}
b.Session.ChannelMessageSend(m.ChannelID, fmt.Sprint(t))
return nil
}
}

View File

@ -1,25 +0,0 @@
package bot
import (
"fmt"
"runtime"
"github.com/bwmarrin/discordgo"
)
const (
SourceURI = "https://git.kill0.net/chill9/bb"
)
func (b *Bot) VersionCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) error {
b.Session.ChannelMessageSend(m.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,56 +0,0 @@
package bot
import (
"fmt"
"git.kill0.net/chill9/beepboop/lib/weather"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
func (b *Bot) WeatherCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) error {
var (
err error
loc string
w weather.Weather
)
if len(args) != 1 {
b.Session.ChannelMessageSend(m.ChannelID, "help: `!weather <CITY>,<STATE>,<COUNTRY>`")
return nil
}
loc = args[0]
if b.Config.OpenWeatherMapToken == "" {
log.Error("OpenWeather token is not set")
return nil
}
wc := weather.NewClient(b.Config.OpenWeatherMapToken)
log.Debugf("weather requested for '%s'", loc)
w, err = wc.Get(loc)
if err != nil {
log.Errorf("weather client error: %v", err)
return nil
}
log.Debugf("weather returned for '%s': %+v", loc, w)
b.Session.ChannelMessageSend(m.ChannelID, fmt.Sprintf(
"%s (%.1f, %.1f) — C:%.1f F:%.1f K:%.1f",
loc,
w.Coord.Lat,
w.Coord.Lon,
w.Main.Temp.Celcius(),
w.Main.Temp.Fahrenheit(),
w.Main.Temp.Kelvin(),
))
return nil
}
}

View File

@ -1,13 +1,13 @@
package main
import (
"os"
"git.kill0.net/chill9/beepboop/bot"
log "github.com/sirupsen/logrus"
)
func main() {
if err := bot.Run(); err != nil {
os.Exit(1)
log.Fatal(err)
}
}

29
command/coin.go Normal file
View File

@ -0,0 +1,29 @@
package command
import (
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
)
type Coin bool
func (c *Coin) Flip() bool {
*c = Coin(lib.Itob(lib.RandInt(0, 1)))
return bool(*c)
}
func (h *Handlers) Coin(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
var (
c Coin
msg string
)
if c.Flip() {
msg = "heads"
} else {
msg = "tails"
}
s.ChannelMessageSend(m.ChannelID, msg)
return nil
}

11
command/commands.go Normal file
View File

@ -0,0 +1,11 @@
package command
import "git.kill0.net/chill9/beepboop/config"
type Handlers struct {
config *config.Config
}
func NewHandlers(config *config.Config) *Handlers {
return &Handlers{config: config}
}

View File

@ -1,4 +1,4 @@
package bot
package command
import (
"errors"
@ -45,8 +45,7 @@ func (d *Deck) Deal(n int) ([]Card, error) {
return hand, err
}
func (b *Bot) DealCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) error {
func (h *Handlers) Deal(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
rand.Shuffle(len(deck), func(i, j int) {
deck[i], deck[j] = deck[j], deck[i]
})
@ -54,7 +53,7 @@ func (b *Bot) DealCommand() CommandFunc {
log.Debugf("%+v", deck)
if len(args) != 1 {
b.Session.ChannelMessageSend(m.ChannelID, "help: `!deal <n>`")
s.ChannelMessageSend(m.ChannelID, "help: `!deal <n>`")
return nil
}
@ -65,14 +64,13 @@ func (b *Bot) DealCommand() CommandFunc {
hand, err := deck.Deal(n)
if err != nil {
b.Session.ChannelMessageSend(m.ChannelID, fmt.Sprintf("error: %s\n", err))
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("error: %s\n", err))
return nil
}
b.Session.ChannelMessageSend(m.ChannelID, JoinCards(hand, " "))
s.ChannelMessageSend(m.ChannelID, JoinCards(hand, " "))
return nil
}
}
func JoinCards(h []Card, sep string) string {
b := make([]string, len(h))

View File

@ -1,4 +1,4 @@
package bot
package command
import (
"errors"
@ -78,8 +78,7 @@ func (r *Roll) RollDice() {
}
}
func (b *Bot) RollCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) error {
func (h *Handlers) Roll(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
var (
err error
msg, roll string
@ -90,7 +89,7 @@ func (b *Bot) RollCommand() CommandFunc {
r, err = ParseRoll(roll)
if err != nil {
b.Session.ChannelMessageSend(m.ChannelID, err.Error())
s.ChannelMessageSend(m.ChannelID, err.Error())
return nil
}
@ -99,7 +98,6 @@ func (b *Bot) RollCommand() CommandFunc {
msg = fmt.Sprintf("🎲 %s = %d", lib.JoinInt(r.Rolls, " + "), r.Sum)
b.Session.ChannelMessageSend(m.ChannelID, msg)
s.ChannelMessageSend(m.ChannelID, msg)
return nil
}
}

10
command/ping.go Normal file
View File

@ -0,0 +1,10 @@
package command
import (
"github.com/bwmarrin/discordgo"
)
func (h *Handlers) Ping(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
s.ChannelMessageSend(m.ChannelID, "pong")
return nil
}

View File

@ -1,4 +1,4 @@
package bot
package command
import (
"git.kill0.net/chill9/beepboop/lib"
@ -66,8 +66,7 @@ func (g *Gun) IsEmpty() bool {
return true
}
func (b *Bot) RouletteCommand() CommandFunc {
return func(args []string, m *discordgo.MessageCreate) error {
func (h *Handlers) Roulette(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
if gun.IsEmpty() {
gun.Load(Bullets)
log.Debugf("reloading gun: %+v\n", gun)
@ -75,10 +74,9 @@ func (b *Bot) RouletteCommand() CommandFunc {
log.Debugf("firing gun: %+v\n", gun)
if gun.Fire() {
b.Session.ChannelMessageSend(m.ChannelID, GunFireMessage)
s.ChannelMessageSend(m.ChannelID, GunFireMessage)
} else {
b.Session.ChannelMessageSend(m.ChannelID, GunClickMessage)
s.ChannelMessageSend(m.ChannelID, GunClickMessage)
}
return nil
}
}

34
command/rps.go Normal file
View File

@ -0,0 +1,34 @@
package command
import (
"strings"
"git.kill0.net/chill9/beepboop/lib/rps"
"github.com/bwmarrin/discordgo"
)
func (h *Handlers) Rps(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
if len(args) != 1 {
s.ChannelMessageSend(
m.ChannelID, "help: `!rps (rock | paper | scissors)`",
)
return nil
}
pc := strings.ToLower(args[0]) // player's choice
g := rps.NewGame(rps.RulesRps, rps.EmojiMapRps)
bc := g.Rand() // bot's choice
out, err := g.Play(bc, pc)
if _, ok := err.(rps.InvalidChoiceError); ok {
s.ChannelMessageSend(
m.ChannelID, "help: `!rps (rock | paper | scissors)`",
)
}
s.ChannelMessageSend(m.ChannelID, out)
return nil
}

34
command/rpsls.go Normal file
View File

@ -0,0 +1,34 @@
package command
import (
"strings"
"git.kill0.net/chill9/beepboop/lib/rps"
"github.com/bwmarrin/discordgo"
)
func (h *Handlers) Rpsls(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
if len(args) != 1 {
s.ChannelMessageSend(
m.ChannelID, "help: `!rps (rock | paper | scissors | lizard | spock)`",
)
return nil
}
pc := strings.ToLower(args[0]) // player's choice
g := rps.NewGame(rps.RulesRpsls, rps.EmojiMapRpsls)
bc := g.Rand() // bot's choice
out, err := g.Play(bc, pc)
if _, ok := err.(rps.InvalidChoiceError); ok {
s.ChannelMessageSend(
m.ChannelID, "help: `!rps (rock | paper | scissors | lizard | spock)`",
)
}
s.ChannelMessageSend(m.ChannelID, out)
return nil
}

34
command/time.go Normal file
View File

@ -0,0 +1,34 @@
package command
import (
"fmt"
"time"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
func (h *Handlers) Time(args []string, s *discordgo.Session, m *discordgo.MessageCreate) 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)
s.ChannelMessageSend(m.ChannelID, err.Error())
return nil
}
t = now.In(loc)
} else {
t = now
}
s.ChannelMessageSend(m.ChannelID, fmt.Sprint(t))
return nil
}

23
command/version.go Normal file
View File

@ -0,0 +1,23 @@
package command
import (
"fmt"
"runtime"
"github.com/bwmarrin/discordgo"
)
const (
SourceURI = "https://git.kill0.net/chill9/bb"
)
func (h *Handlers) Version(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf(
"go version: %s\nplatform: %s\nos: %s\nsource: %s\n",
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
SourceURI,
))
return nil
}

54
command/weather.go Normal file
View File

@ -0,0 +1,54 @@
package command
import (
"fmt"
"git.kill0.net/chill9/beepboop/lib/weather"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
func (h *Handlers) Weather(args []string, s *discordgo.Session, m *discordgo.MessageCreate) error {
var (
err error
loc string
w weather.Weather
)
if len(args) != 1 {
s.ChannelMessageSend(m.ChannelID, "help: `!weather <CITY>,<STATE>,<COUNTRY>`")
return nil
}
loc = args[0]
if h.config.OpenWeatherMapToken == "" {
log.Error("OpenWeather token is not set")
return nil
}
wc := weather.NewClient(h.config.OpenWeatherMapToken)
log.Debugf("weather requested for '%s'", loc)
w, err = wc.Get(loc)
if err != nil {
log.Errorf("weather client error: %v", err)
return nil
}
log.Debugf("weather returned for '%s': %+v", loc, w)
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf(
"%s (%.1f, %.1f) — C:%.1f F:%.1f K:%.1f",
loc,
w.Coord.Lat,
w.Coord.Lon,
w.Main.Temp.Celcius(),
w.Main.Temp.Fahrenheit(),
w.Main.Temp.Kelvin(),
))
return nil
}

58
config/config.go Normal file
View File

@ -0,0 +1,58 @@
package config
const (
defaultPrefix = "!"
)
var (
defaultReactions []string = []string{
"👍", "🌶️", "🤣", "😂", "🍆", "🍑", "❤️", "💦", "😍", "💩",
"🔥", "🍒", "🎉", "🥳", "🎊", "📉", "📈", "💀", "☠️",
}
)
type (
Config struct {
Debug bool `mapstructure:"debug"`
Handler HandlerConfig `mapstructure:"handler"`
Prefix string `mapstructure:"prefix"`
DiscordToken string `mapstructure:"discord_token"`
OpenWeatherMapToken string `mapstructure:"open_weather_map_token"`
Mongo MongoConfig `mapstructure:"mongo"`
Redis RedisConfig `mapstructure:"redis"`
Postgres PostgresConfig `mapstructure:"postgres"`
}
HandlerConfig struct {
Reaction ReactionConfig `mapstructure:"reaction"`
}
ReactionConfig struct {
Emojis []string
Channels []string
}
MongoConfig struct {
Uri string `mapstructure:"uri"`
Database string `mapstructure:"database"`
}
RedisConfig struct {
Addr string `mapstructure:"addr"`
Password string `mapstructure:"password"`
DB int `mapstructure:"database"`
}
PostgresConfig struct {
Uri string `mapstructure:"uri"`
}
)
func NewConfig() *Config {
var c *Config = &Config{}
c.Prefix = defaultPrefix
c.Handler.Reaction.Emojis = defaultReactions
return c
}

15
handler/handlers.go Normal file
View File

@ -0,0 +1,15 @@
package handler
import (
"git.kill0.net/chill9/beepboop/config"
)
type Handlers struct {
config *config.Config
}
func NewHandlers(config *config.Config) *Handlers {
return &Handlers{
config: config,
}
}

50
handler/reaction.go Normal file
View File

@ -0,0 +1,50 @@
package handler
import (
"math/rand"
"strings"
"git.kill0.net/chill9/beepboop/lib"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
func (h *Handlers) Reaction(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
emojis := h.config.Handler.Reaction.Emojis
channels := h.config.Handler.Reaction.Channels
if len(emojis) == 0 {
log.Warning("emoji list is empty")
return
}
channel, err := s.Channel(m.ChannelID)
if err != nil {
log.Fatalf("unable to get channel name: %v", err)
}
if len(channels) > 0 && !lib.Contains(channels, channel.Name) {
return
}
for _, a := range m.Attachments {
if strings.HasPrefix(a.ContentType, "image/") {
for i := 1; i <= lib.RandInt(1, len(emojis)); i++ {
r := emojis[rand.Intn(len(emojis))]
s.MessageReactionAdd(m.ChannelID, m.ID, r)
}
}
}
for range m.Embeds {
for i := 1; i <= lib.RandInt(1, len(emojis)); i++ {
r := emojis[rand.Intn(len(emojis))]
s.MessageReactionAdd(m.ChannelID, m.ID, r)
}
}
}

View File

@ -118,6 +118,10 @@ func SplitCommandAndArg(s, prefix string) (cmd string, arg string) {
func SplitCommandAndArgs(s, prefix string, n int) (cmd string, args []string) {
cmd, arg := SplitCommandAndArg(s, prefix)
if arg == "" {
return cmd, []string{}
}
if n == 0 {
return cmd, strings.Split(arg, " ")
}
@ -126,6 +130,10 @@ func SplitCommandAndArgs(s, prefix string, n int) (cmd string, args []string) {
}
func SplitArgs(s string, n int) (args []string) {
if s == "" {
return []string{}
}
if n > 0 {
args = strings.SplitN(s, " ", n)
} else {
@ -133,3 +141,21 @@ func SplitArgs(s string, n int) (args []string) {
}
return
}
func MapKeys[K comparable, V any](m map[K]V) []K {
keys := make([]K, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
func MapKey[K comparable, V comparable](m map[K]V, v V) K {
var r K
for k := range m {
if m[k] == v {
return k
}
}
return r
}

View File

@ -90,8 +90,8 @@ func TestSplitCommandAndArgs(t *testing.T) {
}{
{"!command x y", "!", 2, "command", []string{"x", "y"}},
{"!command x y z", "!", 2, "command", []string{"x", "y z"}},
{"!command", "!", 1, "command", []string{""}},
{"hey man", "!", 1, "", []string{""}},
{"!command", "!", 1, "command", []string{}},
{"hey man", "!", 1, "", []string{}},
}
for _, table := range tables {
gotCmd, gotArgs := SplitCommandAndArgs(table.s, table.prefix, table.n)
@ -99,7 +99,7 @@ func TestSplitCommandAndArgs(t *testing.T) {
t.Errorf("got: %s, want: %s", gotCmd, table.wantCmd)
}
if !reflect.DeepEqual(gotArgs, table.wantArgs) {
t.Errorf("got: %+v, want: %+v", gotArgs, table.wantArgs)
t.Errorf("got: %#v, want: %#v", gotArgs, table.wantArgs)
}
}
}
@ -115,6 +115,7 @@ func TestSplitArgs(t *testing.T) {
{"a b c", 2, []string{"a", "b c"}},
{"a b c", 3, []string{"a", "b", "c"}},
{"a b c", 4, []string{"a", "b", "c"}},
{"", 0, []string{}},
}
for _, table := range tables {
if got, want := SplitArgs(table.s, table.n), table.want; !reflect.DeepEqual(got, want) {
@ -122,3 +123,37 @@ func TestSplitArgs(t *testing.T) {
}
}
}
func TestMapKeys(t *testing.T) {
tables := []struct {
m map[string]int
want []string
}{
{map[string]int{"a": 0, "b": 1, "c": 3}, []string{"a", "b", "c"}},
}
for _, table := range tables {
if got, want := MapKeys(table.m), table.want; !reflect.DeepEqual(got, want) {
t.Errorf("got: %#v, want: %#v", got, want)
}
}
}
func TestMapKey(t *testing.T) {
tables := []struct {
m map[string]int
n int
want string
}{
{map[string]int{"a": 0, "b": 1, "c": 2}, 0, "a"},
{map[string]int{"a": 0, "b": 1, "c": 2}, 1, "b"},
{map[string]int{"a": 0, "b": 1, "c": 2}, 2, "c"},
{map[string]int{"a": 0, "b": 1, "c": 2, "d": 0}, 0, "a"},
}
for _, table := range tables {
if got, want := MapKey(table.m, table.n), table.want; got != want {
t.Errorf("got: %#v, want: %#v", got, want)
}
}
}

View File

@ -37,3 +37,21 @@ func SeedMathRand() error {
func RandInt(min int, max int) int {
return rand.Intn(max-min+1) + min
}
func MapRand[K comparable, V any](m map[K]V) V {
n := rand.Intn(len(m))
i := 0
for _, v := range m {
if i == n {
return v
}
i++
}
panic("unreachable")
}
func MapRandKey[K comparable, V any](m map[K]V) K {
keys := MapKeys(m)
n := rand.Intn(len(m))
return keys[n]
}

118
lib/rps/rps.go Normal file
View File

@ -0,0 +1,118 @@
package rps
import (
"fmt"
"strings"
"git.kill0.net/chill9/beepboop/lib"
)
type (
Game struct {
rules [][]string
emojiMap map[string]string
}
)
type InvalidChoiceError struct {
s string
}
func (e InvalidChoiceError) Error() string {
return fmt.Sprintf("%q is an invalid choice", e.s)
}
var (
RulesRps [][]string = [][]string{
{"rock", "scissors", "crushes"},
{"paper", "rock", "covers"},
{"scissors", "paper", "cuts"},
}
EmojiMapRps map[string]string = map[string]string{
"rock": "🪨️",
"paper": "📝",
"scissors": "✂️",
}
RulesRpsls [][]string = [][]string{
{"rock", "scissors", "crushes"},
{"rock", "lizard", "crushes"},
{"paper", "rock", "covers"},
{"paper", "spock", "disproves"},
{"scissors", "paper", "cuts"},
{"scissors", "lizard", "decapitates"},
{"lizard", "paper", "eats"},
{"lizard", "spock", "poisons"},
{"spock", "scissors", "smashes"},
{"spock", "rock", "vaporizes"},
}
EmojiMapRpsls map[string]string = map[string]string{
"rock": "🪨️",
"paper": "📝",
"scissors": "✂️",
"lizard": "🦎",
"spock": "🖖",
}
)
func NewGame(rules [][]string, emojiMap map[string]string) *Game {
return &Game{rules: rules, emojiMap: emojiMap}
}
func (g *Game) Rand() string {
return lib.MapRandKey(g.emojiMap)
}
func (g *Game) Play(c1, c2 string) (string, error) {
var b strings.Builder
if !g.Valid(c1) {
return "", InvalidChoiceError{s: c1}
}
if !g.Valid(c2) {
return "", InvalidChoiceError{s: c2}
}
fmt.Fprintf(&b, "%s v %s: ", g.emojiMap[c1], g.emojiMap[c2])
for _, rule := range g.rules {
verb := rule[2]
if c1 == c2 {
fmt.Fprintf(&b, "draw")
return b.String(), nil
}
if c1 == rule[0] && c2 == rule[1] {
fmt.Fprintf(&b, "%s %s %s", c1, verb, c2)
return b.String(), nil
} else if c2 == rule[0] && c1 == rule[1] {
fmt.Fprintf(&b, "%s %s %s", c2, verb, c1)
return b.String(), nil
}
}
return b.String(), nil
}
func (g *Game) Valid(c string) bool {
_, ok := g.emojiMap[c]
return ok
}
func Play(rules [][]string, c1, c2 string) string {
for _, rule := range rules {
if c1 == c2 {
return "draw"
}
if c1 == rule[0] && c2 == rule[1] {
return fmt.Sprintf("%s %s %s", c1, rule[2], c2)
} else if c2 == rule[0] && c1 == rule[1] {
return fmt.Sprintf("%s %s %s", c2, rule[2], c1)
}
}
return ""
}

View File

@ -22,6 +22,12 @@ type (
H1 float32 `json:"1h"`
H3 float32 `json:"3h"`
} `json:"rain"`
Weather []struct {
Main string `json:"main"`
Description string `json:"description"`
Icon string `json:"icon"`
} `json:"weather"`
}
WeatherError struct {