From 886cbd7b326837e31c709846d54e35f2ac64ae2a Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Fri, 30 Oct 2026 10:45:22 -0600 Subject: [PATCH 01/26] Attempt to fix parser issues with Pss 51. Changes are being committed on this branch partially because I need to implement announcements. --- internal/bible/types.go | 10 +++++++++- internal/bible/types_test.go | 30 ++++++++++++++++++++++++------ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/internal/bible/types.go b/internal/bible/types.go index 0faa821..33b3768 100644 --- a/internal/bible/types.go +++ b/internal/bible/types.go @@ -518,10 +518,18 @@ func (v *VerseSet) String() string { sb.WriteByte('\n') sb.WriteString(strings.Repeat(" ", 4*verse.PoemOffset)) } + + sb.WriteString(verse.Text) if lastOffset != verse.PoemOffset { + if lastOffset > 0 && verse.PoemOffset == 0 { + if v.SkipLineBreaks { + sb.WriteByte(' ') + } else { + sb.WriteByte('\n') + } + } lastOffset = verse.PoemOffset } - sb.WriteString(verse.Text) if i == 0 && len(v.Verses) > 1 { sb.WriteByte(' ') continue diff --git a/internal/bible/types_test.go b/internal/bible/types_test.go index a3a8450..cb3401e 100644 --- a/internal/bible/types_test.go +++ b/internal/bible/types_test.go @@ -13,12 +13,13 @@ import ( ) const ( - Gen1_1_2 string = `In the beginning God created the heavens and the earth. Now the earth was formless and void, and darkness was over the surface of the deep. And the Spirit of God was hovering over the surface of the waters.` - Jude5 string = `Although you are fully aware of this, I want to remind you that after Jesus had delivered His people out of the land of Egypt, He destroyed those who did not believe.` - Jude6 string = `And the angels who did not stay within their own domain but abandoned their proper dwelling—these He has kept in eternal chains under darkness, bound for judgment on that great day.` - Obadiah5 string = `“If thieves came to you, if robbers by night—oh, how you will be ruined—would they not steal only what they wanted? If grape gatherers came to you, would they not leave some gleanings?` - Psa32_4 string = `For day and night Your hand was heavy upon me; my strength was drained as in the summer heat. Selah` - John1_4_6 string = `In Him was life, and that life was the light of men. The Light shines in the darkness, and the darkness has not overcome it. There came a man who was sent from God. His name was John.` + Gen1_1_2 string = `In the beginning God created the heavens and the earth. Now the earth was formless and void, and darkness was over the surface of the deep. And the Spirit of God was hovering over the surface of the waters.` + Jude5 string = `Although you are fully aware of this, I want to remind you that after Jesus had delivered His people out of the land of Egypt, He destroyed those who did not believe.` + Jude6 string = `And the angels who did not stay within their own domain but abandoned their proper dwelling—these He has kept in eternal chains under darkness, bound for judgment on that great day.` + Obadiah5 string = `“If thieves came to you, if robbers by night—oh, how you will be ruined—would they not steal only what they wanted? If grape gatherers came to you, would they not leave some gleanings?` + Psa32_4 string = `For day and night Your hand was heavy upon me; my strength was drained as in the summer heat. Selah` + Psa51_10_12 string = `Create in me a clean heart, O God, and renew a right spirit within me. Cast me not away from Your presence; take not your Holy Spirit from me. Restore to me the joy of Your salvation, and sustain me with a willing spirit.` + John1_4_6 string = `In Him was life, and that life was the light of men. The Light shines in the darkness, and the darkness has not overcome it. There came a man who was sent from God. His name was John.` ) func loadScripture(s string) (*bible.Chapter, error) { @@ -124,6 +125,23 @@ func Test_ChapterJSON(t *testing.T) { t.Error(" should be ->", John1_4_6) } + testJSON = &bytes.Buffer{} + testJSON.WriteString(`{"numberOfVerses": 19, "chapter": {"number": 51, "content": [{"type": "verse", "number": 10, "content": [{"text": "Create in me a clean heart, O God,", "poem": 1}, {"text": "and renew a right spirit within me.", "poem": 2}]}, {"type": "verse", "number": 11, "content": [{"text": "Cast me not away from Your presence;", "poem": 1}, {"text": "take not Your Holy Spirit from me.", "poem": 2}]}, {"type": "verse", "number": 12, "content": [{"text": "Restore to me the joy of Your salvation,", "poem": 1}, {"text": "and sustain me with a willing spirit.", "poem": 2}]}]}}`) + + c = &bible.Chapter{} + if err := json.Unmarshal(testJSON.Bytes(), c); err != nil { + t.Fatal(err) + } + + vv = c.FilterVerses(10, 12) + vv.SkipLineBreaks = true + if vv.String() != Psa51_10_12 { + t.Error("Psalm 51:10-12 did not match as expected:") + t.Error(vv.String()) + t.Error("Should be ->") + t.Error(Psa51_10_12) + } + } func Test_VerseFilter(t *testing.T) { From 4cf1f2836e3d0bbe3111bde48dccde4ef9841cc9 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Fri, 30 Oct 2026 15:38:24 -0600 Subject: [PATCH 02/26] Added birthday cakes. --- internal/app/app.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index d7f4323..c44a4d3 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -141,11 +141,11 @@ func (a *App) daily() { } bdays, err := a.db.Birthdays().BirthdaysToday(chat.ID) if err == nil && len(bdays) > 0 { - sb.WriteString("**Today's Birthday") + sb.WriteString("**🎂 Today's Birthday") if len(bdays) > 1 { sb.WriteString("s") } - sb.WriteString(":**\n\n") + sb.WriteString(" 🎂**\n\n") for _, bday := range bdays { sb.WriteString(" * ") sb.WriteString(bday.Name) From 71a487feba61bbc302809fc05a94315bf74acfcd Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Sat, 31 Oct 2026 10:10:54 -0600 Subject: [PATCH 03/26] Column "translations" is no longer part of verses table. --- internal/commands/verse.go | 4 ++++ internal/models/verses.go | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/internal/commands/verse.go b/internal/commands/verse.go index b3873c2..117eb14 100644 --- a/internal/commands/verse.go +++ b/internal/commands/verse.go @@ -41,6 +41,10 @@ func (m *verse) AddVerse(ctx context.Context, cmd *cli.Command) error { logger := logging.Get("commands") logger.SetFormat("{{message}}") logger.SetLevel(logging.Info) + + // TODO: If a translation is specified other than the default it should be + // added to the translations table for the given verse once that verse is + // added. tn := strings.ToLower(cmd.String("translation")) tnfs := m.fs.Clone() diff --git a/internal/models/verses.go b/internal/models/verses.go index f1d52da..ef9a962 100644 --- a/internal/models/verses.go +++ b/internal/models/verses.go @@ -44,9 +44,9 @@ func NewVerseModel(ctx context.Context, db *sqlx.DB) *VerseModel { func (vm *VerseModel) AddVerse(verse *Verse) error { err := vm.db.GetContext(vm.ctx, verse, - `insert into verses (translation, book, chapter, verse_start, verse_stop) - values (?, ?, ?, ?, ?) returning id, added`, - verse.Translation, verse.Book, verse.Chapter, verse.VerseStart, verse.VerseStop) + `insert into verses (book, chapter, verse_start, verse_stop) + values (?, ?, ?, ?) returning id, added`, + verse.Book, verse.Chapter, verse.VerseStart, verse.VerseStop) if err != nil { var serr sqlite3.Error if errors.As(err, &serr) { From a8d812495a9d62b29e4c446ce9b422317e547896 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Sun, 1 Nov 2026 20:35:45 -0700 Subject: [PATCH 04/26] Bumped birthday announcements to 2 weeks. --- internal/app/app.go | 2 +- internal/commands/birthdays.go | 6 ++---- internal/models/birthdays.go | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index c44a4d3..1a0ead0 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -105,7 +105,7 @@ func (a *App) daily() { if time.Now().Format("Monday") == a.settings.Scheduler.Announcements.Weekly { bdays, err := a.db.Birthdays().BirthdaysThisWeek(chat.ID) if err == nil && len(bdays) > 0 { - sb.WriteString("**Birthdays this week (Sunday-to-Sunday):**\n\n") + sb.WriteString("**Upcoming Birthdays (next 2 weeks):**\n\n") for _, bday := range bdays { d, derr := time.Parse("2006-01-02", bday.Birthdate) if derr == nil { diff --git a/internal/commands/birthdays.go b/internal/commands/birthdays.go index e62f378..8a7f99f 100644 --- a/internal/commands/birthdays.go +++ b/internal/commands/birthdays.go @@ -110,14 +110,12 @@ func (b *birthday) ListWeeklyBirthdays(ctx context.Context, cmd *cli.Command) er } return err } + logger.Info("Upcoming Birthdays (next 2 weeks):") + logger.Info("=======================================") if len(bdays) == 0 { - logger.Info("Birthdays this week (Sunday to Sunday):") - logger.Info("=======================================") logger.Info(" (none)") return nil } - logger.Info("Birthdays this week (Sunday to Sunday):") - logger.Info("=======================================") for _, bday := range bdays { d, err := time.Parse("2006-01-02", bday.Birthdate) if err != nil { diff --git a/internal/models/birthdays.go b/internal/models/birthdays.go index b1b77a2..26277c2 100644 --- a/internal/models/birthdays.go +++ b/internal/models/birthdays.go @@ -66,7 +66,7 @@ func (bm *BirthdayModel) BirthdaysThisWeek(chatid int64) ([]*Birthday, error) { chatid = ? and birthdate != date('now', 'localtime') and (birthdate >= date('now', 'localtime', 'weekday 0') and - birthdate <= date('now', 'localtime', 'weekday 0', '+7 days')) order by birthdate asc;` + birthdate <= date('now', 'localtime', 'weekday 0', '+14 days')) order by birthdate asc;` err := bm.db.SelectContext(bm.ctx, &bdays, q, chatid) if err != nil { var serr sqlite3.Error From ad4c747aea72fb19e7edc215514999cc404bf917 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Mon, 2 Nov 2026 23:03:41 -0700 Subject: [PATCH 05/26] Adding library table. --- migrations/sqlite/0004_library.sql | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 migrations/sqlite/0004_library.sql diff --git a/migrations/sqlite/0004_library.sql b/migrations/sqlite/0004_library.sql new file mode 100644 index 0000000..154b488 --- /dev/null +++ b/migrations/sqlite/0004_library.sql @@ -0,0 +1,10 @@ +create table library_books ( + id integer primary key autoincrement, + isbn integer default 0 not null, + -- ISBN-10 check digit. If it is the maximum allowable value in the base-11 format (i.e. the ISBN-10 ends with "X") this will be "1". + isbn_check integer default 0 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); \ No newline at end of file From 6c7cf689aa3e988553e59a5814d8db3d0e0797bf Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Tue, 3 Nov 2026 18:09:50 -0700 Subject: [PATCH 06/26] Added logger and version (printed during Start()). --- internal/app/app.go | 2 ++ internal/commands/common.go | 3 +++ 2 files changed, 5 insertions(+) diff --git a/internal/app/app.go b/internal/app/app.go index 1a0ead0..b29eea2 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -204,6 +204,8 @@ func (a *App) scripture() { } 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 { return err } diff --git a/internal/commands/common.go b/internal/commands/common.go index f8db6cb..fa79cb8 100644 --- a/internal/commands/common.go +++ b/internal/commands/common.go @@ -18,6 +18,8 @@ type commands struct { meta *metadata verse *verse settings *settings.Settings + logger *logging.Log + version string } func NewCommandHost(ctx context.Context, root vfs.VFS) (*commands, error) { @@ -38,6 +40,7 @@ func NewCommandHost(ctx context.Context, root vfs.VFS) (*commands, error) { ctx: ctx, root: root, settings: conf, + logger: logger, } cmd.meta = OpenMetadata(root, cmd) From 79469477943f0a91f07afb4fc53afe257c1f9ca0 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Tue, 3 Nov 2026 20:49:00 -0700 Subject: [PATCH 07/26] Added version injection and `release` recipe. --- Makefile | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Makefile b/Makefile index 5b670f7..51a9b10 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,8 @@ +#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=. @@ -8,3 +13,12 @@ test: build: go build ./cmd/bot + + +release: + go build \ + -ldflags="-s -w -X main.Version=$(version)-$(revision)" \ + -trimpath \ + -o build/bot-linux-$(suffix)/bot \ + ./cmd/bot + From c39dc95387232ad7d023be7b4dd13c0572a29bf3 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Tue, 3 Nov 2026 20:49:26 -0700 Subject: [PATCH 08/26] Added version. --- cmd/bot/main.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cmd/bot/main.go b/cmd/bot/main.go index 2414728..42adf85 100644 --- a/cmd/bot/main.go +++ b/cmd/bot/main.go @@ -13,7 +13,7 @@ import ( "code.destrealm.net/zancarius/justusbot/internal/commands" ) -// Send any text message to the bot after the bot has been started +var Version string func main() { var rootfs vfs.VFS @@ -33,7 +33,12 @@ func main() { os.Exit(1) } + if Version == "" { + Version = "devbuild" + } + cmd := cli.Command{ + Version: Version, Flags: []cli.Flag{ &cli.StringFlag{ Name: "config", From 477419ef63948eded6ceb6ea560ec862e61fd876 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Tue, 3 Nov 2026 22:41:44 -0700 Subject: [PATCH 09/26] Preliminary library-related tables. --- migrations/sqlite/0004_library.sql | 32 +++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/migrations/sqlite/0004_library.sql b/migrations/sqlite/0004_library.sql index 154b488..d1562ac 100644 --- a/migrations/sqlite/0004_library.sql +++ b/migrations/sqlite/0004_library.sql @@ -1,3 +1,5 @@ +-- @up + create table library_books ( id integer primary key autoincrement, isbn integer default 0 not null, @@ -7,4 +9,32 @@ create table library_books ( authors text default '' not null, meta jsonb default '{}' not null ); -create unique index library_books_isbn_check_idx on library_books(isbn, isbn_check); \ No newline at end of file +create unique index library_books_isbn_check_idx on library_books(isbn, isbn_check); + +create table library_checkout ( + bookid 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 (bookid) references library_books(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) + +); \ No newline at end of file From 12e0ba00106b359cf7649ff374daafdb6b5dc6bf Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Wed, 4 Nov 2026 13:07:48 -0700 Subject: [PATCH 10/26] Add index. --- migrations/sqlite/0004_library.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/migrations/sqlite/0004_library.sql b/migrations/sqlite/0004_library.sql index d1562ac..fd4c2c6 100644 --- a/migrations/sqlite/0004_library.sql +++ b/migrations/sqlite/0004_library.sql @@ -37,4 +37,5 @@ create table library_queue( foreign key (bookid) references library_books(id), foreign key (userid) references users(id) -); \ No newline at end of file +); +create index library_queue_bookid_idx on library_queue (bookid); \ No newline at end of file From fd608a857cc46e835abad61787a3fb4fea63191b Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Thu, 5 Nov 2026 19:50:12 -0700 Subject: [PATCH 11/26] Committing current WIP with command set for administrators. For whatever reason, it wasn't displaying or refreshing in Telegram for Desktop. --- internal/app/bot.go | 55 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/internal/app/bot.go b/internal/app/bot.go index 54f0829..cab7707 100644 --- a/internal/app/bot.go +++ b/internal/app/bot.go @@ -70,7 +70,7 @@ func (b *bot) init() { } func (b *bot) AttachHandlers() { - fmt.Println("add handlers") + 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) { @@ -88,6 +88,21 @@ func (b *bot) AttachHandlers() { ))*/ return nil }, th.CommandEqual("start")) + + b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error { + fmt.Println("received help command:", message.Text) + // 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("help")) + } func (b *bot) SendMarkdownMessage(chatid int64, message string) error { @@ -143,7 +158,19 @@ func (b *bot) SendScripture() { } 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) if len(commands) > 0 { if b.settings.Debug.Commands.Reset { @@ -152,12 +179,13 @@ func (b *bot) SetCommands(ctx context.Context) (err error) { Type: "all_chat_administrators", }, }) - b.tgbot.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{}) + b.tgbot.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{ + Scope: &telego.BotCommandScopeAllGroupChats{ + Type: "all_group_chats", + }, + }) } - for _, command := range commands { - fmt.Println(command) - } - return + //return } if !b.settings.Debug.Commands.Register { return @@ -210,6 +238,9 @@ func (b *bot) SetCommands(ctx context.Context) (err error) { }, }) b.tgbot.SetMyCommands(ctx, &telego.SetMyCommandsParams{ + Scope: &telego.BotCommandScopeAllGroupChats{ + Type: "all_group_chats", + }, Commands: []telego.BotCommand{ { Command: "help", @@ -285,6 +316,11 @@ func (b *bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err erro 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, SecretToken: b.tgbot.SecretToken(), @@ -292,11 +328,6 @@ func (b *bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err erro if err != nil { return } - info, err := b.tgbot.GetWebhookInfo(b.ctx) - if err != nil { - fmt.Println(info, err) - return - } mux := http.NewServeMux() updates, err := b.tgbot.UpdatesViaWebhook(ctx, From d06ecc76e35c95aad1cc0f7cab950ccff82a5ac8 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Mon, 9 Nov 2026 14:12:06 -0700 Subject: [PATCH 12/26] Added guard. This should be refactored to handle generalized announcements or have some API for collecting all scheduled messages. --- internal/app/app.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/app/app.go b/internal/app/app.go index b29eea2..0e2c9b8 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -161,7 +161,9 @@ func (a *App) daily() { // I'm somewhat concerned that once the error handling is resolved, this // could get triggered without some guards. Considering checkout // sb.Len() or the total birthdays. - a.bot.SendMarkdownMessage(chat.ID, sb.String()) + if sb.Len() > 0 { + a.bot.SendMarkdownMessage(chat.ID, sb.String()) + } } } From 5a401687698fe12c9b2b081d9d0dd5a936187364 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Mon, 9 Nov 2026 14:26:18 -0700 Subject: [PATCH 13/26] Added guard in bot.SendMarkdownMessage as well. --- internal/app/bot.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/app/bot.go b/internal/app/bot.go index cab7707..8eabfeb 100644 --- a/internal/app/bot.go +++ b/internal/app/bot.go @@ -106,8 +106,9 @@ func (b *bot) AttachHandlers() { } func (b *bot) SendMarkdownMessage(chatid int64, message string) error { - fmt.Println("bot:", b.tgbot) - fmt.Println("bot context:", b.ctx) + if len(message) == 0 { + return nil + } _, err := b.tgbot.SendRichMessage(b.ctx, &telego.SendRichMessageParams{ ChatID: tu.ID(chatid), From 3f91c9f3bfeb0e6add0c097c73732af57051a112 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Mon, 9 Nov 2026 14:36:13 -0700 Subject: [PATCH 14/26] Cleanup. --- internal/app/bot.go | 41 ----------------------------------------- 1 file changed, 41 deletions(-) diff --git a/internal/app/bot.go b/internal/app/bot.go index 8eabfeb..3754f73 100644 --- a/internal/app/bot.go +++ b/internal/app/bot.go @@ -115,47 +115,6 @@ func (b *bot) SendMarkdownMessage(chatid int64, message string) error { RichMessage: tu.RichMessageMarkdown(message), }) 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("**Daily Scripture:
%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("**Daily Scripture:
%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) { From 43d3cdc508ab8dc980ada015d54bc9793c6797bf Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Mon, 9 Nov 2026 15:27:25 -0700 Subject: [PATCH 15/26] Tracking down mysterious refusal to handle commands. --- internal/app/app.go | 1 + internal/app/bot.go | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index 0e2c9b8..558714f 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -218,6 +218,7 @@ func (a *App) Start(ctx context.Context, cmd *cli.Command) error { fmt.Println("context:", ctx, a.ctx) a.bot = NewBot(ctx, a.settings) a.bot.Run() + fmt.Println("a.bot.Run() exited") return nil } diff --git a/internal/app/bot.go b/internal/app/bot.go index 3754f73..777f47d 100644 --- a/internal/app/bot.go +++ b/internal/app/bot.go @@ -282,8 +282,9 @@ func (b *bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err erro } fmt.Println("webhook info:", info) err = b.tgbot.SetWebhook(b.ctx, &telego.SetWebhookParams{ - URL: b.settings.Service.Webhook.URI, - SecretToken: b.tgbot.SecretToken(), + URL: b.settings.Service.Webhook.URI, + AllowedUpdates: []string{"message", "edited_message", "callback_query"}, + SecretToken: b.tgbot.SecretToken(), }) if err != nil { return @@ -304,6 +305,11 @@ func (b *bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err erro return } + b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error { + fmt.Println("received raw message:", message.Text) + return nil + }) + go func() { _ = http.ListenAndServe( conf.Service.Webhook.ListenAddr(), @@ -317,6 +323,7 @@ func (b *bot) Run() error { fmt.Println("bot.Run()") defer func() { b.handler.Stop() + fmt.Println("handler.Stop()") b.cancel() }() return b.handler.Start() From a0c3103d279147f0a18db47d436530fc1dda4c7c Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Mon, 9 Nov 2026 23:08:57 -0700 Subject: [PATCH 16/26] Remove catch-all handler. The webhook issue was due to an incorrectly configured endpoint for the Cloudflare tunnel and not *actually* the bot code. --- internal/app/bot.go | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/internal/app/bot.go b/internal/app/bot.go index 777f47d..0cd447a 100644 --- a/internal/app/bot.go +++ b/internal/app/bot.go @@ -100,7 +100,10 @@ func (b *bot) AttachHandlers() { tu.InlineKeyboardButton("Go!").WithCallbackData("go"), )), ))*/ - return nil + _, err := ctx.Bot().SendMessage(ctx, tu.Message( + tu.ID(message.Chat.ID), + "This is a help message")) + return err }, th.CommandEqual("help")) } @@ -305,11 +308,6 @@ func (b *bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err erro return } - b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error { - fmt.Println("received raw message:", message.Text) - return nil - }) - go func() { _ = http.ListenAndServe( conf.Service.Webhook.ListenAddr(), From 0b163faf325882618398e24040baec414d01fe59 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Tue, 10 Nov 2026 21:33:28 -0700 Subject: [PATCH 17/26] Discovered ephemeral replies are, in fact, possible. --- internal/app/bot.go | 106 ++++++++++++++++++++++++-------------------- 1 file changed, 59 insertions(+), 47 deletions(-) diff --git a/internal/app/bot.go b/internal/app/bot.go index 0cd447a..a9cc1c0 100644 --- a/internal/app/bot.go +++ b/internal/app/bot.go @@ -69,6 +69,22 @@ func (b *bot) init() { 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 { @@ -90,22 +106,33 @@ func (b *bot) AttachHandlers() { }, th.CommandEqual("start")) b.handler.HandleMessage(func(ctx *th.Context, message telego.Message) error { - fmt.Println("received help command:", message.Text) - // 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"), - )), - ))*/ - _, err := ctx.Bot().SendMessage(ctx, tu.Message( - tu.ID(message.Chat.ID), - "This is a help message")) + 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)) + + return nil + }, th.CommandEqual("verse")) + } func (b *bot) SendMarkdownMessage(chatid int64, message string) error { @@ -165,24 +192,13 @@ func (b *bot) SetCommands(ctx context.Context) (err error) { }, { Command: "add", - Description: "Submits a passage to the bot's daily passage rotation.", + Description: "Adds a verse, announcement, or birthday.", IsEphemeral: true, }, { - Command: "announce", - Description: "Adds an announcement to the bot.", - }, - { - 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: "list", + Description: "List announcements or birthdays.", + IsEphemeral: true, }, { Command: "settings", @@ -194,9 +210,15 @@ func (b *bot) SetCommands(ctx context.Context) (err error) { 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. Optionally accepts a translation identifier as its second argument.", + Description: "Looks up a Bible passage.", + IsEphemeral: true, }, }, }) @@ -205,35 +227,25 @@ func (b *bot) SetCommands(ctx context.Context) (err error) { Type: "all_group_chats", }, Commands: []telego.BotCommand{ - { + /*{ Command: "help", Description: "Displays bot usage and help.", IsEphemeral: true, }, { Command: "add", - Description: "Submits a passage to the bot's daily passage rotation.", + Description: "Adds a verse, announcement, or birthday.", IsEphemeral: true, }, { - Command: "announce", - Description: "Adds an announcement to the bot.", - }, - { - 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: "list", + Description: "List announcements or birthdays.", + IsEphemeral: true, + },*/ { Command: "verse", - Description: "Looks up a Bible passage. Optionally accepts a translation identifier as its second argument.", + Description: "Looks up a Bible passage.", + IsEphemeral: true, }, }, }) From 8f64441079e7482994febb416c1fd6f60763be77 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Tue, 10 Nov 2026 21:50:37 -0700 Subject: [PATCH 18/26] Partial /verse implementation, fixes. Removed some fmt.Printlns and pass *app pointer to bot for model access. --- internal/app/app.go | 4 +--- internal/app/bot.go | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index 558714f..24c006c 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -196,8 +196,6 @@ func (a *App) scripture() { verses, err := a.txns.LoadRef(vv.Translation, ref) verses.SkipLineBreaks = true verses.IncludeVerseNum = false - fmt.Println(verses.String()) - fmt.Println("to bot:", a.bot) for _, chat := range chats { a.bot.SendMarkdownMessage(chat.ID, @@ -216,7 +214,7 @@ func (a *App) Start(ctx context.Context, cmd *cli.Command) error { } fmt.Println("context:", ctx, a.ctx) - a.bot = NewBot(ctx, a.settings) + a.bot = NewBot(ctx, a.settings, a) a.bot.Run() fmt.Println("a.bot.Run() exited") diff --git a/internal/app/bot.go b/internal/app/bot.go index a9cc1c0..3c86601 100644 --- a/internal/app/bot.go +++ b/internal/app/bot.go @@ -8,8 +8,10 @@ import ( "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" @@ -18,6 +20,7 @@ import ( ) type bot struct { + app *App settings *settings.Settings tgbot *telego.Bot handler *th.BotHandler @@ -27,8 +30,9 @@ type bot struct { chats *chats } -func NewBot(ctx context.Context, conf *settings.Settings) *bot { +func NewBot(ctx context.Context, conf *settings.Settings, app *App) *bot { b := &bot{ + app: app, settings: conf, ctx: ctx, } @@ -130,6 +134,33 @@ Adds an announcement, birthday, or verse where **[what]** is one of **announceme 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( + "**User-submitted passage:**
**%s**\n\n%s (*%s*)\n\n---\n\nThanks, %s!", + ref.String(), verses.String(), "BSB", user)) + return nil }, th.CommandEqual("verse")) From e285521c88d31871fa103b38ebc44d47e2bf401d Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Wed, 11 Nov 2026 15:30:32 -0700 Subject: [PATCH 19/26] Added user-agent. --- settings.sample.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/settings.sample.toml b/settings.sample.toml index 047c481..31b73b7 100644 --- a/settings.sample.toml +++ b/settings.sample.toml @@ -15,6 +15,10 @@ active = [ ] default = "bsb" +[library] + [lookup] + useragent = "BibleBot/$version ($contact)" + [scheduler] [scheduler.announcements] weekly = "Sunday" From 826269619f220d096074e131c951bc44136d39f6 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Wed, 11 Nov 2026 15:30:54 -0700 Subject: [PATCH 20/26] Added user-agent config. This is not presently at parity with what will actually be reported to IA. --- migrations/base/sqlite/base_initial-layout.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/migrations/base/sqlite/base_initial-layout.sql b/migrations/base/sqlite/base_initial-layout.sql index e7f29a2..fc18262 100644 --- a/migrations/base/sqlite/base_initial-layout.sql +++ b/migrations/base/sqlite/base_initial-layout.sql @@ -100,6 +100,7 @@ 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.active', '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 ( id integer primary key, From af20b3ac2571508527016437a847116c27cabe2f Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Wed, 11 Nov 2026 15:31:20 -0700 Subject: [PATCH 21/26] User library-supporting tables. --- migrations/sqlite/0004_library.sql | 44 ++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/migrations/sqlite/0004_library.sql b/migrations/sqlite/0004_library.sql index fd4c2c6..8400913 100644 --- a/migrations/sqlite/0004_library.sql +++ b/migrations/sqlite/0004_library.sql @@ -1,6 +1,6 @@ -- @up -create table library_books ( +create table books ( id integer primary key autoincrement, isbn integer default 0 not null, -- ISBN-10 check digit. If it is the maximum allowable value in the base-11 format (i.e. the ISBN-10 ends with "X") this will be "1". @@ -11,8 +11,18 @@ create table library_books ( ); 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 books(id) +) +create unique index bookid_chatid_library_idx on library(bookid, chatid); + create table library_checkout ( - bookid integer default 0 not null, + libraryid integer default 0 not null, -- Checkout user, if available. userid integer default null, @@ -24,12 +34,12 @@ create table library_checkout ( returned_at datetime default null, foreign key (userid) references users(id), - foreign key (bookid) references library_books(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( +create table library_queue ( bookid integer default 0 not null, userid integer default null, requester text default '' not null, @@ -38,4 +48,28 @@ create table library_queue( foreign key (userid) references users(id) ); -create index library_queue_bookid_idx on library_queue (bookid); \ No newline at end of file +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)'); \ No newline at end of file From fd63b2473bc8b6f73cb0c06d75a6ac69214fd733 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Wed, 11 Nov 2026 15:36:57 -0700 Subject: [PATCH 22/26] Typoes. (Also, "books" already exists as part of the Bible API.) --- migrations/sqlite/0004_library.sql | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/migrations/sqlite/0004_library.sql b/migrations/sqlite/0004_library.sql index 8400913..66b6c89 100644 --- a/migrations/sqlite/0004_library.sql +++ b/migrations/sqlite/0004_library.sql @@ -1,6 +1,6 @@ -- @up -create table books ( +create table library_books ( id integer primary key autoincrement, isbn integer default 0 not null, -- ISBN-10 check digit. If it is the maximum allowable value in the base-11 format (i.e. the ISBN-10 ends with "X") this will be "1". @@ -17,8 +17,8 @@ create table library ( chatid integer, available boolean default true not null, - foreign key bookid references books(id) -) + foreign key (bookid) references library_books(id) +); create unique index bookid_chatid_library_idx on library(bookid, chatid); create table library_checkout ( @@ -46,7 +46,6 @@ create table library_queue ( foreign key (bookid) references library_books(id), foreign key (userid) references users(id) - ); create index library_queue_bookid_idx on library_queue (bookid); @@ -68,7 +67,7 @@ create table ol_cache ( requested datetime default current_timestamp not null, -- We cache the full response for later debugging, if needed. - json_response text default '' not null, + json_response text default '' not null ); create unique index ol_cache_isbn_idx on ol_cache(isbn); From 93918286f4a2c6e422553c404e8eea95ec7daa90 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Thu, 12 Nov 2026 19:27:20 -0700 Subject: [PATCH 23/26] WIP. --- internal/models/library.go | 105 +++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 internal/models/library.go diff --git a/internal/models/library.go b/internal/models/library.go new file mode 100644 index 0000000..e5eada0 --- /dev/null +++ b/internal/models/library.go @@ -0,0 +1,105 @@ +package models + +import ( + "context" + "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, meta) values (?, ?, ?, ?)` + + fn := lm.db.ExecContext + if lm.tx != nil { + fn = lm.tx.ExecContext + } + + if _, err := fn(lm.ctx, q, book.ISBN, book.Title, book.Authors, book.Meta); err != nil { + return err + } + + return nil +} + +func (lm *LibraryModel) AddToLibrary(book *LibraryBook) error { + + 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 +} From 23bd589e456ebd6ddd8dd1adb2a8bdeecf3a146e Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Thu, 12 Nov 2026 19:28:09 -0700 Subject: [PATCH 24/26] Switch to storing ISBNs as text. --- migrations/sqlite/0004_library.sql | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/migrations/sqlite/0004_library.sql b/migrations/sqlite/0004_library.sql index 66b6c89..6f0602a 100644 --- a/migrations/sqlite/0004_library.sql +++ b/migrations/sqlite/0004_library.sql @@ -2,9 +2,7 @@ create table library_books ( id integer primary key autoincrement, - isbn integer default 0 not null, - -- ISBN-10 check digit. If it is the maximum allowable value in the base-11 format (i.e. the ISBN-10 ends with "X") this will be "1". - isbn_check integer default 0 not null, + isbn text default '' not null, title text default '' not null, authors text default '' not null, meta jsonb default '{}' not null From e3f270b40e15e69b4407a533d29f02975845a753 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Thu, 12 Nov 2026 19:28:26 -0700 Subject: [PATCH 25/26] Accept modern Go suggestions to correct error type. --- internal/models/verses.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/internal/models/verses.go b/internal/models/verses.go index ef9a962..4909b4c 100644 --- a/internal/models/verses.go +++ b/internal/models/verses.go @@ -94,8 +94,7 @@ func (vm *VerseModel) verseFromRotation() (*Verse, error) { err := fn(vm.ctx, verse, qrand) if err != nil { - var serr sqlite3.Error - if errors.As(err, &serr) { + if serr, ok := errors.AsType[sqlite3.Error](err); ok { switch serr.Code { case sqlite3.ErrMismatch: return nil, ErrNoRows.Do(err) From b6fc87817b56e69ffa862b5094c41307092fb8f7 Mon Sep 17 00:00:00 2001 From: "Benjamin A. Shelton" Date: Fri, 13 Nov 2026 19:28:44 -0700 Subject: [PATCH 26/26] API implementations (added). --- internal/models/library.go | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/internal/models/library.go b/internal/models/library.go index e5eada0..c95dfcf 100644 --- a/internal/models/library.go +++ b/internal/models/library.go @@ -2,6 +2,7 @@ package models import ( "context" + "database/sql" "time" "github.com/jmoiron/sqlx" @@ -54,21 +55,47 @@ func NewLibraryModel(ctx context.Context, db *sqlx.DB) *LibraryModel { } func (lm *LibraryModel) AddBook(book *LibraryBook) error { - q := `insert or ignore into library_books (isbn, title, authors, meta) values (?, ?, ?, ?)` + q := `insert or ignore into library_books (isbn, title, authors) values (?, ?, ?) returning id` - fn := lm.db.ExecContext + fn := lm.db.GetContext if lm.tx != nil { - fn = lm.tx.ExecContext + fn = lm.tx.GetContext } - if _, err := fn(lm.ctx, q, book.ISBN, book.Title, book.Authors, book.Meta); err != nil { + 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) error { +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 }