Return flat modifier in dice roll Use log.Print instead of log.Fatal where makes sense
105 lines
2.5 KiB
Go
105 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/bwmarrin/discordgo"
|
|
"log"
|
|
"strings"
|
|
"treerazer/dice"
|
|
)
|
|
|
|
var (
|
|
commands = []*discordgo.ApplicationCommand{
|
|
{
|
|
Name: "roll",
|
|
Description: "Roll dice",
|
|
Options: []*discordgo.ApplicationCommandOption{
|
|
{
|
|
Name: "dice",
|
|
Description: "Dice to roll",
|
|
Type: discordgo.ApplicationCommandOptionString,
|
|
Required: true,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
slashCommandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate, opts optionMap){
|
|
"roll": func(s *discordgo.Session, i *discordgo.InteractionCreate, opts optionMap) {
|
|
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
|
|
Type: discordgo.InteractionResponseChannelMessageWithSource,
|
|
Data: &discordgo.InteractionResponseData{
|
|
Content: roll(opts),
|
|
},
|
|
})
|
|
if err != nil {
|
|
log.Printf("Error responding to interaction: %s\n", err)
|
|
}
|
|
},
|
|
}
|
|
dotCommandHandlers = map[string]func([]string) string{
|
|
"roll": func(s []string) string {
|
|
if len(s) == 0 {
|
|
return "Error rolling dice: no expression provided"
|
|
}
|
|
if len(s) > 1 {
|
|
return "Error rolling dice: dice expression should have no spaces"
|
|
}
|
|
opts := optionMap{
|
|
"dice": &discordgo.ApplicationCommandInteractionDataOption{
|
|
Type: discordgo.ApplicationCommandOptionString,
|
|
Value: s[0],
|
|
},
|
|
}
|
|
return roll(opts)
|
|
},
|
|
}
|
|
)
|
|
|
|
func roll(opts optionMap) string {
|
|
var exp string
|
|
if v, ok := opts["dice"]; ok {
|
|
exp = v.StringValue()
|
|
} else {
|
|
return "Error rolling dice: no expression provided"
|
|
}
|
|
d, err := dice.CreateFromExp(exp)
|
|
if err != nil {
|
|
return "Error rolling dice: " + err.Error()
|
|
}
|
|
roll, flat, err := d.Roll()
|
|
if err != nil {
|
|
ret := fmt.Sprintf("Error rolling dice: %s", err)
|
|
fmt.Println(ret)
|
|
return ret
|
|
}
|
|
var ret strings.Builder
|
|
_, err = fmt.Fprint(&ret, "Rolled dice: `")
|
|
if err != nil {
|
|
return fmt.Sprintf("Error rolling dice: %s", err)
|
|
}
|
|
total := flat
|
|
for i, die := range roll {
|
|
_, err = fmt.Fprintf(&ret, "%v", die.Result)
|
|
if err != nil {
|
|
return fmt.Sprintf("Error rolling dice: %s", err)
|
|
}
|
|
if i < len(roll)-1 {
|
|
fmt.Fprint(&ret, ", ")
|
|
}
|
|
total += die.Result
|
|
}
|
|
_, err = fmt.Fprint(&ret, "`")
|
|
if err != nil {
|
|
return fmt.Sprintf("Error rolling dice: %s", err)
|
|
}
|
|
_, err = fmt.Fprintf(&ret, "\nTotal: %v", total)
|
|
if err != nil {
|
|
return fmt.Sprintf("Error rolling dice: %s", err)
|
|
}
|
|
if ret.Len() < 2000 {
|
|
return ret.String()
|
|
}
|
|
return fmt.Sprintf("Too many dice to display. Omitting.\nTotal: %v", total)
|
|
}
|