Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
b6fc87817b |
|||
|
e3f270b40e |
|||
|
23bd589e45 |
|||
|
93918286f4 |
|||
|
fd63b2473b |
|||
|
af20b3ac25 |
|||
|
826269619f |
|||
|
e285521c88 |
|||
|
8f64441079 |
|||
|
0b163faf32 |
|||
|
a0c3103d27 |
|||
|
43d3cdc508 |
|||
|
3f91c9f3bf |
|||
|
5a40168769 |
|||
|
d06ecc76e3 |
|||
|
fd608a857c |
|||
|
12e0ba0010 |
|||
|
477419ef63 |
|||
|
c39dc95387 |
|||
|
7946947794 |
|||
|
6c7cf689aa |
|||
|
ad4c747aea |
|||
|
a8d812495a |
|||
|
71a487feba |
|||
|
4cf1f2836e |
15 changed files with 390 additions and 142 deletions
14
Makefile
14
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
|
||||
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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("**<u>Birthdays this week (Sunday-to-Sunday):</u>**\n\n")
|
||||
sb.WriteString("**<u>Upcoming Birthdays (next 2 weeks):</u>**\n\n")
|
||||
for _, bday := range bdays {
|
||||
d, derr := time.Parse("2006-01-02", bday.Birthdate)
|
||||
if derr == nil {
|
||||
|
|
@ -141,11 +141,11 @@ func (a *App) daily() {
|
|||
}
|
||||
bdays, err := a.db.Birthdays().BirthdaysToday(chat.ID)
|
||||
if err == nil && len(bdays) > 0 {
|
||||
sb.WriteString("**<u>Today's Birthday")
|
||||
sb.WriteString("**<u>🎂 Today's Birthday")
|
||||
if len(bdays) > 1 {
|
||||
sb.WriteString("s")
|
||||
}
|
||||
sb.WriteString(":</u>**\n\n")
|
||||
sb.WriteString(" 🎂</u>**\n\n")
|
||||
for _, bday := range bdays {
|
||||
sb.WriteString(" * ")
|
||||
sb.WriteString(bday.Name)
|
||||
|
|
@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -194,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,
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -212,8 +214,9 @@ 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")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
}
|
||||
|
|
@ -69,8 +73,24 @@ 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")
|
||||
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,62 +108,90 @@ func (b *bot) AttachHandlers() {
|
|||
))*/
|
||||
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 {
|
||||
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),
|
||||
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("**<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) {
|
||||
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 +200,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
|
||||
|
|
@ -174,24 +223,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",
|
||||
|
|
@ -203,43 +241,42 @@ 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,
|
||||
},
|
||||
},
|
||||
})
|
||||
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: "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,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
|
@ -285,16 +322,17 @@ func (b *bot) SetWebhook(ctx context.Context, conf *settings.Settings) (err erro
|
|||
return
|
||||
}
|
||||
|
||||
err = b.tgbot.SetWebhook(b.ctx, &telego.SetWebhookParams{
|
||||
URL: b.settings.Service.Webhook.URI,
|
||||
SecretToken: b.tgbot.SecretToken(),
|
||||
})
|
||||
info, err := b.tgbot.GetWebhookInfo(b.ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
info, err := b.tgbot.GetWebhookInfo(b.ctx)
|
||||
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 {
|
||||
fmt.Println(info, err)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -326,6 +364,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()
|
||||
|
|
|
|||
|
|
@ -518,18 +518,10 @@ 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
|
||||
|
|
|
|||
|
|
@ -13,13 +13,12 @@ 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`
|
||||
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.`
|
||||
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.`
|
||||
)
|
||||
|
||||
func loadScripture(s string) (*bible.Chapter, error) {
|
||||
|
|
@ -125,23 +124,6 @@ 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) {
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
132
internal/models/library.go
Normal file
132
internal/models/library.go
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -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) {
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
72
migrations/sqlite/0004_library.sql
Normal file
72
migrations/sqlite/0004_library.sql
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
-- @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,6 +15,10 @@ active = [
|
|||
]
|
||||
default = "bsb"
|
||||
|
||||
[library]
|
||||
[lookup]
|
||||
useragent = "BibleBot/$version ($contact)"
|
||||
|
||||
[scheduler]
|
||||
[scheduler.announcements]
|
||||
weekly = "Sunday"
|
||||
|
|
|
|||
Loading…
Reference in a new issue