82 lines
1.9 KiB
Go
82 lines
1.9 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 TrollCommand struct{}
|
|
|
|
func (t TrollCommand) Name() string {
|
|
return "troll"
|
|
}
|
|
|
|
func (t TrollCommand) Help() string {
|
|
return "Get a random troll message from the database. Usage: /troll"
|
|
}
|
|
|
|
func (t TrollCommand) Execute(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
|
|
// Send "typing" action
|
|
typingAction := tgbotapi.NewChatAction(update.Message.Chat.ID, tgbotapi.ChatTyping)
|
|
bot.Send(typingAction)
|
|
|
|
trollMessage, err := getRandomTrollMessage()
|
|
if err != nil {
|
|
log.Printf("Error getting troll message: %v", err)
|
|
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "❌ Error loading troll database. Please try again later.")
|
|
bot.Send(msg)
|
|
return
|
|
}
|
|
|
|
// Limit message length for Telegram (max 4096 characters)
|
|
if len(trollMessage) > 4000 {
|
|
trollMessage = trollMessage[:3997] + "..."
|
|
}
|
|
|
|
msg := tgbotapi.NewMessage(update.Message.Chat.ID, trollMessage)
|
|
bot.Send(msg)
|
|
}
|
|
|
|
func getRandomTrollMessage() (string, error) {
|
|
// Open the troll database file
|
|
file, err := os.Open("json/trolldb.json")
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to open trolldb.json: %v", err)
|
|
}
|
|
defer file.Close()
|
|
|
|
// Read the file content
|
|
data, err := io.ReadAll(file)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to read trolldb.json: %v", err)
|
|
}
|
|
|
|
// Parse JSON array
|
|
var trollMessages []string
|
|
if err := json.Unmarshal(data, &trollMessages); err != nil {
|
|
return "", fmt.Errorf("failed to parse trolldb.json: %v", err)
|
|
}
|
|
|
|
if len(trollMessages) == 0 {
|
|
return "", fmt.Errorf("troll database is empty")
|
|
}
|
|
|
|
// Seed random number generator
|
|
rand.Seed(time.Now().UnixNano())
|
|
|
|
// Pick a random message
|
|
randomIndex := rand.Intn(len(trollMessages))
|
|
return trollMessages[randomIndex], nil
|
|
}
|
|
|
|
func init() {
|
|
Register(TrollCommand{})
|
|
}
|