matrix-bot/words/words.go
shinya 64b6e71b0e
Some checks failed
Deploy Matrix Bot / deploy (push) Waiting to run
Docker Build / build (push) Failing after 20m2s
new init without secrets
2026-03-04 22:00:42 +01:00

74 lines
1.3 KiB
Go

package words
import (
"encoding/csv"
"fmt"
"io"
"math/rand"
"matrix-bot/krkrkr"
"os"
"slices"
"strings"
"time"
)
type Dictionary struct {
words map[int][]string // key: word length, value: slice of words of that length
rng *rand.Rand
}
func New(path string) (*Dictionary, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
reader := csv.NewReader(file)
words := make(map[int][]string)
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if len(record) > 0 {
word := strings.ToUpper(strings.TrimSpace(record[0]))
l := len(word)
if l > 0 {
words[l] = append(words[l], word)
}
}
}
return &Dictionary{
words: words,
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
}, nil
}
func (d *Dictionary) RandomWord(length int) (string, error) {
words := d.words[length]
if len(words) == 0 {
return "", fmt.Errorf("no words of length %d", length)
}
return words[d.rng.Intn(len(words))], nil
}
func (d *Dictionary) DailyWord(length int) string {
words := d.words[length]
if len(words) == 0 {
return ""
}
return words[krkrkr.Today()%len(words)]
}
func (d *Dictionary) Contains(word string) bool {
word = strings.ToUpper(strings.TrimSpace(word))
l := len(word)
return slices.Contains(d.words[l], word)
}