3 Commits

Author SHA1 Message Date
7b9292557e 0.8.0 beta 1 2026-02-19 13:27:03 +03:00
466093e39b version fix 2026-02-19 12:07:03 +03:00
0e0f8a0813 v0.7.0; support for test server and local bot api 2026-02-19 11:49:04 +03:00
14 changed files with 375 additions and 432 deletions

284
bot.go
View File

@@ -10,12 +10,9 @@ import (
"git.nix13.pw/scuroneko/extypes" "git.nix13.pw/scuroneko/extypes"
"git.nix13.pw/scuroneko/laniakea/tgapi" "git.nix13.pw/scuroneko/laniakea/tgapi"
"git.nix13.pw/scuroneko/slog" "git.nix13.pw/scuroneko/slog"
"github.com/redis/go-redis/v9"
"github.com/vinovest/sqlx"
"go.mongodb.org/mongo-driver/v2/mongo"
) )
type BotSettings struct { type BotOpts struct {
Token string Token string
Debug bool Debug bool
ErrorTemplate string ErrorTemplate string
@@ -24,10 +21,12 @@ type BotSettings struct {
LoggerBasePath string LoggerBasePath string
UseRequestLogger bool UseRequestLogger bool
WriteToFile bool WriteToFile bool
UseTestServer bool
APIUrl string
} }
func LoadSettingsFromEnv() *BotSettings { func LoadOptsFromEnv() *BotOpts {
return &BotSettings{ return &BotOpts{
Token: os.Getenv("TG_TOKEN"), Token: os.Getenv("TG_TOKEN"),
Debug: os.Getenv("DEBUG") == "true", Debug: os.Getenv("DEBUG") == "true",
ErrorTemplate: os.Getenv("ERROR_TEMPLATE"), ErrorTemplate: os.Getenv("ERROR_TEMPLATE"),
@@ -35,9 +34,10 @@ func LoadSettingsFromEnv() *BotSettings {
UpdateTypes: strings.Split(os.Getenv("UPDATE_TYPES"), ";"), UpdateTypes: strings.Split(os.Getenv("UPDATE_TYPES"), ";"),
UseRequestLogger: os.Getenv("USE_REQ_LOG") == "true", UseRequestLogger: os.Getenv("USE_REQ_LOG") == "true",
WriteToFile: os.Getenv("WRITE_TO_FILE") == "true", WriteToFile: os.Getenv("WRITE_TO_FILE") == "true",
UseTestServer: os.Getenv("USE_TEST_SERVER") == "true",
APIUrl: os.Getenv("API_URL"),
} }
} }
func LoadPrefixesFromEnv() []string { func LoadPrefixesFromEnv() []string {
prefixesS, exists := os.LookupEnv("PREFIXES") prefixesS, exists := os.LookupEnv("PREFIXES")
if !exists { if !exists {
@@ -46,7 +46,8 @@ func LoadPrefixesFromEnv() []string {
return strings.Split(prefixesS, ";") return strings.Split(prefixesS, ";")
} }
type Bot struct { type DbContext interface{}
type Bot[T DbContext] struct {
token string token string
debug bool debug bool
errorTemplate string errorTemplate string
@@ -54,14 +55,15 @@ type Bot struct {
logger *slog.Logger logger *slog.Logger
RequestLogger *slog.Logger RequestLogger *slog.Logger
plugins []Plugin plugins []Plugin[T]
middlewares []Middleware middlewares []Middleware[T]
prefixes []string prefixes []string
runners []Runner runners []Runner[T]
dbContext *DatabaseContext
api *tgapi.API api *tgapi.API
l10n L10n uploader *tgapi.Uploader
dbContext *T
l10n *L10n
dbWriterRequested extypes.Slice[*slog.Logger] dbWriterRequested extypes.Slice[*slog.Logger]
@@ -70,33 +72,74 @@ type Bot struct {
updateQueue *extypes.Queue[*tgapi.Update] updateQueue *extypes.Queue[*tgapi.Update]
} }
func NewBot(settings *BotSettings) *Bot { func NewBot[T any](opts *BotOpts) *Bot[T] {
updateQueue := extypes.CreateQueue[*tgapi.Update](256) updateQueue := extypes.CreateQueue[*tgapi.Update](512)
api := tgapi.NewAPI(settings.Token)
bot := &Bot{
updateOffset: 0, plugins: make([]Plugin, 0), debug: settings.Debug, errorTemplate: "%s",
prefixes: settings.Prefixes, updateTypes: make([]tgapi.UpdateType, 0), runners: make([]Runner, 0),
updateQueue: updateQueue, api: api, dbWriterRequested: make([]*slog.Logger, 0),
token: settings.Token, l10n: L10n{},
}
bot.dbWriterRequested = bot.dbWriterRequested.Push(api.Logger)
if len(settings.ErrorTemplate) > 0 { apiOpts := tgapi.NewAPIOpts(opts.Token).SetAPIUrl(opts.APIUrl).UseTestServer(opts.UseTestServer)
bot.errorTemplate = settings.ErrorTemplate api := tgapi.NewAPI(apiOpts)
}
if len(settings.LoggerBasePath) == 0 {
settings.LoggerBasePath = "./"
}
uploader := tgapi.NewUploader(api)
bot := &Bot[T]{
updateOffset: 0,
errorTemplate: "%s",
updateQueue: updateQueue,
api: api,
uploader: uploader,
debug: opts.Debug,
prefixes: opts.Prefixes,
token: opts.Token,
plugins: make([]Plugin[T], 0),
updateTypes: make([]tgapi.UpdateType, 0),
runners: make([]Runner[T], 0),
dbWriterRequested: make([]*slog.Logger, 0),
l10n: &L10n{},
}
bot.dbWriterRequested = bot.dbWriterRequested.Push(api.GetLogger()).Push(uploader.GetLogger())
if len(opts.ErrorTemplate) > 0 {
bot.errorTemplate = opts.ErrorTemplate
}
if len(opts.LoggerBasePath) == 0 {
opts.LoggerBasePath = "./"
}
bot.initLoggers(opts)
u, err := api.GetMe()
if err != nil {
_ = api.CloseApi()
_ = uploader.Close()
bot.logger.Fatal(err)
}
bot.logger.Infof("Authorized as %s\n", u.FirstName)
return bot
}
func (bot *Bot[T]) Close() error {
if err := bot.uploader.Close(); err != nil {
bot.logger.Errorln(err)
}
if err := bot.api.CloseApi(); err != nil {
bot.logger.Errorln(err)
}
if err := bot.RequestLogger.Close(); err != nil {
bot.logger.Errorln(err)
}
if err := bot.logger.Close(); err != nil {
return err
}
return nil
}
func (bot *Bot[T]) initLoggers(opts *BotOpts) {
level := slog.FATAL level := slog.FATAL
if settings.Debug { if opts.Debug {
level = slog.DEBUG level = slog.DEBUG
} }
bot.logger = slog.CreateLogger().Level(level).Prefix("BOT") bot.logger = slog.CreateLogger().Level(level).Prefix("BOT")
bot.logger.AddWriter(bot.logger.CreateJsonStdoutWriter()) bot.logger.AddWriter(bot.logger.CreateJsonStdoutWriter())
if settings.WriteToFile { if opts.WriteToFile {
path := fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/")) path := fmt.Sprintf("%s/main.log", strings.TrimRight(opts.LoggerBasePath, "/"))
fileWriter, err := bot.logger.CreateTextFileWriter(path) fileWriter, err := bot.logger.CreateTextFileWriter(path)
if err != nil { if err != nil {
bot.logger.Fatal(err) bot.logger.Fatal(err)
@@ -104,11 +147,11 @@ func NewBot(settings *BotSettings) *Bot {
bot.logger.AddWriter(fileWriter) bot.logger.AddWriter(fileWriter)
} }
if settings.UseRequestLogger { if opts.UseRequestLogger {
bot.RequestLogger = slog.CreateLogger().Level(level).Prefix("REQUESTS") bot.RequestLogger = slog.CreateLogger().Level(level).Prefix("REQUESTS")
bot.RequestLogger.AddWriter(bot.RequestLogger.CreateJsonStdoutWriter()) bot.RequestLogger.AddWriter(bot.RequestLogger.CreateJsonStdoutWriter())
if settings.WriteToFile { if opts.WriteToFile {
path := fmt.Sprintf("%s/requests.log", strings.TrimRight(settings.LoggerBasePath, "/")) path := fmt.Sprintf("%s/requests.log", strings.TrimRight(opts.LoggerBasePath, "/"))
fileWriter, err := bot.RequestLogger.CreateTextFileWriter(path) fileWriter, err := bot.RequestLogger.CreateTextFileWriter(path)
if err != nil { if err != nil {
bot.logger.Fatal(err) bot.logger.Fatal(err)
@@ -116,142 +159,112 @@ func NewBot(settings *BotSettings) *Bot {
bot.RequestLogger.AddWriter(fileWriter) bot.RequestLogger.AddWriter(fileWriter)
} }
} }
}
u, err := api.GetMe() func (bot *Bot[T]) GetUpdateOffset() int { return bot.updateOffset }
if err != nil { func (bot *Bot[T]) SetUpdateOffset(offset int) { bot.updateOffset = offset }
bot.logger.Fatal(err) func (bot *Bot[T]) GetUpdateTypes() []tgapi.UpdateType { return bot.updateTypes }
func (bot *Bot[T]) GetQueue() *extypes.Queue[*tgapi.Update] { return bot.updateQueue }
func (bot *Bot[T]) GetLogger() *slog.Logger { return bot.logger }
func (bot *Bot[T]) GetDBContext() *T { return bot.dbContext }
func (bot *Bot[T]) L10n(lang, key string) string { return bot.l10n.Translate(lang, key) }
func (bot *Bot[T]) AddDatabaseLogger(writer func(db *T) slog.LoggerWriter) *Bot[T] {
w := writer(bot.dbContext)
bot.logger.AddWriter(w)
if bot.RequestLogger != nil {
bot.RequestLogger.AddWriter(w)
}
for _, l := range bot.dbWriterRequested {
l.AddWriter(w)
} }
bot.logger.Infof("Authorized as %s\n", u.FirstName)
return bot return bot
} }
func (b *Bot) Close() error { func (bot *Bot[T]) DatabaseContext(ctx *T) *Bot[T] {
err := b.logger.Close() bot.dbContext = ctx
if err != nil { return bot
return err
}
err = b.RequestLogger.Close()
return err
} }
func (bot *Bot[T]) UpdateTypes(t ...tgapi.UpdateType) *Bot[T] {
func (b *Bot) GetUpdateOffset() int { return b.updateOffset } bot.updateTypes = make([]tgapi.UpdateType, 0)
func (b *Bot) SetUpdateOffset(offset int) { b.updateOffset = offset } bot.updateTypes = append(bot.updateTypes, t...)
func (b *Bot) GetUpdateTypes() []tgapi.UpdateType { return b.updateTypes } return bot
func (b *Bot) GetQueue() *extypes.Queue[*tgapi.Update] { return b.updateQueue }
type DatabaseContext struct {
PostgresSQL *sqlx.DB
MongoDB *mongo.Client
Redis *redis.Client
} }
func (bot *Bot[T]) AddUpdateType(t ...tgapi.UpdateType) *Bot[T] {
func (b *Bot) AddDatabaseLogger(writer func(db *DatabaseContext) slog.LoggerWriter) *Bot { bot.updateTypes = append(bot.updateTypes, t...)
w := writer(b.dbContext) return bot
b.logger.AddWriter(w)
if b.RequestLogger != nil {
b.RequestLogger.AddWriter(w)
}
for _, l := range b.dbWriterRequested {
l.AddWriter(w)
}
return b
} }
func (bot *Bot[T]) AddPrefixes(prefixes ...string) *Bot[T] {
func (b *Bot) DatabaseContext(ctx *DatabaseContext) *Bot { bot.prefixes = append(bot.prefixes, prefixes...)
b.dbContext = ctx return bot
return b
} }
func (b *Bot) UpdateTypes(t ...tgapi.UpdateType) *Bot { func (bot *Bot[T]) ErrorTemplate(s string) *Bot[T] {
b.updateTypes = make([]tgapi.UpdateType, 0) bot.errorTemplate = s
b.updateTypes = append(b.updateTypes, t...) return bot
return b
} }
func (b *Bot) AddUpdateType(t ...tgapi.UpdateType) *Bot { func (bot *Bot[T]) Debug(debug bool) *Bot[T] {
b.updateTypes = append(b.updateTypes, t...) bot.debug = debug
return b return bot
} }
func (b *Bot) AddPrefixes(prefixes ...string) *Bot { func (bot *Bot[T]) AddPlugins(plugin ...*Plugin[T]) *Bot[T] {
b.prefixes = append(b.prefixes, prefixes...)
return b
}
func (b *Bot) ErrorTemplate(s string) *Bot {
b.errorTemplate = s
return b
}
func (b *Bot) Debug(debug bool) *Bot {
b.debug = debug
return b
}
func (b *Bot) AddPlugins(plugin ...*Plugin) *Bot {
for _, p := range plugin { for _, p := range plugin {
b.plugins = append(b.plugins, *p) bot.plugins = append(bot.plugins, *p)
b.logger.Debugln(fmt.Sprintf("plugins with name \"%s\" registered", p.Name)) bot.logger.Debugln(fmt.Sprintf("plugins with name \"%s\" registered", p.Name))
} }
return b return bot
} }
func (b *Bot) AddMiddleware(middleware ...Middleware) *Bot { func (bot *Bot[T]) AddMiddleware(middleware ...Middleware[T]) *Bot[T] {
b.middlewares = append(b.middlewares, middleware...) bot.middlewares = append(bot.middlewares, middleware...)
for _, m := range middleware { for _, m := range middleware {
b.logger.Debugln(fmt.Sprintf("middleware with name \"%s\" registered", m.name)) bot.logger.Debugln(fmt.Sprintf("middleware with name \"%s\" registered", m.name))
} }
sort.Slice(b.middlewares, func(i, j int) bool { sort.Slice(bot.middlewares, func(i, j int) bool {
first := b.middlewares[i] first := bot.middlewares[i]
second := b.middlewares[j] second := bot.middlewares[j]
if first.order == second.order { if first.order == second.order {
return first.name < second.name return first.name < second.name
} }
return first.order < second.order return first.order < second.order
}) })
return b return bot
} }
func (b *Bot) AddRunner(runner Runner) *Bot { func (bot *Bot[T]) AddRunner(runner Runner[T]) *Bot[T] {
b.runners = append(b.runners, runner) bot.runners = append(bot.runners, runner)
b.logger.Debugln(fmt.Sprintf("runner with name \"%s\" registered", runner.Name)) bot.logger.Debugln(fmt.Sprintf("runner with name \"%s\" registered", runner.name))
return b return bot
} }
func (b *Bot) AddL10n(l L10n) *Bot { func (bot *Bot[T]) AddL10n(l *L10n) *Bot[T] {
b.l10n = l bot.l10n = l
return b return bot
}
func (b *Bot) L10n(lang, key string) string {
return b.l10n.Translate(lang, key)
}
func (b *Bot) Logger() *slog.Logger {
return b.logger
}
func (b *Bot) GetDBContext() *DatabaseContext {
return b.dbContext
} }
func (b *Bot) Run() { func (bot *Bot[T]) Run() {
if len(b.prefixes) == 0 { if len(bot.prefixes) == 0 {
b.logger.Fatalln("no prefixes defined") bot.logger.Fatalln("no prefixes defined")
return return
} }
if len(b.plugins) == 0 { if len(bot.plugins) == 0 {
b.logger.Fatalln("no plugins defined") bot.logger.Fatalln("no plugins defined")
return return
} }
b.logger.Infoln("Executing runners...") bot.ExecRunners()
b.ExecRunners()
b.logger.Infoln("Bot running. Press CTRL+C to exit.") bot.logger.Infoln("Bot running. Press CTRL+C to exit.")
go func() { go func() {
for { for {
_, err := b.Updates() _, err := bot.Updates()
if err != nil { if err != nil {
b.logger.Errorln(err) bot.logger.Errorln(err)
} }
} }
}() }()
for { for {
queue := b.updateQueue queue := bot.updateQueue
if queue.IsEmpty() { if queue.IsEmpty() {
time.Sleep(time.Millisecond * 25) time.Sleep(time.Millisecond * 25)
continue continue
@@ -259,19 +272,10 @@ func (b *Bot) Run() {
u := queue.Dequeue() u := queue.Dequeue()
if u == nil { if u == nil {
b.logger.Errorln("update is nil") bot.logger.Errorln("update is nil")
continue continue
} }
ctx := &MsgContext{Bot: b, Update: *u, Api: b.api} bot.handle(u)
for _, middleware := range b.middlewares {
middleware.Execute(ctx, b.dbContext)
}
if u.CallbackQuery != nil {
b.handleCallback(u, ctx)
} else {
b.handleMessage(u, ctx)
}
} }
} }

View File

@@ -1,13 +1,14 @@
package laniakea package laniakea
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
"git.nix13.pw/scuroneko/laniakea/tgapi" "git.nix13.pw/scuroneko/laniakea/tgapi"
) )
func generateBotCommand(cmd Command) tgapi.BotCommand { func generateBotCommand[T any](cmd Command[T]) tgapi.BotCommand {
desc := cmd.command desc := cmd.command
if len(cmd.description) > 0 { if len(cmd.description) > 0 {
desc = cmd.description desc = cmd.description
@@ -24,7 +25,7 @@ func generateBotCommand(cmd Command) tgapi.BotCommand {
return tgapi.BotCommand{Command: cmd.command, Description: desc} return tgapi.BotCommand{Command: cmd.command, Description: desc}
} }
func generateBotCommandForPlugin(pl Plugin) []tgapi.BotCommand { func generateBotCommandForPlugin[T any](pl Plugin[T]) []tgapi.BotCommand {
commands := make([]tgapi.BotCommand, 0) commands := make([]tgapi.BotCommand, 0)
for _, cmd := range pl.Commands { for _, cmd := range pl.Commands {
if cmd.skipAutoCmd { if cmd.skipAutoCmd {
@@ -35,28 +36,33 @@ func generateBotCommandForPlugin(pl Plugin) []tgapi.BotCommand {
return commands return commands
} }
func (b *Bot) AutoGenerateCommands() error { var ErrTooManyCommands = errors.New("too many commands. max 100")
_, err := b.api.DeleteMyCommands(tgapi.DeleteMyCommandsP{})
func (bot *Bot[T]) AutoGenerateCommands() error {
_, err := bot.api.DeleteMyCommands(tgapi.DeleteMyCommandsP{})
if err != nil { if err != nil {
return err return err
} }
commands := make([]tgapi.BotCommand, 0) commands := make([]tgapi.BotCommand, 0)
for _, pl := range b.plugins { for _, pl := range bot.plugins {
commands = append(commands, generateBotCommandForPlugin(pl)...) commands = append(commands, generateBotCommandForPlugin(pl)...)
} }
if len(commands) > 100 {
return ErrTooManyCommands
}
privateChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopePrivateType} privateChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopePrivateType}
groupChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopeGroupType} groupChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopeGroupType}
chatAdminsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopeAllChatAdministratorsType} chatAdminsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopeAllChatAdministratorsType}
_, err = b.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: privateChatsScope}) _, err = bot.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: privateChatsScope})
if err != nil { if err != nil {
return err return err
} }
_, err = b.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: groupChatsScope}) _, err = bot.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: groupChatsScope})
if err != nil { if err != nil {
return err return err
} }
_, err = b.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: chatAdminsScope}) _, err = bot.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: chatAdminsScope})
return err return err
} }

16
go.mod
View File

@@ -5,27 +5,11 @@ go 1.26
require ( require (
git.nix13.pw/scuroneko/extypes v1.2.0 git.nix13.pw/scuroneko/extypes v1.2.0
git.nix13.pw/scuroneko/slog v1.0.2 git.nix13.pw/scuroneko/slog v1.0.2
github.com/redis/go-redis/v9 v9.18.0
github.com/vinovest/sqlx v1.7.1
go.mongodb.org/mongo-driver/v2 v2.5.0
) )
require ( require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/fatih/color v1.18.0 // indirect github.com/fatih/color v1.18.0 // indirect
github.com/klauspost/compress v1.18.4 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/muir/list v1.2.1 // indirect
github.com/muir/sqltoken v0.3.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.2.0 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.48.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.41.0 // indirect golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.34.0 // indirect
) )

82
go.sum
View File

@@ -1,95 +1,13 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
git.nix13.pw/scuroneko/extypes v1.2.0 h1:2n2hD6KsMAted+6MGhAyeWyli2Qzc9G2y+pQNB7C1dM= git.nix13.pw/scuroneko/extypes v1.2.0 h1:2n2hD6KsMAted+6MGhAyeWyli2Qzc9G2y+pQNB7C1dM=
git.nix13.pw/scuroneko/extypes v1.2.0/go.mod h1:uZVs8Yo3RrYAG9dMad6qR6lsYY67t+459D9c65QAYAw= git.nix13.pw/scuroneko/extypes v1.2.0/go.mod h1:uZVs8Yo3RrYAG9dMad6qR6lsYY67t+459D9c65QAYAw=
git.nix13.pw/scuroneko/slog v1.0.2 h1:vZyUROygxC2d5FJHUQM/30xFEHY1JT/aweDZXA4rm2g= git.nix13.pw/scuroneko/slog v1.0.2 h1:vZyUROygxC2d5FJHUQM/30xFEHY1JT/aweDZXA4rm2g=
git.nix13.pw/scuroneko/slog v1.0.2/go.mod h1:3Qm2wzkR5KjwOponMfG7TcGSDjmYaFqRAmLvSPTuWJI= git.nix13.pw/scuroneko/slog v1.0.2/go.mod h1:3Qm2wzkR5KjwOponMfG7TcGSDjmYaFqRAmLvSPTuWJI=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/go-sql-driver/mysql v1.9.0 h1:Y0zIbQXhQKmQgTp44Y1dp3wTXcn804QoTptLZT1vtvo=
github.com/go-sql-driver/mysql v1.9.0/go.mod h1:pDetrLJeA3oMujJuvXc8RJoasr589B6A9fwzD3QMrqw=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/muir/list v1.2.1 h1:lmF8fz2B1WbXkzHr/Eh0oWPJArDBzWqIifOwbA4gWSo=
github.com/muir/list v1.2.1/go.mod h1:v0l2f997MxCohQlD7PTejJqyYKwFVz/i3mTpDl4LAf0=
github.com/muir/sqltoken v0.3.0 h1:3xbcqr80f3IA4OlwkOpdIHC4DTu6gsi1TwMqgYL4Dpg=
github.com/muir/sqltoken v0.3.0/go.mod h1:+OSmbGI22QcVZ6DCzlHT8EAzEq/mqtqedtPP91Le+3A=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/vinovest/sqlx v1.7.1 h1:kdq4v0N9kRLpytWGSWOw4aulOGdQPmIoMR6Y+cTBxow=
github.com/vinovest/sqlx v1.7.1/go.mod h1:3fAv74r4iDMv2PpFomADb+vex5ukzfYn4GseC9KngD8=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs=
github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8=
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -8,20 +8,20 @@ import (
"git.nix13.pw/scuroneko/laniakea/tgapi" "git.nix13.pw/scuroneko/laniakea/tgapi"
) )
func (b *Bot) handle(u *tgapi.Update) { func (bot *Bot[T]) handle(u *tgapi.Update) {
ctx := &MsgContext{Bot: b, Update: *u, Api: b.api} ctx := &MsgContext{Update: *u, Api: bot.api, botLogger: bot.logger, errorTemplate: bot.errorTemplate, l10n: bot.l10n}
for _, middleware := range b.middlewares { for _, middleware := range bot.middlewares {
middleware.Execute(ctx, b.dbContext) middleware.Execute(ctx, bot.dbContext)
} }
if u.CallbackQuery != nil { if u.CallbackQuery != nil {
b.handleCallback(u, ctx) bot.handleCallback(u, ctx)
} else { } else {
b.handleMessage(u, ctx) bot.handleMessage(u, ctx)
} }
} }
func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) { func (bot *Bot[T]) handleMessage(update *tgapi.Update, ctx *MsgContext) {
if update.Message == nil { if update.Message == nil {
return return
} }
@@ -34,7 +34,7 @@ func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) {
} }
text = strings.TrimSpace(text) text = strings.TrimSpace(text)
prefix, hasPrefix := b.checkPrefixes(text) prefix, hasPrefix := bot.checkPrefixes(text)
if !hasPrefix { if !hasPrefix {
return return
} }
@@ -45,7 +45,7 @@ func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) {
text = strings.TrimSpace(text[len(prefix):]) text = strings.TrimSpace(text[len(prefix):])
for _, plugin := range b.plugins { for _, plugin := range bot.plugins {
for cmd := range plugin.Commands { for cmd := range plugin.Commands {
if !strings.HasPrefix(text, cmd) { if !strings.HasPrefix(text, cmd) {
continue continue
@@ -71,20 +71,20 @@ func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) {
ctx.Args = strings.Split(ctx.Text, " ") ctx.Args = strings.Split(ctx.Text, " ")
} }
if !plugin.executeMiddlewares(ctx, b.dbContext) { if !plugin.executeMiddlewares(ctx, bot.dbContext) {
return return
} }
go plugin.executeCmd(cmd, ctx, b.dbContext) go plugin.executeCmd(cmd, ctx, bot.dbContext)
return return
} }
} }
} }
func (b *Bot) handleCallback(update *tgapi.Update, ctx *MsgContext) { func (bot *Bot[T]) handleCallback(update *tgapi.Update, ctx *MsgContext) {
data := new(CallbackData) data := new(CallbackData)
err := json.Unmarshal([]byte(update.CallbackQuery.Data), data) err := json.Unmarshal([]byte(update.CallbackQuery.Data), data)
if err != nil { if err != nil {
b.logger.Errorln(err) bot.logger.Errorln(err)
return return
} }
@@ -95,22 +95,22 @@ func (b *Bot) handleCallback(update *tgapi.Update, ctx *MsgContext) {
ctx.CallbackQueryId = update.CallbackQuery.ID ctx.CallbackQueryId = update.CallbackQuery.ID
ctx.Args = data.Args ctx.Args = data.Args
for _, plugin := range b.plugins { for _, plugin := range bot.plugins {
_, ok := plugin.Payloads[data.Command] _, ok := plugin.Payloads[data.Command]
if !ok { if !ok {
continue continue
} }
if !plugin.executeMiddlewares(ctx, b.dbContext) { if !plugin.executeMiddlewares(ctx, bot.dbContext) {
return return
} }
go plugin.executePayload(data.Command, ctx, b.dbContext) go plugin.executePayload(data.Command, ctx, bot.dbContext)
return return
} }
} }
func (b *Bot) checkPrefixes(text string) (string, bool) { func (bot *Bot[T]) checkPrefixes(text string) (string, bool) {
for _, prefix := range b.prefixes { for _, prefix := range bot.prefixes {
if strings.HasPrefix(text, prefix) { if strings.HasPrefix(text, prefix) {
return prefix, true return prefix, true
} }

View File

@@ -17,7 +17,6 @@ func (l *L10n) AddDictEntry(key string, value DictEntry) *L10n {
func (l *L10n) GetFallbackLanguage() string { func (l *L10n) GetFallbackLanguage() string {
return l.fallbackLang return l.fallbackLang
} }
func (l *L10n) Translate(lang, key string) string { func (l *L10n) Translate(lang, key string) string {
s, ok := l.entries[key] s, ok := l.entries[key]
if !ok { if !ok {

View File

@@ -9,39 +9,39 @@ import (
"git.nix13.pw/scuroneko/laniakea/tgapi" "git.nix13.pw/scuroneko/laniakea/tgapi"
) )
func (b *Bot) Updates() ([]tgapi.Update, error) { func (bot *Bot[T]) Updates() ([]tgapi.Update, error) {
offset := b.GetUpdateOffset() offset := bot.GetUpdateOffset()
params := tgapi.UpdateParams{ params := tgapi.UpdateParams{
Offset: Ptr(offset), Offset: Ptr(offset),
Timeout: Ptr(30), Timeout: Ptr(30),
AllowedUpdates: b.GetUpdateTypes(), AllowedUpdates: bot.GetUpdateTypes(),
} }
updates, err := b.api.GetUpdates(params) updates, err := bot.api.GetUpdates(params)
if err != nil { if err != nil {
return nil, err return nil, err
} }
for _, u := range updates { for _, u := range updates {
b.SetUpdateOffset(u.UpdateID + 1) bot.SetUpdateOffset(u.UpdateID + 1)
err = b.GetQueue().Enqueue(&u) err = bot.GetQueue().Enqueue(&u)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if b.RequestLogger != nil { if bot.RequestLogger != nil {
j, err := json.Marshal(u) j, err := json.Marshal(u)
if err != nil { if err != nil {
b.Logger().Error(err) bot.GetLogger().Error(err)
} }
b.RequestLogger.Debugf("UPDATE %s\n", j) bot.RequestLogger.Debugf("UPDATE %s\n", j)
} }
} }
return updates, err return updates, err
} }
func (b *Bot) GetFileByLink(link string) ([]byte, error) { func (bot *Bot[T]) GetFileByLink(link string) ([]byte, error) {
u := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", b.token, link) u := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", bot.token, link)
res, err := http.Get(u) res, err := http.Get(u)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@@ -5,10 +5,10 @@ import (
"git.nix13.pw/scuroneko/laniakea/tgapi" "git.nix13.pw/scuroneko/laniakea/tgapi"
"git.nix13.pw/scuroneko/laniakea/utils" "git.nix13.pw/scuroneko/laniakea/utils"
"git.nix13.pw/scuroneko/slog"
) )
type MsgContext struct { type MsgContext struct {
Bot *Bot
Api *tgapi.API Api *tgapi.API
Msg *tgapi.Message Msg *tgapi.Message
@@ -20,6 +20,10 @@ type MsgContext struct {
Prefix string Prefix string
Text string Text string
Args []string Args []string
errorTemplate string
botLogger *slog.Logger
l10n *L10n
} }
type AnswerMessage struct { type AnswerMessage struct {
@@ -41,7 +45,7 @@ func (ctx *MsgContext) edit(messageId int, text string, keyboard *InlineKeyboard
} }
msg, _, err := ctx.Api.EditMessageText(params) msg, _, err := ctx.Api.EditMessageText(params)
if err != nil { if err != nil {
ctx.Api.Logger.Errorln(err) ctx.botLogger.Errorln(err)
return nil return nil
} }
return &AnswerMessage{ return &AnswerMessage{
@@ -53,7 +57,7 @@ func (m *AnswerMessage) Edit(text string) *AnswerMessage {
} }
func (ctx *MsgContext) EditCallback(text string, keyboard *InlineKeyboard) *AnswerMessage { func (ctx *MsgContext) EditCallback(text string, keyboard *InlineKeyboard) *AnswerMessage {
if ctx.CallbackMsgId == 0 { if ctx.CallbackMsgId == 0 {
ctx.Api.Logger.Errorln("Can't edit non-callback update message") ctx.botLogger.Errorln("Can't edit non-callback update message")
return nil return nil
} }
@@ -75,7 +79,7 @@ func (ctx *MsgContext) editPhotoText(messageId int, text string, kb *InlineKeybo
} }
msg, _, err := ctx.Api.EditMessageCaption(params) msg, _, err := ctx.Api.EditMessageCaption(params)
if err != nil { if err != nil {
ctx.Api.Logger.Errorln(err) ctx.botLogger.Errorln(err)
} }
return &AnswerMessage{ return &AnswerMessage{
MessageID: msg.MessageID, ctx: ctx, Text: text, IsMedia: true, MessageID: msg.MessageID, ctx: ctx, Text: text, IsMedia: true,
@@ -83,7 +87,7 @@ func (ctx *MsgContext) editPhotoText(messageId int, text string, kb *InlineKeybo
} }
func (m *AnswerMessage) EditCaption(text string) *AnswerMessage { func (m *AnswerMessage) EditCaption(text string) *AnswerMessage {
if m.MessageID == 0 { if m.MessageID == 0 {
m.ctx.Api.Logger.Errorln("Can't edit caption message, message id is zero") m.ctx.botLogger.Errorln("Can't edit caption message, message id is zero")
return m return m
} }
return m.ctx.editPhotoText(m.MessageID, text, nil) return m.ctx.editPhotoText(m.MessageID, text, nil)
@@ -104,7 +108,7 @@ func (ctx *MsgContext) answer(text string, keyboard *InlineKeyboard) *AnswerMess
msg, err := ctx.Api.SendMessage(params) msg, err := ctx.Api.SendMessage(params)
if err != nil { if err != nil {
ctx.Api.Logger.Errorln(err) ctx.botLogger.Errorln(err)
return nil return nil
} }
return &AnswerMessage{ return &AnswerMessage{
@@ -133,7 +137,7 @@ func (ctx *MsgContext) answerPhoto(photoId, text string, kb *InlineKeyboard) *An
} }
msg, err := ctx.Api.SendPhoto(params) msg, err := ctx.Api.SendPhoto(params)
if err != nil { if err != nil {
ctx.Api.Logger.Errorln(err) ctx.botLogger.Errorln(err)
return &AnswerMessage{ return &AnswerMessage{
ctx: ctx, Text: text, IsMedia: true, ctx: ctx, Text: text, IsMedia: true,
} }
@@ -155,7 +159,7 @@ func (ctx *MsgContext) delete(messageId int) {
MessageID: messageId, MessageID: messageId,
}) })
if err != nil { if err != nil {
ctx.Api.Logger.Errorln(err) ctx.botLogger.Errorln(err)
} }
} }
func (m *AnswerMessage) Delete() { func (m *AnswerMessage) Delete() {
@@ -174,7 +178,7 @@ func (ctx *MsgContext) answerCallbackQuery(url, text string, showAlert bool) {
Text: text, ShowAlert: showAlert, URL: url, Text: text, ShowAlert: showAlert, URL: url,
}) })
if err != nil { if err != nil {
ctx.Api.Logger.Errorln(err) ctx.botLogger.Errorln(err)
} }
} }
func (ctx *MsgContext) AnswerCbQuery() { func (ctx *MsgContext) AnswerCbQuery() {
@@ -195,19 +199,19 @@ func (ctx *MsgContext) SendAction(action tgapi.ChatActionType) {
ChatID: ctx.Msg.Chat.ID, Action: action, ChatID: ctx.Msg.Chat.ID, Action: action,
}) })
if err != nil { if err != nil {
ctx.Api.Logger.Errorln(err) ctx.botLogger.Errorln(err)
} }
} }
func (ctx *MsgContext) error(err error) { func (ctx *MsgContext) error(err error) {
text := fmt.Sprintf(ctx.Bot.errorTemplate, utils.EscapeMarkdown(err.Error())) text := fmt.Sprintf(ctx.errorTemplate, utils.EscapeMarkdown(err.Error()))
if ctx.CallbackQueryId != "" { if ctx.CallbackQueryId != "" {
ctx.answerCallbackQuery("", text, false) ctx.answerCallbackQuery("", text, false)
} else { } else {
ctx.answer(text, nil) ctx.answer(text, nil)
} }
ctx.Bot.Logger().Errorln(err) ctx.botLogger.Errorln(err)
} }
func (ctx *MsgContext) Error(err error) { func (ctx *MsgContext) Error(err error) {
ctx.error(err) ctx.error(err)
@@ -217,6 +221,6 @@ func (ctx *MsgContext) Translate(key string) string {
if ctx.From == nil { if ctx.From == nil {
return key return key
} }
lang := Val(ctx.From.LanguageCode, ctx.Bot.l10n.GetFallbackLanguage()) lang := Val(ctx.From.LanguageCode, ctx.l10n.GetFallbackLanguage())
return ctx.Bot.L10n(lang, key) return ctx.l10n.Translate(lang, key)
} }

View File

@@ -45,32 +45,33 @@ func (c *CommandArg) SetRequired() *CommandArg {
return c return c
} }
type CommandExecutor func(ctx *MsgContext, dbContext *DatabaseContext) type CommandExecutor[T DbContext] func(ctx *MsgContext, dbContext *T)
type Command struct {
type Command[T DbContext] struct {
command string command string
description string description string
exec CommandExecutor exec CommandExecutor[T]
args extypes.Slice[CommandArg] args extypes.Slice[CommandArg]
middlewares extypes.Slice[Middleware] middlewares extypes.Slice[Middleware[T]]
skipAutoCmd bool skipAutoCmd bool
} }
func NewCommand(exec CommandExecutor, command string, args ...CommandArg) *Command { func NewCommand[T any](exec CommandExecutor[T], command string, args ...CommandArg) *Command[T] {
return &Command{command, "", exec, args, make(extypes.Slice[Middleware], 0), false} return &Command[T]{command, "", exec, args, make(extypes.Slice[Middleware[T]], 0), false}
} }
func (c *Command) Use(m Middleware) *Command { func (c *Command[T]) Use(m Middleware[T]) *Command[T] {
c.middlewares = c.middlewares.Push(m) c.middlewares = c.middlewares.Push(m)
return c return c
} }
func (c *Command) SetDescription(desc string) *Command { func (c *Command[T]) SetDescription(desc string) *Command[T] {
c.description = desc c.description = desc
return c return c
} }
func (c *Command) SkipCommandAutoGen() *Command { func (c *Command[T]) SkipCommandAutoGen() *Command[T] {
c.skipAutoCmd = true c.skipAutoCmd = true
return c return c
} }
func (c *Command) validateArgs(args []string) error { func (c *Command[T]) validateArgs(args []string) error {
cmdArgs := c.args.Filter(func(e CommandArg) bool { return !e.required }) cmdArgs := c.args.Filter(func(e CommandArg) bool { return !e.required })
if len(args) < cmdArgs.Len() { if len(args) < cmdArgs.Len() {
return ErrCmdArgCountMismatch return ErrCmdArgCountMismatch
@@ -91,37 +92,37 @@ func (c *Command) validateArgs(args []string) error {
return nil return nil
} }
type Plugin struct { type Plugin[T DbContext] struct {
Name string Name string
Commands map[string]Command Commands map[string]Command[T]
Payloads map[string]Command Payloads map[string]Command[T]
Middlewares extypes.Slice[Middleware] Middlewares extypes.Slice[Middleware[T]]
} }
func NewPlugin(name string) *Plugin { func NewPlugin[T DbContext](name string) *Plugin[T] {
return &Plugin{ return &Plugin[T]{
name, map[string]Command{}, name, map[string]Command[T]{},
map[string]Command{}, extypes.Slice[Middleware]{}, map[string]Command[T]{}, extypes.Slice[Middleware[T]]{},
} }
} }
func (p *Plugin) AddCommand(command *Command) *Plugin { func (p *Plugin[T]) AddCommand(command *Command[T]) *Plugin[T] {
p.Commands[command.command] = *command p.Commands[command.command] = *command
return p return p
} }
func (p *Plugin) NewCommand(exec CommandExecutor, command string, args ...CommandArg) *Command { func (p *Plugin[T]) NewCommand(exec CommandExecutor[T], command string, args ...CommandArg) *Command[T] {
return NewCommand(exec, command, args...) return NewCommand(exec, command, args...)
} }
func (p *Plugin) AddPayload(command *Command) *Plugin { func (p *Plugin[T]) AddPayload(command *Command[T]) *Plugin[T] {
p.Payloads[command.command] = *command p.Payloads[command.command] = *command
return p return p
} }
func (p *Plugin) AddMiddleware(middleware Middleware) *Plugin { func (p *Plugin[T]) AddMiddleware(middleware Middleware[T]) *Plugin[T] {
p.Middlewares = p.Middlewares.Push(middleware) p.Middlewares = p.Middlewares.Push(middleware)
return p return p
} }
func (p *Plugin) executeCmd(cmd string, ctx *MsgContext, dbContext *DatabaseContext) { func (p *Plugin[T]) executeCmd(cmd string, ctx *MsgContext, dbContext *T) {
command := p.Commands[cmd] command := p.Commands[cmd]
if err := command.validateArgs(ctx.Args); err != nil { if err := command.validateArgs(ctx.Args); err != nil {
ctx.error(err) ctx.error(err)
@@ -129,7 +130,7 @@ func (p *Plugin) executeCmd(cmd string, ctx *MsgContext, dbContext *DatabaseCont
} }
command.exec(ctx, dbContext) command.exec(ctx, dbContext)
} }
func (p *Plugin) executePayload(payload string, ctx *MsgContext, dbContext *DatabaseContext) { func (p *Plugin[T]) executePayload(payload string, ctx *MsgContext, dbContext *T) {
pl := p.Payloads[payload] pl := p.Payloads[payload]
if err := pl.validateArgs(ctx.Args); err != nil { if err := pl.validateArgs(ctx.Args); err != nil {
ctx.error(err) ctx.error(err)
@@ -137,7 +138,7 @@ func (p *Plugin) executePayload(payload string, ctx *MsgContext, dbContext *Data
} }
pl.exec(ctx, dbContext) pl.exec(ctx, dbContext)
} }
func (p *Plugin) executeMiddlewares(ctx *MsgContext, db *DatabaseContext) bool { func (p *Plugin[T]) executeMiddlewares(ctx *MsgContext, db *T) bool {
for _, m := range p.Middlewares { for _, m := range p.Middlewares {
if !m.Execute(ctx, db) { if !m.Execute(ctx, db) {
return false return false
@@ -146,29 +147,29 @@ func (p *Plugin) executeMiddlewares(ctx *MsgContext, db *DatabaseContext) bool {
return true return true
} }
type MiddlewareExecutor func(ctx *MsgContext, db *DatabaseContext) bool type MiddlewareExecutor[T DbContext] func(ctx *MsgContext, db *T) bool
// Middleware // Middleware
// When async, returned value ignored // When async, returned value ignored
type Middleware struct { type Middleware[T DbContext] struct {
name string name string
executor MiddlewareExecutor executor MiddlewareExecutor[T]
order int order int
async bool async bool
} }
func NewMiddleware(name string, executor MiddlewareExecutor) *Middleware { func NewMiddleware[T DbContext](name string, executor MiddlewareExecutor[T]) *Middleware[T] {
return &Middleware{name, executor, 0, false} return &Middleware[T]{name, executor, 0, false}
} }
func (m *Middleware) SetOrder(order int) *Middleware { func (m *Middleware[T]) SetOrder(order int) *Middleware[T] {
m.order = order m.order = order
return m return m
} }
func (m *Middleware) SetAsync(async bool) *Middleware { func (m *Middleware[T]) SetAsync(async bool) *Middleware[T] {
m.async = async m.async = async
return m return m
} }
func (m *Middleware) Execute(ctx *MsgContext, db *DatabaseContext) bool { func (m *Middleware[T]) Execute(ctx *MsgContext, db *T) bool {
if m.async { if m.async {
go m.executor(ctx, db) go m.executor(ctx, db)
return true return true

View File

@@ -4,81 +4,69 @@ import (
"time" "time"
) )
type RunnerFn func(*Bot) error type RunnerFn[T DbContext] func(*Bot[T]) error
type RunnerBuilder struct { type Runner[T DbContext] struct {
name string name string
onetime bool onetime bool
async bool async bool
timeout time.Duration timeout time.Duration
fn RunnerFn fn RunnerFn[T]
}
type Runner struct {
Name string
Onetime bool
Async bool
Timeout time.Duration
Fn RunnerFn
} }
func NewRunner(name string, fn RunnerFn) *RunnerBuilder { func NewRunner[T DbContext](name string, fn RunnerFn[T]) *Runner[T] {
return &RunnerBuilder{ return &Runner[T]{
name: name, fn: fn, async: true, name: name, fn: fn, async: true,
} }
} }
func (b *RunnerBuilder) Onetime(onetime bool) *RunnerBuilder { func (b *Runner[T]) Onetime(onetime bool) *Runner[T] {
b.onetime = onetime b.onetime = onetime
return b return b
} }
func (b *RunnerBuilder) Async(async bool) *RunnerBuilder { func (b *Runner[T]) Async(async bool) *Runner[T] {
b.async = async b.async = async
return b return b
} }
func (b *RunnerBuilder) Timeout(timeout time.Duration) *RunnerBuilder { func (b *Runner[T]) Timeout(timeout time.Duration) *Runner[T] {
b.timeout = timeout b.timeout = timeout
return b return b
} }
func (b *RunnerBuilder) Build() Runner {
return Runner{
Name: b.name, Onetime: b.onetime, Async: b.async, Fn: b.fn, Timeout: b.timeout,
}
}
func (b *Bot) ExecRunners() { func (bot *Bot[T]) ExecRunners() {
b.logger.Infoln("Executing runners...") bot.logger.Infoln("Executing runners...")
for _, runner := range b.runners { for _, runner := range bot.runners {
if !runner.Onetime && !runner.Async { if !runner.onetime && !runner.async {
b.logger.Warnf("Runner %s not onetime, but sync\n", runner.Name) bot.logger.Warnf("Runner %s not onetime, but sync\n", runner.name)
continue continue
} }
if !runner.Onetime && runner.Async && runner.Timeout == (time.Second*0) { if !runner.onetime && runner.async && runner.timeout == (time.Second*0) {
b.logger.Warnf("Background runner \"%s\" should have timeout", runner.Name) bot.logger.Warnf("Background runner \"%s\" should have timeout", runner.name)
} }
if runner.Async && runner.Onetime { if runner.async && runner.onetime {
go func() { go func() {
err := runner.Fn(b) err := runner.fn(bot)
if err != nil { if err != nil {
b.logger.Warnf("Runner %s failed: %s\n", runner.Name, err) bot.logger.Warnf("Runner %s failed: %s\n", runner.name, err)
} }
}() }()
} else if !runner.Async && runner.Onetime { } else if !runner.async && runner.onetime {
t := time.Now() t := time.Now()
err := runner.Fn(b) err := runner.fn(bot)
if err != nil { if err != nil {
b.logger.Warnf("Runner %s failed: %s\n", runner.Name, err) bot.logger.Warnf("Runner %s failed: %s\n", runner.name, err)
} }
elapsed := time.Since(t) elapsed := time.Since(t)
if elapsed > time.Second*2 { if elapsed > time.Second*2 {
b.logger.Warnf("Runner %s too slow. Elapsed time %s>=2s", runner.Name, elapsed) bot.logger.Warnf("Runner %s too slow. Elapsed time %s>=2s", runner.name, elapsed)
} }
} else if !runner.Onetime { } else if !runner.onetime {
go func() { go func() {
for { for {
err := runner.Fn(b) err := runner.fn(bot)
if err != nil { if err != nil {
b.logger.Warnf("Runner %s failed: %s\n", runner.Name, err) bot.logger.Warnf("Runner %s failed: %s\n", runner.name, err)
} }
time.Sleep(runner.Timeout) time.Sleep(runner.timeout)
} }
}() }()
} }

View File

@@ -13,21 +13,52 @@ import (
"git.nix13.pw/scuroneko/slog" "git.nix13.pw/scuroneko/slog"
) )
type API struct { type APIOpts struct {
token string token string
client *http.Client client *http.Client
Logger *slog.Logger useTestServer bool
apiUrl string
} }
func NewAPI(token string) *API { func NewAPIOpts(token string) *APIOpts {
return &APIOpts{token: token, client: nil, useTestServer: false, apiUrl: "https://api.telegram.org"}
}
func (opts *APIOpts) SetHTTPClient(client *http.Client) *APIOpts {
if client != nil {
opts.client = client
}
return opts
}
func (opts *APIOpts) UseTestServer(use bool) *APIOpts {
opts.useTestServer = use
return opts
}
func (opts *APIOpts) SetAPIUrl(apiUrl string) *APIOpts {
if apiUrl != "" {
opts.apiUrl = apiUrl
}
return opts
}
type API struct {
token string
client *http.Client
logger *slog.Logger
useTestServer bool
apiUrl string
}
func NewAPI(opts *APIOpts) *API {
l := slog.CreateLogger().Level(utils.GetLoggerLevel()).Prefix("API") l := slog.CreateLogger().Level(utils.GetLoggerLevel()).Prefix("API")
l.AddWriter(l.CreateJsonStdoutWriter()) l.AddWriter(l.CreateJsonStdoutWriter())
client := &http.Client{Timeout: time.Second * 45} client := opts.client
return &API{token, client, l} if client == nil {
} client = &http.Client{Timeout: time.Second * 45}
func (api *API) CloseApi() error { }
return api.Logger.Close() return &API{opts.token, client, l, opts.useTestServer, opts.apiUrl}
} }
func (api *API) CloseApi() error { return api.logger.Close() }
func (api *API) GetLogger() *slog.Logger { return api.logger }
type ApiResponse[R any] struct { type ApiResponse[R any] struct {
Ok bool `json:"ok"` Ok bool `json:"ok"`
@@ -35,7 +66,6 @@ type ApiResponse[R any] struct {
Result R `json:"result,omitempty"` Result R `json:"result,omitempty"`
ErrorCode int `json:"error_code,omitempty"` ErrorCode int `json:"error_code,omitempty"`
} }
type TelegramRequest[R, P any] struct { type TelegramRequest[R, P any] struct {
method string method string
params P params P
@@ -52,8 +82,12 @@ func (r TelegramRequest[R, P]) DoWithContext(ctx context.Context, api *API) (R,
} }
buf := bytes.NewBuffer(data) buf := bytes.NewBuffer(data)
u := fmt.Sprintf("https://api.telegram.org/bot%s/%s", api.token, r.method) methodPrefix := ""
req, err := http.NewRequestWithContext(ctx, "POST", u, buf) if api.useTestServer {
methodPrefix = "/test"
}
url := fmt.Sprintf("%s/bot%s%s/%s", api.apiUrl, api.token, methodPrefix, r.method)
req, err := http.NewRequestWithContext(ctx, "POST", url, buf)
if err != nil { if err != nil {
return zero, err return zero, err
} }
@@ -61,25 +95,38 @@ func (r TelegramRequest[R, P]) DoWithContext(ctx context.Context, api *API) (R,
req.Header.Set("Accept", "application/json") req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString)) req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString))
api.Logger.Debugln("REQ", r.method, buf.String()) api.logger.Debugln("REQ", api.apiUrl, r.method, buf.String())
res, err := api.client.Do(req) res, err := api.client.Do(req)
if err != nil { if err != nil {
return zero, err return zero, err
} }
defer res.Body.Close() defer func(Body io.ReadCloser) {
_ = Body.Close()
}(res.Body)
reader := io.LimitReader(res.Body, 10<<20) data, err = readBody(res.Body)
data, err = io.ReadAll(reader)
if err != nil { if err != nil {
return zero, err return zero, err
} }
api.Logger.Debugln("RES", r.method, string(data)) api.logger.Debugln("RES", r.method, string(data))
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
return zero, fmt.Errorf("unexpected status code: %d, %s", res.StatusCode, string(data)) return zero, fmt.Errorf("unexpected status code: %d, %s", res.StatusCode, string(data))
} }
return parseBody[R](data)
}
func (r TelegramRequest[R, P]) Do(api *API) (R, error) {
return r.DoWithContext(context.Background(), api)
}
func readBody(body io.ReadCloser) ([]byte, error) {
reader := io.LimitReader(body, 10<<20)
return io.ReadAll(reader)
}
func parseBody[R any](data []byte) (R, error) {
var zero R
var resp ApiResponse[R] var resp ApiResponse[R]
err = json.Unmarshal(data, &resp) err := json.Unmarshal(data, &resp)
if err != nil { if err != nil {
return zero, err return zero, err
} }
@@ -87,9 +134,4 @@ func (r TelegramRequest[R, P]) DoWithContext(ctx context.Context, api *API) (R,
return zero, fmt.Errorf("[%d] %s", resp.ErrorCode, resp.Description) return zero, fmt.Errorf("[%d] %s", resp.ErrorCode, resp.Description)
} }
return resp.Result, nil return resp.Result, nil
}
func (r TelegramRequest[R, P]) Do(api *API) (R, error) {
ctx := context.Background()
return r.DoWithContext(ctx, api)
} }

View File

@@ -3,9 +3,7 @@ package tgapi
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/json"
"fmt" "fmt"
"io"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"path/filepath" "path/filepath"
@@ -53,7 +51,8 @@ func NewUploader(api *API) *Uploader {
logger.AddWriter(logger.CreateJsonStdoutWriter()) logger.AddWriter(logger.CreateJsonStdoutWriter())
return &Uploader{api, logger} return &Uploader{api, logger}
} }
func (u *Uploader) Close() error { return u.logger.Close() } func (u *Uploader) Close() error { return u.logger.Close() }
func (u *Uploader) GetLogger() *slog.Logger { return u.logger }
type UploaderRequest[R, P any] struct { type UploaderRequest[R, P any] struct {
method string method string
@@ -66,39 +65,22 @@ func NewUploaderRequest[R, P any](method string, params P, files ...UploaderFile
} }
func (u UploaderRequest[R, P]) DoWithContext(ctx context.Context, up *Uploader) (R, error) { func (u UploaderRequest[R, P]) DoWithContext(ctx context.Context, up *Uploader) (R, error) {
var zero R var zero R
url := fmt.Sprintf("https://api.telegram.org/bot%s/%s", up.api.token, u.method)
buf := bytes.NewBuffer(nil) buf, contentType, err := prepareMultipart(u.files, u.params)
w := multipart.NewWriter(buf)
for _, file := range u.files {
fw, err := w.CreateFormFile(string(file.field), file.filename)
if err != nil {
_ = w.Close()
return zero, err
}
_, err = fw.Write(file.data)
if err != nil {
_ = w.Close()
return zero, err
}
}
err := utils.Encode(w, u.params)
if err != nil {
_ = w.Close()
return zero, err
}
err = w.Close()
if err != nil { if err != nil {
return zero, err return zero, err
} }
methodPrefix := ""
if up.api.useTestServer {
methodPrefix = "/test"
}
url := fmt.Sprintf("%s/bot%s%s/%s", up.api.apiUrl, up.api.token, methodPrefix, u.method)
req, err := http.NewRequestWithContext(ctx, "POST", url, buf) req, err := http.NewRequestWithContext(ctx, "POST", url, buf)
if err != nil { if err != nil {
return zero, err return zero, err
} }
req.Header.Set("Content-Type", w.FormDataContentType()) req.Header.Set("Content-Type", contentType)
req.Header.Set("Accept", "application/json") req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString)) req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString))
@@ -109,30 +91,45 @@ func (u UploaderRequest[R, P]) DoWithContext(ctx context.Context, up *Uploader)
} }
defer res.Body.Close() defer res.Body.Close()
reader := io.LimitReader(res.Body, 10<<20) body, err := readBody(res.Body)
body, err := io.ReadAll(reader)
if err != nil {
return zero, err
}
up.logger.Debugln("UPLOADER RES", u.method, string(body)) up.logger.Debugln("UPLOADER RES", u.method, string(body))
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
return zero, fmt.Errorf("unexpected status code: %d, %s", res.StatusCode, string(body)) return zero, fmt.Errorf("unexpected status code: %d, %s", res.StatusCode, string(body))
} }
var resp ApiResponse[R] return parseBody[R](body)
err = json.Unmarshal(body, &resp)
if err != nil {
return zero, err
}
if !resp.Ok {
return zero, fmt.Errorf("[%d] %s", resp.ErrorCode, resp.Description)
}
return resp.Result, nil
} }
func (u UploaderRequest[R, P]) Do(up *Uploader) (R, error) { func (u UploaderRequest[R, P]) Do(up *Uploader) (R, error) {
return u.DoWithContext(context.Background(), up) return u.DoWithContext(context.Background(), up)
} }
func prepareMultipart[P any](files []UploaderFile, params P) (*bytes.Buffer, string, error) {
buf := bytes.NewBuffer(nil)
w := multipart.NewWriter(buf)
for _, file := range files {
fw, err := w.CreateFormFile(string(file.field), file.filename)
if err != nil {
_ = w.Close()
return buf, w.FormDataContentType(), err
}
_, err = fw.Write(file.data)
if err != nil {
_ = w.Close()
return buf, w.FormDataContentType(), err
}
}
err := utils.Encode(w, params)
if err != nil {
_ = w.Close()
return buf, w.FormDataContentType(), err
}
err = w.Close()
return buf, w.FormDataContentType(), err
}
func uploaderTypeByExt(filename string) UploaderFileType { func uploaderTypeByExt(filename string) UploaderFileType {
ext := filepath.Ext(filename) ext := filepath.Ext(filename)
switch ext { switch ext {

View File

@@ -3,14 +3,13 @@ package laniakea
import "git.nix13.pw/scuroneko/laniakea/utils" import "git.nix13.pw/scuroneko/laniakea/utils"
func Ptr[T any](v T) *T { return &v } func Ptr[T any](v T) *T { return &v }
func Val[T any](p *T, def T) T { func Val[T any](p *T, def T) T {
if p != nil { if p != nil {
return *p return *p
} }
return def return def
} }
func EscapeMarkdown(s string) string { return utils.EscapeMarkdown(s) }
func EscapeMarkdownV2(s string) string { return utils.EscapeMarkdownV2(s) }
const VersionString = utils.VersionString const VersionString = utils.VersionString
var EscapeMarkdown = utils.EscapeMarkdown

View File

@@ -1,8 +1,9 @@
package utils package utils
const ( const (
VersionString = "0.6.2" VersionString = "0.8.0-beta.1"
VersionMajor = 0 VersionMajor = 0
VersionMinor = 6 VersionMinor = 8
VersionPatch = 2 VersionPatch = 0
Beta = 1
) )