447 lines
11 KiB
Go
447 lines
11 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/signal"
|
|
"slices"
|
|
_ "sync"
|
|
|
|
"github.com/mymmrac/telego"
|
|
th "github.com/mymmrac/telego/telegohandler"
|
|
"github.com/robfig/cron/v3"
|
|
"github.com/urfave/cli/v3"
|
|
"go.destrealm.net/errors"
|
|
"go.destrealm.net/logging/v3"
|
|
"go.destrealm.net/vfs"
|
|
|
|
"code.destrealm.net/zancarius/justusbot/internal/commands"
|
|
"code.destrealm.net/zancarius/justusbot/internal/settings"
|
|
)
|
|
|
|
// Send any text message to the bot after the bot has been started
|
|
|
|
func main() {
|
|
var rootfs vfs.VFS
|
|
ctx := context.Background()
|
|
logger := logging.Logger()
|
|
|
|
if root, err := os.Getwd(); err != nil {
|
|
logger.Error("could not discern working directory:", err)
|
|
os.Exit(1)
|
|
} else {
|
|
rootfs = vfs.MustVFS(vfs.NewVFS(root))
|
|
}
|
|
|
|
cmdHost, err := commands.NewCommandHost(ctx, rootfs)
|
|
if err != nil {
|
|
logger.Error("unable to configure host:", errors.Unfurl(err))
|
|
os.Exit(1)
|
|
}
|
|
|
|
cmd := cli.Command{
|
|
Flags: []cli.Flag{
|
|
&cli.StringFlag{
|
|
Name: "config",
|
|
Aliases: []string{"c"},
|
|
Usage: "Configuration location. Defaults to working directory.",
|
|
Value: "settings.toml",
|
|
},
|
|
},
|
|
Commands: []*cli.Command{
|
|
{
|
|
Name: "chats",
|
|
Description: "Chats management",
|
|
Commands: []*cli.Command{
|
|
{
|
|
Name: "add",
|
|
Description: "Adds a chat to the bot. This is analogous to running /start within a chat.",
|
|
Action: cmdHost.Chats().AddChat,
|
|
Flags: []cli.Flag{
|
|
&cli.IntFlag{
|
|
Name: "id",
|
|
Aliases: []string{"i"},
|
|
Usage: "Specifies the chat id.",
|
|
},
|
|
&cli.StringFlag{
|
|
Name: "name",
|
|
Aliases: []string{"n"},
|
|
Usage: "Specifies the chat name.",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
Name: "init",
|
|
Description: "Initialize the bot, its database, and prepare for first run.",
|
|
Action: cmdHost.Initalizer().DoInstall,
|
|
},
|
|
{
|
|
Name: "metadata",
|
|
Description: "Bible metadata-related management.",
|
|
Flags: []cli.Flag{
|
|
&cli.StringFlag{
|
|
Name: "translation",
|
|
Aliases: []string{"t"},
|
|
Value: "bsb",
|
|
Usage: "Specifies the Bible translation to use for metadata extraction and inspection.",
|
|
},
|
|
},
|
|
Commands: []*cli.Command{
|
|
{
|
|
Name: "dump",
|
|
Description: "Dump Bible metadata",
|
|
Commands: []*cli.Command{
|
|
{
|
|
Name: "structure",
|
|
Description: "Dumps an entire translation's book, chapter, and verse structure.",
|
|
Action: cmdHost.Meta().DumpStructure,
|
|
Flags: []cli.Flag{
|
|
&cli.StringFlag{
|
|
Name: "format",
|
|
Aliases: []string{"f"},
|
|
Value: "json",
|
|
Usage: `Output format. One of "json" or "toml".`,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
Name: "migrate",
|
|
Description: "Migration-related commands and options.",
|
|
Commands: []*cli.Command{
|
|
{
|
|
Name: "up",
|
|
Description: `Perform upgrade.`,
|
|
},
|
|
{
|
|
Name: "down",
|
|
Description: `Perform downgrade.`,
|
|
},
|
|
},
|
|
},
|
|
{
|
|
Name: "start",
|
|
Description: "Start the bot.",
|
|
Action: cmdHost.App().Start,
|
|
},
|
|
{
|
|
Name: "verse",
|
|
Description: "Bible verse helpers and tools.",
|
|
Commands: []*cli.Command{
|
|
{
|
|
Name: "add",
|
|
Description: "Add a verse to the random rotation.",
|
|
Action: cmdHost.Verse().AddVerse,
|
|
//Future implementation.
|
|
Flags: []cli.Flag{
|
|
&cli.StringFlag{
|
|
Name: "translation",
|
|
Usage: "Specifies which translation this verse should be included from.",
|
|
Aliases: []string{"t"},
|
|
Value: "bsb",
|
|
},
|
|
&cli.StringFlag{
|
|
Name: "date",
|
|
Usage: "Specifies a date for the provided verse to be displayed. Overrides random rotation. Use with caution as this will override random verses for all connected chats.",
|
|
Aliases: []string{"d"},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
Name: "list",
|
|
Description: "List verses configured for this bot.",
|
|
Action: cmdHost.Verse().ListVerses,
|
|
Flags: []cli.Flag{
|
|
&cli.IntFlag{
|
|
Name: "chatid",
|
|
Usage: "Include verses configured for the specified chat ID",
|
|
Aliases: []string{"i"},
|
|
},
|
|
&cli.BoolFlag{
|
|
Name: "random",
|
|
Usage: "Include verse random rotation status (if available); requires --chatid",
|
|
Aliases: []string{"r"},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
Name: "random",
|
|
Description: "select a random verse from the bot's database",
|
|
Action: cmdHost.Verse().RandomVerse,
|
|
Flags: []cli.Flag{
|
|
&cli.BoolFlag{
|
|
Name: "simulate",
|
|
Usage: "Simulates a random verse selection from the bot and populates the internal verse rotation status. Requires --chatid.",
|
|
},
|
|
&cli.Int64Flag{
|
|
Name: "chatid",
|
|
Usage: "Specifies the chat ID to generate a random verse from. If --simulate is specified, this will update the verse rotation statues.",
|
|
},
|
|
},
|
|
},
|
|
{
|
|
Name: "rotation",
|
|
Description: "Random verse rotation management",
|
|
Commands: []*cli.Command{
|
|
{
|
|
Name: "delete",
|
|
Description: "Delete rotations; this will reset the specified chat's exhausted verses list",
|
|
Action: cmdHost.Verse().DeleteRotation,
|
|
Flags: []cli.Flag{
|
|
&cli.Int64Flag{
|
|
Name: "chatid",
|
|
Aliases: []string{"i"},
|
|
Usage: "Specifies the chat from which rotation records will be removed.",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
err = cmd.Run(ctx, os.Args)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
/*b, c, err := NewBot()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
_ = c
|
|
|
|
wg := &sync.WaitGroup{}
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
err := b.Start()
|
|
fmt.Println(err)
|
|
}()
|
|
wg.Wait()*/
|
|
|
|
/*fmt.Println(bible.FindAlias("mat"))
|
|
s, err := settings.LoadSettings("settings.toml")
|
|
fmt.Println(s, err)*/
|
|
}
|
|
|
|
type Bot struct {
|
|
Settings *settings.Settings
|
|
Cron *cron.Cron
|
|
Bot *telego.Bot
|
|
Handler *th.BotHandler
|
|
context context.Context
|
|
cancel context.CancelFunc
|
|
}
|
|
|
|
func NewBot() (bot *Bot, errch chan error, err error) {
|
|
bot = &Bot{}
|
|
|
|
conf, err := settings.LoadSettings("settings.toml", vfs.MustVFS(vfs.NewVFS(".")))
|
|
if err != nil {
|
|
return
|
|
}
|
|
bot.Settings = conf
|
|
|
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
|
bot.context = ctx
|
|
bot.cancel = cancel
|
|
|
|
b, err := telego.NewBot(os.Getenv("TOKEN"), telego.WithDefaultDebugLogger())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
bot.Bot = b
|
|
|
|
err = b.SetWebhook(ctx, &telego.SetWebhookParams{
|
|
URL: conf.Service.Webhook.URI,
|
|
SecretToken: b.SecretToken(),
|
|
})
|
|
if err != nil {
|
|
panic(fmt.Sprintf("failed setting up webhook: %s", err))
|
|
}
|
|
info, err := b.GetWebhookInfo(ctx)
|
|
fmt.Println(info, err)
|
|
|
|
c := cron.New()
|
|
c.AddFunc(fmt.Sprintf("TZ=%s %s",
|
|
conf.System.TimeZone,
|
|
conf.DailyScripture.Schedule), func() { bot.SendScripture() })
|
|
c.Start()
|
|
bot.Cron = c
|
|
|
|
switch conf.Service.Method {
|
|
case "polling":
|
|
err = bot.SetPolling(ctx, conf)
|
|
case "webhook":
|
|
err = bot.SetWebhook(ctx, conf)
|
|
}
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
bot.AttachHandlers()
|
|
bot.SetCommands(ctx)
|
|
|
|
return
|
|
}
|
|
|
|
func (b *Bot) AttachHandlers() {
|
|
fmt.Println("add handlers")
|
|
b.Handler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
|
|
fmt.Println("handling message")
|
|
if !slices.Contains(b.Settings.Chat.Channels, message.Chat.ID) {
|
|
fmt.Println("adding chat:", message.Chat.ID)
|
|
b.Settings.Chat.Channels = append(b.Settings.Chat.Channels, message.Chat.ID)
|
|
b.SaveConfig()
|
|
}
|
|
// Send a message with inline keyboard
|
|
/*_, _ = ctx.Bot().SendMessage(ctx, tu.Message(
|
|
tu.ID(message.Chat.ID),
|
|
fmt.Sprintf("Hello %s!", message.From.FirstName),
|
|
).WithReplyMarkup(tu.InlineKeyboard(
|
|
tu.InlineKeyboardRow(
|
|
tu.InlineKeyboardButton("Go!").WithCallbackData("go"),
|
|
)),
|
|
))*/
|
|
return nil
|
|
}, th.CommandEqual("start"))
|
|
}
|
|
|
|
func (b *Bot) SendScripture() {
|
|
/*script, err := bible.OpenStore("scripture.json")
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
v := script.GetVerse()
|
|
err = bible.SaveStore("scripture.json", script)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
for _, c := range b.Settings.Chat.Channels {
|
|
b.Bot.SendRichMessage(b.context,
|
|
&telego.SendRichMessageParams{
|
|
ChatID: tu.ID(c),
|
|
RichMessage: tu.RichMessageMarkdown(fmt.Sprintf("**<u>Daily Scripture:</u><br>%s**\n\n%s (*%s*)", v.Verse, v.Content, v.Translation)),
|
|
})
|
|
//b.Bot.SendMessage(b.context, tu.Message(tu.ID(c), fmt.Sprintf("*%s*\n\n%s (%s)", v.Verse, v.Content, v.Translation)))
|
|
}*/
|
|
}
|
|
|
|
func (b *Bot) SetCommands(ctx context.Context) (err error) {
|
|
commands, err := b.Bot.GetMyCommands(ctx, &telego.GetMyCommandsParams{})
|
|
fmt.Println(commands)
|
|
if len(commands) > 0 {
|
|
return
|
|
}
|
|
b.Bot.SetMyCommands(ctx, &telego.SetMyCommandsParams{
|
|
Commands: []telego.BotCommand{
|
|
{
|
|
Command: "help",
|
|
Description: "Displays bot usage and help.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "settings",
|
|
Description: "Bot settings.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "start",
|
|
Description: "Starts the bot and links it to the current user's channel.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "verse",
|
|
Description: "Looks up a Bible passage. Optionally accepts a translation identifier as its second argument.",
|
|
},
|
|
{
|
|
Command: "random",
|
|
Description: "Submits a random Bible passage to the current chat.",
|
|
},
|
|
{
|
|
Command: "add",
|
|
Description: "Submits a passage to the bot's daily passage rotation.",
|
|
IsEphemeral: true,
|
|
},
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
func (b *Bot) SetPolling(ctx context.Context, conf *settings.Settings) (err error) {
|
|
err = b.Bot.DeleteWebhook(ctx,
|
|
&telego.DeleteWebhookParams{
|
|
DropPendingUpdates: false,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
updates, err := b.Bot.UpdatesViaLongPolling(ctx, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
b.Handler, err = th.NewBotHandler(b.Bot, updates)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func (b *Bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err error) {
|
|
u, err := url.Parse(conf.Service.Webhook.URI)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
updates, err := b.Bot.UpdatesViaWebhook(ctx,
|
|
telego.WebhookHTTPServeMux(
|
|
mux,
|
|
u.Path,
|
|
b.Bot.SecretToken()))
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
b.Handler, err = th.NewBotHandler(b.Bot, updates)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
go func() {
|
|
_ = http.ListenAndServe(
|
|
conf.Service.Webhook.ListenAddr(),
|
|
mux)
|
|
}()
|
|
|
|
return
|
|
}
|
|
|
|
func (b *Bot) SaveConfig() {
|
|
settings.SaveSettings("settings.toml", b.Settings)
|
|
}
|
|
|
|
func (b *Bot) Start() error {
|
|
defer func() {
|
|
b.Handler.Stop()
|
|
b.cancel()
|
|
}()
|
|
return b.Handler.Start()
|
|
}
|