Compare commits
10 changed files with 98 additions and 370 deletions
14
Makefile
14
Makefile
|
|
@ -1,8 +1,3 @@
|
||||||
#version := $(shell cat BOT_VERSION)
|
|
||||||
version := 0.1.0
|
|
||||||
revision := $(shell git rev-parse HEAD | head -c 8)
|
|
||||||
revcount := $(shell git rev-list --count HEAD)
|
|
||||||
suffix := amd64
|
|
||||||
|
|
||||||
TEST=.
|
TEST=.
|
||||||
|
|
||||||
|
|
@ -13,12 +8,3 @@ test:
|
||||||
|
|
||||||
build:
|
build:
|
||||||
go build ./cmd/bot
|
go build ./cmd/bot
|
||||||
|
|
||||||
|
|
||||||
release:
|
|
||||||
go build \
|
|
||||||
-ldflags="-s -w -X main.Version=$(version)-$(revision)" \
|
|
||||||
-trimpath \
|
|
||||||
-o build/bot-linux-$(suffix)/bot \
|
|
||||||
./cmd/bot
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import (
|
||||||
"code.destrealm.net/zancarius/justusbot/internal/commands"
|
"code.destrealm.net/zancarius/justusbot/internal/commands"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Version string
|
// Send any text message to the bot after the bot has been started
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var rootfs vfs.VFS
|
var rootfs vfs.VFS
|
||||||
|
|
@ -33,12 +33,7 @@ func main() {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if Version == "" {
|
|
||||||
Version = "devbuild"
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd := cli.Command{
|
cmd := cli.Command{
|
||||||
Version: Version,
|
|
||||||
Flags: []cli.Flag{
|
Flags: []cli.Flag{
|
||||||
&cli.StringFlag{
|
&cli.StringFlag{
|
||||||
Name: "config",
|
Name: "config",
|
||||||
|
|
|
||||||
|
|
@ -161,9 +161,7 @@ func (a *App) daily() {
|
||||||
// I'm somewhat concerned that once the error handling is resolved, this
|
// I'm somewhat concerned that once the error handling is resolved, this
|
||||||
// could get triggered without some guards. Considering checkout
|
// could get triggered without some guards. Considering checkout
|
||||||
// sb.Len() or the total birthdays.
|
// sb.Len() or the total birthdays.
|
||||||
if sb.Len() > 0 {
|
a.bot.SendMarkdownMessage(chat.ID, sb.String())
|
||||||
a.bot.SendMarkdownMessage(chat.ID, sb.String())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -196,6 +194,8 @@ func (a *App) scripture() {
|
||||||
verses, err := a.txns.LoadRef(vv.Translation, ref)
|
verses, err := a.txns.LoadRef(vv.Translation, ref)
|
||||||
verses.SkipLineBreaks = true
|
verses.SkipLineBreaks = true
|
||||||
verses.IncludeVerseNum = false
|
verses.IncludeVerseNum = false
|
||||||
|
fmt.Println(verses.String())
|
||||||
|
fmt.Println("to bot:", a.bot)
|
||||||
|
|
||||||
for _, chat := range chats {
|
for _, chat := range chats {
|
||||||
a.bot.SendMarkdownMessage(chat.ID,
|
a.bot.SendMarkdownMessage(chat.ID,
|
||||||
|
|
@ -204,8 +204,6 @@ func (a *App) scripture() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) Start(ctx context.Context, cmd *cli.Command) error {
|
func (a *App) Start(ctx context.Context, cmd *cli.Command) error {
|
||||||
logger := logging.Logger()
|
|
||||||
logger.Infof("Starting version %s", cmd.Root().Version)
|
|
||||||
if err := a.loadEnv(); err != nil {
|
if err := a.loadEnv(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -214,9 +212,8 @@ func (a *App) Start(ctx context.Context, cmd *cli.Command) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("context:", ctx, a.ctx)
|
fmt.Println("context:", ctx, a.ctx)
|
||||||
a.bot = NewBot(ctx, a.settings, a)
|
a.bot = NewBot(ctx, a.settings)
|
||||||
a.bot.Run()
|
a.bot.Run()
|
||||||
fmt.Println("a.bot.Run() exited")
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,10 +8,8 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"code.destrealm.net/zancarius/justusbot/internal/bible"
|
|
||||||
"code.destrealm.net/zancarius/justusbot/internal/settings"
|
"code.destrealm.net/zancarius/justusbot/internal/settings"
|
||||||
"github.com/mymmrac/telego"
|
"github.com/mymmrac/telego"
|
||||||
th "github.com/mymmrac/telego/telegohandler"
|
th "github.com/mymmrac/telego/telegohandler"
|
||||||
|
|
@ -20,7 +18,6 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
type bot struct {
|
type bot struct {
|
||||||
app *App
|
|
||||||
settings *settings.Settings
|
settings *settings.Settings
|
||||||
tgbot *telego.Bot
|
tgbot *telego.Bot
|
||||||
handler *th.BotHandler
|
handler *th.BotHandler
|
||||||
|
|
@ -30,9 +27,8 @@ type bot struct {
|
||||||
chats *chats
|
chats *chats
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBot(ctx context.Context, conf *settings.Settings, app *App) *bot {
|
func NewBot(ctx context.Context, conf *settings.Settings) *bot {
|
||||||
b := &bot{
|
b := &bot{
|
||||||
app: app,
|
|
||||||
settings: conf,
|
settings: conf,
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
}
|
}
|
||||||
|
|
@ -73,24 +69,8 @@ func (b *bot) init() {
|
||||||
b.SetCommands(b.ctx)
|
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() {
|
func (b *bot) AttachHandlers() {
|
||||||
fmt.Println("add handlers", b.handler)
|
fmt.Println("add handlers")
|
||||||
b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
|
b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
|
||||||
fmt.Println("handling message")
|
fmt.Println("handling message")
|
||||||
if !slices.Contains(b.settings.Chat.Channels, message.Chat.ID) {
|
if !slices.Contains(b.settings.Chat.Channels, message.Chat.ID) {
|
||||||
|
|
@ -108,90 +88,62 @@ func (b *bot) AttachHandlers() {
|
||||||
))*/
|
))*/
|
||||||
return nil
|
return nil
|
||||||
}, th.CommandEqual("start"))
|
}, 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 {
|
func (b *bot) SendMarkdownMessage(chatid int64, message string) error {
|
||||||
if len(message) == 0 {
|
fmt.Println("bot:", b.tgbot)
|
||||||
return nil
|
fmt.Println("bot context:", b.ctx)
|
||||||
}
|
|
||||||
_, err := b.tgbot.SendRichMessage(b.ctx,
|
_, err := b.tgbot.SendRichMessage(b.ctx,
|
||||||
&telego.SendRichMessageParams{
|
&telego.SendRichMessageParams{
|
||||||
ChatID: tu.ID(chatid),
|
ChatID: tu.ID(chatid),
|
||||||
RichMessage: tu.RichMessageMarkdown(message),
|
RichMessage: tu.RichMessageMarkdown(message),
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
|
/*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) 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) {
|
func (b *bot) SetCommands(ctx context.Context) (err error) {
|
||||||
commands, err := b.tgbot.GetMyCommands(ctx, &telego.GetMyCommandsParams{
|
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)
|
fmt.Println(commands)
|
||||||
if len(commands) > 0 {
|
if len(commands) > 0 {
|
||||||
if b.settings.Debug.Commands.Reset {
|
if b.settings.Debug.Commands.Reset {
|
||||||
|
|
@ -200,13 +152,12 @@ func (b *bot) SetCommands(ctx context.Context) (err error) {
|
||||||
Type: "all_chat_administrators",
|
Type: "all_chat_administrators",
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
b.tgbot.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{
|
b.tgbot.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{})
|
||||||
Scope: &telego.BotCommandScopeAllGroupChats{
|
|
||||||
Type: "all_group_chats",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
//return
|
for _, command := range commands {
|
||||||
|
fmt.Println(command)
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
if !b.settings.Debug.Commands.Register {
|
if !b.settings.Debug.Commands.Register {
|
||||||
return
|
return
|
||||||
|
|
@ -223,13 +174,24 @@ func (b *bot) SetCommands(ctx context.Context) (err error) {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Command: "add",
|
Command: "add",
|
||||||
Description: "Adds a verse, announcement, or birthday.",
|
Description: "Submits a passage to the bot's daily passage rotation.",
|
||||||
IsEphemeral: true,
|
IsEphemeral: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Command: "list",
|
Command: "announce",
|
||||||
Description: "List announcements or birthdays.",
|
Description: "Adds an announcement to the bot.",
|
||||||
IsEphemeral: true,
|
},
|
||||||
|
{
|
||||||
|
Command: "announcements",
|
||||||
|
Description: "Lists the current announcements for the week.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Command: "birthday",
|
||||||
|
Description: "Add, remove, or list birthdays.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Command: "random",
|
||||||
|
Description: "Submits a random Bible passage to the current chat.",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Command: "settings",
|
Command: "settings",
|
||||||
|
|
@ -241,42 +203,43 @@ func (b *bot) SetCommands(ctx context.Context) (err error) {
|
||||||
Description: "Starts the bot and links it to the current user's channel.",
|
Description: "Starts the bot and links it to the current user's channel.",
|
||||||
IsEphemeral: true,
|
IsEphemeral: true,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
Command: "stop",
|
|
||||||
Description: "Stops the bot from participating in the current channel.",
|
|
||||||
IsEphemeral: true,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
Command: "verse",
|
Command: "verse",
|
||||||
Description: "Looks up a Bible passage.",
|
Description: "Looks up a Bible passage. Optionally accepts a translation identifier as its second argument.",
|
||||||
IsEphemeral: true,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
b.tgbot.SetMyCommands(ctx, &telego.SetMyCommandsParams{
|
b.tgbot.SetMyCommands(ctx, &telego.SetMyCommandsParams{
|
||||||
Scope: &telego.BotCommandScopeAllGroupChats{
|
|
||||||
Type: "all_group_chats",
|
|
||||||
},
|
|
||||||
Commands: []telego.BotCommand{
|
Commands: []telego.BotCommand{
|
||||||
/*{
|
{
|
||||||
Command: "help",
|
Command: "help",
|
||||||
Description: "Displays bot usage and help.",
|
Description: "Displays bot usage and help.",
|
||||||
IsEphemeral: true,
|
IsEphemeral: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Command: "add",
|
Command: "add",
|
||||||
Description: "Adds a verse, announcement, or birthday.",
|
Description: "Submits a passage to the bot's daily passage rotation.",
|
||||||
IsEphemeral: true,
|
IsEphemeral: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Command: "list",
|
Command: "announce",
|
||||||
Description: "List announcements or birthdays.",
|
Description: "Adds an announcement to the bot.",
|
||||||
IsEphemeral: true,
|
},
|
||||||
},*/
|
{
|
||||||
|
Command: "announcements",
|
||||||
|
Description: "Lists the current announcements for the week.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Command: "birthday",
|
||||||
|
Description: "Add, remove, or list birthdays.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Command: "random",
|
||||||
|
Description: "Submits a random Bible passage to the current chat.",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Command: "verse",
|
Command: "verse",
|
||||||
Description: "Looks up a Bible passage.",
|
Description: "Looks up a Bible passage. Optionally accepts a translation identifier as its second argument.",
|
||||||
IsEphemeral: true,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
@ -322,17 +285,16 @@ func (b *bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err erro
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
info, err := b.tgbot.GetWebhookInfo(b.ctx)
|
err = b.tgbot.SetWebhook(b.ctx, &telego.SetWebhookParams{
|
||||||
|
URL: b.settings.Service.Webhook.URI,
|
||||||
|
SecretToken: b.tgbot.SecretToken(),
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fmt.Println("webhook info:", info)
|
info, err := b.tgbot.GetWebhookInfo(b.ctx)
|
||||||
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 {
|
if err != nil {
|
||||||
|
fmt.Println(info, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -364,7 +326,6 @@ func (b *bot) Run() error {
|
||||||
fmt.Println("bot.Run()")
|
fmt.Println("bot.Run()")
|
||||||
defer func() {
|
defer func() {
|
||||||
b.handler.Stop()
|
b.handler.Stop()
|
||||||
fmt.Println("handler.Stop()")
|
|
||||||
b.cancel()
|
b.cancel()
|
||||||
}()
|
}()
|
||||||
return b.handler.Start()
|
return b.handler.Start()
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,6 @@ type commands struct {
|
||||||
meta *metadata
|
meta *metadata
|
||||||
verse *verse
|
verse *verse
|
||||||
settings *settings.Settings
|
settings *settings.Settings
|
||||||
logger *logging.Log
|
|
||||||
version string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCommandHost(ctx context.Context, root vfs.VFS) (*commands, error) {
|
func NewCommandHost(ctx context.Context, root vfs.VFS) (*commands, error) {
|
||||||
|
|
@ -40,7 +38,6 @@ func NewCommandHost(ctx context.Context, root vfs.VFS) (*commands, error) {
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
root: root,
|
root: root,
|
||||||
settings: conf,
|
settings: conf,
|
||||||
logger: logger,
|
|
||||||
}
|
}
|
||||||
cmd.meta = OpenMetadata(root, cmd)
|
cmd.meta = OpenMetadata(root, cmd)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,132 +0,0 @@
|
||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"database/sql"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jmoiron/sqlx"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Library struct {
|
|
||||||
Id int `db:"id"`
|
|
||||||
BookID int `db:"bookid"`
|
|
||||||
ChatID int `db:"chatid"`
|
|
||||||
Available bool `db:"available"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LibraryBook struct {
|
|
||||||
ID int `db:"id"`
|
|
||||||
ISBN string `db:"isbn"`
|
|
||||||
Title string `db:"title"`
|
|
||||||
Authors string `db:"authors"`
|
|
||||||
Meta map[string]string `db:"meta"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LibraryCheckout struct {
|
|
||||||
LibraryID int `db:"libraryid"`
|
|
||||||
UserID int `db:"userid"`
|
|
||||||
Recipient string `db:"recipient"`
|
|
||||||
CheckedOut time.Time `db:"checked_out"`
|
|
||||||
ReturnedAt *time.Time `db:"returned_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LibraryQueue struct {
|
|
||||||
BookID int `db:"bookid"`
|
|
||||||
UserID int `db:"userid"`
|
|
||||||
Requester string `db:"requester"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type OLCache struct {
|
|
||||||
ISBN string `db:"isbn"`
|
|
||||||
ResponseCode int `db:"response_code"`
|
|
||||||
Requested time.Time `db:"requested"`
|
|
||||||
JSONResponse string `db:"json_response"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LibraryModel struct {
|
|
||||||
ctx context.Context
|
|
||||||
db *sqlx.DB
|
|
||||||
tx *sqlx.Tx
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLibraryModel(ctx context.Context, db *sqlx.DB) *LibraryModel {
|
|
||||||
return &LibraryModel{ctx, db, nil}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lm *LibraryModel) AddBook(book *LibraryBook) error {
|
|
||||||
q := `insert or ignore into library_books (isbn, title, authors) values (?, ?, ?) returning id`
|
|
||||||
|
|
||||||
fn := lm.db.GetContext
|
|
||||||
if lm.tx != nil {
|
|
||||||
fn = lm.tx.GetContext
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := fn(lm.ctx, book, q, book.ISBN, book.Title, book.Authors); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lm *LibraryModel) AddToLibrary(book *LibraryBook, chatid int64) error {
|
|
||||||
tx, err := lm.db.BeginTxx(lm.ctx, &sql.TxOptions{})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
mdl := NewLibraryModel(lm.ctx, lm.db)
|
|
||||||
mdl.tx = tx
|
|
||||||
|
|
||||||
if err := lm.AddBook(book); err != nil {
|
|
||||||
if terr := tx.Rollback(); terr != nil {
|
|
||||||
return terr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
q := `insert into library (bookid, chatid) values (?, ?)`
|
|
||||||
l := &Library{}
|
|
||||||
if err := tx.GetContext(lm.ctx, l, q, book.ID, chatid); err != nil {
|
|
||||||
if terr := tx.Rollback(); terr != nil {
|
|
||||||
return terr
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if terr := tx.Commit(); terr != nil {
|
|
||||||
return terr
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lm *LibraryModel) CacheOLResponse(ol *OLCache) error {
|
|
||||||
q := `insert or replace into ol_cache (isbn, response_code, json_response) values (?, ?, ?)`
|
|
||||||
|
|
||||||
fn := lm.db.ExecContext
|
|
||||||
if lm.tx != nil {
|
|
||||||
fn = lm.tx.ExecContext
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := fn(lm.ctx, q, ol.ISBN, ol.ResponseCode, ol.JSONResponse); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lm *LibraryModel) GetOLCache(isbn string) (*LibraryBook, error) {
|
|
||||||
q := `select isbn, response_code, requested, json_response from ol_cache where isbn = ?`
|
|
||||||
|
|
||||||
fn := lm.db.GetContext
|
|
||||||
if lm.tx != nil {
|
|
||||||
fn = lm.tx.GetContext
|
|
||||||
}
|
|
||||||
|
|
||||||
b := &LibraryBook{}
|
|
||||||
if err := fn(lm.ctx, b, q, isbn); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return b, nil
|
|
||||||
}
|
|
||||||
|
|
@ -94,7 +94,8 @@ func (vm *VerseModel) verseFromRotation() (*Verse, error) {
|
||||||
|
|
||||||
err := fn(vm.ctx, verse, qrand)
|
err := fn(vm.ctx, verse, qrand)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if serr, ok := errors.AsType[sqlite3.Error](err); ok {
|
var serr sqlite3.Error
|
||||||
|
if errors.As(err, &serr) {
|
||||||
switch serr.Code {
|
switch serr.Code {
|
||||||
case sqlite3.ErrMismatch:
|
case sqlite3.ErrMismatch:
|
||||||
return nil, ErrNoRows.Do(err)
|
return nil, ErrNoRows.Do(err)
|
||||||
|
|
|
||||||
|
|
@ -100,7 +100,6 @@ insert into settings (config, value) values ('system.timezone', 'America/Denver'
|
||||||
insert into settings (config, value) values ('translations.basedir', 'data/translations');
|
insert into settings (config, value) values ('translations.basedir', 'data/translations');
|
||||||
insert into settings (config, value) values ('translations.active', 'bsb');
|
insert into settings (config, value) values ('translations.active', 'bsb');
|
||||||
insert into settings (config, value) values ('translations.default', 'bsb');
|
insert into settings (config, value) values ('translations.default', 'bsb');
|
||||||
insert into settings (config, value) values ('library.lookup.useragent', 'BibleBot/$version ($contact)');
|
|
||||||
|
|
||||||
create table users (
|
create table users (
|
||||||
id integer primary key,
|
id integer primary key,
|
||||||
|
|
|
||||||
|
|
@ -1,72 +0,0 @@
|
||||||
-- @up
|
|
||||||
|
|
||||||
create table library_books (
|
|
||||||
id integer primary key autoincrement,
|
|
||||||
isbn text default '' not null,
|
|
||||||
title text default '' not null,
|
|
||||||
authors text default '' not null,
|
|
||||||
meta jsonb default '{}' not null
|
|
||||||
);
|
|
||||||
create unique index library_books_isbn_check_idx on library_books(isbn, isbn_check);
|
|
||||||
|
|
||||||
create table library (
|
|
||||||
id integer primary key autoincrement,
|
|
||||||
bookid integer,
|
|
||||||
chatid integer,
|
|
||||||
available boolean default true not null,
|
|
||||||
|
|
||||||
foreign key (bookid) references library_books(id)
|
|
||||||
);
|
|
||||||
create unique index bookid_chatid_library_idx on library(bookid, chatid);
|
|
||||||
|
|
||||||
create table library_checkout (
|
|
||||||
libraryid integer default 0 not null,
|
|
||||||
-- Checkout user, if available.
|
|
||||||
userid integer default null,
|
|
||||||
|
|
||||||
-- Checkout recipient. This should only be populated if the user ID is not
|
|
||||||
-- present.
|
|
||||||
recipient text default '' not null,
|
|
||||||
|
|
||||||
checked_out datetime default current_timestamp not null,
|
|
||||||
returned_at datetime default null,
|
|
||||||
|
|
||||||
foreign key (userid) references users(id),
|
|
||||||
foreign key (libraryid) references library(id)
|
|
||||||
);
|
|
||||||
|
|
||||||
-- The queue table contains individuals waiting in the queue for a book that is
|
|
||||||
-- currently loaned out.
|
|
||||||
create table library_queue (
|
|
||||||
bookid integer default 0 not null,
|
|
||||||
userid integer default null,
|
|
||||||
requester text default '' not null,
|
|
||||||
|
|
||||||
foreign key (bookid) references library_books(id),
|
|
||||||
foreign key (userid) references users(id)
|
|
||||||
);
|
|
||||||
create index library_queue_bookid_idx on library_queue (bookid);
|
|
||||||
|
|
||||||
-- OpenLibrary response cache.
|
|
||||||
--
|
|
||||||
-- 4xx status codes will be rechecked no sooner than 1 month if a user attempts
|
|
||||||
-- to add a book with the missing ISBN to the library.
|
|
||||||
--
|
|
||||||
-- 5xx status codes will be rechecked no sooner than 1 week if a user attempts
|
|
||||||
-- to add a book matching an ISBN that generated the error.
|
|
||||||
--
|
|
||||||
-- 3xx redirects are not recorded. These should resolve into 200 or an error.
|
|
||||||
--
|
|
||||||
-- 200 OK status codes will not be rechecked. JSON data will be retrieved from
|
|
||||||
-- this table instead of upstream.
|
|
||||||
create table ol_cache (
|
|
||||||
isbn text default '' not null,
|
|
||||||
response_code integer default 0 not null,
|
|
||||||
requested datetime default current_timestamp not null,
|
|
||||||
|
|
||||||
-- We cache the full response for later debugging, if needed.
|
|
||||||
json_response text default '' not null
|
|
||||||
);
|
|
||||||
create unique index ol_cache_isbn_idx on ol_cache(isbn);
|
|
||||||
|
|
||||||
insert into settings (config, value) values ('library.lookup.useragent', 'BibleBot/1.0 (contact: $contact; using go/please)');
|
|
||||||
|
|
@ -15,10 +15,6 @@ active = [
|
||||||
]
|
]
|
||||||
default = "bsb"
|
default = "bsb"
|
||||||
|
|
||||||
[library]
|
|
||||||
[lookup]
|
|
||||||
useragent = "BibleBot/$version ($contact)"
|
|
||||||
|
|
||||||
[scheduler]
|
[scheduler]
|
||||||
[scheduler.announcements]
|
[scheduler.announcements]
|
||||||
weekly = "Sunday"
|
weekly = "Sunday"
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue