Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
da122a3be4
|
|||
|
1bf7499496
|
|||
|
7b9292557e
|
|||
|
466093e39b
|
277
bot.go
277
bot.go
@@ -10,9 +10,6 @@ import (
|
||||
"git.nix13.pw/scuroneko/extypes"
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
"git.nix13.pw/scuroneko/slog"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/vinovest/sqlx"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
)
|
||||
|
||||
type BotOpts struct {
|
||||
@@ -41,7 +38,6 @@ func LoadOptsFromEnv() *BotOpts {
|
||||
APIUrl: os.Getenv("API_URL"),
|
||||
}
|
||||
}
|
||||
|
||||
func LoadPrefixesFromEnv() []string {
|
||||
prefixesS, exists := os.LookupEnv("PREFIXES")
|
||||
if !exists {
|
||||
@@ -50,7 +46,9 @@ func LoadPrefixesFromEnv() []string {
|
||||
return strings.Split(prefixesS, ";")
|
||||
}
|
||||
|
||||
type Bot struct {
|
||||
type DbContext interface{}
|
||||
type NoDB struct{ DbContext }
|
||||
type Bot[T DbContext] struct {
|
||||
token string
|
||||
debug bool
|
||||
errorTemplate string
|
||||
@@ -58,50 +56,91 @@ type Bot struct {
|
||||
logger *slog.Logger
|
||||
RequestLogger *slog.Logger
|
||||
|
||||
plugins []Plugin
|
||||
middlewares []Middleware
|
||||
plugins []Plugin[T]
|
||||
middlewares []Middleware[T]
|
||||
prefixes []string
|
||||
runners []Runner
|
||||
runners []Runner[T]
|
||||
|
||||
dbContext *DatabaseContext
|
||||
api *tgapi.API
|
||||
l10n L10n
|
||||
uploader *tgapi.Uploader
|
||||
dbContext *T
|
||||
l10n *L10n
|
||||
|
||||
dbWriterRequested extypes.Slice[*slog.Logger]
|
||||
extraLoggers extypes.Slice[*slog.Logger]
|
||||
|
||||
updateOffset int
|
||||
updateTypes []tgapi.UpdateType
|
||||
updateQueue *extypes.Queue[*tgapi.Update]
|
||||
}
|
||||
|
||||
func NewBot(settings *BotOpts) *Bot {
|
||||
updateQueue := extypes.CreateQueue[*tgapi.Update](256)
|
||||
apiOpts := tgapi.NewAPIOpts(settings.Token).SetAPIUrl(settings.APIUrl).UseTestServer(settings.UseTestServer)
|
||||
func NewBot[T any](opts *BotOpts) *Bot[T] {
|
||||
updateQueue := extypes.CreateQueue[*tgapi.Update](512)
|
||||
|
||||
apiOpts := tgapi.NewAPIOpts(opts.Token).SetAPIUrl(opts.APIUrl).UseTestServer(opts.UseTestServer)
|
||||
api := tgapi.NewAPI(apiOpts)
|
||||
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 {
|
||||
bot.errorTemplate = settings.ErrorTemplate
|
||||
}
|
||||
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),
|
||||
extraLoggers: make([]*slog.Logger, 0),
|
||||
l10n: &L10n{},
|
||||
}
|
||||
bot.extraLoggers = bot.extraLoggers.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
|
||||
if settings.Debug {
|
||||
if opts.Debug {
|
||||
level = slog.DEBUG
|
||||
}
|
||||
|
||||
bot.logger = slog.CreateLogger().Level(level).Prefix("BOT")
|
||||
bot.logger.AddWriter(bot.logger.CreateJsonStdoutWriter())
|
||||
if settings.WriteToFile {
|
||||
path := fmt.Sprintf("%s/main.log", strings.TrimRight(settings.LoggerBasePath, "/"))
|
||||
if opts.WriteToFile {
|
||||
path := fmt.Sprintf("%s/main.log", strings.TrimRight(opts.LoggerBasePath, "/"))
|
||||
fileWriter, err := bot.logger.CreateTextFileWriter(path)
|
||||
if err != nil {
|
||||
bot.logger.Fatal(err)
|
||||
@@ -109,11 +148,11 @@ func NewBot(settings *BotOpts) *Bot {
|
||||
bot.logger.AddWriter(fileWriter)
|
||||
}
|
||||
|
||||
if settings.UseRequestLogger {
|
||||
if opts.UseRequestLogger {
|
||||
bot.RequestLogger = slog.CreateLogger().Level(level).Prefix("REQUESTS")
|
||||
bot.RequestLogger.AddWriter(bot.RequestLogger.CreateJsonStdoutWriter())
|
||||
if settings.WriteToFile {
|
||||
path := fmt.Sprintf("%s/requests.log", strings.TrimRight(settings.LoggerBasePath, "/"))
|
||||
if opts.WriteToFile {
|
||||
path := fmt.Sprintf("%s/requests.log", strings.TrimRight(opts.LoggerBasePath, "/"))
|
||||
fileWriter, err := bot.RequestLogger.CreateTextFileWriter(path)
|
||||
if err != nil {
|
||||
bot.logger.Fatal(err)
|
||||
@@ -121,141 +160,114 @@ func NewBot(settings *BotOpts) *Bot {
|
||||
bot.RequestLogger.AddWriter(fileWriter)
|
||||
}
|
||||
}
|
||||
|
||||
u, err := api.GetMe()
|
||||
if err != nil {
|
||||
bot.logger.Fatal(err)
|
||||
}
|
||||
bot.logger.Infof("Authorized as %s\n", u.FirstName)
|
||||
|
||||
func (bot *Bot[T]) GetUpdateOffset() int { return bot.updateOffset }
|
||||
func (bot *Bot[T]) SetUpdateOffset(offset int) { bot.updateOffset = offset }
|
||||
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) }
|
||||
|
||||
type DbLogger[T DbContext] func(db *T) slog.LoggerWriter
|
||||
|
||||
func (bot *Bot[T]) AddDatabaseLoggerWriter(writer DbLogger[T]) *Bot[T] {
|
||||
w := writer(bot.dbContext)
|
||||
bot.logger.AddWriter(w)
|
||||
if bot.RequestLogger != nil {
|
||||
bot.RequestLogger.AddWriter(w)
|
||||
}
|
||||
for _, l := range bot.extraLoggers {
|
||||
l.AddWriter(w)
|
||||
}
|
||||
return bot
|
||||
}
|
||||
|
||||
func (b *Bot) Close() error {
|
||||
err := b.logger.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
func (bot *Bot[T]) DatabaseContext(ctx *T) *Bot[T] {
|
||||
bot.dbContext = ctx
|
||||
return bot
|
||||
}
|
||||
err = b.RequestLogger.Close()
|
||||
return err
|
||||
func (bot *Bot[T]) UpdateTypes(t ...tgapi.UpdateType) *Bot[T] {
|
||||
bot.updateTypes = make([]tgapi.UpdateType, 0)
|
||||
bot.updateTypes = append(bot.updateTypes, t...)
|
||||
return bot
|
||||
}
|
||||
|
||||
func (b *Bot) GetUpdateOffset() int { return b.updateOffset }
|
||||
func (b *Bot) SetUpdateOffset(offset int) { b.updateOffset = offset }
|
||||
func (b *Bot) GetUpdateTypes() []tgapi.UpdateType { return b.updateTypes }
|
||||
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] {
|
||||
bot.updateTypes = append(bot.updateTypes, t...)
|
||||
return bot
|
||||
}
|
||||
|
||||
func (b *Bot) AddDatabaseLogger(writer func(db *DatabaseContext) slog.LoggerWriter) *Bot {
|
||||
w := writer(b.dbContext)
|
||||
b.logger.AddWriter(w)
|
||||
if b.RequestLogger != nil {
|
||||
b.RequestLogger.AddWriter(w)
|
||||
func (bot *Bot[T]) AddPrefixes(prefixes ...string) *Bot[T] {
|
||||
bot.prefixes = append(bot.prefixes, prefixes...)
|
||||
return bot
|
||||
}
|
||||
for _, l := range b.dbWriterRequested {
|
||||
l.AddWriter(w)
|
||||
func (bot *Bot[T]) ErrorTemplate(s string) *Bot[T] {
|
||||
bot.errorTemplate = s
|
||||
return bot
|
||||
}
|
||||
return b
|
||||
func (bot *Bot[T]) Debug(debug bool) *Bot[T] {
|
||||
bot.debug = debug
|
||||
return bot
|
||||
}
|
||||
|
||||
func (b *Bot) DatabaseContext(ctx *DatabaseContext) *Bot {
|
||||
b.dbContext = ctx
|
||||
return b
|
||||
}
|
||||
func (b *Bot) UpdateTypes(t ...tgapi.UpdateType) *Bot {
|
||||
b.updateTypes = make([]tgapi.UpdateType, 0)
|
||||
b.updateTypes = append(b.updateTypes, t...)
|
||||
return b
|
||||
}
|
||||
func (b *Bot) AddUpdateType(t ...tgapi.UpdateType) *Bot {
|
||||
b.updateTypes = append(b.updateTypes, t...)
|
||||
return b
|
||||
}
|
||||
func (b *Bot) AddPrefixes(prefixes ...string) *Bot {
|
||||
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 {
|
||||
func (bot *Bot[T]) AddPlugins(plugin ...*Plugin[T]) *Bot[T] {
|
||||
for _, p := range plugin {
|
||||
b.plugins = append(b.plugins, *p)
|
||||
b.logger.Debugln(fmt.Sprintf("plugins with name \"%s\" registered", p.Name))
|
||||
bot.plugins = append(bot.plugins, *p)
|
||||
bot.logger.Debugln(fmt.Sprintf("plugins with name \"%s\" registered", p.Name))
|
||||
}
|
||||
return b
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) AddMiddleware(middleware ...Middleware) *Bot {
|
||||
b.middlewares = append(b.middlewares, middleware...)
|
||||
func (bot *Bot[T]) AddMiddleware(middleware ...Middleware[T]) *Bot[T] {
|
||||
bot.middlewares = append(bot.middlewares, 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 {
|
||||
first := b.middlewares[i]
|
||||
second := b.middlewares[j]
|
||||
sort.Slice(bot.middlewares, func(i, j int) bool {
|
||||
first := bot.middlewares[i]
|
||||
second := bot.middlewares[j]
|
||||
if first.order == second.order {
|
||||
return first.name < second.name
|
||||
}
|
||||
return first.order < second.order
|
||||
})
|
||||
|
||||
return b
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) AddRunner(runner Runner) *Bot {
|
||||
b.runners = append(b.runners, runner)
|
||||
b.logger.Debugln(fmt.Sprintf("runner with name \"%s\" registered", runner.Name))
|
||||
return b
|
||||
func (bot *Bot[T]) AddRunner(runner Runner[T]) *Bot[T] {
|
||||
bot.runners = append(bot.runners, runner)
|
||||
bot.logger.Debugln(fmt.Sprintf("runner with name \"%s\" registered", runner.name))
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) AddL10n(l L10n) *Bot {
|
||||
b.l10n = l
|
||||
return b
|
||||
}
|
||||
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 (bot *Bot[T]) AddL10n(l *L10n) *Bot[T] {
|
||||
bot.l10n = l
|
||||
return bot
|
||||
}
|
||||
|
||||
func (b *Bot) Run() {
|
||||
if len(b.prefixes) == 0 {
|
||||
b.logger.Fatalln("no prefixes defined")
|
||||
func (bot *Bot[T]) Run() {
|
||||
if len(bot.prefixes) == 0 {
|
||||
bot.logger.Fatalln("no prefixes defined")
|
||||
return
|
||||
}
|
||||
|
||||
if len(b.plugins) == 0 {
|
||||
b.logger.Fatalln("no plugins defined")
|
||||
if len(bot.plugins) == 0 {
|
||||
bot.logger.Fatalln("no plugins defined")
|
||||
return
|
||||
}
|
||||
|
||||
b.ExecRunners()
|
||||
bot.ExecRunners()
|
||||
|
||||
b.logger.Infoln("Bot running. Press CTRL+C to exit.")
|
||||
bot.logger.Infoln("Bot running. Press CTRL+C to exit.")
|
||||
go func() {
|
||||
for {
|
||||
_, err := b.Updates()
|
||||
_, err := bot.Updates()
|
||||
if err != nil {
|
||||
b.logger.Errorln(err)
|
||||
bot.logger.Errorln(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
queue := b.updateQueue
|
||||
queue := bot.updateQueue
|
||||
if queue.IsEmpty() {
|
||||
time.Sleep(time.Millisecond * 25)
|
||||
continue
|
||||
@@ -263,19 +275,10 @@ func (b *Bot) Run() {
|
||||
|
||||
u := queue.Dequeue()
|
||||
if u == nil {
|
||||
b.logger.Errorln("update is nil")
|
||||
bot.logger.Errorln("update is nil")
|
||||
continue
|
||||
}
|
||||
|
||||
ctx := &MsgContext{Bot: b, Update: *u, Api: b.api}
|
||||
for _, middleware := range b.middlewares {
|
||||
middleware.Execute(ctx, b.dbContext)
|
||||
}
|
||||
|
||||
if u.CallbackQuery != nil {
|
||||
b.handleCallback(u, ctx)
|
||||
} else {
|
||||
b.handleMessage(u, ctx)
|
||||
}
|
||||
bot.handle(u)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
)
|
||||
|
||||
func generateBotCommand(cmd Command) tgapi.BotCommand {
|
||||
func generateBotCommand[T any](cmd Command[T]) tgapi.BotCommand {
|
||||
desc := cmd.command
|
||||
if len(cmd.description) > 0 {
|
||||
desc = cmd.description
|
||||
@@ -25,7 +25,7 @@ func generateBotCommand(cmd Command) tgapi.BotCommand {
|
||||
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)
|
||||
for _, cmd := range pl.Commands {
|
||||
if cmd.skipAutoCmd {
|
||||
@@ -38,14 +38,14 @@ func generateBotCommandForPlugin(pl Plugin) []tgapi.BotCommand {
|
||||
|
||||
var ErrTooManyCommands = errors.New("too many commands. max 100")
|
||||
|
||||
func (b *Bot) AutoGenerateCommands() error {
|
||||
_, err := b.api.DeleteMyCommands(tgapi.DeleteMyCommandsP{})
|
||||
func (bot *Bot[T]) AutoGenerateCommands() error {
|
||||
_, err := bot.api.DeleteMyCommands(tgapi.DeleteMyCommandsP{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
commands := make([]tgapi.BotCommand, 0)
|
||||
for _, pl := range b.plugins {
|
||||
for _, pl := range bot.plugins {
|
||||
commands = append(commands, generateBotCommandForPlugin(pl)...)
|
||||
}
|
||||
if len(commands) > 100 {
|
||||
@@ -55,14 +55,14 @@ func (b *Bot) AutoGenerateCommands() error {
|
||||
privateChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopePrivateType}
|
||||
groupChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopeGroupType}
|
||||
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 {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
_, err = b.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: chatAdminsScope})
|
||||
_, err = bot.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: chatAdminsScope})
|
||||
return err
|
||||
}
|
||||
|
||||
16
go.mod
16
go.mod
@@ -5,27 +5,11 @@ go 1.26
|
||||
require (
|
||||
git.nix13.pw/scuroneko/extypes v1.2.0
|
||||
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 (
|
||||
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/klauspost/compress v1.18.4 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // 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/text v0.34.0 // indirect
|
||||
)
|
||||
|
||||
82
go.sum
82
go.sum
@@ -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/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/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/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/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/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.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
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=
|
||||
|
||||
36
handler.go
36
handler.go
@@ -8,20 +8,20 @@ import (
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
)
|
||||
|
||||
func (b *Bot) handle(u *tgapi.Update) {
|
||||
ctx := &MsgContext{Bot: b, Update: *u, Api: b.api}
|
||||
for _, middleware := range b.middlewares {
|
||||
middleware.Execute(ctx, b.dbContext)
|
||||
func (bot *Bot[T]) handle(u *tgapi.Update) {
|
||||
ctx := &MsgContext{Update: *u, Api: bot.api, botLogger: bot.logger, errorTemplate: bot.errorTemplate, l10n: bot.l10n}
|
||||
for _, middleware := range bot.middlewares {
|
||||
middleware.Execute(ctx, bot.dbContext)
|
||||
}
|
||||
|
||||
if u.CallbackQuery != nil {
|
||||
b.handleCallback(u, ctx)
|
||||
bot.handleCallback(u, ctx)
|
||||
} 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 {
|
||||
return
|
||||
}
|
||||
@@ -34,7 +34,7 @@ func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) {
|
||||
}
|
||||
|
||||
text = strings.TrimSpace(text)
|
||||
prefix, hasPrefix := b.checkPrefixes(text)
|
||||
prefix, hasPrefix := bot.checkPrefixes(text)
|
||||
if !hasPrefix {
|
||||
return
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) {
|
||||
|
||||
text = strings.TrimSpace(text[len(prefix):])
|
||||
|
||||
for _, plugin := range b.plugins {
|
||||
for _, plugin := range bot.plugins {
|
||||
for cmd := range plugin.Commands {
|
||||
if !strings.HasPrefix(text, cmd) {
|
||||
continue
|
||||
@@ -71,20 +71,20 @@ func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) {
|
||||
ctx.Args = strings.Split(ctx.Text, " ")
|
||||
}
|
||||
|
||||
if !plugin.executeMiddlewares(ctx, b.dbContext) {
|
||||
if !plugin.executeMiddlewares(ctx, bot.dbContext) {
|
||||
return
|
||||
}
|
||||
go plugin.executeCmd(cmd, ctx, b.dbContext)
|
||||
go plugin.executeCmd(cmd, ctx, bot.dbContext)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) handleCallback(update *tgapi.Update, ctx *MsgContext) {
|
||||
func (bot *Bot[T]) handleCallback(update *tgapi.Update, ctx *MsgContext) {
|
||||
data := new(CallbackData)
|
||||
err := json.Unmarshal([]byte(update.CallbackQuery.Data), data)
|
||||
if err != nil {
|
||||
b.logger.Errorln(err)
|
||||
bot.logger.Errorln(err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -95,22 +95,22 @@ func (b *Bot) handleCallback(update *tgapi.Update, ctx *MsgContext) {
|
||||
ctx.CallbackQueryId = update.CallbackQuery.ID
|
||||
ctx.Args = data.Args
|
||||
|
||||
for _, plugin := range b.plugins {
|
||||
for _, plugin := range bot.plugins {
|
||||
_, ok := plugin.Payloads[data.Command]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if !plugin.executeMiddlewares(ctx, b.dbContext) {
|
||||
if !plugin.executeMiddlewares(ctx, bot.dbContext) {
|
||||
return
|
||||
}
|
||||
go plugin.executePayload(data.Command, ctx, b.dbContext)
|
||||
go plugin.executePayload(data.Command, ctx, bot.dbContext)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) checkPrefixes(text string) (string, bool) {
|
||||
for _, prefix := range b.prefixes {
|
||||
func (bot *Bot[T]) checkPrefixes(text string) (string, bool) {
|
||||
for _, prefix := range bot.prefixes {
|
||||
if strings.HasPrefix(text, prefix) {
|
||||
return prefix, true
|
||||
}
|
||||
|
||||
1
l10n.go
1
l10n.go
@@ -17,7 +17,6 @@ func (l *L10n) AddDictEntry(key string, value DictEntry) *L10n {
|
||||
func (l *L10n) GetFallbackLanguage() string {
|
||||
return l.fallbackLang
|
||||
}
|
||||
|
||||
func (l *L10n) Translate(lang, key string) string {
|
||||
s, ok := l.entries[key]
|
||||
if !ok {
|
||||
|
||||
31
methods.go
31
methods.go
@@ -2,50 +2,37 @@ package laniakea
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
)
|
||||
|
||||
func (b *Bot) Updates() ([]tgapi.Update, error) {
|
||||
offset := b.GetUpdateOffset()
|
||||
func (bot *Bot[T]) Updates() ([]tgapi.Update, error) {
|
||||
offset := bot.GetUpdateOffset()
|
||||
params := tgapi.UpdateParams{
|
||||
Offset: Ptr(offset),
|
||||
Timeout: Ptr(30),
|
||||
AllowedUpdates: b.GetUpdateTypes(),
|
||||
AllowedUpdates: bot.GetUpdateTypes(),
|
||||
}
|
||||
|
||||
updates, err := b.api.GetUpdates(params)
|
||||
updates, err := bot.api.GetUpdates(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, u := range updates {
|
||||
b.SetUpdateOffset(u.UpdateID + 1)
|
||||
err = b.GetQueue().Enqueue(&u)
|
||||
bot.SetUpdateOffset(u.UpdateID + 1)
|
||||
err = bot.GetQueue().Enqueue(&u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if b.RequestLogger != nil {
|
||||
if bot.RequestLogger != nil {
|
||||
j, err := json.Marshal(u)
|
||||
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
|
||||
}
|
||||
|
||||
func (b *Bot) GetFileByLink(link string) ([]byte, error) {
|
||||
u := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", b.token, link)
|
||||
res, err := http.Get(u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
return io.ReadAll(res.Body)
|
||||
}
|
||||
|
||||
@@ -5,10 +5,10 @@ import (
|
||||
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
"git.nix13.pw/scuroneko/laniakea/utils"
|
||||
"git.nix13.pw/scuroneko/slog"
|
||||
)
|
||||
|
||||
type MsgContext struct {
|
||||
Bot *Bot
|
||||
Api *tgapi.API
|
||||
|
||||
Msg *tgapi.Message
|
||||
@@ -20,6 +20,10 @@ type MsgContext struct {
|
||||
Prefix string
|
||||
Text string
|
||||
Args []string
|
||||
|
||||
errorTemplate string
|
||||
botLogger *slog.Logger
|
||||
l10n *L10n
|
||||
}
|
||||
|
||||
type AnswerMessage struct {
|
||||
@@ -41,7 +45,7 @@ func (ctx *MsgContext) edit(messageId int, text string, keyboard *InlineKeyboard
|
||||
}
|
||||
msg, _, err := ctx.Api.EditMessageText(params)
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
return nil
|
||||
}
|
||||
return &AnswerMessage{
|
||||
@@ -53,7 +57,7 @@ func (m *AnswerMessage) Edit(text string) *AnswerMessage {
|
||||
}
|
||||
func (ctx *MsgContext) EditCallback(text string, keyboard *InlineKeyboard) *AnswerMessage {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -75,7 +79,7 @@ func (ctx *MsgContext) editPhotoText(messageId int, text string, kb *InlineKeybo
|
||||
}
|
||||
msg, _, err := ctx.Api.EditMessageCaption(params)
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
}
|
||||
return &AnswerMessage{
|
||||
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 {
|
||||
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.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)
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
return nil
|
||||
}
|
||||
return &AnswerMessage{
|
||||
@@ -133,7 +137,7 @@ func (ctx *MsgContext) answerPhoto(photoId, text string, kb *InlineKeyboard) *An
|
||||
}
|
||||
msg, err := ctx.Api.SendPhoto(params)
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
return &AnswerMessage{
|
||||
ctx: ctx, Text: text, IsMedia: true,
|
||||
}
|
||||
@@ -155,7 +159,7 @@ func (ctx *MsgContext) delete(messageId int) {
|
||||
MessageID: messageId,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
}
|
||||
}
|
||||
func (m *AnswerMessage) Delete() {
|
||||
@@ -174,7 +178,7 @@ func (ctx *MsgContext) answerCallbackQuery(url, text string, showAlert bool) {
|
||||
Text: text, ShowAlert: showAlert, URL: url,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
}
|
||||
}
|
||||
func (ctx *MsgContext) AnswerCbQuery() {
|
||||
@@ -195,19 +199,19 @@ func (ctx *MsgContext) SendAction(action tgapi.ChatActionType) {
|
||||
ChatID: ctx.Msg.Chat.ID, Action: action,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
}
|
||||
}
|
||||
|
||||
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 != "" {
|
||||
ctx.answerCallbackQuery("", text, false)
|
||||
} else {
|
||||
ctx.answer(text, nil)
|
||||
}
|
||||
ctx.Bot.Logger().Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
}
|
||||
func (ctx *MsgContext) Error(err error) {
|
||||
ctx.error(err)
|
||||
@@ -217,6 +221,6 @@ func (ctx *MsgContext) Translate(key string) string {
|
||||
if ctx.From == nil {
|
||||
return key
|
||||
}
|
||||
lang := Val(ctx.From.LanguageCode, ctx.Bot.l10n.GetFallbackLanguage())
|
||||
return ctx.Bot.L10n(lang, key)
|
||||
lang := Val(ctx.From.LanguageCode, ctx.l10n.GetFallbackLanguage())
|
||||
return ctx.l10n.Translate(lang, key)
|
||||
}
|
||||
|
||||
67
plugins.go
67
plugins.go
@@ -45,32 +45,33 @@ func (c *CommandArg) SetRequired() *CommandArg {
|
||||
return c
|
||||
}
|
||||
|
||||
type CommandExecutor func(ctx *MsgContext, dbContext *DatabaseContext)
|
||||
type Command struct {
|
||||
type CommandExecutor[T DbContext] func(ctx *MsgContext, dbContext *T)
|
||||
|
||||
type Command[T DbContext] struct {
|
||||
command string
|
||||
description string
|
||||
exec CommandExecutor
|
||||
exec CommandExecutor[T]
|
||||
args extypes.Slice[CommandArg]
|
||||
middlewares extypes.Slice[Middleware]
|
||||
middlewares extypes.Slice[Middleware[T]]
|
||||
skipAutoCmd bool
|
||||
}
|
||||
|
||||
func NewCommand(exec CommandExecutor, command string, args ...CommandArg) *Command {
|
||||
return &Command{command, "", exec, args, make(extypes.Slice[Middleware], 0), false}
|
||||
func NewCommand[T any](exec CommandExecutor[T], command string, args ...CommandArg) *Command[T] {
|
||||
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)
|
||||
return c
|
||||
}
|
||||
func (c *Command) SetDescription(desc string) *Command {
|
||||
func (c *Command[T]) SetDescription(desc string) *Command[T] {
|
||||
c.description = desc
|
||||
return c
|
||||
}
|
||||
func (c *Command) SkipCommandAutoGen() *Command {
|
||||
func (c *Command[T]) SkipCommandAutoGen() *Command[T] {
|
||||
c.skipAutoCmd = true
|
||||
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 })
|
||||
if len(args) < cmdArgs.Len() {
|
||||
return ErrCmdArgCountMismatch
|
||||
@@ -91,37 +92,37 @@ func (c *Command) validateArgs(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type Plugin struct {
|
||||
type Plugin[T DbContext] struct {
|
||||
Name string
|
||||
Commands map[string]Command
|
||||
Payloads map[string]Command
|
||||
Middlewares extypes.Slice[Middleware]
|
||||
Commands map[string]Command[T]
|
||||
Payloads map[string]Command[T]
|
||||
Middlewares extypes.Slice[Middleware[T]]
|
||||
}
|
||||
|
||||
func NewPlugin(name string) *Plugin {
|
||||
return &Plugin{
|
||||
name, map[string]Command{},
|
||||
map[string]Command{}, extypes.Slice[Middleware]{},
|
||||
func NewPlugin[T DbContext](name string) *Plugin[T] {
|
||||
return &Plugin[T]{
|
||||
name, map[string]Command[T]{},
|
||||
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
|
||||
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...)
|
||||
}
|
||||
func (p *Plugin) AddPayload(command *Command) *Plugin {
|
||||
func (p *Plugin[T]) AddPayload(command *Command[T]) *Plugin[T] {
|
||||
p.Payloads[command.command] = *command
|
||||
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)
|
||||
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]
|
||||
if err := command.validateArgs(ctx.Args); err != nil {
|
||||
ctx.error(err)
|
||||
@@ -129,7 +130,7 @@ func (p *Plugin) executeCmd(cmd string, ctx *MsgContext, dbContext *DatabaseCont
|
||||
}
|
||||
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]
|
||||
if err := pl.validateArgs(ctx.Args); err != nil {
|
||||
ctx.error(err)
|
||||
@@ -137,7 +138,7 @@ func (p *Plugin) executePayload(payload string, ctx *MsgContext, dbContext *Data
|
||||
}
|
||||
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 {
|
||||
if !m.Execute(ctx, db) {
|
||||
return false
|
||||
@@ -146,29 +147,29 @@ func (p *Plugin) executeMiddlewares(ctx *MsgContext, db *DatabaseContext) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
type MiddlewareExecutor func(ctx *MsgContext, db *DatabaseContext) bool
|
||||
type MiddlewareExecutor[T DbContext] func(ctx *MsgContext, db *T) bool
|
||||
|
||||
// Middleware
|
||||
// When async, returned value ignored
|
||||
type Middleware struct {
|
||||
type Middleware[T DbContext] struct {
|
||||
name string
|
||||
executor MiddlewareExecutor
|
||||
executor MiddlewareExecutor[T]
|
||||
order int
|
||||
async bool
|
||||
}
|
||||
|
||||
func NewMiddleware(name string, executor MiddlewareExecutor) *Middleware {
|
||||
return &Middleware{name, executor, 0, false}
|
||||
func NewMiddleware[T DbContext](name string, executor MiddlewareExecutor[T]) *Middleware[T] {
|
||||
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
|
||||
return m
|
||||
}
|
||||
func (m *Middleware) SetAsync(async bool) *Middleware {
|
||||
func (m *Middleware[T]) SetAsync(async bool) *Middleware[T] {
|
||||
m.async = async
|
||||
return m
|
||||
}
|
||||
func (m *Middleware) Execute(ctx *MsgContext, db *DatabaseContext) bool {
|
||||
func (m *Middleware[T]) Execute(ctx *MsgContext, db *T) bool {
|
||||
if m.async {
|
||||
go m.executor(ctx, db)
|
||||
return true
|
||||
|
||||
64
runners.go
64
runners.go
@@ -4,81 +4,69 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type RunnerFn func(*Bot) error
|
||||
type RunnerBuilder struct {
|
||||
type RunnerFn[T DbContext] func(*Bot[T]) error
|
||||
type Runner[T DbContext] struct {
|
||||
name string
|
||||
onetime bool
|
||||
async bool
|
||||
timeout time.Duration
|
||||
fn RunnerFn
|
||||
}
|
||||
type Runner struct {
|
||||
Name string
|
||||
Onetime bool
|
||||
Async bool
|
||||
Timeout time.Duration
|
||||
Fn RunnerFn
|
||||
fn RunnerFn[T]
|
||||
}
|
||||
|
||||
func NewRunner(name string, fn RunnerFn) *RunnerBuilder {
|
||||
return &RunnerBuilder{
|
||||
func NewRunner[T DbContext](name string, fn RunnerFn[T]) *Runner[T] {
|
||||
return &Runner[T]{
|
||||
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
|
||||
return b
|
||||
}
|
||||
func (b *RunnerBuilder) Async(async bool) *RunnerBuilder {
|
||||
func (b *Runner[T]) Async(async bool) *Runner[T] {
|
||||
b.async = async
|
||||
return b
|
||||
}
|
||||
func (b *RunnerBuilder) Timeout(timeout time.Duration) *RunnerBuilder {
|
||||
func (b *Runner[T]) Timeout(timeout time.Duration) *Runner[T] {
|
||||
b.timeout = timeout
|
||||
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() {
|
||||
b.logger.Infoln("Executing runners...")
|
||||
for _, runner := range b.runners {
|
||||
if !runner.Onetime && !runner.Async {
|
||||
b.logger.Warnf("Runner %s not onetime, but sync\n", runner.Name)
|
||||
func (bot *Bot[T]) ExecRunners() {
|
||||
bot.logger.Infoln("Executing runners...")
|
||||
for _, runner := range bot.runners {
|
||||
if !runner.onetime && !runner.async {
|
||||
bot.logger.Warnf("Runner %s not onetime, but sync\n", runner.name)
|
||||
continue
|
||||
}
|
||||
if !runner.Onetime && runner.Async && runner.Timeout == (time.Second*0) {
|
||||
b.logger.Warnf("Background runner \"%s\" should have timeout", runner.Name)
|
||||
if !runner.onetime && runner.async && runner.timeout == (time.Second*0) {
|
||||
bot.logger.Warnf("Background runner \"%s\" should have timeout", runner.name)
|
||||
}
|
||||
|
||||
if runner.Async && runner.Onetime {
|
||||
if runner.async && runner.onetime {
|
||||
go func() {
|
||||
err := runner.Fn(b)
|
||||
err := runner.fn(bot)
|
||||
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()
|
||||
err := runner.Fn(b)
|
||||
err := runner.fn(bot)
|
||||
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)
|
||||
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() {
|
||||
for {
|
||||
err := runner.Fn(b)
|
||||
err := runner.fn(bot)
|
||||
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)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
12
tgapi/api.go
12
tgapi/api.go
@@ -43,7 +43,7 @@ func (opts *APIOpts) SetAPIUrl(apiUrl string) *APIOpts {
|
||||
type API struct {
|
||||
token string
|
||||
client *http.Client
|
||||
Logger *slog.Logger
|
||||
logger *slog.Logger
|
||||
useTestServer bool
|
||||
apiUrl string
|
||||
}
|
||||
@@ -57,9 +57,8 @@ func NewAPI(opts *APIOpts) *API {
|
||||
}
|
||||
return &API{opts.token, client, l, opts.useTestServer, opts.apiUrl}
|
||||
}
|
||||
func (api *API) CloseApi() error {
|
||||
return api.Logger.Close()
|
||||
}
|
||||
func (api *API) CloseApi() error { return api.logger.Close() }
|
||||
func (api *API) GetLogger() *slog.Logger { return api.logger }
|
||||
|
||||
type ApiResponse[R any] struct {
|
||||
Ok bool `json:"ok"`
|
||||
@@ -67,7 +66,6 @@ type ApiResponse[R any] struct {
|
||||
Result R `json:"result,omitempty"`
|
||||
ErrorCode int `json:"error_code,omitempty"`
|
||||
}
|
||||
|
||||
type TelegramRequest[R, P any] struct {
|
||||
method string
|
||||
params P
|
||||
@@ -97,7 +95,7 @@ func (r TelegramRequest[R, P]) DoWithContext(ctx context.Context, api *API) (R,
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString))
|
||||
|
||||
api.Logger.Debugln("REQ", api.apiUrl, r.method, buf.String())
|
||||
api.logger.Debugln("REQ", api.apiUrl, r.method, buf.String())
|
||||
res, err := api.client.Do(req)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
@@ -110,7 +108,7 @@ func (r TelegramRequest[R, P]) DoWithContext(ctx context.Context, api *API) (R,
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
api.Logger.Debugln("RES", r.method, string(data))
|
||||
api.logger.Debugln("RES", r.method, string(data))
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return zero, fmt.Errorf("unexpected status code: %d, %s", res.StatusCode, string(data))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
package tgapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ParseMode string
|
||||
|
||||
const (
|
||||
@@ -44,3 +50,13 @@ func (api *API) GetFile(params GetFileP) (File, error) {
|
||||
req := NewRequest[File]("getFile", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
func (api *API) GetFileByLink(link string) ([]byte, error) {
|
||||
u := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", api.token, link)
|
||||
res, err := http.Get(u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
return io.ReadAll(res.Body)
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ func NewUploader(api *API) *Uploader {
|
||||
return &Uploader{api, logger}
|
||||
}
|
||||
func (u *Uploader) Close() error { return u.logger.Close() }
|
||||
func (u *Uploader) GetLogger() *slog.Logger { return u.logger }
|
||||
|
||||
type UploaderRequest[R, P any] struct {
|
||||
method string
|
||||
|
||||
5
utils.go
5
utils.go
@@ -3,14 +3,13 @@ package laniakea
|
||||
import "git.nix13.pw/scuroneko/laniakea/utils"
|
||||
|
||||
func Ptr[T any](v T) *T { return &v }
|
||||
|
||||
func Val[T any](p *T, def T) T {
|
||||
if p != nil {
|
||||
return *p
|
||||
}
|
||||
return def
|
||||
}
|
||||
func EscapeMarkdown(s string) string { return utils.EscapeMarkdown(s) }
|
||||
func EscapeMarkdownV2(s string) string { return utils.EscapeMarkdownV2(s) }
|
||||
|
||||
const VersionString = utils.VersionString
|
||||
|
||||
var EscapeMarkdown = utils.EscapeMarkdown
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package utils
|
||||
|
||||
const (
|
||||
VersionString = "0.6.2"
|
||||
VersionString = "0.8.0-beta.3"
|
||||
VersionMajor = 0
|
||||
VersionMinor = 6
|
||||
VersionPatch = 2
|
||||
VersionMinor = 8
|
||||
VersionPatch = 0
|
||||
Beta = 3
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user