Removed some fmt.Printlns and pass *app pointer to bot for model access.
371 lines
8.9 KiB
Go
371 lines
8.9 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/signal"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"code.destrealm.net/zancarius/justusbot/internal/bible"
|
|
"code.destrealm.net/zancarius/justusbot/internal/settings"
|
|
"github.com/mymmrac/telego"
|
|
th "github.com/mymmrac/telego/telegohandler"
|
|
tu "github.com/mymmrac/telego/telegoutil"
|
|
"go.destrealm.net/logging/v3"
|
|
)
|
|
|
|
type bot struct {
|
|
app *App
|
|
settings *settings.Settings
|
|
tgbot *telego.Bot
|
|
handler *th.BotHandler
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
|
|
chats *chats
|
|
}
|
|
|
|
func NewBot(ctx context.Context, conf *settings.Settings, app *App) *bot {
|
|
b := &bot{
|
|
app: app,
|
|
settings: conf,
|
|
ctx: ctx,
|
|
}
|
|
|
|
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
|
|
b.ctx = ctx
|
|
b.cancel = cancel
|
|
|
|
b.init()
|
|
|
|
return b
|
|
}
|
|
|
|
func (b *bot) init() {
|
|
logger := logging.Logger().Get("bot")
|
|
logger.SetLevel(logging.Debug)
|
|
|
|
tgbot, err := telego.NewBot(b.settings.Service.BotToken,
|
|
telego.WithLogger(logger))
|
|
//telego.WithDefaultDebugLogger())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
b.tgbot = tgbot
|
|
|
|
switch b.settings.Service.Method {
|
|
case "polling":
|
|
err = b.SetPolling(b.ctx, b.settings)
|
|
case "webhook":
|
|
err = b.SetWebhook(b.ctx, b.settings)
|
|
}
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
b.AttachHandlers()
|
|
b.SetCommands(b.ctx)
|
|
}
|
|
|
|
func (b *bot) SendEphemeralMarkdown(ctx *th.Context, message telego.Message, markdown string) error {
|
|
_, err := ctx.Bot().SendRichMessage(ctx, &telego.SendRichMessageParams{
|
|
ChatID: tu.ID(message.Chat.ID),
|
|
EphemeralMessageParameters: &telego.EphemeralMessageParameters{
|
|
ReceiverUserID: int(message.Message().From.ID),
|
|
},
|
|
ReplyParameters: &telego.ReplyParameters{
|
|
EphemeralMessageID: message.Message().EphemeralMessageID,
|
|
},
|
|
RichMessage: telego.InputRichMessage{
|
|
Markdown: markdown,
|
|
},
|
|
})
|
|
return err
|
|
}
|
|
|
|
func (b *bot) AttachHandlers() {
|
|
fmt.Println("add handlers", b.handler)
|
|
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)
|
|
}
|
|
// 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"))
|
|
|
|
b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
|
|
err := b.SendEphemeralMarkdown(ctx, message,
|
|
`# BibleBot Command Help
|
|
|
|
**/help** this dialog.
|
|
|
|
**/add [what] [arguments]**
|
|
|
|
Adds an announcement, birthday, or verse where **[what]** is one of **announcement**, **birthday**, or **verse**. Both **announcement** and **birthday** do not accept arguments and will initialize a transactional prompt. **verse** will accept a Bible verse as its sole argument or, absent a verse, will prompt the user for the book, chapter, and verse(s). Acceptable verse formats are "book chapter:verse" where **book* may be a standardized book abbreviation or full name, and verse spans may be indicated with a hyphen ("-").
|
|
|
|
**Examples**
|
|
|
|
**/add birthday** will add a birthday after the user answers the bot's prompts.
|
|
|
|
**/add verse rom 5:12** will add Romans 5:12.
|
|
|
|
**Note:** Announcements, birthdays, or verses added to the bot may be subject to admin review.
|
|
`)
|
|
return err
|
|
}, th.CommandEqual("help"))
|
|
|
|
b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
|
|
fmt.Println("received verse command")
|
|
fmt.Println(tu.ParseCommand(message.Text))
|
|
|
|
_, _, args := tu.ParseCommand(message.Text)
|
|
|
|
// Show keyboard options or a prompt instead.
|
|
if len(args) <= 1 {
|
|
return nil
|
|
}
|
|
|
|
ref, err := bible.ParseRef(strings.Join(args, " "))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
verses, err := b.app.txns.LoadRef("bsb", ref)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
verses.SkipLineBreaks = true
|
|
verses.IncludeVerseNum = false
|
|
|
|
user := message.From.FirstName
|
|
if user == "" {
|
|
user = message.From.Username
|
|
}
|
|
|
|
b.SendMarkdownMessage(message.Chat.ID, fmt.Sprintf(
|
|
"**<u>User-submitted passage:</u>**<br>**%s**\n\n%s (*%s*)\n\n---\n\nThanks, %s!",
|
|
ref.String(), verses.String(), "BSB", user))
|
|
|
|
return nil
|
|
}, th.CommandEqual("verse"))
|
|
|
|
}
|
|
|
|
func (b *bot) SendMarkdownMessage(chatid int64, message string) error {
|
|
if len(message) == 0 {
|
|
return nil
|
|
}
|
|
_, err := b.tgbot.SendRichMessage(b.ctx,
|
|
&telego.SendRichMessageParams{
|
|
ChatID: tu.ID(chatid),
|
|
RichMessage: tu.RichMessageMarkdown(message),
|
|
})
|
|
return err
|
|
}
|
|
|
|
func (b *bot) SetCommands(ctx context.Context) (err error) {
|
|
commands, err := b.tgbot.GetMyCommands(ctx, &telego.GetMyCommandsParams{
|
|
Scope: &telego.BotCommandScopeAllGroupChats{
|
|
Type: "all_group_chats",
|
|
},
|
|
})
|
|
fmt.Println("all_group_chats:")
|
|
fmt.Println(commands)
|
|
commands, err = b.tgbot.GetMyCommands(ctx, &telego.GetMyCommandsParams{
|
|
Scope: &telego.BotCommandScopeAllChatAdministrators{
|
|
Type: "all_chat_administrators",
|
|
},
|
|
})
|
|
fmt.Println("all_chat_administrators:")
|
|
fmt.Println(commands)
|
|
if len(commands) > 0 {
|
|
if b.settings.Debug.Commands.Reset {
|
|
b.tgbot.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{
|
|
Scope: &telego.BotCommandScopeAllChatAdministrators{
|
|
Type: "all_chat_administrators",
|
|
},
|
|
})
|
|
b.tgbot.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{
|
|
Scope: &telego.BotCommandScopeAllGroupChats{
|
|
Type: "all_group_chats",
|
|
},
|
|
})
|
|
}
|
|
//return
|
|
}
|
|
if !b.settings.Debug.Commands.Register {
|
|
return
|
|
}
|
|
b.tgbot.SetMyCommands(ctx, &telego.SetMyCommandsParams{
|
|
Scope: &telego.BotCommandScopeAllChatAdministrators{
|
|
Type: "all_chat_administrators",
|
|
},
|
|
Commands: []telego.BotCommand{
|
|
{
|
|
Command: "help",
|
|
Description: "Displays bot usage and help.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "add",
|
|
Description: "Adds a verse, announcement, or birthday.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "list",
|
|
Description: "List announcements or birthdays.",
|
|
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: "stop",
|
|
Description: "Stops the bot from participating in the current channel.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "verse",
|
|
Description: "Looks up a Bible passage.",
|
|
IsEphemeral: true,
|
|
},
|
|
},
|
|
})
|
|
b.tgbot.SetMyCommands(ctx, &telego.SetMyCommandsParams{
|
|
Scope: &telego.BotCommandScopeAllGroupChats{
|
|
Type: "all_group_chats",
|
|
},
|
|
Commands: []telego.BotCommand{
|
|
/*{
|
|
Command: "help",
|
|
Description: "Displays bot usage and help.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "add",
|
|
Description: "Adds a verse, announcement, or birthday.",
|
|
IsEphemeral: true,
|
|
},
|
|
{
|
|
Command: "list",
|
|
Description: "List announcements or birthdays.",
|
|
IsEphemeral: true,
|
|
},*/
|
|
{
|
|
Command: "verse",
|
|
Description: "Looks up a Bible passage.",
|
|
IsEphemeral: true,
|
|
},
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
func (b *bot) SetPolling(ctx context.Context, conf *settings.Settings) (err error) {
|
|
info, err := b.tgbot.GetWebhookInfo(b.ctx)
|
|
if err != nil {
|
|
fmt.Println("webhook info error:", err)
|
|
return err
|
|
}
|
|
fmt.Println("webhook info:", info)
|
|
|
|
if info.URL == "" {
|
|
err = b.tgbot.DeleteWebhook(ctx,
|
|
&telego.DeleteWebhookParams{
|
|
DropPendingUpdates: false,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
updates, err := b.tgbot.UpdatesViaLongPolling(ctx, &telego.GetUpdatesParams{
|
|
Timeout: 300,
|
|
}, telego.WithLongPollingUpdateInterval(time.Second*30))
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
b.handler, err = th.NewBotHandler(b.tgbot, 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
|
|
}
|
|
|
|
info, err := b.tgbot.GetWebhookInfo(b.ctx)
|
|
if err != nil {
|
|
return
|
|
}
|
|
fmt.Println("webhook info:", info)
|
|
err = b.tgbot.SetWebhook(b.ctx, &telego.SetWebhookParams{
|
|
URL: b.settings.Service.Webhook.URI,
|
|
AllowedUpdates: []string{"message", "edited_message", "callback_query"},
|
|
SecretToken: b.tgbot.SecretToken(),
|
|
})
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
updates, err := b.tgbot.UpdatesViaWebhook(ctx,
|
|
telego.WebhookHTTPServeMux(
|
|
mux,
|
|
u.Path,
|
|
b.tgbot.SecretToken()))
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
b.handler, err = th.NewBotHandler(b.tgbot, updates)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
go func() {
|
|
_ = http.ListenAndServe(
|
|
conf.Service.Webhook.ListenAddr(),
|
|
mux)
|
|
}()
|
|
|
|
return
|
|
}
|
|
|
|
func (b *bot) Run() error {
|
|
fmt.Println("bot.Run()")
|
|
defer func() {
|
|
b.handler.Stop()
|
|
fmt.Println("handler.Stop()")
|
|
b.cancel()
|
|
}()
|
|
return b.handler.Start()
|
|
}
|