initial commit

This commit is contained in:
abelith committed 2026-10-02 00:48:55 +03:00
commit bec2cfd017
18 files changed
+781

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
.idea
*.env
View File
Whitespace-only changes.
+7
View File
@@ -0,0 +1,7 @@
Copyright 2026 abelith
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+1
View File
@@ -0,0 +1 @@
**gomax** is a framework for MAX BotAPI, originating from [github.com/abelith/etu-bot/pkg/maxlib](https://github.com/abelith/etu-bot/tree/main/pkg/maxlib)
+96
View File
@@ -0,0 +1,96 @@
package context
import (
"context"
"github.com/abelith/gomax/state"
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
"github.com/max-messenger/max-bot-api-client-go/v2/model"
"time"
)
type Context struct {
ctx context.Context
upd model.Update
state *state.Context
api *maxbot.Api
}
type Option interface {
applyOption(opts *msgOptions)
}
type msgOptions struct {
kb *model.Keyboard
}
type responseOptionWrapper struct {
fn func(options *msgOptions)
}
func New(ctx context.Context, upd model.Update, state *state.Context, api *maxbot.Api) *Context {
return &Context{
ctx: ctx,
upd: upd,
state: state,
api: api,
}
}
func (c *Context) Context() context.Context {
return c.ctx
}
func (c *Context) SetContext(ctx context.Context) {
c.ctx = ctx
}
func (c *Context) State() *state.Context {
return c.state
}
func (c *Context) Update() model.Update {
return c.upd
}
func (c *Context) Respond(text string, opts ...Option) error {
msg := maxbot.NewMessage().
SetChat(c.upd.ChatID).
SetUser(c.upd.UserID).
SetText(text)
var cfg msgOptions
for _, opt := range opts {
opt.applyOption(&cfg)
}
if cfg.kb != nil {
msg.AddKeyboard(cfg.kb)
}
_, err := c.api.Messages.Send(c.ctx, msg)
return err
}
func (c *Context) Deadline() (deadline time.Time, ok bool) {
return c.ctx.Deadline()
}
func (c *Context) Done() <-chan struct{} {
return c.ctx.Done()
}
func (c *Context) Err() error {
return c.ctx.Err()
}
func (c *Context) Value(key any) any {
return c.ctx.Value(key)
}
func (w responseOptionWrapper) applyOption(cfg *msgOptions) {
w.fn(cfg)
}
func newOption(fn func(options *msgOptions)) Option {
return responseOptionWrapper{fn: fn}
}
+9
View File
@@ -0,0 +1,9 @@
package context
import "github.com/max-messenger/max-bot-api-client-go/v2/model"
func WithKeyboard(kb *model.Keyboard) Option {
return newOption(func(opts *msgOptions) {
opts.kb = kb
})
}
+118
View File
@@ -0,0 +1,118 @@
package core
import (
"context"
"errors"
mcontext "github.com/abelith/gomax/context"
"github.com/abelith/gomax/state"
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
"github.com/max-messenger/max-bot-api-client-go/v2/model"
"github.com/rs/zerolog/log"
"time"
)
type FSMStorage interface {
Get(ctx context.Context, userID int) (state.Snapshot, error)
Put(ctx context.Context, state state.Snapshot) error
Delete(ctx context.Context, userID int) error
}
type UpdateHandler interface {
HandleUpdate(c *mcontext.Context) error
Use(mw ...Middleware)
}
type Dispatcher struct {
PollInterval time.Duration
Api *maxbot.Api
Handler UpdateHandler
FSMStorage FSMStorage
}
func (d *Dispatcher) getUpdates(ctx context.Context) <-chan model.Update {
var updates []model.Update
var marker int64
var err error
ch := make(chan model.Update)
go func() {
defer close(ch)
for {
select {
case <-ctx.Done():
return
case <-time.Tick(d.PollInterval):
start := time.Now()
updates, marker, err = d.Api.Subscriptions.GetUpdates(ctx, marker)
latency := time.Since(start)
if err != nil && !errors.Is(err, context.Canceled) {
log.Error().Err(err).Send()
}
log.Ctx(ctx).Debug().
Int("received", len(updates)).
Dur("latency", latency).
Msg("received updates")
for _, update := range updates {
select {
case <-ctx.Done():
return
case ch <- update:
}
}
}
}
}()
return ch
}
func (d *Dispatcher) handleUpdates(ch <-chan model.Update) {
for update := range ch {
go d.handleUpdate(update)
}
}
func (d *Dispatcher) StartPolling(ctx context.Context) {
d.handleUpdates(d.getUpdates(ctx))
<-ctx.Done()
}
func (d *Dispatcher) handleUpdate(upd model.Update) {
ctx := context.Background()
var st *state.Context
snapshot, err := d.FSMStorage.Get(ctx, int(upd.UserID))
if err != nil && !errors.Is(err, state.ErrStateNotFound) {
log.Error().Err(err).Send()
return
}
if errors.Is(err, state.ErrStateNotFound) {
st = state.New(int(upd.UserID))
} else {
st = state.Restore(snapshot)
}
c := mcontext.New(ctx, upd, st, d.Api)
if err := d.Handler.HandleUpdate(c); err != nil {
log.Error().Err(err).Send()
return
}
st = c.State()
if st.State() == state.ClearState {
if err := d.FSMStorage.Delete(ctx, int(upd.UserID)); err != nil {
log.Error().Err(err).Send()
return
}
}
if st.State() != "" {
if err := d.FSMStorage.Put(ctx, st.Snapshot()); err != nil {
log.Error().Err(err).Send()
return
}
}
}
+7
View File
@@ -0,0 +1,7 @@
package core
import "fmt"
var (
ErrRouteNotFound = fmt.Errorf("route not foun")
)
+13
View File
@@ -0,0 +1,13 @@
package core
import mcontext "github.com/abelith/gomax/context"
type HandlerFunc func(c *mcontext.Context) error
func (h HandlerFunc) HandleUpdate(c *mcontext.Context) error {
return h(c)
}
func (h HandlerFunc) Use(_ ...Middleware) {
panic("HandlerFunc.Use must never be called")
}
+72
View File
@@ -0,0 +1,72 @@
package core
import (
"errors"
mcontext "github.com/abelith/gomax/context"
)
type Middleware func(next HandlerFunc) HandlerFunc
type Filter func(c *mcontext.Context) bool
type route struct {
h UpdateHandler
filters []func(c *mcontext.Context) bool
}
type Router struct {
routes []route
mw []Middleware
}
func (r *Router) HandleUpdate(c *mcontext.Context) error {
var current HandlerFunc = r.dispatch
for i := len(r.mw) - 1; i >= 0; i-- {
current = r.mw[i](current)
}
return current.HandleUpdate(c)
}
func (r *Router) Use(mws ...Middleware) {
r.mw = append(r.mw, mws...)
}
func (r *Router) HandleFunc(h HandlerFunc, filters ...func(c *mcontext.Context) bool) {
r.routes = append(r.routes, route{
h: h,
filters: filters,
})
}
func (r *Router) Handle(h UpdateHandler, filters ...func(c *mcontext.Context) bool) {
r.routes = append(r.routes, route{
h: h,
filters: filters,
})
}
func (r *Router) dispatch(c *mcontext.Context) error {
for _, rt := range r.routes {
if match(rt.filters, c) {
err := rt.h.HandleUpdate(c)
if errors.Is(err, ErrRouteNotFound) {
continue
}
return err
}
}
return ErrRouteNotFound
}
func match(filters []func(c *mcontext.Context) bool, c *mcontext.Context) bool {
for _, filter := range filters {
if !filter(c) {
return false
}
}
return true
}
+17
View File
@@ -0,0 +1,17 @@
package errors
type GomaxError struct {
Message string
Err error
}
func (ge *GomaxError) Error() string {
return ge.Err.Error()
}
func New(parent error, text string) error {
return &GomaxError{
Message: text,
Err: parent,
}
}
+118
View File
@@ -0,0 +1,118 @@
package filters
import (
mcontext "github.com/abelith/gomax/context"
"github.com/abelith/gomax/core"
"github.com/abelith/gomax/state"
"github.com/max-messenger/max-bot-api-client-go/v2/model"
"regexp"
"strings"
)
type CallbackFilter core.Filter
func StartCommand() core.Filter {
return func(c *mcontext.Context) bool {
upd := c.Update()
if upd.UpdateType == model.UpdateBotStarted {
return true
}
return strings.HasPrefix(upd.GetCommand().Command, "/start")
}
}
func Command(cmd string) core.Filter {
return func(c *mcontext.Context) bool {
upd := c.Update()
return upd.UpdateType == model.UpdateMessageCreated && strings.HasPrefix(upd.GetCommand().Command, cmd)
}
}
func State(state state.State) core.Filter {
return func(c *mcontext.Context) bool {
return c.State().State() == state
}
}
func MessageText(s string) core.Filter {
return func(c *mcontext.Context) bool {
if msg := c.Update().Message; msg != nil {
return s == msg.Body.Text
}
return false
}
}
func MessageTextRe(re *regexp.Regexp) core.Filter {
return func(c *mcontext.Context) bool {
if msg := c.Update().Message; msg != nil {
s := strings.TrimSpace(msg.Body.Text)
return re.MatchString(s)
}
return false
}
}
func MessageGeo() core.Filter {
return func(c *mcontext.Context) bool {
if c.Update().Message == nil {
return false
}
for _, attachment := range c.Update().Message.Body.Attachments {
if attachment.Type == model.AttachLocation {
return true
}
}
return false
}
}
func BotStopped() core.Filter {
return func(c *mcontext.Context) bool {
return c.Update().UpdateType == model.UpdateBotStopped
}
}
func Or(filters ...core.Filter) core.Filter {
return func(c *mcontext.Context) bool {
for _, filter := range filters {
if filter(c) {
return true
}
}
return false
}
}
func Message() core.Filter {
return func(c *mcontext.Context) bool {
return c.Update().UpdateType == model.UpdateMessageCreated && c.Update().Message != nil
}
}
func Callback() CallbackFilter {
return func(c *mcontext.Context) bool {
return c.Update().UpdateType == model.UpdateMessageCallback
}
}
func (cf CallbackFilter) StartsWith(prefix string) CallbackFilter {
return func(c *mcontext.Context) bool {
if !cf(c) {
return false
}
payload, ok := getCallbackPayload(c)
return ok && strings.HasPrefix(payload, prefix)
}
}
func getCallbackPayload(c *mcontext.Context) (string, bool) {
upd := c.Update()
if upd.Callback == nil {
return "", false
}
return upd.Callback.Payload, true
}
+14
View File
@@ -0,0 +1,14 @@
module github.com/abelith/gomax
go 1.26.8
require (
github.com/max-messenger/max-bot-api-client-go/v2 v2.4.1
github.com/rs/zerolog v1.35.1
)
require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
golang.org/x/sys v0.29.0 // indirect
)
+15
View File
@@ -0,0 +1,15 @@
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/max-messenger/max-bot-api-client-go/v2 v2.4.1 h1:HFtlpKMMuktl22VW7zPwM9Brx8k810gIuLvaBF+0w2w=
github.com/max-messenger/max-bot-api-client-go/v2 v2.4.1/go.mod h1:+jiRkKZlmKeqSN+MY033xkv+j5hfDFlPX961k8a58F0=
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+1
View File
@@ -0,0 +1 @@
package gomax
+59
View File
@@ -0,0 +1,59 @@
package middleware
import (
"errors"
mcontext "github.com/abelith/gomax/context"
"github.com/abelith/gomax/core"
merrors "github.com/abelith/gomax/errors"
"github.com/rs/zerolog/log"
)
func MwErrorResponder(defaultMsg string) core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
err := next.HandleUpdate(c)
var maxErr *merrors.GomaxError
if errors.As(err, &maxErr) {
return c.Respond(maxErr.Message)
}
if err != nil {
return c.Respond(defaultMsg)
}
return nil
}
}
}
func MwLoggerInjector() core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
ctx := log.Logger.With().Int64("user_id", c.Update().UserID).
Logger().WithContext(c.Context())
c.SetContext(ctx)
return next.HandleUpdate(c)
}
}
}
func MwDebugState() core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
log.Debug().Any("state", c.State()).Any("update", c.Update()).Send()
return next.HandleUpdate(c)
}
}
}
func MwErrorLogger() core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
if err := next.HandleUpdate(c); err != nil {
log.Ctx(c).Err(err).Send()
return err
}
return nil
}
}
}
+34
View File
@@ -0,0 +1,34 @@
package memory
import (
"context"
"github.com/abelith/gomax/state"
"sync"
)
type FSMStorage struct {
m sync.Map
}
func NewMemoryFSMStorage() *FSMStorage {
return &FSMStorage{}
}
func (f *FSMStorage) Get(_ context.Context, userID int) (*state.Snapshot, error) {
st, ok := f.m.Load(userID)
if !ok {
return nil, state.ErrStateNotFound
}
return st.(*state.Snapshot), nil
}
func (f *FSMStorage) Put(_ context.Context, snapshot *state.Snapshot) error {
f.m.Store(snapshot.ID, snapshot)
return nil
}
func (f *FSMStorage) Delete(_ context.Context, snapshot *state.Snapshot) error {
f.m.Delete(snapshot.ID)
return nil
}
+198
View File
@@ -0,0 +1,198 @@
package state
import (
"encoding/json"
"fmt"
"github.com/rs/zerolog/log"
)
var (
ErrStateNotFound = fmt.Errorf("state not found")
ErrKeyNotFound = fmt.Errorf("state: key not found")
)
const ClearState State = "clear"
type State string
type Codec interface {
Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v any) error
}
type JSONCodec struct{}
func (JSONCodec) Marshal(v any) ([]byte, error) {
return json.Marshal(v)
}
func (JSONCodec) Unmarshal(d []byte, v any) error {
return json.Unmarshal(d, v)
}
type Snapshot struct {
ID int `json:"id"`
State State `json:"state"`
Data map[string][]byte `json:"data"`
}
type Context struct {
id int
state State
data map[string][]byte
codec Codec
}
type Option func(*Context)
func WithCodec(c Codec) Option { return func(sc *Context) { sc.codec = c } }
func New(id int, opts ...Option) *Context {
sc := &Context{
id: id,
data: make(map[string][]byte),
codec: JSONCodec{},
}
for _, o := range opts {
o(sc)
}
return sc
}
func Restore(s Snapshot, opts ...Option) *Context {
sc := New(s.ID, opts...)
sc.state = s.State
for k, v := range s.Data {
sc.data[k] = v
}
return sc
}
func (sc *Context) Snapshot() Snapshot {
data := make(map[string][]byte, len(sc.data))
for k, v := range sc.data {
data[k] = v
}
return Snapshot{ID: sc.id, State: sc.state, Data: data}
}
func (sc *Context) Set(state State) {
log.Debug().
Int("user_id", sc.id).
Str("from", string(sc.state)).
Str("to", string(state)).
Msg("fsm state transition")
sc.state = state
}
func (sc *Context) State() State { return sc.state }
func (sc *Context) Clear() {
sc.state = ClearState
sc.data = make(map[string][]byte)
}
func (sc *Context) Store(key string, val any) error {
b, err := sc.codec.Marshal(val)
if err != nil {
return fmt.Errorf("sc.Store: failed to encode %q: %w", key, err)
}
sc.data[key] = b
return nil
}
func (sc *Context) Delete(key string) {
delete(sc.data, key)
}
func (sc *Context) Load(key string) Value {
b, ok := sc.data[key]
return Value{key: key, raw: b, ok: ok, codec: sc.codec}
}
type Value struct {
key string
raw []byte
ok bool
codec Codec
}
func (v Value) Exists() bool { return v.ok }
func (v Value) Raw() []byte { return v.raw }
func (v Value) Decode(dst any) error {
if !v.ok {
return fmt.Errorf("%w: %q", ErrKeyNotFound, v.key)
}
if err := v.codec.Unmarshal(v.raw, dst); err != nil {
return fmt.Errorf("state: decode %q as %T: %w", v.key, dst, err)
}
return nil
}
func (v Value) Str() (string, error) {
var s string
if err := v.Decode(&s); err != nil {
return "", err
}
return s, nil
}
func (v Value) Int() (int, error) {
var i int
if err := v.Decode(&i); err != nil {
return 0, err
}
return i, nil
}
func (v Value) Bool() (bool, error) {
var b bool
if err := v.Decode(&b); err != nil {
return false, err
}
return b, nil
}
func (v Value) Float() (float64, error) {
var f float64
if err := v.Decode(&f); err != nil {
return 0, err
}
return f, nil
}
func (v Value) Bytes() ([]byte, error) {
var b []byte
if err := v.Decode(&b); err != nil {
return nil, err
}
return b, nil
}
func (v Value) StrOr(def string) string {
if s, err := v.Str(); err == nil {
return s
}
return def
}
func (v Value) IntOr(def int) int {
if i, err := v.Int(); err == nil {
return i
}
return def
}
func (v Value) BoolOr(def bool) bool {
if b, err := v.Bool(); err == nil {
return b
}
return def
}
func (v Value) FloatOr(def float64) float64 {
if f, err := v.Float(); err == nil {
return f
}
return def
}