Add chat management.

Presently this only allows adding a chat to the bot.
This commit is contained in:
Benjamin A. Shelton 2026-10-14 14:26:18 -06:00
commit 6a02e2f4fe
Signed by: zancarius
GPG key ID: 8BD42DBD6C337E01
4 changed files with 100 additions and 2 deletions

View file

@ -57,6 +57,29 @@ func main() {
},
},
Commands: []*cli.Command{
{
Name: "chats",
Description: "Chats management",
Commands: []*cli.Command{
{
Name: "add",
Description: "Adds a chat to the bot. This is analogous to running /start within a chat.",
Action: cmdHost.Chats().AddChat,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "id",
Aliases: []string{"i"},
Usage: "Specifies the chat id.",
},
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Usage: "Specifies the chat name.",
},
},
},
},
},
{
Name: "init",
Description: "Initialize the bot, its database, and prepare for first run.",

View file

@ -0,0 +1,41 @@
package commands
import (
"context"
"fmt"
"code.destrealm.net/zancarius/justusbot/internal/models"
"code.destrealm.net/zancarius/justusbot/internal/settings"
"github.com/urfave/cli/v3"
"go.destrealm.net/errors"
"go.destrealm.net/logging/v3"
"go.destrealm.net/vfs"
)
type chats struct {
fs vfs.VFS
settings *settings.Settings
}
func (c *chats) AddChat(ctx context.Context, cmd *cli.Command) error {
logger := logging.Get("commands")
logger.SetFormat("chat add: {{message}}")
id := cmd.Int("id")
name := cmd.String("name")
mdb := models.OpenDatabase(c.settings)
if err := mdb.Open(); err != nil {
logger.Error("connection error:", errors.Unfurl(err))
return err
}
mdl := models.NewChatModel(ctx, mdb.DB())
_, err := mdl.AddChat(id, name)
if err != nil {
return err
}
fmt.Printf(`added chat "%s" (%d)\n`, name, id)
return nil
}

View file

@ -7,6 +7,7 @@ import (
type commands struct {
root vfs.VFS
chats *chats
meta *metadata
verse *verse
settings *settings.Settings
@ -32,6 +33,16 @@ func (c *commands) Initalizer() *installer {
return i
}
func (c *commands) Chats() *chats {
if c.chats == nil {
c.chats = &chats{
fs: c.root,
settings: c.settings,
}
}
return c.chats
}
func (c *commands) Meta() *metadata {
if c.meta == nil {
c.meta = &metadata{

View file

@ -2,16 +2,39 @@ package models
import (
"context"
"errors"
"github.com/jmoiron/sqlx"
"github.com/mattn/go-sqlite3"
)
type Chat struct {
ID int
Name string
ID int `db:"id"`
Name string `db:"name"`
}
type ChatModel struct {
ctx context.Context
db *sqlx.DB
}
func NewChatModel(ctx context.Context, db *sqlx.DB) *ChatModel {
return &ChatModel{ctx, db}
}
func (cm *ChatModel) AddChat(id int, name string) (*Chat, error) {
var chat *Chat
err := cm.db.GetContext(cm.ctx, chat,
`insert into chats (id, name) values (?, ?)`, id, name)
if err != nil {
var serr sqlite3.Error
if errors.As(err, &serr) {
switch serr.ExtendedCode {
case sqlite3.ErrConstraintUnique:
return nil, ErrUniqueConstraint.Do(err)
}
}
return nil, err
}
return chat, nil
}