You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

118 lines
2.5 KiB

package main
import (
"fmt"
"log"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"github.com/bwmarrin/discordgo"
)
const TriggerWord = "!syl-"
var points = map[rune]int{
'A': 1, 'O': 1, 'I': 1, 'E': 1,
'C': 2, 'R': 2, 'S': 2, 'T': 2,
'L': 3, 'M': 3, 'N': 3, 'U': 3,
'W': 4, 'Y': 4,
'B': 5, 'D': 5, 'F': 5, 'P': 5, 'V': 5, 'K': 5,
'G': 8, 'H': 8, 'Z': 8, 'J': 8, 'X': 8,
'Q': 10,
}
func scrabbleScore(letters string) int {
letters = strings.ToUpper(letters)
totalScore := 0
for _, glyph := range letters {
letterScore, ok := points[glyph]
if ok {
totalScore += letterScore
}
}
return totalScore
}
func scrabbleToStr(letters string) string {
letters = strings.ToUpper(letters)
arr := []string{}
for _, glyph := range letters {
letterScore, ok := points[glyph]
if ok {
arr = append(arr, fmt.Sprintf("%s=%d", string(glyph), letterScore))
}
}
return strings.Join(arr, " + ")
}
func main() {
token := os.Getenv("TOKEN")
if token == "" {
panic("TOKEN env var is missing")
}
// Create a new Discordgo session
dg, err := discordgo.New(token)
checkErr(err)
dg.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore bot commands
if m.Author.Bot {
return
}
if strings.HasPrefix(m.Content, TriggerWord) {
msg := m.Content[len(TriggerWord):]
parts := strings.SplitN(msg, " ", 2)
if len(parts) < 2 {
return
}
maxsize, err := strconv.Atoi(parts[0])
if err != nil {
return
}
score := scrabbleScore(parts[1])
slot := score % maxsize
_, err = s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{
Name: "Scrabble Sylladex",
},
Title: fmt.Sprintf("Risultato: %d", slot+1),
Description: fmt.Sprintf("\"%s\" va nello slot %d (di %d)", parts[1], slot+1, maxsize),
Fields: []*discordgo.MessageEmbedField{
{
Name: "Valore parola",
Value: fmt.Sprintf("%s = %d", scrabbleToStr(parts[1]), score),
}, {
Name: "Posizionamento",
Value: fmt.Sprintf("%d mod %d = %d → %d", score, maxsize, slot, slot+1),
},
},
})
if err != nil {
log.Printf("Error: %s\n", err.Error())
}
}
})
dg.AddHandler(func(s *discordgo.Session, m *discordgo.Ready) {
log.Print("ready")
})
checkErr(dg.Open())
defer dg.Close()
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, syscall.SIGSEGV, syscall.SIGHUP)
<-sc
}
func checkErr(err error) {
if err != nil {
log.Fatalf("FATAL ERROR: %s", err.Error())
os.Exit(1)
}
}