Files
nignoggobot/commands/fortune.go
2025-06-25 15:53:42 +02:00

77 lines
1.7 KiB
Go

package commands
import (
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"os"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type FortuneCommand struct{}
func (f FortuneCommand) Name() string {
return "fortune"
}
func (f FortuneCommand) Help() string {
return "Get your fortune. Usage: /fortune"
}
func (f FortuneCommand) Execute(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
fortune, err := getRandomFortune()
if err != nil {
log.Printf("Error getting fortune: %v", err)
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "❌ Error loading fortune database. Please try again later.")
bot.Send(msg)
return
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, fortune)
bot.Send(msg)
}
func getRandomFortune() (string, error) {
// Try current json directory first, then fallback to old_json
file, err := os.Open("json/fortune.json")
if err != nil {
// Try old_json directory
file, err = os.Open("old_json/fortune.json")
if err != nil {
return "", fmt.Errorf("failed to open fortune.json: %v", err)
}
}
defer file.Close()
// Read the file content
data, err := io.ReadAll(file)
if err != nil {
return "", fmt.Errorf("failed to read fortune.json: %v", err)
}
// Parse JSON array
var fortunes []string
if err := json.Unmarshal(data, &fortunes); err != nil {
return "", fmt.Errorf("failed to parse fortune.json: %v", err)
}
if len(fortunes) == 0 {
return "", fmt.Errorf("fortune database is empty")
}
// Seed random number generator
rand.Seed(time.Now().UnixNano())
// Pick a random fortune
randomIndex := rand.Intn(len(fortunes))
return fortunes[randomIndex], nil
}
func init() {
Register(FortuneCommand{})
}