Compare commits
27 Commits
main
...
v1.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
|
f42d47af53
|
|||
|
9895edf966
|
|||
|
6cf3355a36
|
|||
|
fa7a296a66
|
|||
| 7101aba548 | |||
| 2de46a27c8 | |||
| ae7426c36a | |||
| 61562e8a3b | |||
|
a84e24ff25
|
|||
|
c0a26024f4
|
|||
|
786da652e6
|
|||
|
28ec2b7ca9
|
|||
|
da122a3be4
|
|||
|
1bf7499496
|
|||
|
7b9292557e
|
|||
|
466093e39b
|
|||
|
0e0f8a0813
|
|||
|
d84b0a1b55
|
|||
|
434638a61d
|
|||
|
c2909b4cfb
|
|||
|
746847cf61
|
|||
|
b2bda02c0f
|
|||
| bb51a0ecb1 | |||
|
4527dd661a
|
|||
|
4129b8e688
|
|||
|
12883f428e
|
|||
|
f29ef979bf
|
15
Makefile
Normal file
15
Makefile
Normal file
@@ -0,0 +1,15 @@
|
||||
# Проверка наличия golangci-lint
|
||||
GO_LINT := $(shell command -v golangci-lint 2>/dev/null)
|
||||
|
||||
# Цель: запуск всех проверок кода
|
||||
check:
|
||||
@echo "🔍 Running code checks..."
|
||||
@go mod tidy -v
|
||||
@go vet ./...
|
||||
@if [ -n "$(GO_LINT)" ]; then \
|
||||
echo "✅ golangci-lint found, running..." && \
|
||||
golangci-lint run --timeout=5m --verbose; \
|
||||
else \
|
||||
echo "⚠️ golangci-lint not installed. Install with: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.57.2"; \
|
||||
fi
|
||||
@go test -race -v ./... 2>/dev/null || echo "⚠️ Tests skipped or failed (run manually with 'go test -race ./...')"
|
||||
418
bot.go
418
bot.go
@@ -1,106 +1,179 @@
|
||||
package laniakea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"sync"
|
||||
|
||||
"git.nix13.pw/scuroneko/extypes"
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
"git.nix13.pw/scuroneko/laniakea/utils"
|
||||
"git.nix13.pw/scuroneko/slog"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/vinovest/sqlx"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"github.com/alitto/pond/v2"
|
||||
)
|
||||
|
||||
type Bot struct {
|
||||
token string
|
||||
debug bool
|
||||
errorTemplate string
|
||||
type BotOpts struct {
|
||||
Token string
|
||||
UpdateTypes []string
|
||||
|
||||
logger *slog.Logger
|
||||
RequestLogger *slog.Logger
|
||||
Debug bool
|
||||
ErrorTemplate string
|
||||
Prefixes []string
|
||||
|
||||
plugins []Plugin
|
||||
middlewares []Middleware
|
||||
prefixes []string
|
||||
runners []Runner
|
||||
|
||||
dbContext *DatabaseContext
|
||||
api *tgapi.Api
|
||||
|
||||
dbWriterRequested extypes.Slice[*slog.Logger]
|
||||
|
||||
updateOffset int
|
||||
updateTypes []tgapi.UpdateType
|
||||
updateQueue *extypes.Queue[*tgapi.Update]
|
||||
}
|
||||
|
||||
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 BotSettings struct {
|
||||
Token string
|
||||
Debug bool
|
||||
ErrorTemplate string
|
||||
Prefixes []string
|
||||
UpdateTypes []string
|
||||
LoggerBasePath string
|
||||
UseRequestLogger bool
|
||||
WriteToFile bool
|
||||
|
||||
UseTestServer bool
|
||||
APIUrl string
|
||||
|
||||
RateLimit int
|
||||
DropRLOverflow bool
|
||||
}
|
||||
|
||||
func LoadSettingsFromEnv() *BotSettings {
|
||||
return &BotSettings{
|
||||
Token: os.Getenv("TG_TOKEN"),
|
||||
Debug: os.Getenv("DEBUG") == "true",
|
||||
ErrorTemplate: os.Getenv("ERROR_TEMPLATE"),
|
||||
Prefixes: LoadPrefixesFromEnv(),
|
||||
UpdateTypes: strings.Split(os.Getenv("UPDATE_TYPES"), ";"),
|
||||
func NewOpts() *BotOpts { return new(BotOpts) }
|
||||
func LoadOptsFromEnv() *BotOpts {
|
||||
rateLimit := 30
|
||||
if rl := os.Getenv("RATE_LIMIT"); rl != "" {
|
||||
rateLimit, _ = strconv.Atoi(rl)
|
||||
}
|
||||
|
||||
return &BotOpts{
|
||||
Token: os.Getenv("TG_TOKEN"),
|
||||
UpdateTypes: strings.Split(os.Getenv("UPDATE_TYPES"), ";"),
|
||||
|
||||
Debug: os.Getenv("DEBUG") == "true",
|
||||
ErrorTemplate: os.Getenv("ERROR_TEMPLATE"),
|
||||
Prefixes: LoadPrefixesFromEnv(),
|
||||
|
||||
UseRequestLogger: os.Getenv("USE_REQ_LOG") == "true",
|
||||
WriteToFile: os.Getenv("WRITE_TO_FILE") == "true",
|
||||
|
||||
UseTestServer: os.Getenv("USE_TEST_SERVER") == "true",
|
||||
APIUrl: os.Getenv("API_URL"),
|
||||
|
||||
RateLimit: rateLimit,
|
||||
DropRLOverflow: os.Getenv("DROP_RL_OVERFLOW") == "true",
|
||||
}
|
||||
}
|
||||
|
||||
func LoadPrefixesFromEnv() []string {
|
||||
prefixesS, exists := os.LookupEnv("PREFIXES")
|
||||
if !exists {
|
||||
return []string{"!"}
|
||||
return []string{"/"}
|
||||
}
|
||||
return strings.Split(prefixesS, ";")
|
||||
}
|
||||
func NewBot(settings *BotSettings) *Bot {
|
||||
updateQueue := extypes.CreateQueue[*tgapi.Update](256)
|
||||
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,
|
||||
}
|
||||
bot.dbWriterRequested = bot.dbWriterRequested.Push(api.Logger)
|
||||
|
||||
if len(settings.ErrorTemplate) > 0 {
|
||||
bot.errorTemplate = settings.ErrorTemplate
|
||||
}
|
||||
if len(settings.LoggerBasePath) == 0 {
|
||||
settings.LoggerBasePath = "./"
|
||||
type DbContext interface{}
|
||||
type NoDB struct{ DbContext }
|
||||
type Bot[T DbContext] struct {
|
||||
token string
|
||||
debug bool
|
||||
errorTemplate string
|
||||
username string
|
||||
|
||||
logger *slog.Logger
|
||||
RequestLogger *slog.Logger
|
||||
extraLoggers extypes.Slice[*slog.Logger]
|
||||
|
||||
plugins []Plugin[T]
|
||||
middlewares []Middleware[T]
|
||||
prefixes []string
|
||||
runners []Runner[T]
|
||||
|
||||
api *tgapi.API
|
||||
uploader *tgapi.Uploader
|
||||
dbContext *T
|
||||
l10n *L10n
|
||||
draftProvider *DraftProvider
|
||||
|
||||
updateOffsetMu sync.Mutex
|
||||
updateOffset int
|
||||
updateTypes []tgapi.UpdateType
|
||||
updateQueue chan *tgapi.Update
|
||||
}
|
||||
|
||||
func NewBot[T any](opts *BotOpts) *Bot[T] {
|
||||
updateQueue := make(chan *tgapi.Update, 512)
|
||||
|
||||
var limiter *utils.RateLimiter
|
||||
if opts.RateLimit > 0 {
|
||||
limiter = utils.NewRateLimiter()
|
||||
}
|
||||
|
||||
apiOpts := tgapi.NewAPIOpts(opts.Token).SetAPIUrl(opts.APIUrl).UseTestServer(opts.UseTestServer).SetLimiter(limiter)
|
||||
api := tgapi.NewAPI(apiOpts)
|
||||
|
||||
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{},
|
||||
draftProvider: NewRandomDraftProvider(api),
|
||||
}
|
||||
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 {
|
||||
_ = bot.Close()
|
||||
bot.logger.Fatal(err)
|
||||
}
|
||||
bot.username = Val(u.Username, "")
|
||||
if bot.username == "" {
|
||||
bot.logger.Warn("Can't get bot username. Named command wouldn't work!")
|
||||
}
|
||||
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)
|
||||
@@ -108,11 +181,11 @@ func NewBot(settings *BotSettings) *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)
|
||||
@@ -120,152 +193,153 @@ func NewBot(settings *BotSettings) *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 {
|
||||
bot.updateOffsetMu.Lock()
|
||||
defer bot.updateOffsetMu.Unlock()
|
||||
return bot.updateOffset
|
||||
}
|
||||
func (bot *Bot[T]) SetUpdateOffset(offset int) {
|
||||
bot.updateOffsetMu.Lock()
|
||||
defer bot.updateOffsetMu.Unlock()
|
||||
bot.updateOffset = offset
|
||||
}
|
||||
func (bot *Bot[T]) GetUpdateTypes() []tgapi.UpdateType { return bot.updateTypes }
|
||||
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]) SetDraftProvider(p *DraftProvider) *Bot[T] {
|
||||
bot.draftProvider = p
|
||||
return bot
|
||||
}
|
||||
|
||||
func (b *Bot) Close() {
|
||||
err := b.logger.Close()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
err = b.RequestLogger.Close()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}
|
||||
type DbLogger[T DbContext] func(db *T) slog.LoggerWriter
|
||||
|
||||
type DatabaseContext struct {
|
||||
PostgresSQL *sqlx.DB
|
||||
MongoDB *mongo.Client
|
||||
Redis *redis.Client
|
||||
}
|
||||
|
||||
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]) 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 b.dbWriterRequested {
|
||||
for _, l := range bot.extraLoggers {
|
||||
l.AddWriter(w)
|
||||
}
|
||||
return b
|
||||
return bot
|
||||
}
|
||||
|
||||
func (b *Bot) DatabaseContext(ctx *DatabaseContext) *Bot {
|
||||
b.dbContext = ctx
|
||||
return b
|
||||
func (bot *Bot[T]) DatabaseContext(ctx *T) *Bot[T] {
|
||||
bot.dbContext = ctx
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) UpdateTypes(t ...tgapi.UpdateType) *Bot {
|
||||
b.updateTypes = make([]tgapi.UpdateType, 0)
|
||||
b.updateTypes = append(b.updateTypes, t...)
|
||||
return b
|
||||
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) AddUpdateType(t ...tgapi.UpdateType) *Bot {
|
||||
b.updateTypes = append(b.updateTypes, t...)
|
||||
return b
|
||||
func (bot *Bot[T]) AddUpdateType(t ...tgapi.UpdateType) *Bot[T] {
|
||||
bot.updateTypes = append(bot.updateTypes, t...)
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) AddPrefixes(prefixes ...string) *Bot {
|
||||
b.prefixes = append(b.prefixes, prefixes...)
|
||||
return b
|
||||
func (bot *Bot[T]) AddPrefixes(prefixes ...string) *Bot[T] {
|
||||
bot.prefixes = append(bot.prefixes, prefixes...)
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) ErrorTemplate(s string) *Bot {
|
||||
b.errorTemplate = s
|
||||
return b
|
||||
func (bot *Bot[T]) ErrorTemplate(s string) *Bot[T] {
|
||||
bot.errorTemplate = s
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) Debug(debug bool) *Bot {
|
||||
b.debug = debug
|
||||
return b
|
||||
func (bot *Bot[T]) Debug(debug bool) *Bot[T] {
|
||||
bot.debug = debug
|
||||
return bot
|
||||
}
|
||||
func (b *Bot) AddPlugins(plugin ...Plugin) *Bot {
|
||||
b.plugins = append(b.plugins, plugin...)
|
||||
func (bot *Bot[T]) AddPlugins(plugin ...*Plugin[T]) *Bot[T] {
|
||||
for _, p := range plugin {
|
||||
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]
|
||||
if first.Order == second.Order {
|
||||
return first.Name < second.Name
|
||||
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 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) 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]) enqueueUpdate(u *tgapi.Update) error {
|
||||
select {
|
||||
case bot.updateQueue <- u:
|
||||
return nil
|
||||
default:
|
||||
return extypes.QueueFullErr
|
||||
}
|
||||
}
|
||||
func (bot *Bot[T]) RunWithContext(ctx context.Context) {
|
||||
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.logger.Infoln("Executing runners...")
|
||||
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()
|
||||
if err != nil {
|
||||
b.logger.Errorln(err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
updates, err := bot.Updates()
|
||||
if err != nil {
|
||||
bot.logger.Errorln(err)
|
||||
continue
|
||||
}
|
||||
|
||||
for _, u := range updates {
|
||||
select {
|
||||
case bot.updateQueue <- new(u):
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
queue := b.updateQueue
|
||||
if queue.IsEmpty() {
|
||||
time.Sleep(time.Millisecond * 25)
|
||||
continue
|
||||
}
|
||||
|
||||
u := queue.Dequeue()
|
||||
if u == nil {
|
||||
b.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)
|
||||
}
|
||||
pool := pond.NewPool(16)
|
||||
for update := range bot.updateQueue {
|
||||
update := update
|
||||
pool.Submit(func() {
|
||||
bot.handle(update)
|
||||
})
|
||||
}
|
||||
}
|
||||
func (bot *Bot[T]) Run() {
|
||||
bot.RunWithContext(context.Background())
|
||||
}
|
||||
|
||||
72
cmd_generator.go
Normal file
72
cmd_generator.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package laniakea
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
)
|
||||
|
||||
func generateBotCommand[T any](cmd Command[T]) tgapi.BotCommand {
|
||||
desc := cmd.command
|
||||
if len(cmd.description) > 0 {
|
||||
desc = cmd.description
|
||||
}
|
||||
var descArgs []string
|
||||
for _, a := range cmd.args {
|
||||
if a.required {
|
||||
descArgs = append(descArgs, a.text)
|
||||
} else {
|
||||
descArgs = append(descArgs, fmt.Sprintf("[%s]", a.text))
|
||||
}
|
||||
}
|
||||
desc = fmt.Sprintf("%s. Usage: /%s %s", desc, cmd.command, strings.Join(descArgs, " "))
|
||||
return tgapi.BotCommand{Command: cmd.command, Description: desc}
|
||||
}
|
||||
|
||||
func generateBotCommandForPlugin[T any](pl Plugin[T]) []tgapi.BotCommand {
|
||||
commands := make([]tgapi.BotCommand, 0)
|
||||
for _, cmd := range pl.commands {
|
||||
if cmd.skipAutoCmd {
|
||||
continue
|
||||
}
|
||||
commands = append(commands, generateBotCommand(cmd))
|
||||
}
|
||||
return commands
|
||||
}
|
||||
|
||||
var ErrTooManyCommands = errors.New("too many commands. max 100")
|
||||
|
||||
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 bot.plugins {
|
||||
if pl.skipAutoCmd {
|
||||
continue
|
||||
}
|
||||
|
||||
commands = append(commands, generateBotCommandForPlugin(pl)...)
|
||||
}
|
||||
if len(commands) > 100 {
|
||||
return ErrTooManyCommands
|
||||
}
|
||||
|
||||
privateChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopePrivateType}
|
||||
groupChatsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopeGroupType}
|
||||
chatAdminsScope := &tgapi.BotCommandScope{Type: tgapi.BotCommandScopeAllChatAdministratorsType}
|
||||
_, err = bot.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: privateChatsScope})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = bot.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: groupChatsScope})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = bot.api.SetMyCommands(tgapi.SetMyCommandsP{Commands: commands, Scope: chatAdminsScope})
|
||||
return err
|
||||
}
|
||||
126
drafts.go
Normal file
126
drafts.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package laniakea
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
"sync/atomic"
|
||||
|
||||
"git.nix13.pw/scuroneko/laniakea/tgapi"
|
||||
)
|
||||
|
||||
type draftIdGenerator interface {
|
||||
Next() uint64
|
||||
}
|
||||
|
||||
type RandomDraftIdGenerator struct {
|
||||
draftIdGenerator
|
||||
}
|
||||
|
||||
func (g *RandomDraftIdGenerator) Next() uint64 {
|
||||
return rand.Uint64()
|
||||
}
|
||||
|
||||
type LinearDraftIdGenerator struct {
|
||||
draftIdGenerator
|
||||
lastId atomic.Uint64
|
||||
}
|
||||
|
||||
func (g *LinearDraftIdGenerator) Next() uint64 {
|
||||
return g.lastId.Add(1)
|
||||
}
|
||||
|
||||
type DraftProvider struct {
|
||||
api *tgapi.API
|
||||
|
||||
chatID int64
|
||||
messageThreadID int
|
||||
parseMode tgapi.ParseMode
|
||||
entities []tgapi.MessageEntity
|
||||
|
||||
drafts map[uint64]*Draft
|
||||
generator draftIdGenerator
|
||||
}
|
||||
type Draft struct {
|
||||
api *tgapi.API
|
||||
provider *DraftProvider
|
||||
|
||||
chatID int64
|
||||
messageThreadID int
|
||||
parseMode tgapi.ParseMode
|
||||
entities []tgapi.MessageEntity
|
||||
|
||||
ID uint64
|
||||
Message string
|
||||
}
|
||||
|
||||
func NewRandomDraftProvider(api *tgapi.API) *DraftProvider {
|
||||
return &DraftProvider{
|
||||
api: api, generator: &RandomDraftIdGenerator{},
|
||||
drafts: make(map[uint64]*Draft),
|
||||
}
|
||||
}
|
||||
func NewLinearDraftProvider(api *tgapi.API, startValue uint64) *DraftProvider {
|
||||
g := &LinearDraftIdGenerator{}
|
||||
g.lastId.Store(startValue)
|
||||
return &DraftProvider{
|
||||
api: api,
|
||||
generator: g,
|
||||
drafts: make(map[uint64]*Draft),
|
||||
}
|
||||
}
|
||||
func (d *DraftProvider) NewDraft() *Draft {
|
||||
id := d.generator.Next()
|
||||
entitiesCopy := make([]tgapi.MessageEntity, 0)
|
||||
copy(entitiesCopy, d.entities)
|
||||
draft := &Draft{
|
||||
api: d.api,
|
||||
provider: d,
|
||||
chatID: d.chatID,
|
||||
messageThreadID: d.messageThreadID,
|
||||
parseMode: d.parseMode,
|
||||
entities: entitiesCopy,
|
||||
ID: id,
|
||||
Message: "",
|
||||
}
|
||||
d.drafts[id] = draft
|
||||
return draft
|
||||
}
|
||||
|
||||
func (d *Draft) Push(newText string) error {
|
||||
d.Message += newText
|
||||
params := tgapi.SendMessageDraftP{
|
||||
ChatID: d.chatID,
|
||||
DraftID: d.ID,
|
||||
Text: d.Message,
|
||||
ParseMode: d.parseMode,
|
||||
Entities: d.entities,
|
||||
}
|
||||
if d.messageThreadID > 0 {
|
||||
params.MessageThreadID = d.messageThreadID
|
||||
}
|
||||
_, err := d.api.SendMessageDraft(params)
|
||||
return err
|
||||
}
|
||||
func (d *Draft) Clear() {
|
||||
d.Message = ""
|
||||
}
|
||||
func (d *Draft) Flush() error {
|
||||
if d.Message == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
params := tgapi.SendMessageP{
|
||||
ChatID: d.chatID,
|
||||
ParseMode: d.parseMode,
|
||||
Entities: d.entities,
|
||||
Text: d.Message,
|
||||
}
|
||||
if d.messageThreadID > 0 {
|
||||
params.MessageThreadID = d.messageThreadID
|
||||
}
|
||||
_, err := d.api.SendMessage(params)
|
||||
if err == nil {
|
||||
d.Clear()
|
||||
delete(d.provider.drafts, d.ID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
21
go.mod
21
go.mod
@@ -1,30 +1,17 @@
|
||||
module git.nix13.pw/scuroneko/laniakea
|
||||
|
||||
go 1.25
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
git.nix13.pw/scuroneko/extypes v1.1.0
|
||||
git.nix13.pw/scuroneko/extypes v1.2.1
|
||||
git.nix13.pw/scuroneko/slog v1.0.2
|
||||
github.com/redis/go-redis/v9 v9.17.3
|
||||
github.com/vinovest/sqlx v1.7.1
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0
|
||||
github.com/alitto/pond/v2 v2.6.2
|
||||
golang.org/x/time v0.14.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
|
||||
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
|
||||
)
|
||||
|
||||
92
go.sum
92
go.sum
@@ -1,97 +1,17 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
git.nix13.pw/scuroneko/extypes v1.1.0 h1:kdAraybAqQgVhArVkVfrIi7KVEX8HgTr8mzbIZAAAqg=
|
||||
git.nix13.pw/scuroneko/extypes v1.1.0/go.mod h1:uZVs8Yo3RrYAG9dMad6qR6lsYY67t+459D9c65QAYAw=
|
||||
git.nix13.pw/scuroneko/extypes v1.2.1 h1:IYrOjnWKL2EAuJYtYNa+luB1vBe6paE8VY/YD+5/RpQ=
|
||||
git.nix13.pw/scuroneko/extypes v1.2.1/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/alitto/pond/v2 v2.6.2 h1:Sphe40g0ILeM1pA2c2K+Th0DGU+pt0A/Kprr+WB24Pw=
|
||||
github.com/alitto/pond/v2 v2.6.2/go.mod h1:xkjYEgQ05RSpWdfSd1nM3OVv7TBhLdy7rMp3+2Nq+yE=
|
||||
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/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.2.1 h1:19KvJrCj9aOMfU921hjnizWPlQmPTe+tb36zupOY2FA=
|
||||
github.com/muir/sqltoken v0.2.1/go.mod h1:sSlj5M0VqQ4OuedmxwWs1TmzzRXaH3DLf5ukzg6meIo=
|
||||
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.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
|
||||
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
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=
|
||||
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=
|
||||
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.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||
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.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
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.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
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=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
|
||||
116
handler.go
116
handler.go
@@ -1,26 +1,33 @@
|
||||
package laniakea
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"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,
|
||||
draftProvider: bot.draftProvider,
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -33,7 +40,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
|
||||
}
|
||||
@@ -42,44 +49,48 @@ func (b *Bot) handleMessage(update *tgapi.Update, ctx *MsgContext) {
|
||||
ctx.From = update.Message.From
|
||||
ctx.Msg = update.Message
|
||||
|
||||
// Убираем префикс
|
||||
text = strings.TrimSpace(text[len(prefix):])
|
||||
|
||||
for _, plugin := range b.plugins {
|
||||
// Check every command
|
||||
for cmd := range plugin.Commands {
|
||||
if !strings.HasPrefix(text, cmd) {
|
||||
continue
|
||||
}
|
||||
requestParts := strings.Split(text, " ")
|
||||
cmdParts := strings.Split(cmd, " ")
|
||||
isValid := true
|
||||
for i, part := range cmdParts {
|
||||
if part != requestParts[i] {
|
||||
isValid = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isValid {
|
||||
continue
|
||||
}
|
||||
// Извлекаем команду как первое слово
|
||||
spaceIndex := strings.Index(text, " ")
|
||||
var cmd string
|
||||
var args string
|
||||
|
||||
ctx.Text = strings.TrimSpace(text[len(cmd):])
|
||||
ctx.Args = strings.Split(ctx.Text, " ")
|
||||
if spaceIndex == -1 {
|
||||
cmd = text
|
||||
args = ""
|
||||
} else {
|
||||
cmd = text[:spaceIndex]
|
||||
args = strings.TrimSpace(text[spaceIndex:])
|
||||
}
|
||||
|
||||
if !plugin.executeMiddlewares(ctx, b.dbContext) {
|
||||
if strings.Contains(cmd, "@") {
|
||||
botUsername := bot.username
|
||||
if botUsername != "" && strings.HasSuffix(cmd, "@"+botUsername) {
|
||||
cmd = cmd[:len(cmd)-len("@"+botUsername)] // убираем @botname
|
||||
}
|
||||
}
|
||||
|
||||
// Ищем команду по точному совпадению
|
||||
for _, plugin := range bot.plugins {
|
||||
if _, exists := plugin.commands[cmd]; exists {
|
||||
ctx.Text = args
|
||||
ctx.Args = strings.Fields(args) // Убирает лишние пробелы
|
||||
if !plugin.executeMiddlewares(ctx, bot.dbContext) {
|
||||
return
|
||||
}
|
||||
go plugin.Execute(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
|
||||
}
|
||||
|
||||
@@ -90,25 +101,54 @@ func (b *Bot) handleCallback(update *tgapi.Update, ctx *MsgContext) {
|
||||
ctx.CallbackQueryId = update.CallbackQuery.ID
|
||||
ctx.Args = data.Args
|
||||
|
||||
for _, plugin := range b.plugins {
|
||||
_, ok := plugin.Payloads[data.Command]
|
||||
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
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func encodeJsonPayload(d CallbackData) (string, error) {
|
||||
b, err := json.Marshal(d)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
func decodeJsonPayload(s string) (CallbackData, error) {
|
||||
var data CallbackData
|
||||
err := json.Unmarshal([]byte(s), &data)
|
||||
return data, err
|
||||
}
|
||||
func encodeBase64Payload(d CallbackData) (string, error) {
|
||||
data, err := encodeJsonPayload(d)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dst := make([]byte, base64.StdEncoding.EncodedLen(len([]byte(data))))
|
||||
base64.StdEncoding.Encode(dst, []byte(data))
|
||||
return string(dst), nil
|
||||
}
|
||||
func decodeBase64Payload(s string) (CallbackData, error) {
|
||||
b, err := base64.StdEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return CallbackData{}, err
|
||||
}
|
||||
return decodeJsonPayload(string(b))
|
||||
}
|
||||
|
||||
26
l10n.go
Normal file
26
l10n.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package laniakea
|
||||
|
||||
// DictEntry {key:{ru:123,en:123}}
|
||||
type DictEntry map[string]string
|
||||
type L10n struct {
|
||||
entries map[string]DictEntry
|
||||
fallbackLang string
|
||||
}
|
||||
|
||||
func NewL10n(fallbackLanguage string) *L10n {
|
||||
return &L10n{make(map[string]DictEntry), fallbackLanguage}
|
||||
}
|
||||
func (l *L10n) AddDictEntry(key string, value DictEntry) *L10n {
|
||||
l.entries[key] = value
|
||||
return l
|
||||
}
|
||||
func (l *L10n) GetFallbackLanguage() string {
|
||||
return l.fallbackLang
|
||||
}
|
||||
func (l *L10n) Translate(lang, key string) string {
|
||||
s, ok := l.entries[key]
|
||||
if !ok {
|
||||
return key
|
||||
}
|
||||
return s[lang]
|
||||
}
|
||||
38
methods.go
38
methods.go
@@ -2,50 +2,34 @@ 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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if b.RequestLogger != nil {
|
||||
if bot.RequestLogger != nil {
|
||||
for _, u := range updates {
|
||||
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)
|
||||
}
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
bot.SetUpdateOffset(updates[len(updates)-1].UpdateID + 1)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
105
msg_context.go
105
msg_context.go
@@ -1,15 +1,16 @@
|
||||
package laniakea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"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
|
||||
Api *tgapi.API
|
||||
|
||||
Msg *tgapi.Message
|
||||
Update tgapi.Update
|
||||
@@ -20,13 +21,17 @@ type MsgContext struct {
|
||||
Prefix string
|
||||
Text string
|
||||
Args []string
|
||||
|
||||
errorTemplate string
|
||||
botLogger *slog.Logger
|
||||
l10n *L10n
|
||||
draftProvider *DraftProvider
|
||||
}
|
||||
|
||||
type AnswerMessage struct {
|
||||
MessageID int
|
||||
Text string
|
||||
IsMedia bool
|
||||
Keyboard *InlineKeyboard
|
||||
ctx *MsgContext
|
||||
}
|
||||
|
||||
@@ -42,7 +47,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{
|
||||
@@ -54,7 +59,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
|
||||
}
|
||||
|
||||
@@ -74,9 +79,10 @@ func (ctx *MsgContext) editPhotoText(messageId int, text string, kb *InlineKeybo
|
||||
if kb != nil {
|
||||
params.ReplyMarkup = kb.Get()
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -84,7 +90,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)
|
||||
@@ -97,15 +103,26 @@ func (ctx *MsgContext) answer(text string, keyboard *InlineKeyboard) *AnswerMess
|
||||
params := tgapi.SendMessageP{
|
||||
ChatID: ctx.Msg.Chat.ID,
|
||||
Text: text,
|
||||
ParseMode: tgapi.ParseMD,
|
||||
ParseMode: tgapi.ParseMDV2,
|
||||
}
|
||||
if keyboard != nil {
|
||||
params.ReplyMarkup = keyboard.Get()
|
||||
}
|
||||
if ctx.Msg.MessageThreadID > 0 {
|
||||
params.MessageThreadID = ctx.Msg.MessageThreadID
|
||||
}
|
||||
if ctx.Msg.DirectMessageTopic != nil {
|
||||
params.DirectMessagesTopicID = ctx.Msg.DirectMessageTopic.TopicID
|
||||
}
|
||||
|
||||
cont := context.Background()
|
||||
if err := ctx.Api.Limiter.Wait(cont, ctx.Msg.Chat.ID); err != nil {
|
||||
ctx.botLogger.Errorln(err)
|
||||
return nil
|
||||
}
|
||||
msg, err := ctx.Api.SendMessage(params)
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
return nil
|
||||
}
|
||||
return &AnswerMessage{
|
||||
@@ -132,9 +149,13 @@ func (ctx *MsgContext) answerPhoto(photoId, text string, kb *InlineKeyboard) *An
|
||||
if kb != nil {
|
||||
params.ReplyMarkup = kb.Get()
|
||||
}
|
||||
if ctx.Msg.MessageThreadID > 0 {
|
||||
params.MessageThreadID = ctx.Msg.MessageThreadID
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
@@ -156,15 +177,11 @@ func (ctx *MsgContext) delete(messageId int) {
|
||||
MessageID: messageId,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Api.Logger.Errorln(err)
|
||||
ctx.botLogger.Errorln(err)
|
||||
}
|
||||
}
|
||||
func (m *AnswerMessage) Delete() {
|
||||
m.ctx.delete(m.MessageID)
|
||||
}
|
||||
func (ctx *MsgContext) CallbackDelete() {
|
||||
ctx.delete(ctx.CallbackMsgId)
|
||||
}
|
||||
func (m *AnswerMessage) Delete() { m.ctx.delete(m.MessageID) }
|
||||
func (ctx *MsgContext) CallbackDelete() { ctx.delete(ctx.CallbackMsgId) }
|
||||
|
||||
func (ctx *MsgContext) answerCallbackQuery(url, text string, showAlert bool) {
|
||||
if len(ctx.CallbackQueryId) == 0 {
|
||||
@@ -175,41 +192,55 @@ 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() {
|
||||
ctx.answerCallbackQuery("", "", false)
|
||||
}
|
||||
func (ctx *MsgContext) AnswerCbQueryText(text string) {
|
||||
ctx.answerCallbackQuery("", text, false)
|
||||
}
|
||||
func (ctx *MsgContext) AnswerCbQueryAlert(text string) {
|
||||
ctx.answerCallbackQuery("", text, true)
|
||||
}
|
||||
func (ctx *MsgContext) AnswerCbQueryUrl(u string) {
|
||||
ctx.answerCallbackQuery(u, "", false)
|
||||
}
|
||||
func (ctx *MsgContext) AnswerCbQuery() { ctx.answerCallbackQuery("", "", false) }
|
||||
func (ctx *MsgContext) AnswerCbQueryText(text string) { ctx.answerCallbackQuery("", text, false) }
|
||||
func (ctx *MsgContext) AnswerCbQueryAlert(text string) { ctx.answerCallbackQuery("", text, true) }
|
||||
func (ctx *MsgContext) AnswerCbQueryUrl(u string) { ctx.answerCallbackQuery(u, "", false) }
|
||||
|
||||
func (ctx *MsgContext) SendAction(action tgapi.ChatActionType) {
|
||||
_, err := ctx.Api.SendChatAction(tgapi.SendChatActionP{
|
||||
params := tgapi.SendChatActionP{
|
||||
ChatID: ctx.Msg.Chat.ID, Action: action,
|
||||
})
|
||||
}
|
||||
if ctx.Msg.MessageThreadID > 0 {
|
||||
params.MessageThreadID = ctx.Msg.MessageThreadID
|
||||
}
|
||||
_, err := ctx.Api.SendChatAction(params)
|
||||
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)
|
||||
func (ctx *MsgContext) Error(err error) { ctx.error(err) }
|
||||
|
||||
func (ctx *MsgContext) NewDraft() *Draft {
|
||||
c := context.Background()
|
||||
if err := ctx.Api.Limiter.Wait(c, ctx.Msg.Chat.ID); err != nil {
|
||||
ctx.botLogger.Errorln(err)
|
||||
return nil
|
||||
}
|
||||
|
||||
draft := ctx.draftProvider.NewDraft()
|
||||
draft.chatID = ctx.Msg.Chat.ID
|
||||
draft.messageThreadID = ctx.Msg.MessageThreadID
|
||||
return draft
|
||||
}
|
||||
func (ctx *MsgContext) Translate(key string) string {
|
||||
if ctx.From == nil {
|
||||
return key
|
||||
}
|
||||
lang := Val(ctx.From.LanguageCode, ctx.l10n.GetFallbackLanguage())
|
||||
return ctx.l10n.Translate(lang, key)
|
||||
}
|
||||
|
||||
231
plugins.go
231
plugins.go
@@ -1,74 +1,150 @@
|
||||
package laniakea
|
||||
|
||||
import (
|
||||
"log"
|
||||
"errors"
|
||||
"regexp"
|
||||
|
||||
"git.nix13.pw/scuroneko/extypes"
|
||||
)
|
||||
|
||||
type CommandExecutor func(ctx *MsgContext, dbContext *DatabaseContext)
|
||||
const (
|
||||
CommandValueStringType CommandValueType = "string"
|
||||
CommandValueIntType CommandValueType = "int"
|
||||
CommandValueBoolType CommandValueType = "bool"
|
||||
CommandValueAnyType CommandValueType = "any"
|
||||
)
|
||||
|
||||
type PluginBuilder struct {
|
||||
var (
|
||||
CommandRegexInt = regexp.MustCompile(`\d+`)
|
||||
CommandRegexString = regexp.MustCompile(".+")
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCmdArgCountMismatch = errors.New("command arg count mismatch")
|
||||
ErrCmdArgRegexpMismatch = errors.New("command arg regexp mismatch")
|
||||
)
|
||||
|
||||
type CommandValueType string
|
||||
type CommandArg struct {
|
||||
valueType CommandValueType
|
||||
text string
|
||||
regex *regexp.Regexp
|
||||
required bool
|
||||
}
|
||||
|
||||
func NewCommandArg(text string, valueType CommandValueType) *CommandArg {
|
||||
regex := CommandRegexString
|
||||
switch valueType {
|
||||
case CommandValueIntType:
|
||||
regex = CommandRegexInt
|
||||
}
|
||||
return &CommandArg{valueType, text, regex, false}
|
||||
}
|
||||
func (c *CommandArg) SetRequired() *CommandArg {
|
||||
c.required = true
|
||||
return c
|
||||
}
|
||||
|
||||
type CommandExecutor[T DbContext] func(ctx *MsgContext, dbContext *T)
|
||||
|
||||
type Command[T DbContext] struct {
|
||||
command string
|
||||
description string
|
||||
exec CommandExecutor[T]
|
||||
args extypes.Slice[CommandArg]
|
||||
middlewares extypes.Slice[Middleware[T]]
|
||||
skipAutoCmd bool
|
||||
}
|
||||
|
||||
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[T]) Use(m Middleware[T]) *Command[T] {
|
||||
c.middlewares = c.middlewares.Push(m)
|
||||
return c
|
||||
}
|
||||
func (c *Command[T]) SetDescription(desc string) *Command[T] {
|
||||
c.description = desc
|
||||
return c
|
||||
}
|
||||
func (c *Command[T]) SkipCommandAutoGen() *Command[T] {
|
||||
c.skipAutoCmd = true
|
||||
return c
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
for i, arg := range args {
|
||||
if i >= c.args.Len() {
|
||||
break
|
||||
}
|
||||
cmdArg := c.args.Get(i)
|
||||
if cmdArg.regex == nil {
|
||||
continue
|
||||
}
|
||||
if !cmdArg.regex.MatchString(arg) {
|
||||
return ErrCmdArgRegexpMismatch
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Plugin[T DbContext] struct {
|
||||
name string
|
||||
commands map[string]CommandExecutor
|
||||
payloads map[string]CommandExecutor
|
||||
middlewares extypes.Slice[*PluginMiddleware]
|
||||
commands map[string]Command[T]
|
||||
payloads map[string]Command[T]
|
||||
middlewares extypes.Slice[Middleware[T]]
|
||||
skipAutoCmd bool
|
||||
}
|
||||
|
||||
type Plugin struct {
|
||||
Name string
|
||||
Commands map[string]CommandExecutor
|
||||
Payloads map[string]CommandExecutor
|
||||
Middlewares extypes.Slice[*PluginMiddleware]
|
||||
}
|
||||
|
||||
func NewPlugin(name string) *PluginBuilder {
|
||||
return &PluginBuilder{
|
||||
name: name,
|
||||
commands: make(map[string]CommandExecutor),
|
||||
payloads: make(map[string]CommandExecutor),
|
||||
func NewPlugin[T DbContext](name string) *Plugin[T] {
|
||||
return &Plugin[T]{
|
||||
name, map[string]Command[T]{},
|
||||
map[string]Command[T]{}, extypes.Slice[Middleware[T]]{}, false,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PluginBuilder) Command(f CommandExecutor, cmd ...string) *PluginBuilder {
|
||||
for _, c := range cmd {
|
||||
p.commands[c] = f
|
||||
}
|
||||
func (p *Plugin[T]) AddCommand(command *Command[T]) *Plugin[T] {
|
||||
p.commands[command.command] = *command
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *PluginBuilder) Payload(f CommandExecutor, payloads ...string) *PluginBuilder {
|
||||
for _, payload := range payloads {
|
||||
p.payloads[payload] = f
|
||||
}
|
||||
func (p *Plugin[T]) NewCommand(exec CommandExecutor[T], command string, args ...CommandArg) *Command[T] {
|
||||
return NewCommand(exec, command, args...)
|
||||
}
|
||||
func (p *Plugin[T]) AddPayload(command *Command[T]) *Plugin[T] {
|
||||
p.payloads[command.command] = *command
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *PluginBuilder) AddMiddleware(middleware *PluginMiddleware) *PluginBuilder {
|
||||
func (p *Plugin[T]) AddMiddleware(middleware Middleware[T]) *Plugin[T] {
|
||||
p.middlewares = p.middlewares.Push(middleware)
|
||||
return p
|
||||
}
|
||||
func (p *Plugin[T]) SkipCommandAutoGen() *Plugin[T] {
|
||||
p.skipAutoCmd = true
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *PluginBuilder) Build() Plugin {
|
||||
if len(p.commands) == 0 && len(p.payloads) == 0 {
|
||||
log.Printf("no command or payloads for %s", p.name)
|
||||
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)
|
||||
return
|
||||
}
|
||||
return Plugin{
|
||||
p.name, p.commands,
|
||||
p.payloads, p.middlewares,
|
||||
command.exec(ctx, dbContext)
|
||||
}
|
||||
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)
|
||||
return
|
||||
}
|
||||
pl.exec(ctx, dbContext)
|
||||
}
|
||||
|
||||
func (p *Plugin) Execute(cmd string, ctx *MsgContext, dbContext *DatabaseContext) {
|
||||
(p.Commands[cmd])(ctx, dbContext)
|
||||
}
|
||||
|
||||
func (p *Plugin) ExecutePayload(payload string, ctx *MsgContext, dbContext *DatabaseContext) {
|
||||
(p.Payloads[payload])(ctx, dbContext)
|
||||
}
|
||||
|
||||
func (p *Plugin) executeMiddlewares(ctx *MsgContext, db *DatabaseContext) bool {
|
||||
for _, m := range p.Middlewares {
|
||||
func (p *Plugin[T]) executeMiddlewares(ctx *MsgContext, db *T) bool {
|
||||
for _, m := range p.middlewares {
|
||||
if !m.Execute(ctx, db) {
|
||||
return false
|
||||
}
|
||||
@@ -76,72 +152,29 @@ func (p *Plugin) executeMiddlewares(ctx *MsgContext, db *DatabaseContext) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
type Middleware struct {
|
||||
Name string
|
||||
Executor CommandExecutor
|
||||
Order int
|
||||
Async bool
|
||||
}
|
||||
type MiddlewareBuilder struct {
|
||||
name string
|
||||
executor CommandExecutor
|
||||
order int
|
||||
async bool
|
||||
}
|
||||
type MiddlewareExecutor[T DbContext] func(ctx *MsgContext, db *T) bool
|
||||
|
||||
func NewMiddleware(name string, executor CommandExecutor) *MiddlewareBuilder {
|
||||
return &MiddlewareBuilder{name: name, executor: executor, order: 0, async: false}
|
||||
}
|
||||
func (m *MiddlewareBuilder) SetOrder(order int) *MiddlewareBuilder {
|
||||
m.order = order
|
||||
return m
|
||||
}
|
||||
func (m *MiddlewareBuilder) SetAsync(async bool) *MiddlewareBuilder {
|
||||
m.async = async
|
||||
return m
|
||||
}
|
||||
func (m *MiddlewareBuilder) Build() Middleware {
|
||||
return Middleware{
|
||||
Name: m.name,
|
||||
Executor: m.executor,
|
||||
Order: m.order,
|
||||
Async: m.async,
|
||||
}
|
||||
}
|
||||
func (m Middleware) Execute(ctx *MsgContext, db *DatabaseContext) {
|
||||
if m.Async {
|
||||
go m.Executor(ctx, db)
|
||||
} else {
|
||||
m.Execute(ctx, db)
|
||||
}
|
||||
}
|
||||
|
||||
type PluginMiddlewareExecutor func(ctx *MsgContext, db *DatabaseContext) bool
|
||||
|
||||
// PluginMiddleware
|
||||
// Middleware
|
||||
// When async, returned value ignored
|
||||
type PluginMiddleware struct {
|
||||
executor PluginMiddlewareExecutor
|
||||
type Middleware[T DbContext] struct {
|
||||
name string
|
||||
executor MiddlewareExecutor[T]
|
||||
order int
|
||||
async bool
|
||||
}
|
||||
|
||||
func NewPluginMiddleware(executor PluginMiddlewareExecutor) *PluginMiddleware {
|
||||
return &PluginMiddleware{
|
||||
executor: executor,
|
||||
order: 0,
|
||||
async: false,
|
||||
}
|
||||
func NewMiddleware[T DbContext](name string, executor MiddlewareExecutor[T]) *Middleware[T] {
|
||||
return &Middleware[T]{name, executor, 0, false}
|
||||
}
|
||||
func (m *PluginMiddleware) SetOrder(order int) *PluginMiddleware {
|
||||
func (m *Middleware[T]) SetOrder(order int) *Middleware[T] {
|
||||
m.order = order
|
||||
return m
|
||||
}
|
||||
func (m *PluginMiddleware) SetAsync(async bool) *PluginMiddleware {
|
||||
func (m *Middleware[T]) SetAsync(async bool) *Middleware[T] {
|
||||
m.async = async
|
||||
return m
|
||||
}
|
||||
func (m *PluginMiddleware) 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
|
||||
|
||||
67
runners.go
67
runners.go
@@ -4,81 +4,72 @@ 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{
|
||||
// NewRunner creates a new Runner with async=true by default.
|
||||
// Builder methods (Onetime, Async, Timeout) modify the Runner in-place.
|
||||
// DO NOT call builder methods concurrently or after Execute().
|
||||
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)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
321
tgapi/api.go
321
tgapi/api.go
@@ -7,99 +7,326 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.nix13.pw/scuroneko/laniakea/utils"
|
||||
"git.nix13.pw/scuroneko/slog"
|
||||
)
|
||||
|
||||
type Api struct {
|
||||
token string
|
||||
client *http.Client
|
||||
Logger *slog.Logger
|
||||
// APIOpts holds configuration options for initializing the Telegram API client.
|
||||
// Use the provided setter methods to build options — do not construct directly.
|
||||
type APIOpts struct {
|
||||
token string
|
||||
client *http.Client
|
||||
useTestServer bool
|
||||
apiUrl string
|
||||
|
||||
limiter *utils.RateLimiter
|
||||
dropOverflowLimit bool
|
||||
}
|
||||
|
||||
func NewAPI(token string) *Api {
|
||||
// NewAPIOpts creates a new APIOpts with default values.
|
||||
// Use setter methods to customize behavior.
|
||||
func NewAPIOpts(token string) *APIOpts {
|
||||
return &APIOpts{
|
||||
token: token,
|
||||
client: nil,
|
||||
useTestServer: false,
|
||||
apiUrl: "https://api.telegram.org",
|
||||
}
|
||||
}
|
||||
|
||||
// SetHTTPClient sets a custom HTTP client. Use this for timeouts, proxies, or custom transport.
|
||||
// If not set, a default client with 45s timeout is used.
|
||||
func (opts *APIOpts) SetHTTPClient(client *http.Client) *APIOpts {
|
||||
if client != nil {
|
||||
opts.client = client
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
// UseTestServer enables use of Telegram's test server (https://api.test.telegram.org).
|
||||
// Only for development/testing.
|
||||
func (opts *APIOpts) UseTestServer(use bool) *APIOpts {
|
||||
opts.useTestServer = use
|
||||
return opts
|
||||
}
|
||||
|
||||
// SetAPIUrl overrides the default Telegram API URL.
|
||||
// Useful for self-hosted bots or proxies.
|
||||
func (opts *APIOpts) SetAPIUrl(apiUrl string) *APIOpts {
|
||||
if apiUrl != "" {
|
||||
opts.apiUrl = apiUrl
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
// SetLimiter sets a rate limiter to enforce Telegram's API limits.
|
||||
// Recommended: use utils.NewRateLimiter() for correct per-chat and global throttling.
|
||||
func (opts *APIOpts) SetLimiter(limiter *utils.RateLimiter) *APIOpts {
|
||||
opts.limiter = limiter
|
||||
return opts
|
||||
}
|
||||
|
||||
// SetLimiterDrop enables "drop mode" for rate limiting.
|
||||
// If true, requests exceeding limits return ErrDropOverflow immediately.
|
||||
// If false, requests block until capacity is available.
|
||||
func (opts *APIOpts) SetLimiterDrop(b bool) *APIOpts {
|
||||
opts.dropOverflowLimit = b
|
||||
return opts
|
||||
}
|
||||
|
||||
// API is the main Telegram Bot API client.
|
||||
// It manages HTTP requests, rate limiting, retries, and connection pooling.
|
||||
type API struct {
|
||||
token string
|
||||
client *http.Client
|
||||
logger *slog.Logger
|
||||
useTestServer bool
|
||||
apiUrl string
|
||||
|
||||
pool *workerPool
|
||||
Limiter *utils.RateLimiter
|
||||
dropOverflowLimit bool
|
||||
}
|
||||
|
||||
// NewAPI creates a new API client from options.
|
||||
// Always call CloseApi() when done to release resources.
|
||||
func NewAPI(opts *APIOpts) *API {
|
||||
l := slog.CreateLogger().Level(utils.GetLoggerLevel()).Prefix("API")
|
||||
l.AddWriter(l.CreateJsonStdoutWriter())
|
||||
client := &http.Client{Timeout: time.Second * 45}
|
||||
return &Api{token, client, l}
|
||||
}
|
||||
func (api *Api) CloseApi() error {
|
||||
return api.Logger.Close()
|
||||
|
||||
client := opts.client
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: time.Second * 45}
|
||||
}
|
||||
|
||||
pool := newWorkerPool(16, 256)
|
||||
pool.start(context.Background())
|
||||
|
||||
return &API{
|
||||
token: opts.token,
|
||||
client: client,
|
||||
logger: l,
|
||||
useTestServer: opts.useTestServer,
|
||||
apiUrl: opts.apiUrl,
|
||||
pool: pool,
|
||||
Limiter: opts.limiter,
|
||||
dropOverflowLimit: opts.dropOverflowLimit,
|
||||
}
|
||||
}
|
||||
|
||||
// CloseApi shuts down the internal worker pool and closes the logger.
|
||||
// Must be called to avoid resource leaks.
|
||||
func (api *API) CloseApi() error {
|
||||
api.pool.stop()
|
||||
return api.logger.Close()
|
||||
}
|
||||
|
||||
// GetLogger returns the internal logger for custom logging.
|
||||
func (api *API) GetLogger() *slog.Logger {
|
||||
return api.logger
|
||||
}
|
||||
|
||||
// ResponseParameters contains Telegram API response metadata (e.g., retry_after, migrate_to_chat_id).
|
||||
type ResponseParameters struct {
|
||||
MigrateToChatID *int64 `json:"migrate_to_chat_id,omitempty"`
|
||||
RetryAfter *int `json:"retry_after,omitempty"`
|
||||
}
|
||||
|
||||
// ApiResponse is the standard Telegram Bot API response structure.
|
||||
// Generic over Result type R.
|
||||
type ApiResponse[R any] struct {
|
||||
Ok bool `json:"ok"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Result R `json:"result,omitempty"`
|
||||
ErrorCode int `json:"error_code,omitempty"`
|
||||
Ok bool `json:"ok"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Result R `json:"result,omitempty"`
|
||||
ErrorCode int `json:"error_code,omitempty"`
|
||||
Parameters *ResponseParameters `json:"parameters,omitempty"`
|
||||
}
|
||||
|
||||
// TelegramRequest is an internal helper struct.
|
||||
// DO NOT USE NewRequest or NewRequestWithChatID — they are unsafe and discouraged.
|
||||
// Instead, use explicit methods like SendMessage, GetUpdates, etc.
|
||||
//
|
||||
// Why? Because using generics with arbitrary types P and R leads to:
|
||||
// - No compile-time validation of parameters
|
||||
// - No IDE autocompletion
|
||||
// - Runtime panics on malformed JSON
|
||||
// - Hard-to-debug errors
|
||||
//
|
||||
// Recommended: Define specific methods for each Telegram method (see below).
|
||||
type TelegramRequest[R, P any] struct {
|
||||
method string
|
||||
params P
|
||||
chatId int64
|
||||
}
|
||||
|
||||
// NewRequest and NewRequestWithChatID are DEPRECATED.
|
||||
// They encourage unsafe, untyped usage and bypass Go's type safety.
|
||||
// Instead, define explicit, type-safe methods for each Telegram API endpoint.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// func (api *API) SendMessage(ctx context.Context, chatID int64, text string) (Message, error) { ... }
|
||||
//
|
||||
// This provides:
|
||||
//
|
||||
// ✅ Compile-time validation
|
||||
// ✅ IDE autocompletion
|
||||
// ✅ Clear API surface
|
||||
// ✅ Better error messages
|
||||
//
|
||||
// DO NOT use these constructors in production code.
|
||||
// This can be used ONLY for testing or if you NEED method, that wasn't added as function.
|
||||
func NewRequest[R, P any](method string, params P) TelegramRequest[R, P] {
|
||||
return TelegramRequest[R, P]{method: method, params: params}
|
||||
return TelegramRequest[R, P]{method, params, 0}
|
||||
}
|
||||
func (r TelegramRequest[R, P]) DoWithContext(ctx context.Context, api *Api) (R, error) {
|
||||
|
||||
func NewRequestWithChatID[R, P any](method string, params P, chatId int64) TelegramRequest[R, P] {
|
||||
return TelegramRequest[R, P]{method, params, chatId}
|
||||
}
|
||||
|
||||
// doRequest performs a single HTTP request to Telegram API.
|
||||
// Handles rate limiting, retries on 429, and parses responses.
|
||||
// Must be called within a worker pool context if using DoWithContext.
|
||||
func (r TelegramRequest[R, P]) doRequest(ctx context.Context, api *API) (R, error) {
|
||||
var zero R
|
||||
|
||||
data, err := json.Marshal(r.params)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
return zero, fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
buf := bytes.NewBuffer(data)
|
||||
|
||||
u := fmt.Sprintf("https://api.telegram.org/bot%s/%s", api.token, r.method)
|
||||
if api.Logger != nil {
|
||||
api.Logger.Debugln(strings.ReplaceAll(fmt.Sprintf(
|
||||
"POST %s %s", u, buf.String(),
|
||||
), api.token, "<TOKEN>"))
|
||||
methodPrefix := ""
|
||||
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 {
|
||||
return zero, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", u, buf)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString))
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
req.ContentLength = int64(len(data))
|
||||
|
||||
res, err := api.client.Do(req)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return zero, fmt.Errorf("unexpected status code: %d", res.StatusCode)
|
||||
}
|
||||
for {
|
||||
// Apply rate limiting before making the request
|
||||
if api.Limiter != nil {
|
||||
if err := api.Limiter.Check(ctx, api.dropOverflowLimit, r.chatId); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
}
|
||||
|
||||
reader := io.LimitReader(res.Body, 10<<20)
|
||||
data, err = io.ReadAll(reader)
|
||||
api.logger.Debugln("REQ", url, string(data))
|
||||
|
||||
resp, err := api.client.Do(req)
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("HTTP request failed: %w", err)
|
||||
}
|
||||
|
||||
data, err = readBody(resp.Body)
|
||||
_ = resp.Body.Close() // ensure body is closed
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
api.logger.Debugln("RES", r.method, string(data))
|
||||
|
||||
response, err := parseBody[R](data)
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("failed to parse response: %w", err)
|
||||
}
|
||||
|
||||
if !response.Ok {
|
||||
// Handle rate limiting (429)
|
||||
if response.ErrorCode == 429 && response.Parameters != nil && response.Parameters.RetryAfter != nil {
|
||||
after := *response.Parameters.RetryAfter
|
||||
api.logger.Warnf("Rate limited by Telegram, retry after %d seconds (chat: %d)", after, r.chatId)
|
||||
|
||||
// Apply cooldown to global or chat-specific limiter
|
||||
if r.chatId > 0 {
|
||||
api.Limiter.SetChatLock(r.chatId, after)
|
||||
} else {
|
||||
api.Limiter.SetGlobalLock(after)
|
||||
}
|
||||
|
||||
// Wait and retry
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return zero, ctx.Err()
|
||||
case <-time.After(time.Duration(after) * time.Second):
|
||||
continue // retry request
|
||||
}
|
||||
}
|
||||
|
||||
// Other API errors
|
||||
return zero, fmt.Errorf("[%d] %s", response.ErrorCode, response.Description)
|
||||
}
|
||||
|
||||
return response.Result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// DoWithContext executes the request asynchronously via the worker pool.
|
||||
// Returns result or error via channel. Respects context cancellation.
|
||||
func (r TelegramRequest[R, P]) DoWithContext(ctx context.Context, api *API) (R, error) {
|
||||
var zero R
|
||||
|
||||
resultChan, err := api.pool.submit(ctx, func(ctx context.Context) (any, error) {
|
||||
return r.doRequest(ctx, api)
|
||||
})
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
if api.Logger != nil {
|
||||
api.Logger.Debugln(fmt.Sprintf("RES %s %s", r.method, string(data)))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return zero, ctx.Err()
|
||||
case res := <-resultChan:
|
||||
if res.err != nil {
|
||||
return zero, res.err
|
||||
}
|
||||
if val, ok := res.value.(R); ok {
|
||||
return val, nil
|
||||
}
|
||||
return zero, ErrPoolUnexpected
|
||||
}
|
||||
}
|
||||
|
||||
// Do executes the request synchronously with a background context.
|
||||
// Use only for simple, non-critical calls.
|
||||
func (r TelegramRequest[R, P]) Do(api *API) (R, error) {
|
||||
return r.DoWithContext(context.Background(), api)
|
||||
}
|
||||
|
||||
// readBody reads and limits response body to prevent memory exhaustion.
|
||||
// Telegram responses are typically small (<1MB), but we cap at 10MB.
|
||||
func readBody(body io.ReadCloser) ([]byte, error) {
|
||||
reader := io.LimitReader(body, 10<<20) // 10 MB
|
||||
return io.ReadAll(reader)
|
||||
}
|
||||
|
||||
// parseBody unmarshals Telegram API response and returns structured result.
|
||||
// Returns ErrRateLimit internally if error_code == 429 — caller must handle via response.Ok check.
|
||||
func parseBody[R any](data []byte) (ApiResponse[R], error) {
|
||||
var resp ApiResponse[R]
|
||||
err = json.Unmarshal(data, &resp)
|
||||
err := json.Unmarshal(data, &resp)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
return resp, fmt.Errorf("failed to unmarshal JSON: %w", err)
|
||||
}
|
||||
|
||||
if !resp.Ok {
|
||||
return zero, fmt.Errorf("[%d] %s", resp.ErrorCode, resp.Description)
|
||||
if resp.ErrorCode == 429 {
|
||||
return resp, ErrRateLimit // internal use only
|
||||
}
|
||||
return resp, fmt.Errorf("[%d] %s", resp.ErrorCode, resp.Description)
|
||||
}
|
||||
return resp.Result, nil
|
||||
|
||||
}
|
||||
func (r TelegramRequest[R, P]) Do(api *Api) (R, error) {
|
||||
ctx := context.Background()
|
||||
return r.DoWithContext(ctx, api)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package tgapi
|
||||
|
||||
type SendPhotoP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -23,14 +23,14 @@ type SendPhotoP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendPhoto(params SendPhotoP) (Message, error) {
|
||||
req := NewRequest[Message]("sendPhoto", params)
|
||||
func (api *API) SendPhoto(params SendPhotoP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendPhoto", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendAudioP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -52,14 +52,14 @@ type SendAudioP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendAudio(params SendAudioP) (Message, error) {
|
||||
req := NewRequest[Message]("sendAudio", params)
|
||||
func (api *API) SendAudio(params SendAudioP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendAudio", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendDocumentP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -78,14 +78,14 @@ type SendDocumentP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendDocument(params SendDocumentP) (Message, error) {
|
||||
req := NewRequest[Message]("sendDocument", params)
|
||||
func (api *API) SendDocument(params SendDocumentP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendDocument", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendVideoP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -113,14 +113,14 @@ type SendVideoP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendVideo(params SendVideoP) (Message, error) {
|
||||
req := NewRequest[Message]("sendVideo", params)
|
||||
func (api *API) SendVideo(params SendVideoP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendVideo", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendAnimationP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -144,14 +144,14 @@ type SendAnimationP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendAnimation(params SendAnimationP) (Message, error) {
|
||||
req := NewRequest[Message]("sendAnimation", params)
|
||||
func (api *API) SendAnimation(params SendAnimationP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendAnimation", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendVoiceP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -170,14 +170,14 @@ type SendVoiceP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendVoice(params *SendVoiceP) (Message, error) {
|
||||
req := NewRequest[Message]("sendVoice", params)
|
||||
func (api *API) SendVoice(params *SendVoiceP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendVoice", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendVideoNoteP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -194,14 +194,14 @@ type SendVideoNoteP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendVideoNote(params SendVideoNoteP) (Message, error) {
|
||||
req := NewRequest[Message]("sendVideoNote", params)
|
||||
func (api *API) SendVideoNote(params SendVideoNoteP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendVideoNote", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendPaidMediaP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
StarCount int `json:"star_count,omitempty"`
|
||||
@@ -221,14 +221,14 @@ type SendPaidMediaP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendPaidMedia(params SendPaidMediaP) (Message, error) {
|
||||
req := NewRequest[Message]("sendPaidMedia", params)
|
||||
func (api *API) SendPaidMedia(params SendPaidMediaP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendPaidMedia", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendMediaGroupP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -240,7 +240,7 @@ type SendMediaGroupP struct {
|
||||
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendMediaGroup(params SendMediaGroupP) (Message, error) {
|
||||
req := NewRequest[Message]("sendMediaGroup", params)
|
||||
func (api *API) SendMediaGroup(params SendMediaGroupP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendMediaGroup", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ type SetMyCommandsP struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetMyCommands(params SetMyCommandsP) (bool, error) {
|
||||
func (api *API) SetMyCommands(params SetMyCommandsP) (bool, error) {
|
||||
req := NewRequest[bool]("setMyCommands", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -16,7 +16,7 @@ type DeleteMyCommandsP struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteMyCommands(params DeleteMyCommandsP) (bool, error) {
|
||||
func (api *API) DeleteMyCommands(params DeleteMyCommandsP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteMyCommands", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -26,7 +26,7 @@ type GetMyCommands struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetMyCommands(params GetMyCommands) ([]BotCommand, error) {
|
||||
func (api *API) GetMyCommands(params GetMyCommands) ([]BotCommand, error) {
|
||||
req := NewRequest[[]BotCommand]("getMyCommands", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -36,7 +36,7 @@ type SetMyName struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetMyName(params SetMyName) (bool, error) {
|
||||
func (api *API) SetMyName(params SetMyName) (bool, error) {
|
||||
req := NewRequest[bool]("setMyName", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ type GetMyName struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetMyName(params GetMyName) (BotName, error) {
|
||||
func (api *API) GetMyName(params GetMyName) (BotName, error) {
|
||||
req := NewRequest[BotName]("getMyName", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -55,7 +55,7 @@ type SetMyDescription struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetMyDescription(params SetMyDescription) (bool, error) {
|
||||
func (api *API) SetMyDescription(params SetMyDescription) (bool, error) {
|
||||
req := NewRequest[bool]("setMyDescription", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -64,7 +64,7 @@ type GetMyDescription struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetMyDescription(params GetMyDescription) (BotDescription, error) {
|
||||
func (api *API) GetMyDescription(params GetMyDescription) (BotDescription, error) {
|
||||
req := NewRequest[BotDescription]("getMyDescription", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -74,7 +74,7 @@ type SetMyShortDescription struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetMyShortDescription(params SetMyShortDescription) (bool, error) {
|
||||
func (api *API) SetMyShortDescription(params SetMyShortDescription) (bool, error) {
|
||||
req := NewRequest[bool]("setMyShortDescription", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -83,7 +83,7 @@ type GetMyShortDescription struct {
|
||||
Language string `json:"language_code,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetMyShortDescription(params GetMyShortDescription) (BotShortDescription, error) {
|
||||
func (api *API) GetMyShortDescription(params GetMyShortDescription) (BotShortDescription, error) {
|
||||
req := NewRequest[BotShortDescription]("getMyShortDescription", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -92,11 +92,11 @@ type SetMyProfilePhotoP struct {
|
||||
Photo InputProfilePhoto `json:"photo"`
|
||||
}
|
||||
|
||||
func (api *Api) SetMyProfilePhoto(params SetMyProfilePhotoP) (bool, error) {
|
||||
func (api *API) SetMyProfilePhoto(params SetMyProfilePhotoP) (bool, error) {
|
||||
req := NewRequest[bool]("setMyProfilePhoto", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) RemoveMyProfilePhoto() (bool, error) {
|
||||
func (api *API) RemoveMyProfilePhoto() (bool, error) {
|
||||
req := NewRequest[bool]("removeMyProfilePhoto", NoParams)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -106,7 +106,7 @@ type SetChatMenuButtonP struct {
|
||||
MenuButton MenuButtonType `json:"menu_button"`
|
||||
}
|
||||
|
||||
func (api *Api) SetChatMenuButton(params SetChatMenuButtonP) (bool, error) {
|
||||
func (api *API) SetChatMenuButton(params SetChatMenuButtonP) (bool, error) {
|
||||
req := NewRequest[bool]("setChatMenuButton", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -115,7 +115,7 @@ type GetChatMenuButtonP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetChatMenuButton(params GetChatMenuButtonP) (BaseMenuButton, error) {
|
||||
func (api *API) GetChatMenuButton(params GetChatMenuButtonP) (BaseMenuButton, error) {
|
||||
req := NewRequest[BaseMenuButton]("getChatMenuButton", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -125,7 +125,7 @@ type SetMyDefaultAdministratorRightsP struct {
|
||||
ForChannels bool `json:"for_channels"`
|
||||
}
|
||||
|
||||
func (api *Api) SetMyDefaultAdministratorRights(params SetMyDefaultAdministratorRightsP) (bool, error) {
|
||||
func (api *API) SetMyDefaultAdministratorRights(params SetMyDefaultAdministratorRightsP) (bool, error) {
|
||||
req := NewRequest[bool]("setMyDefaultAdministratorRights", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -134,12 +134,12 @@ type GetMyDefaultAdministratorRightsP struct {
|
||||
ForChannels bool `json:"for_channels"`
|
||||
}
|
||||
|
||||
func (api *Api) GetMyDefaultAdministratorRights(params GetMyDefaultAdministratorRightsP) (ChatAdministratorRights, error) {
|
||||
func (api *API) GetMyDefaultAdministratorRights(params GetMyDefaultAdministratorRightsP) (ChatAdministratorRights, error) {
|
||||
req := NewRequest[ChatAdministratorRights]("getMyDefaultAdministratorRights", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
func (api *Api) GetAvailableGifts() (Gifts, error) {
|
||||
func (api *API) GetAvailableGifts() (Gifts, error) {
|
||||
req := NewRequest[Gifts]("getAvailableGifts", NoParams)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -154,7 +154,7 @@ type SendGiftP struct {
|
||||
TextEntities []MessageEntity `json:"text_entities,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendGift(params SendGiftP) (bool, error) {
|
||||
func (api *API) SendGift(params SendGiftP) (bool, error) {
|
||||
req := NewRequest[bool]("sendGift", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -168,7 +168,7 @@ type GiftPremiumSubscriptionP struct {
|
||||
TextEntities []MessageEntity `json:"text_entities,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GiftPremiumSubscription(params GiftPremiumSubscriptionP) (bool, error) {
|
||||
func (api *API) GiftPremiumSubscription(params GiftPremiumSubscriptionP) (bool, error) {
|
||||
req := NewRequest[bool]("giftPremiumSubscription", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ type BotCommandScopeType string
|
||||
const (
|
||||
BotCommandScopeDefaultType BotCommandScopeType = "default"
|
||||
BotCommandScopePrivateType BotCommandScopeType = "all_private_chats"
|
||||
BotCommandScopeGroupType BotCommandScopeType = "all_groups_chats"
|
||||
BotCommandScopeGroupType BotCommandScopeType = "all_group_chats"
|
||||
BotCommandScopeAllChatAdministratorsType BotCommandScopeType = "all_chat_administrators"
|
||||
BotCommandScopeChatType BotCommandScopeType = "chat"
|
||||
BotCommandScopeChatAdministratorsType BotCommandScopeType = "chat_administrators"
|
||||
|
||||
@@ -5,7 +5,7 @@ type VerifyUserP struct {
|
||||
CustomDescription string `json:"custom_description,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) VerifyUser(params VerifyUserP) (bool, error) {
|
||||
func (api *API) VerifyUser(params VerifyUserP) (bool, error) {
|
||||
req := NewRequest[bool]("verifyUser", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ type VerifyChatP struct {
|
||||
CustomDescription string `json:"custom_description,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) VerifyChat(params VerifyChatP) (bool, error) {
|
||||
func (api *API) VerifyChat(params VerifyChatP) (bool, error) {
|
||||
req := NewRequest[bool]("verifyChat", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -24,7 +24,7 @@ type RemoveUserVerificationP struct {
|
||||
UserID int `json:"user_id"`
|
||||
}
|
||||
|
||||
func (api *Api) RemoveUserVerification(params RemoveUserVerificationP) (bool, error) {
|
||||
func (api *API) RemoveUserVerification(params RemoveUserVerificationP) (bool, error) {
|
||||
req := NewRequest[bool]("removeUserVerification", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -33,7 +33,7 @@ type RemoveChatVerificationP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) RemoveChatVerification(params RemoveChatVerificationP) (bool, error) {
|
||||
func (api *API) RemoveChatVerification(params RemoveChatVerificationP) (bool, error) {
|
||||
req := NewRequest[bool]("removeChatVerification", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -44,7 +44,7 @@ type ReadBusinessMessageP struct {
|
||||
MessageID int `json:"message_id"`
|
||||
}
|
||||
|
||||
func (api *Api) ReadBusinessMessage(params ReadBusinessMessageP) (bool, error) {
|
||||
func (api *API) ReadBusinessMessage(params ReadBusinessMessageP) (bool, error) {
|
||||
req := NewRequest[bool]("readBusinessMessage", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -54,7 +54,7 @@ type DeleteBusinessMessageP struct {
|
||||
MessageIDs []int `json:"message_ids"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteBusinessMessage(params DeleteBusinessMessageP) (bool, error) {
|
||||
func (api *API) DeleteBusinessMessage(params DeleteBusinessMessageP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteBusinessMessage", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -65,7 +65,7 @@ type SetBusinessAccountNameP struct {
|
||||
LastName string `json:"last_name,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetBusinessAccountName(params SetBusinessAccountNameP) (bool, error) {
|
||||
func (api *API) SetBusinessAccountName(params SetBusinessAccountNameP) (bool, error) {
|
||||
req := NewRequest[bool]("setBusinessAccountName", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -75,7 +75,7 @@ type SetBusinessAccountUsernameP struct {
|
||||
Username string `json:"username,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetBusinessAccountUsername(params SetBusinessAccountUsernameP) (bool, error) {
|
||||
func (api *API) SetBusinessAccountUsername(params SetBusinessAccountUsernameP) (bool, error) {
|
||||
req := NewRequest[bool]("setBusinessAccountUsername", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -85,7 +85,7 @@ type SetBusinessAccountBioP struct {
|
||||
Bio string `json:"bio,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetBusinessAccountBio(params SetBusinessAccountBioP) (bool, error) {
|
||||
func (api *API) SetBusinessAccountBio(params SetBusinessAccountBioP) (bool, error) {
|
||||
req := NewRequest[bool]("setBusinessAccountBio", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -96,7 +96,7 @@ type SetBusinessAccountProfilePhoto struct {
|
||||
IsPublic bool `json:"is_public,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetBusinessAccountProfilePhoto(params SetBusinessAccountProfilePhoto) (bool, error) {
|
||||
func (api *API) SetBusinessAccountProfilePhoto(params SetBusinessAccountProfilePhoto) (bool, error) {
|
||||
req := NewRequest[bool]("setBusinessAccountProfilePhoto", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -106,7 +106,7 @@ type RemoveBusinessAccountProfilePhotoP struct {
|
||||
IsPublic bool `json:"is_public,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) RemoveBusinessAccountProfilePhoto(params RemoveBusinessAccountProfilePhotoP) (bool, error) {
|
||||
func (api *API) RemoveBusinessAccountProfilePhoto(params RemoveBusinessAccountProfilePhotoP) (bool, error) {
|
||||
req := NewRequest[bool]("removeBusinessAccountProfilePhoto", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -117,7 +117,7 @@ type SetBusinessAccountGiftSettingsP struct {
|
||||
AcceptedGiftTypes AcceptedGiftTypes `json:"accepted_gift_types"`
|
||||
}
|
||||
|
||||
func (api *Api) SetBusinessAccountGiftSettings(params SetBusinessAccountGiftSettingsP) (bool, error) {
|
||||
func (api *API) SetBusinessAccountGiftSettings(params SetBusinessAccountGiftSettingsP) (bool, error) {
|
||||
req := NewRequest[bool]("setBusinessAccountGiftSettings", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -126,7 +126,7 @@ type GetBusinessAccountStarBalanceP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetBusinessAccountStarBalance(params GetBusinessAccountStarBalanceP) (StarAmount, error) {
|
||||
func (api *API) GetBusinessAccountStarBalance(params GetBusinessAccountStarBalanceP) (StarAmount, error) {
|
||||
req := NewRequest[StarAmount]("getBusinessAccountGiftSettings", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -136,7 +136,7 @@ type TransferBusinessAccountStartP struct {
|
||||
StarCount int `json:"star_count"`
|
||||
}
|
||||
|
||||
func (api *Api) TransferBusinessAccountStart(params TransferBusinessAccountStartP) (bool, error) {
|
||||
func (api *API) TransferBusinessAccountStart(params TransferBusinessAccountStartP) (bool, error) {
|
||||
req := NewRequest[bool]("transferBusinessAccountStart", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -155,7 +155,7 @@ type GetBusinessAccountGiftsP struct {
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetBusinessAccountGifts(params GetBusinessAccountGiftsP) (OwnedGifts, error) {
|
||||
func (api *API) GetBusinessAccountGifts(params GetBusinessAccountGiftsP) (OwnedGifts, error) {
|
||||
req := NewRequest[OwnedGifts]("getBusinessAccountGifts", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -165,7 +165,7 @@ type ConvertGiftToStarsP struct {
|
||||
OwnedGiftID string `json:"owned_gift_id"`
|
||||
}
|
||||
|
||||
func (api *Api) ConvertGiftToStars(params ConvertGiftToStarsP) (bool, error) {
|
||||
func (api *API) ConvertGiftToStars(params ConvertGiftToStarsP) (bool, error) {
|
||||
req := NewRequest[bool]("convertGiftToStars", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -177,7 +177,7 @@ type UpgradeGiftP struct {
|
||||
StarCount int `json:"star_count,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) UpgradeGift(params UpgradeGiftP) (bool, error) {
|
||||
func (api *API) UpgradeGift(params UpgradeGiftP) (bool, error) {
|
||||
req := NewRequest[bool]("upgradeGift", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -189,7 +189,7 @@ type TransferGiftP struct {
|
||||
StarCount int `json:"star_count,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) TransferGift(params TransferGiftP) (bool, error) {
|
||||
func (api *API) TransferGift(params TransferGiftP) (bool, error) {
|
||||
req := NewRequest[bool]("transferGift", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -208,11 +208,11 @@ type PostStoryP struct {
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) PostStoryPhoto(params PostStoryP) (Story, error) {
|
||||
func (api *API) PostStoryPhoto(params PostStoryP) (Story, error) {
|
||||
req := NewRequest[Story]("postStory", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) PostStoryVideo(params PostStoryP) (Story, error) {
|
||||
func (api *API) PostStoryVideo(params PostStoryP) (Story, error) {
|
||||
req := NewRequest[Story]("postStory", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -226,7 +226,7 @@ type RepostStoryP struct {
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) RepostStory(params RepostStoryP) (Story, error) {
|
||||
func (api *API) RepostStory(params RepostStoryP) (Story, error) {
|
||||
req := NewRequest[Story]("repostStory", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -242,7 +242,7 @@ type EditStoryP struct {
|
||||
Areas []StoryArea `json:"areas,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) EditStory(params EditStoryP) (Story, error) {
|
||||
func (api *API) EditStory(params EditStoryP) (Story, error) {
|
||||
req := NewRequest[Story]("editStory", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -252,7 +252,7 @@ type DeleteStoryP struct {
|
||||
StoryID int `json:"story_id"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteStory(params DeleteStoryP) (bool, error) {
|
||||
func (api *API) DeleteStory(params DeleteStoryP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteStory", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
package tgapi
|
||||
|
||||
type BanChatMemberP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
UntilDate int `json:"until_date,omitempty"`
|
||||
RevokeMessages bool `json:"revoke_messages,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
UntilDate int `json:"until_date,omitempty"`
|
||||
RevokeMessages bool `json:"revoke_messages,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) BanChatMember(params BanChatMemberP) (bool, error) {
|
||||
req := NewRequest[bool]("banChatMember", params)
|
||||
func (api *API) BanChatMember(params BanChatMemberP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("banChatMember", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type UnbanChatMemberP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
OnlyIfBanned bool `json:"only_if_banned"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
OnlyIfBanned bool `json:"only_if_banned"`
|
||||
}
|
||||
|
||||
func (api *Api) UnbanChatMember(params UnbanChatMemberP) (bool, error) {
|
||||
req := NewRequest[bool]("unbanChatMember", params)
|
||||
func (api *API) UnbanChatMember(params UnbanChatMemberP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("unbanChatMember", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type RestrictChatMemberP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
Permissions ChatPermissions `json:"permissions"`
|
||||
UseIndependentChatPermissions bool `json:"use_independent_chat_permissions,omitempty"`
|
||||
UntilDate int `json:"until_date,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) RestrictChatMember(params RestrictChatMemberP) (bool, error) {
|
||||
req := NewRequest[bool]("restrictChatMember", params)
|
||||
func (api *API) RestrictChatMember(params RestrictChatMemberP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("restrictChatMember", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type PromoteChatMember struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
IsAnonymous bool `json:"is_anonymous,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
IsAnonymous bool `json:"is_anonymous,omitempty"`
|
||||
|
||||
CanManageChat bool `json:"can_manage_chat,omitempty"`
|
||||
CanDeleteMessages bool `json:"can_delete_messages,omitempty"`
|
||||
@@ -56,79 +56,91 @@ type PromoteChatMember struct {
|
||||
CanPinMessages bool `json:"can_pin_messages,omitempty"`
|
||||
CanManageTopics bool `json:"can_manage_topics,omitempty"`
|
||||
CanManageDirectMessages bool `json:"can_manage_direct_messages,omitempty"`
|
||||
CanManageTags bool `json:"can_manage_tags,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) PromoteChatMember(params PromoteChatMember) (bool, error) {
|
||||
req := NewRequest[bool]("promoteChatMember", params)
|
||||
func (api *API) PromoteChatMember(params PromoteChatMember) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("promoteChatMember", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SetChatAdministratorCustomTitleP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
CustomTitle string `json:"custom_title"`
|
||||
}
|
||||
|
||||
func (api *Api) SetChatAdministratorCustomTitle(params SetChatAdministratorCustomTitleP) (bool, error) {
|
||||
req := NewRequest[bool]("setChatAdministratorCustomTitle", params)
|
||||
func (api *API) SetChatAdministratorCustomTitle(params SetChatAdministratorCustomTitleP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("setChatAdministratorCustomTitle", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SetChatMemberTagP struct {
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
Tag string `json:"tag,omitempty"`
|
||||
}
|
||||
|
||||
func (api *API) SetChatMemberTag(params SetChatMemberTagP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("setChatMemberTag", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type BanChatSenderChatP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
SenderChatID int `json:"sender_chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
SenderChatID int64 `json:"sender_chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) BanChatSenderChat(params BanChatSenderChatP) (bool, error) {
|
||||
req := NewRequest[bool]("banChatSenderChat", params)
|
||||
func (api *API) BanChatSenderChat(params BanChatSenderChatP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("banChatSenderChat", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type UnbanChatSenderChatP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
SenderChatID int `json:"sender_chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
SenderChatID int64 `json:"sender_chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) UnbanChatSenderChat(params BanChatSenderChatP) (bool, error) {
|
||||
req := NewRequest[bool]("unbanChatSenderChat", params)
|
||||
func (api *API) UnbanChatSenderChat(params BanChatSenderChatP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("unbanChatSenderChat", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SetChatPermissionsP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Permissions ChatPermissions `json:"permissions"`
|
||||
UseIndependentChatPermissions bool `json:"use_independent_chat_permissions,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetChatPermissions(params SetChatPermissionsP) (bool, error) {
|
||||
req := NewRequest[bool]("setChatPermissions", params)
|
||||
func (api *API) SetChatPermissions(params SetChatPermissionsP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("setChatPermissions", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type ExportChatInviteLinkP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) ExportChatInviteLink(params ExportChatInviteLinkP) (string, error) {
|
||||
req := NewRequest[string]("exportChatInviteLink", params)
|
||||
func (api *API) ExportChatInviteLink(params ExportChatInviteLinkP) (string, error) {
|
||||
req := NewRequestWithChatID[string]("exportChatInviteLink", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type CreateChatInviteLinkP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
ExpireDate int `json:"expire_date,omitempty"`
|
||||
MemberLimit int `json:"member_limit,omitempty"`
|
||||
CreatesJoinRequest int `json:"creates_join_request,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) CreateChatInviteLink(params CreateChatInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequest[ChatInviteLink]("createChatInviteLink", params)
|
||||
func (api *API) CreateChatInviteLink(params CreateChatInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequestWithChatID[ChatInviteLink]("createChatInviteLink", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type EditChatInviteLinkP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
InviteLink string `json:"invite_link"`
|
||||
|
||||
Name string `json:"name,omitempty"`
|
||||
@@ -137,207 +149,209 @@ type EditChatInviteLinkP struct {
|
||||
CreatesJoinRequest int `json:"creates_join_request,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) EditChatInviteLink(params EditChatInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequest[ChatInviteLink]("editChatInviteLink", params)
|
||||
func (api *API) EditChatInviteLink(params EditChatInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequestWithChatID[ChatInviteLink]("editChatInviteLink", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type CreateChatSubscriptionInviteLinkP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
SubscriptionPeriod int `json:"subscription_period,omitempty"`
|
||||
SubscriptionPrice int `json:"subscription_price,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) CreateChatSubscriptionInviteLink(params CreateChatSubscriptionInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequest[ChatInviteLink]("createChatSubscriptionInviteLink", params)
|
||||
func (api *API) CreateChatSubscriptionInviteLink(params CreateChatSubscriptionInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequestWithChatID[ChatInviteLink]("createChatSubscriptionInviteLink", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type EditChatSubscriptionInviteLinkP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
InviteLink string `json:"invite_link"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) EditChatSubscriptionInviteLink(params EditChatSubscriptionInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequest[ChatInviteLink]("editChatSubscriptionInviteLink", params)
|
||||
func (api *API) EditChatSubscriptionInviteLink(params EditChatSubscriptionInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequestWithChatID[ChatInviteLink]("editChatSubscriptionInviteLink", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type RevokeChatInviteLinkP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
InviteLink string `json:"invite_link"`
|
||||
}
|
||||
|
||||
func (api *Api) RevokeChatInviteLink(params RevokeChatInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequest[ChatInviteLink]("revokeChatInviteLink", params)
|
||||
func (api *API) RevokeChatInviteLink(params RevokeChatInviteLinkP) (ChatInviteLink, error) {
|
||||
req := NewRequestWithChatID[ChatInviteLink]("revokeChatInviteLink", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type ApproveChatJoinRequestP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
}
|
||||
|
||||
func (api *Api) ApproveChatJoinRequest(params ApproveChatJoinRequestP) (bool, error) {
|
||||
req := NewRequest[bool]("approveChatJoinRequest", params)
|
||||
func (api *API) ApproveChatJoinRequest(params ApproveChatJoinRequestP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("approveChatJoinRequest", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type DeclineChatJoinRequestP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
}
|
||||
|
||||
func (api *Api) DeclineChatJoinRequest(params DeclineChatJoinRequestP) (bool, error) {
|
||||
req := NewRequest[bool]("declineChatJoinRequest", params)
|
||||
func (api *API) DeclineChatJoinRequest(params DeclineChatJoinRequestP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("declineChatJoinRequest", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
func (api *Api) SetChatPhoto() {
|
||||
func (api *API) SetChatPhoto() {
|
||||
uploader := NewUploader(api)
|
||||
defer uploader.Close()
|
||||
defer func() {
|
||||
_ = uploader.Close()
|
||||
}()
|
||||
}
|
||||
|
||||
type DeleteChatPhotoP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteChatPhoto(params DeleteChatPhotoP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteChatPhoto", params)
|
||||
func (api *API) DeleteChatPhoto(params DeleteChatPhotoP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("deleteChatPhoto", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SetChatTitleP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
func (api *Api) SetChatTitle(params SetChatTitleP) (bool, error) {
|
||||
req := NewRequest[bool]("setChatTitle", params)
|
||||
func (api *API) SetChatTitle(params SetChatTitleP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("setChatTitle", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SetChatDescriptionP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func (api *Api) SetChatDescription(params SetChatDescriptionP) (bool, error) {
|
||||
req := NewRequest[bool]("setChatDescription", params)
|
||||
func (api *API) SetChatDescription(params SetChatDescriptionP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("setChatDescription", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type PinChatMessageP struct {
|
||||
BusinessConnectionID *string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
DisableNotification bool `json:"disable_notification,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) PinChatMessage(params PinChatMessageP) (bool, error) {
|
||||
req := NewRequest[bool]("pinChatMessage", params)
|
||||
func (api *API) PinChatMessage(params PinChatMessageP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("pinChatMessage", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type UnpinChatMessageP struct {
|
||||
BusinessConnectionID *string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
}
|
||||
|
||||
func (api *Api) UnpinChatMessage(params UnpinChatMessageP) (bool, error) {
|
||||
req := NewRequest[bool]("unpinChatMessage", params)
|
||||
func (api *API) UnpinChatMessage(params UnpinChatMessageP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("unpinChatMessage", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type UnpinAllChatMessagesP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) UnpinAllChatMessages(params UnpinAllChatMessagesP) (bool, error) {
|
||||
req := NewRequest[bool]("unpinAllChatMessages", params)
|
||||
func (api *API) UnpinAllChatMessages(params UnpinAllChatMessagesP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("unpinAllChatMessages", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type LeaveChatP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) LeaveChat(params LeaveChatP) (bool, error) {
|
||||
req := NewRequest[bool]("leaveChatP", params)
|
||||
func (api *API) LeaveChat(params LeaveChatP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("leaveChatP", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type GetChatP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetChatP(params GetChatP) (ChatFullInfo, error) {
|
||||
req := NewRequest[ChatFullInfo]("getChatP", params)
|
||||
func (api *API) GetChatP(params GetChatP) (ChatFullInfo, error) {
|
||||
req := NewRequestWithChatID[ChatFullInfo]("getChatP", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type GetChatAdministratorsP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetChatAdministrators(params GetChatAdministratorsP) ([]ChatMember, error) {
|
||||
req := NewRequest[[]ChatMember]("getChatAdministrators", params)
|
||||
func (api *API) GetChatAdministrators(params GetChatAdministratorsP) ([]ChatMember, error) {
|
||||
req := NewRequestWithChatID[[]ChatMember]("getChatAdministrators", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type GetChatMembersCountP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetChatMemberCount(params GetChatMembersCountP) (int, error) {
|
||||
req := NewRequest[int]("getChatMemberCount", params)
|
||||
func (api *API) GetChatMemberCount(params GetChatMembersCountP) (int, error) {
|
||||
req := NewRequestWithChatID[int]("getChatMemberCount", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type GetChatMemberP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetChatMember(params GetChatMemberP) (ChatMember, error) {
|
||||
req := NewRequest[ChatMember]("getChatMember", params)
|
||||
func (api *API) GetChatMember(params GetChatMemberP) (ChatMember, error) {
|
||||
req := NewRequestWithChatID[ChatMember]("getChatMember", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SetChatStickerSetP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
StickerSetName string `json:"sticker_set_name"`
|
||||
}
|
||||
|
||||
func (api *Api) SetChatStickerSet(params SetChatStickerSetP) (bool, error) {
|
||||
req := NewRequest[bool]("setChatStickerSet", params)
|
||||
func (api *API) SetChatStickerSet(params SetChatStickerSetP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("setChatStickerSet", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type DeleteChatStickerSetP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteChatStickerSet(params DeleteChatStickerSetP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteChatStickerSet", params)
|
||||
func (api *API) DeleteChatStickerSet(params DeleteChatStickerSetP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("deleteChatStickerSet", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type GetUserChatBoostsP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
UserID int `json:"user_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetUserChatBoosts(params GetUserChatBoostsP) (UserChatBoosts, error) {
|
||||
req := NewRequest[UserChatBoosts]("getUserChatBoosts", params)
|
||||
func (api *API) GetUserChatBoosts(params GetUserChatBoostsP) (UserChatBoosts, error) {
|
||||
req := NewRequestWithChatID[UserChatBoosts]("getUserChatBoosts", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type GetChatGiftsP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ExcludeUnsaved bool `json:"exclude_unsaved,omitempty"`
|
||||
ExcludeSaved bool `json:"exclude_saved,omitempty"`
|
||||
ExcludeUnlimited bool `json:"exclude_unlimited,omitempty"`
|
||||
@@ -350,7 +364,7 @@ type GetChatGiftsP struct {
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetChatGifts(params GetChatGiftsP) (OwnedGifts, error) {
|
||||
req := NewRequest[OwnedGifts]("getChatGifts", params)
|
||||
func (api *API) GetChatGifts(params GetChatGiftsP) (OwnedGifts, error) {
|
||||
req := NewRequestWithChatID[OwnedGifts]("getChatGifts", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package tgapi
|
||||
|
||||
type Chat struct {
|
||||
ID int `json:"id"`
|
||||
ID int64 `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
Username *string `json:"username,omitempty"`
|
||||
@@ -99,6 +99,7 @@ type ChatPermissions struct {
|
||||
CanSendPolls bool `json:"can_send_polls"`
|
||||
CanSendOtherMessages bool `json:"can_send_other_messages"`
|
||||
CanAddWebPagePreview bool `json:"can_add_web_page_preview"`
|
||||
CatEditTag bool `json:"cat_edit_tag"`
|
||||
CanChangeInfo bool `json:"can_change_info"`
|
||||
CanInviteUsers bool `json:"can_invite_users"`
|
||||
CanPinMessages bool `json:"can_pin_messages"`
|
||||
@@ -137,6 +138,7 @@ const (
|
||||
type ChatMember struct {
|
||||
Status ChatMemberStatusType `json:"status"`
|
||||
User User `json:"user"`
|
||||
Tag string `json:"tag,omitempty"`
|
||||
|
||||
// Owner
|
||||
IsAnonymous *bool `json:"is_anonymous"`
|
||||
@@ -160,6 +162,7 @@ type ChatMember struct {
|
||||
CanPinMessages *bool `json:"can_pin_messages,omitempty"`
|
||||
CanManageTopics *bool `json:"can_manage_topics,omitempty"`
|
||||
CanManageDirectMessages *bool `json:"can_manage_direct_messages,omitempty"`
|
||||
CanManageTags *bool `json:"can_manage_tags,omitempty"`
|
||||
|
||||
// Member
|
||||
UntilDate *int `json:"until_date,omitempty"`
|
||||
@@ -175,6 +178,7 @@ type ChatMember struct {
|
||||
CanSendPolls *bool `json:"can_send_polls,omitempty"`
|
||||
CanSendOtherMessages *bool `json:"can_send_other_messages,omitempty"`
|
||||
CanAddWebPagePreview *bool `json:"can_add_web_page_preview,omitempty"`
|
||||
CanEditTag *bool `json:"can_edit_tag,omitempty"`
|
||||
}
|
||||
|
||||
type ChatBoostSource struct {
|
||||
@@ -215,6 +219,7 @@ type ChatAdministratorRights struct {
|
||||
CanPinMessages *bool `json:"can_pin_messages,omitempty"`
|
||||
CanManageTopics *bool `json:"can_manage_topics,omitempty"`
|
||||
CanManageDirectMessages *bool `json:"can_manage_direct_messages,omitempty"`
|
||||
CanManageTags *bool `json:"can_manage_tags,omitempty"`
|
||||
}
|
||||
|
||||
type ChatBoostUpdated struct {
|
||||
|
||||
7
tgapi/errors.go
Normal file
7
tgapi/errors.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package tgapi
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrRateLimit = errors.New("rate limit exceeded")
|
||||
var ErrPoolUnexpected = errors.New("unexpected response from pool")
|
||||
var ErrPoolQueueFull = errors.New("worker pool queue full")
|
||||
@@ -1,24 +1,24 @@
|
||||
package tgapi
|
||||
|
||||
type BaseForumTopicP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetForumTopicIconSet() ([]Sticker, error) {
|
||||
req := NewRequest[[]Sticker]("getForumTopicIconSet", NoParams)
|
||||
func (api *API) GetForumTopicIconStickers() ([]Sticker, error) {
|
||||
req := NewRequest[[]Sticker]("getForumTopicIconStickers", NoParams)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type CreateForumTopicP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Name string `json:"name"`
|
||||
IconColor ForumTopicIconColor `json:"icon_color"`
|
||||
IconCustomEmojiID string `json:"icon_custom_emoji_id"`
|
||||
}
|
||||
|
||||
func (api *Api) CreateForumTopic(params CreateForumTopicP) (ForumTopic, error) {
|
||||
req := NewRequest[ForumTopic]("createForumTopic", params)
|
||||
func (api *API) CreateForumTopic(params CreateForumTopicP) (ForumTopic, error) {
|
||||
req := NewRequestWithChatID[ForumTopic]("createForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -28,59 +28,59 @@ type EditForumTopicP struct {
|
||||
IconCustomEmojiID string `json:"icon_custom_emoji_id"`
|
||||
}
|
||||
|
||||
func (api *Api) EditForumTopic(params EditForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("editForumTopic", params)
|
||||
func (api *API) EditForumTopic(params EditForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("editForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
func (api *Api) CloseForumTopic(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("closeForumTopic", params)
|
||||
func (api *API) CloseForumTopic(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("closeForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) ReopenForumTopic(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("reopenForumTopic", params)
|
||||
func (api *API) ReopenForumTopic(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("reopenForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) DeleteForumTopic(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteForumTopic", params)
|
||||
func (api *API) DeleteForumTopic(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("deleteForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) UnpinAllForumTopicMessages(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("unpinAllForumTopicMessages", params)
|
||||
func (api *API) UnpinAllForumTopicMessages(params BaseForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("unpinAllForumTopicMessages", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type BaseGeneralForumTopicP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
type EditGeneralForumTopicP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (api *Api) EditGeneralForumTopic(params EditGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("editGeneralForumTopic", params)
|
||||
func (api *API) EditGeneralForumTopic(params EditGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("editGeneralForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
func (api *Api) CloseGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("closeGeneralForumTopic", params)
|
||||
func (api *API) CloseGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("closeGeneralForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) ReopenGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("reopenGeneralForumTopic", params)
|
||||
func (api *API) ReopenGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("reopenGeneralForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) HideGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("hideGeneralForumTopic", params)
|
||||
func (api *API) HideGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("hideGeneralForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) UnhideGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("unhideGeneralForumTopic", params)
|
||||
func (api *API) UnhideGeneralForumTopic(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("unhideGeneralForumTopic", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) UnpinAllGeneralForumTopicMessages(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequest[bool]("unpinAllGeneralForumTopicMessages", params)
|
||||
func (api *API) UnpinAllGeneralForumTopicMessages(params BaseGeneralForumTopicP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("unpinAllGeneralForumTopicMessages", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ package tgapi
|
||||
|
||||
type SendMessageP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
Text string `json:"text"`
|
||||
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
||||
@@ -20,53 +20,53 @@ type SendMessageP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendMessage(params SendMessageP) (Message, error) {
|
||||
req := NewRequest[Message, SendMessageP]("sendMessage", params)
|
||||
func (api *API) SendMessage(params SendMessageP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message, SendMessageP]("sendMessage", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type ForwardMessageP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
FromChatID int `json:"from_chat_id,omitempty"`
|
||||
VideoStartTimestamp int `json:"video_start_timestamp,omitempty"`
|
||||
DisableNotification bool `json:"disable_notification,omitempty"`
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
FromChatID int64 `json:"from_chat_id,omitempty"`
|
||||
VideoStartTimestamp int `json:"video_start_timestamp,omitempty"`
|
||||
DisableNotification bool `json:"disable_notification,omitempty"`
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
|
||||
MessageEffectID string `json:"message_effect_id,omitempty"`
|
||||
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) ForwardMessage(params ForwardMessageP) (Message, error) {
|
||||
req := NewRequest[Message]("forwardMessage", params)
|
||||
func (api *API) ForwardMessage(params ForwardMessageP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("forwardMessage", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type ForwardMessagesP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
FromChatID int `json:"from_chat_id,omitempty"`
|
||||
FromChatID int64 `json:"from_chat_id,omitempty"`
|
||||
MessageIDs []int `json:"message_ids,omitempty"`
|
||||
DisableNotification bool `json:"disable_notification,omitempty"`
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) ForwardMessages(params ForwardMessagesP) ([]int, error) {
|
||||
req := NewRequest[[]int]("forwardMessages", params)
|
||||
func (api *API) ForwardMessages(params ForwardMessagesP) ([]int, error) {
|
||||
req := NewRequestWithChatID[[]int]("forwardMessages", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type CopyMessageP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
FromChatID int `json:"from_chat_id"`
|
||||
FromChatID int64 `json:"from_chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
VideoStartTimestamp int `json:"video_start_timestamp,omitempty"`
|
||||
Caption string `json:"caption,omitempty"`
|
||||
@@ -84,33 +84,33 @@ type CopyMessageP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) CopyMessage(params CopyMessageP) (int, error) {
|
||||
req := NewRequest[int]("copyMessage", params)
|
||||
func (api *API) CopyMessage(params CopyMessageP) (int, error) {
|
||||
req := NewRequestWithChatID[int]("copyMessage", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type CopyMessagesP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
FromChatID int `json:"from_chat_id,omitempty"`
|
||||
FromChatID int64 `json:"from_chat_id,omitempty"`
|
||||
MessageIDs []int `json:"message_ids,omitempty"`
|
||||
DisableNotification bool `json:"disable_notification,omitempty"`
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
RemoveCaption bool `json:"remove_caption,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) CopyMessages(params CopyMessagesP) ([]int, error) {
|
||||
req := NewRequest[[]int]("copyMessages", params)
|
||||
func (api *API) CopyMessages(params CopyMessagesP) ([]int, error) {
|
||||
req := NewRequestWithChatID[[]int]("copyMessages", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendLocationP struct {
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
Latitude float64 `json:"latitude"`
|
||||
Longitude float64 `json:"longitude"`
|
||||
@@ -129,16 +129,16 @@ type SendLocationP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendLocation(params SendLocationP) (Message, error) {
|
||||
req := NewRequest[Message]("sendLocation", params)
|
||||
func (api *API) SendLocation(params SendLocationP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendLocation", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendVenueP struct {
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
Latitude float64 `json:"latitude"`
|
||||
Longitude float64 `json:"longitude"`
|
||||
@@ -159,16 +159,16 @@ type SendVenueP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendVenue(params SendVenueP) (Message, error) {
|
||||
req := NewRequest[Message]("sendVenue", params)
|
||||
func (api *API) SendVenue(params SendVenueP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendVenue", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendContactP struct {
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
FirstName string `json:"first_name"`
|
||||
@@ -185,15 +185,15 @@ type SendContactP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendContact(params SendContactP) (Message, error) {
|
||||
req := NewRequest[Message]("sendContact", params)
|
||||
func (api *API) SendContact(params SendContactP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendContact", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendPollP struct {
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
|
||||
Question string `json:"question"`
|
||||
QuestionParseMode ParseMode `json:"question_mode,omitempty"`
|
||||
@@ -219,14 +219,14 @@ type SendPollP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendPoll(params SendPollP) (Message, error) {
|
||||
req := NewRequest[Message]("sendPoll", params)
|
||||
func (api *API) SendPoll(params SendPollP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendPoll", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendChecklistP struct {
|
||||
BusinessConnectionID int `json:"business_connection_id"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
Checklist InputChecklist `json:"checklist"`
|
||||
|
||||
DisableNotification bool `json:"disable_notification,omitempty"`
|
||||
@@ -237,16 +237,16 @@ type SendChecklistP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendChecklist(params SendChecklistP) (Message, error) {
|
||||
req := NewRequest[Message]("sendChecklist", params)
|
||||
func (api *API) SendChecklist(params SendChecklistP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendChecklist", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendDiceP struct {
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
BusinessConnectionID int `json:"business_connection_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
Emoji string `json:"emoji,omitempty"`
|
||||
|
||||
@@ -260,46 +260,46 @@ type SendDiceP struct {
|
||||
ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendDice(params SendDiceP) (Message, error) {
|
||||
req := NewRequest[Message]("sendDice", params)
|
||||
func (api *API) SendDice(params SendDiceP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendDice", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendMessageDraftP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DraftID int `json:"draft_id"`
|
||||
DraftID uint64 `json:"draft_id"`
|
||||
Text string `json:"text"`
|
||||
ParseMode ParseMode `json:"parse_mode,omitempty"`
|
||||
Entities []MessageEntity `json:"entities,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendMessageDraft(params SendMessageDraftP) (bool, error) {
|
||||
req := NewRequest[bool]("sendMessageDraft", params)
|
||||
func (api *API) SendMessageDraft(params SendMessageDraftP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("sendMessageDraft", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SendChatActionP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
Action ChatActionType `json:"action"`
|
||||
}
|
||||
|
||||
func (api *Api) SendChatAction(params SendChatActionP) (bool, error) {
|
||||
req := NewRequest[bool]("sendChatAction", params)
|
||||
func (api *API) SendChatAction(params SendChatActionP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("sendChatAction", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type SetMessageReactionP struct {
|
||||
ChatId int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageId int `json:"message_id"`
|
||||
Reaction []ReactionType `json:"reaction"`
|
||||
IsBig bool `json:"is_big,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetMessageReaction(params SetMessageReactionP) (bool, error) {
|
||||
req := NewRequest[bool]("setMessageReaction", params)
|
||||
func (api *API) SetMessageReaction(params SetMessageReactionP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("setMessageReaction", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -307,7 +307,7 @@ func (api *Api) SetMessageReaction(params SetMessageReactionP) (bool, error) {
|
||||
|
||||
type EditMessageTextP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id,omitempty"`
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||
Text string `json:"text"`
|
||||
@@ -317,21 +317,21 @@ type EditMessageTextP struct {
|
||||
|
||||
// EditMessageText If inline message, first return will be zero-valued, and second will boolean
|
||||
// Otherwise, first return will be Message, and second false
|
||||
func (api *Api) EditMessageText(params EditMessageTextP) (Message, bool, error) {
|
||||
func (api *API) EditMessageText(params EditMessageTextP) (Message, bool, error) {
|
||||
var zero Message
|
||||
if params.InlineMessageID != "" {
|
||||
req := NewRequest[bool]("editMessageText", params)
|
||||
req := NewRequestWithChatID[bool]("editMessageText", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return zero, res, err
|
||||
}
|
||||
req := NewRequest[Message]("editMessageText", params)
|
||||
req := NewRequestWithChatID[Message]("editMessageText", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return res, false, err
|
||||
}
|
||||
|
||||
type EditMessageCaptionP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id,omitempty"`
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||
Caption string `json:"caption"`
|
||||
@@ -341,21 +341,21 @@ type EditMessageCaptionP struct {
|
||||
|
||||
// EditMessageCaption If inline message, first return will be zero-valued, and second will boolean
|
||||
// Otherwise, first return will be Message, and second false
|
||||
func (api *Api) EditMessageCaption(params EditMessageCaptionP) (Message, bool, error) {
|
||||
func (api *API) EditMessageCaption(params EditMessageCaptionP) (Message, bool, error) {
|
||||
var zero Message
|
||||
if params.InlineMessageID != "" {
|
||||
req := NewRequest[bool]("editMessageCaption", params)
|
||||
req := NewRequestWithChatID[bool]("editMessageCaption", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return zero, res, err
|
||||
}
|
||||
req := NewRequest[Message]("editMessageCaption", params)
|
||||
req := NewRequestWithChatID[Message]("editMessageCaption", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return res, false, err
|
||||
}
|
||||
|
||||
type EditMessageMediaP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id,omitempty"`
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||
Message InputMedia `json:"message"`
|
||||
@@ -364,21 +364,21 @@ type EditMessageMediaP struct {
|
||||
|
||||
// EditMessageMedia If inline message, first return will be zero-valued, and second will boolean
|
||||
// Otherwise, first return will be Message, and second false
|
||||
func (api *Api) EditMessageMedia(params EditMessageMediaP) (Message, bool, error) {
|
||||
func (api *API) EditMessageMedia(params EditMessageMediaP) (Message, bool, error) {
|
||||
var zero Message
|
||||
if params.InlineMessageID != "" {
|
||||
req := NewRequest[bool]("editMessageMedia", params)
|
||||
req := NewRequestWithChatID[bool]("editMessageMedia", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return zero, res, err
|
||||
}
|
||||
req := NewRequest[Message]("editMessageMedia", params)
|
||||
req := NewRequestWithChatID[Message]("editMessageMedia", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return res, false, err
|
||||
}
|
||||
|
||||
type EditMessageLiveLocationP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id,omitempty"`
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||
|
||||
@@ -393,21 +393,21 @@ type EditMessageLiveLocationP struct {
|
||||
|
||||
// EditMessageLiveLocation If inline message, first return will be zero-valued, and second will boolean
|
||||
// Otherwise, first return will be Message, and second false
|
||||
func (api *Api) EditMessageLiveLocation(params EditMessageLiveLocationP) (Message, bool, error) {
|
||||
func (api *API) EditMessageLiveLocation(params EditMessageLiveLocationP) (Message, bool, error) {
|
||||
var zero Message
|
||||
if params.InlineMessageID != "" {
|
||||
req := NewRequest[bool]("editMessageLiveLocation", params)
|
||||
req := NewRequestWithChatID[bool]("editMessageLiveLocation", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return zero, res, err
|
||||
}
|
||||
req := NewRequest[Message]("editMessageLiveLocation", params)
|
||||
req := NewRequestWithChatID[Message]("editMessageLiveLocation", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return res, false, err
|
||||
}
|
||||
|
||||
type StopMessageLiveLocationP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id,omitempty"`
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
||||
@@ -415,102 +415,102 @@ type StopMessageLiveLocationP struct {
|
||||
|
||||
// StopMessageLiveLocation If inline message, first return will be zero-valued, and second will boolean
|
||||
// Otherwise, first return will be Message, and second false
|
||||
func (api *Api) StopMessageLiveLocation(params StopMessageLiveLocationP) (Message, bool, error) {
|
||||
func (api *API) StopMessageLiveLocation(params StopMessageLiveLocationP) (Message, bool, error) {
|
||||
var zero Message
|
||||
if params.InlineMessageID != "" {
|
||||
req := NewRequest[bool]("stopMessageLiveLocation", params)
|
||||
req := NewRequestWithChatID[bool]("stopMessageLiveLocation", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return zero, res, err
|
||||
}
|
||||
req := NewRequest[Message]("stopMessageLiveLocation", params)
|
||||
req := NewRequestWithChatID[Message]("stopMessageLiveLocation", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return res, false, err
|
||||
}
|
||||
|
||||
type EditMessageChecklistP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
Checklist InputChecklist `json:"checklist"`
|
||||
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) EditMessageChecklist(params EditMessageChecklistP) (Message, error) {
|
||||
req := NewRequest[Message]("editMessageChecklist", params)
|
||||
func (api *API) EditMessageChecklist(params EditMessageChecklistP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("editMessageChecklist", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type EditMessageReplyMarkupP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id,omitempty"`
|
||||
ChatID int64 `json:"chat_id,omitempty"`
|
||||
MessageID int `json:"message_id,omitempty"`
|
||||
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) EditMessageReplyMarkup(params EditMessageReplyMarkupP) (Message, bool, error) {
|
||||
func (api *API) EditMessageReplyMarkup(params EditMessageReplyMarkupP) (Message, bool, error) {
|
||||
var zero Message
|
||||
if params.InlineMessageID != "" {
|
||||
req := NewRequest[bool]("editMessageReplyMarkup", params)
|
||||
req := NewRequestWithChatID[bool]("editMessageReplyMarkup", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return zero, res, err
|
||||
}
|
||||
req := NewRequest[Message]("editMessageReplyMarkup", params)
|
||||
req := NewRequestWithChatID[Message]("editMessageReplyMarkup", params, params.ChatID)
|
||||
res, err := req.Do(api)
|
||||
return res, false, err
|
||||
}
|
||||
|
||||
type StopPollP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
InlineMessageID string `json:"inline_message_id,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) StopPoll(params StopPollP) (Poll, error) {
|
||||
req := NewRequest[Poll]("stopPoll", params)
|
||||
func (api *API) StopPoll(params StopPollP) (Poll, error) {
|
||||
req := NewRequestWithChatID[Poll]("stopPoll", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type ApproveSuggestedPostP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
SendDate int `json:"send_date,omitempty"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
SendDate int `json:"send_date,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) ApproveSuggestedPost(params ApproveSuggestedPostP) (bool, error) {
|
||||
req := NewRequest[bool]("approveSuggestedPost", params)
|
||||
func (api *API) ApproveSuggestedPost(params ApproveSuggestedPostP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("approveSuggestedPost", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type DeclineSuggestedPostP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
Comment string `json:"comment,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) DeclineSuggestedPost(params DeclineSuggestedPostP) (bool, error) {
|
||||
req := NewRequest[bool]("declineSuggestedPost", params)
|
||||
func (api *API) DeclineSuggestedPost(params DeclineSuggestedPostP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("declineSuggestedPost", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type DeleteMessageP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageID int `json:"message_id"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteMessage(params DeleteMessageP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteMessage", params)
|
||||
func (api *API) DeleteMessage(params DeleteMessageP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("deleteMessage", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
type DeleteMessagesP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageIDs []int `json:"message_ids"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteMessages(params DeleteMessagesP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteMessages", params)
|
||||
func (api *API) DeleteMessages(params DeleteMessagesP) (bool, error) {
|
||||
req := NewRequestWithChatID[bool]("deleteMessages", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -522,7 +522,7 @@ type AnswerCallbackQueryP struct {
|
||||
CacheTime int `json:"cache_time,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) AnswerCallbackQuery(params AnswerCallbackQueryP) (bool, error) {
|
||||
func (api *API) AnswerCallbackQuery(params AnswerCallbackQueryP) (bool, error) {
|
||||
req := NewRequest[bool]("answerCallbackQuery", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -6,16 +6,23 @@ type MessageReplyMarkup struct {
|
||||
InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
MessageID int `json:"message_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
BusinessConnectionId string `json:"business_connection_id,omitempty"`
|
||||
From *User `json:"from,omitempty"`
|
||||
type DirectMessageTopic struct {
|
||||
TopicID int64 `json:"topic_id"`
|
||||
User *User `json:"user,omitempty"`
|
||||
}
|
||||
|
||||
SenderChat *Chat `json:"sender_chat,omitempty"`
|
||||
SenderBoostCount int `json:"sender_boost_count,omitempty"`
|
||||
SenderBusinessBot *User `json:"sender_business_bot,omitempty"`
|
||||
Chat *Chat `json:"chat,omitempty"`
|
||||
type Message struct {
|
||||
MessageID int `json:"message_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessageTopic *DirectMessageTopic `json:"direct_message_topic,omitempty"`
|
||||
BusinessConnectionId string `json:"business_connection_id,omitempty"`
|
||||
From *User `json:"from,omitempty"`
|
||||
|
||||
SenderChat *Chat `json:"sender_chat,omitempty"`
|
||||
SenderBoostCount int `json:"sender_boost_count,omitempty"`
|
||||
SenderBusinessBot *User `json:"sender_business_bot,omitempty"`
|
||||
SenderTag string `json:"sender_tag,omitempty"`
|
||||
Chat *Chat `json:"chat,omitempty"`
|
||||
|
||||
IsTopicMessage bool `json:"is_topic_message,omitempty"`
|
||||
IsAutomaticForward bool `json:"is_automatic_forward,omitempty"`
|
||||
@@ -74,6 +81,7 @@ const (
|
||||
MessageEntityTextLink MessageEntityType = "text_link"
|
||||
MessageEntityTextMention MessageEntityType = "text_mention"
|
||||
MessageEntityCustomEmoji MessageEntityType = "custom_emoji"
|
||||
MessageEntityDateTime MessageEntityType = "date_time"
|
||||
)
|
||||
|
||||
type MessageEntity struct {
|
||||
@@ -85,6 +93,9 @@ type MessageEntity struct {
|
||||
User *User `json:"user,omitempty"`
|
||||
Language string `json:"language,omitempty"`
|
||||
CustomEmojiID string `json:"custom_emoji_id,omitempty"`
|
||||
|
||||
UnixTime int `json:"unix_time,omitempty"`
|
||||
DateTimeFormat string `json:"date_time_format,omitempty"`
|
||||
}
|
||||
|
||||
type ReplyParameters struct {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
package tgapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ParseMode string
|
||||
|
||||
const (
|
||||
@@ -19,19 +25,19 @@ type UpdateParams struct {
|
||||
AllowedUpdates []UpdateType `json:"allowed_updates"`
|
||||
}
|
||||
|
||||
func (api *Api) GetMe() (User, error) {
|
||||
func (api *API) GetMe() (User, error) {
|
||||
req := NewRequest[User, EmptyParams]("getMe", NoParams)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) LogOut() (bool, error) {
|
||||
func (api *API) LogOut() (bool, error) {
|
||||
req := NewRequest[bool, EmptyParams]("logOut", NoParams)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) Close() (bool, error) {
|
||||
func (api *API) Close() (bool, error) {
|
||||
req := NewRequest[bool, EmptyParams]("close", NoParams)
|
||||
return req.Do(api)
|
||||
}
|
||||
func (api *Api) GetUpdates(params UpdateParams) ([]Update, error) {
|
||||
func (api *API) GetUpdates(params UpdateParams) ([]Update, error) {
|
||||
req := NewRequest[[]Update]("getUpdates", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -40,7 +46,19 @@ type GetFileP struct {
|
||||
FileId string `json:"file_id"`
|
||||
}
|
||||
|
||||
func (api *Api) GetFile(params GetFileP) (File, error) {
|
||||
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 func() {
|
||||
_ = res.Body.Close()
|
||||
}()
|
||||
return io.ReadAll(res.Body)
|
||||
}
|
||||
|
||||
142
tgapi/pool.go
Normal file
142
tgapi/pool.go
Normal file
@@ -0,0 +1,142 @@
|
||||
package tgapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// workerPool — приватная структура, управляющая пулом воркеров.
|
||||
// Внешний код не может создавать или напрямую взаимодействовать с этой структурой.
|
||||
// Используется только через экспортируемые методы newWorkerPool, start, stop, submit.
|
||||
type workerPool struct {
|
||||
taskCh chan requestEnvelope // канал для принятия задач (буферизованный)
|
||||
queueSize int // максимальный размер очереди
|
||||
workers int // количество воркеров (горутин)
|
||||
wg sync.WaitGroup // синхронизирует завершение всех воркеров при остановке
|
||||
quit chan struct{} // канал для сигнала остановки
|
||||
started bool // флаг, указывающий, запущен ли пул
|
||||
startedMu sync.Mutex // мьютекс для безопасного доступа к started
|
||||
}
|
||||
|
||||
// requestEnvelope — приватная структура, инкапсулирующая задачу и канал для результата.
|
||||
// Используется только внутри пакета для передачи задач воркерам.
|
||||
type requestEnvelope struct {
|
||||
doFunc func(context.Context) (any, error) // функция, выполняющая запрос
|
||||
resultCh chan requestResult // канал, через который воркер вернёт результат
|
||||
}
|
||||
|
||||
// requestResult — приватная структура, представляющая результат выполнения задачи.
|
||||
// Внешний код получает его через канал, но не знает структуры — только через <-chan requestResult.
|
||||
type requestResult struct {
|
||||
value any // значение, возвращённое задачей
|
||||
err error // ошибка, если возникла
|
||||
}
|
||||
|
||||
// newWorkerPool создаёт новый пул воркеров с заданным количеством горутин и размером очереди.
|
||||
// Это единственный способ создать workerPool — внешний код не может создать его напрямую.
|
||||
func newWorkerPool(workers int, queueSize int) *workerPool {
|
||||
if workers <= 0 {
|
||||
workers = 1 // защита от некорректных значений
|
||||
}
|
||||
if queueSize <= 0 {
|
||||
queueSize = 100 // разумный дефолт
|
||||
}
|
||||
|
||||
return &workerPool{
|
||||
taskCh: make(chan requestEnvelope, queueSize),
|
||||
queueSize: queueSize,
|
||||
workers: workers,
|
||||
quit: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// start запускает воркеры (горутины), которые будут обрабатывать задачи из очереди.
|
||||
// Метод идемпотентен: если пул уже запущен — ничего не делает.
|
||||
// Должен вызываться перед первым вызовом submit.
|
||||
func (p *workerPool) start(ctx context.Context) {
|
||||
p.startedMu.Lock()
|
||||
defer p.startedMu.Unlock()
|
||||
if p.started {
|
||||
return // уже запущен — ничего не делаем
|
||||
}
|
||||
p.started = true
|
||||
|
||||
// Запускаем воркеры — каждый будет обрабатывать задачи в бесконечном цикле
|
||||
for i := 0; i < p.workers; i++ {
|
||||
p.wg.Add(1)
|
||||
go p.worker(ctx) // запускаем горутину с контекстом
|
||||
}
|
||||
}
|
||||
|
||||
// stop останавливает пул воркеров.
|
||||
// Отправляет сигнал остановки через quit-канал и ждёт завершения всех активных задач.
|
||||
// Безопасно вызывать многократно — после остановки повторные вызовы не имеют эффекта.
|
||||
func (p *workerPool) stop() {
|
||||
close(p.quit) // сигнал для всех воркеров — выйти из цикла
|
||||
p.wg.Wait() // ждём, пока все воркеры завершатся
|
||||
}
|
||||
|
||||
// submit отправляет задачу в очередь и возвращает канал, через который будет получен результат.
|
||||
// Если очередь переполнена — возвращает ErrPoolQueueFull.
|
||||
// Канал результата имеет буфер 1, чтобы не блокировать воркера при записи.
|
||||
// Контекст используется для отмены задачи, если клиент отменил запрос до отправки.
|
||||
func (p *workerPool) submit(ctx context.Context, do func(context.Context) (any, error)) (<-chan requestResult, error) {
|
||||
// Проверяем, не превышена ли очередь
|
||||
if len(p.taskCh) >= p.queueSize {
|
||||
return nil, ErrPoolQueueFull
|
||||
}
|
||||
|
||||
// Создаём канал для результата — буферизованный, чтобы не блокировать воркера
|
||||
resultCh := make(chan requestResult, 1)
|
||||
|
||||
// Создаём обёртку задачи
|
||||
envelope := requestEnvelope{
|
||||
doFunc: do,
|
||||
resultCh: resultCh,
|
||||
}
|
||||
|
||||
// Пытаемся отправить задачу в очередь
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// Клиент отменил операцию до отправки — возвращаем ошибку отмены
|
||||
return nil, ctx.Err()
|
||||
case p.taskCh <- envelope:
|
||||
// Успешно отправлено — возвращаем канал для чтения результата
|
||||
return resultCh, nil
|
||||
default:
|
||||
// Очередь переполнена — не должно происходить при проверке len(p.taskCh), но на всякий случай
|
||||
return nil, ErrPoolQueueFull
|
||||
}
|
||||
}
|
||||
|
||||
// worker — приватная горутина, выполняющая задачи из очереди.
|
||||
// Каждый воркер работает в бесконечном цикле, пока не получит сигнал остановки.
|
||||
// При получении задачи:
|
||||
// - вызывает doFunc с контекстом
|
||||
// - записывает результат в resultCh
|
||||
// - закрывает канал, чтобы клиент мог прочитать и завершить
|
||||
//
|
||||
// После закрытия quit-канала — воркер завершает работу.
|
||||
func (p *workerPool) worker(ctx context.Context) {
|
||||
defer p.wg.Done() // уменьшаем WaitGroup при завершении горутины
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-p.quit:
|
||||
// Получен сигнал остановки — выходим из цикла
|
||||
return
|
||||
|
||||
case envelope := <-p.taskCh:
|
||||
// Выполняем задачу с переданным контекстом (клиентский или общий)
|
||||
value, err := envelope.doFunc(ctx)
|
||||
|
||||
// Записываем результат в канал — не блокируем, т.к. буфер 1
|
||||
envelope.resultCh <- requestResult{
|
||||
value: value,
|
||||
err: err,
|
||||
}
|
||||
// Закрываем канал — клиент знает, что результат пришёл и больше не будет
|
||||
close(envelope.resultCh)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package tgapi
|
||||
|
||||
type SendStickerP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -14,8 +14,8 @@ type SendStickerP struct {
|
||||
MessageEffectID string `json:"message_effect_id,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SendSticker(params SendStickerP) (Message, error) {
|
||||
req := NewRequest[Message]("sendSticker", params)
|
||||
func (api *API) SendSticker(params SendStickerP) (Message, error) {
|
||||
req := NewRequestWithChatID[Message]("sendSticker", params, params.ChatID)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ type GetStickerSetP struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (api *Api) GetStickerSet(params GetStickerSetP) (StickerSet, error) {
|
||||
func (api *API) GetStickerSet(params GetStickerSetP) (StickerSet, error) {
|
||||
req := NewRequest[StickerSet]("getStickerSet", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -32,7 +32,7 @@ type GetCustomEmojiStickersP struct {
|
||||
CustomEmojiIDs []string `json:"custom_emoji_ids"`
|
||||
}
|
||||
|
||||
func (api *Api) GetCustomEmojiStickers(params GetCustomEmojiStickersP) ([]Sticker, error) {
|
||||
func (api *API) GetCustomEmojiStickers(params GetCustomEmojiStickersP) ([]Sticker, error) {
|
||||
req := NewRequest[[]Sticker]("getCustomEmojiStickers", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -47,7 +47,7 @@ type CreateNewStickerSetP struct {
|
||||
NeedsRepainting bool `json:"needs_repainting,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) CreateNewStickerSet(params CreateNewStickerSetP) (bool, error) {
|
||||
func (api *API) CreateNewStickerSet(params CreateNewStickerSetP) (bool, error) {
|
||||
req := NewRequest[bool]("createNewStickerSet", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -58,7 +58,7 @@ type AddStickerToSetP struct {
|
||||
Sticker InputSticker `json:"sticker"`
|
||||
}
|
||||
|
||||
func (api *Api) AddStickerToSet(params AddStickerToSetP) (bool, error) {
|
||||
func (api *API) AddStickerToSet(params AddStickerToSetP) (bool, error) {
|
||||
req := NewRequest[bool]("addStickerToSet", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -68,7 +68,7 @@ type SetStickerPositionInSetP struct {
|
||||
Position int `json:"position"`
|
||||
}
|
||||
|
||||
func (api *Api) SetStickerPosition(params SetStickerPositionInSetP) (bool, error) {
|
||||
func (api *API) SetStickerPosition(params SetStickerPositionInSetP) (bool, error) {
|
||||
req := NewRequest[bool]("setStickerPosition", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -77,7 +77,7 @@ type DeleteStickerFromSetP struct {
|
||||
Sticker string `json:"sticker"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteStickerFromSet(params DeleteStickerFromSetP) (bool, error) {
|
||||
func (api *API) DeleteStickerFromSet(params DeleteStickerFromSetP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteStickerFromSet", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -89,7 +89,7 @@ type ReplaceStickerInSetP struct {
|
||||
Sticker InputSticker `json:"sticker"`
|
||||
}
|
||||
|
||||
func (api *Api) ReplaceStickerInSet(params ReplaceStickerInSetP) (bool, error) {
|
||||
func (api *API) ReplaceStickerInSet(params ReplaceStickerInSetP) (bool, error) {
|
||||
req := NewRequest[bool]("replaceStickerInSet", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -99,7 +99,7 @@ type SetStickerEmojiListP struct {
|
||||
EmojiList []string `json:"emoji_list"`
|
||||
}
|
||||
|
||||
func (api *Api) SetStickerEmojiList(params SetStickerEmojiListP) (bool, error) {
|
||||
func (api *API) SetStickerEmojiList(params SetStickerEmojiListP) (bool, error) {
|
||||
req := NewRequest[bool]("setStickerEmojiList", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -109,7 +109,7 @@ type SetStickerKeywordsP struct {
|
||||
Keywords []string `json:"keywords"`
|
||||
}
|
||||
|
||||
func (api *Api) SetStickerKeywords(params SetStickerKeywordsP) (bool, error) {
|
||||
func (api *API) SetStickerKeywords(params SetStickerKeywordsP) (bool, error) {
|
||||
req := NewRequest[bool]("setStickerKeywords", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -119,7 +119,7 @@ type SetStickerMaskPositionP struct {
|
||||
MaskPosition *MaskPosition `json:"mask_position,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetStickerMaskPosition(params SetStickerMaskPositionP) (bool, error) {
|
||||
func (api *API) SetStickerMaskPosition(params SetStickerMaskPositionP) (bool, error) {
|
||||
req := NewRequest[bool]("setStickerMaskPosition", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -129,7 +129,7 @@ type SetStickerSetTitleP struct {
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
func (api *Api) SetStickerSetTitle(params SetStickerSetTitleP) (bool, error) {
|
||||
func (api *API) SetStickerSetTitle(params SetStickerSetTitleP) (bool, error) {
|
||||
req := NewRequest[bool]("setStickerSetTitle", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -141,7 +141,7 @@ type SetStickerSetThumbnailP struct {
|
||||
Format InputStickerFormat `json:"format"`
|
||||
}
|
||||
|
||||
func (api *Api) SetStickerSetThumbnail(params SetStickerSetThumbnailP) (bool, error) {
|
||||
func (api *API) SetStickerSetThumbnail(params SetStickerSetThumbnailP) (bool, error) {
|
||||
req := NewRequest[bool]("setStickerSetThumbnail", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -151,7 +151,7 @@ type SetCustomEmojiStickerSetThumbnailP struct {
|
||||
CustomEmojiID string `json:"custom_emoji_id,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetCustomEmojiStickerSetThumbnail(params SetStickerSetThumbnailP) (bool, error) {
|
||||
func (api *API) SetCustomEmojiStickerSetThumbnail(params SetStickerSetThumbnailP) (bool, error) {
|
||||
req := NewRequest[bool]("setCustomEmojiStickerSetThumbnail", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -160,7 +160,7 @@ type DeleteStickerSetP struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (api *Api) DeleteStickerSet(params DeleteStickerSetP) (bool, error) {
|
||||
func (api *API) DeleteStickerSet(params DeleteStickerSetP) (bool, error) {
|
||||
req := NewRequest[bool]("deleteStickerSet", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -261,20 +261,20 @@ type Gifts struct {
|
||||
Gifts []Gift `json:"gifts"`
|
||||
}
|
||||
|
||||
type OwnedGiftType string
|
||||
|
||||
const (
|
||||
OwnedGiftRegularType OwnedGiftType = "regular"
|
||||
OwnedGiftUniqueType OwnedGiftType = "unique"
|
||||
)
|
||||
|
||||
type OwnedGiftType string
|
||||
type BaseOwnedGift struct {
|
||||
type OwnedGift struct {
|
||||
Type OwnedGiftType `json:"type"`
|
||||
OwnerGiftID *string `json:"owner_gift_id,omitempty"`
|
||||
SendDate *int `json:"send_date,omitempty"`
|
||||
IsSaved *bool `json:"is_saved,omitempty"`
|
||||
}
|
||||
type OwnedGiftRegular struct {
|
||||
BaseOwnedGift
|
||||
|
||||
// Поля, характерные для "regular"
|
||||
Gift Gift `json:"gift"`
|
||||
SenderUser User `json:"sender_user,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
@@ -286,18 +286,15 @@ type OwnedGiftRegular struct {
|
||||
PrepaidUpgradeStarCount *int `json:"prepaid_upgrade_star_count,omitempty"`
|
||||
IsUpgradeSeparate *bool `json:"is_upgrade_separate,omitempty"`
|
||||
UniqueGiftNumber *int `json:"unique_gift_number,omitempty"`
|
||||
}
|
||||
type OwnedGiftUnique struct {
|
||||
BaseOwnedGift
|
||||
|
||||
// Поля, характерные для "unique"
|
||||
CanBeTransferred *bool `json:"can_be_transferred,omitempty"`
|
||||
TransferStarCount *int `json:"transfer_star_count,omitempty"`
|
||||
NextTransferDate *int `json:"next_transfer_date,omitempty"`
|
||||
}
|
||||
|
||||
type OwnedGifts struct {
|
||||
TotalCount int `json:"total_count"`
|
||||
Gifts []struct {
|
||||
OwnedGiftRegular
|
||||
OwnedGiftUnique
|
||||
} `json:"gifts"`
|
||||
NextOffset string `json:"next_offset"`
|
||||
TotalCount int `json:"total_count"`
|
||||
Gifts []OwnedGift `json:"gifts"`
|
||||
NextOffset string `json:"next_offset"`
|
||||
}
|
||||
|
||||
221
tgapi/uploader_api.go
Normal file
221
tgapi/uploader_api.go
Normal file
@@ -0,0 +1,221 @@
|
||||
package tgapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.nix13.pw/scuroneko/laniakea/utils"
|
||||
"git.nix13.pw/scuroneko/slog"
|
||||
)
|
||||
|
||||
const (
|
||||
UploaderPhotoType UploaderFileType = "photo"
|
||||
UploaderVideoType UploaderFileType = "video"
|
||||
UploaderAudioType UploaderFileType = "audio"
|
||||
UploaderDocumentType UploaderFileType = "document"
|
||||
UploaderVoiceType UploaderFileType = "voice"
|
||||
UploaderVideoNoteType UploaderFileType = "video_note"
|
||||
UploaderThumbnailType UploaderFileType = "thumbnail"
|
||||
)
|
||||
|
||||
type UploaderFileType string
|
||||
type UploaderFile struct {
|
||||
filename string
|
||||
data []byte
|
||||
field UploaderFileType
|
||||
}
|
||||
|
||||
func NewUploaderFile(name string, data []byte) UploaderFile {
|
||||
t := uploaderTypeByExt(name)
|
||||
return UploaderFile{filename: name, data: data, field: t}
|
||||
}
|
||||
|
||||
// SetType used when auto-detect failed.
|
||||
// i.e. you sending a voice message, but it detects as audio, or if you send audio with thumbnail
|
||||
func (f UploaderFile) SetType(t UploaderFileType) UploaderFile {
|
||||
f.field = t
|
||||
return f
|
||||
}
|
||||
|
||||
type Uploader struct {
|
||||
api *API
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewUploader(api *API) *Uploader {
|
||||
logger := slog.CreateLogger().Level(utils.GetLoggerLevel()).Prefix("UPLOADER")
|
||||
logger.AddWriter(logger.CreateJsonStdoutWriter())
|
||||
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
|
||||
files []UploaderFile
|
||||
params P
|
||||
chatId int64
|
||||
}
|
||||
|
||||
func NewUploaderRequest[R, P any](method string, params P, files ...UploaderFile) UploaderRequest[R, P] {
|
||||
return UploaderRequest[R, P]{method: method, files: files, params: params, chatId: 0}
|
||||
}
|
||||
func NewUploaderRequestWithChatID[R, P any](method string, params P, chatId int64, files ...UploaderFile) UploaderRequest[R, P] {
|
||||
return UploaderRequest[R, P]{method: method, files: files, params: params, chatId: chatId}
|
||||
}
|
||||
func (r UploaderRequest[R, P]) doRequest(ctx context.Context, up *Uploader) (R, error) {
|
||||
var zero R
|
||||
|
||||
buf, contentType, err := prepareMultipart(r.files, r.params)
|
||||
if err != nil {
|
||||
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, r.method)
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, buf)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString))
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
req.ContentLength = int64(buf.Len())
|
||||
|
||||
for {
|
||||
if up.api.Limiter != nil {
|
||||
if up.api.dropOverflowLimit {
|
||||
if !up.api.Limiter.GlobalAllow() {
|
||||
return zero, errors.New("rate limited")
|
||||
}
|
||||
} else {
|
||||
if err := up.api.Limiter.GlobalWait(ctx); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
up.logger.Debugln("UPLOADER REQ", r.method)
|
||||
resp, err := up.api.client.Do(req)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
body, err := readBody(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
up.logger.Debugln("UPLOADER RES", r.method, string(body))
|
||||
|
||||
response, err := parseBody[R](body)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
if !response.Ok {
|
||||
if response.ErrorCode == 429 && response.Parameters != nil && response.Parameters.RetryAfter != nil {
|
||||
after := *response.Parameters.RetryAfter
|
||||
up.logger.Warnf("Rate limited, retry after %d seconds (chat: %d)", after, r.chatId)
|
||||
if r.chatId > 0 {
|
||||
up.api.Limiter.SetChatLock(r.chatId, after)
|
||||
} else {
|
||||
up.api.Limiter.SetGlobalLock(after)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return zero, ctx.Err()
|
||||
case <-time.After(time.Duration(after) * time.Second):
|
||||
continue // Повторяем запрос
|
||||
}
|
||||
}
|
||||
return zero, fmt.Errorf("[%d] %s", response.ErrorCode, response.Description)
|
||||
}
|
||||
return response.Result, nil
|
||||
}
|
||||
}
|
||||
func (r UploaderRequest[R, P]) DoWithContext(ctx context.Context, up *Uploader) (R, error) {
|
||||
var zero R
|
||||
|
||||
result, err := up.api.pool.submit(ctx, func(ctx context.Context) (any, error) {
|
||||
return r.doRequest(ctx, up)
|
||||
})
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return zero, ctx.Err()
|
||||
case res := <-result:
|
||||
if res.err != nil {
|
||||
return zero, res.err
|
||||
}
|
||||
if val, ok := res.value.(R); ok {
|
||||
return val, nil
|
||||
}
|
||||
return zero, ErrPoolUnexpected
|
||||
}
|
||||
}
|
||||
func (r UploaderRequest[R, P]) Do(up *Uploader) (R, error) {
|
||||
return r.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 nil, "", err
|
||||
}
|
||||
|
||||
_, err = fw.Write(file.data)
|
||||
if err != nil {
|
||||
_ = w.Close()
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
|
||||
err := utils.Encode(w, params) // Предполагается, что это записывает в w
|
||||
if err != nil {
|
||||
_ = w.Close()
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
err = w.Close() // ✅ ОБЯЗАТЕЛЬНО вызвать в конце — иначе запрос битый!
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return buf, w.FormDataContentType(), nil
|
||||
}
|
||||
|
||||
func uploaderTypeByExt(filename string) UploaderFileType {
|
||||
ext := filepath.Ext(filename)
|
||||
switch ext {
|
||||
case ".jpg", ".jpeg", ".png", ".webp", ".bmp":
|
||||
return UploaderPhotoType
|
||||
case ".mp4":
|
||||
return UploaderVideoType
|
||||
case ".mp3", ".m4a":
|
||||
return UploaderAudioType
|
||||
case ".ogg":
|
||||
return UploaderVoiceType
|
||||
default:
|
||||
return UploaderDocumentType
|
||||
}
|
||||
}
|
||||
@@ -1,142 +1,8 @@
|
||||
package tgapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"git.nix13.pw/scuroneko/laniakea/utils"
|
||||
"git.nix13.pw/scuroneko/slog"
|
||||
)
|
||||
|
||||
type Uploader struct {
|
||||
api *Api
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewUploader(api *Api) *Uploader {
|
||||
logger := slog.CreateLogger().Level(GetLoggerLevel()).Prefix("UPLOADER")
|
||||
logger.AddWriter(logger.CreateJsonStdoutWriter())
|
||||
return &Uploader{api, logger}
|
||||
}
|
||||
func (u *Uploader) Close() error {
|
||||
return u.logger.Close()
|
||||
}
|
||||
|
||||
type UploaderFileType string
|
||||
|
||||
const (
|
||||
UploaderPhotoType UploaderFileType = "photo"
|
||||
UploaderVideoType UploaderFileType = "video"
|
||||
UploaderAudioType UploaderFileType = "audio"
|
||||
UploaderDocumentType UploaderFileType = "document"
|
||||
UploaderVoiceType UploaderFileType = "voice"
|
||||
UploaderVideoNoteType UploaderFileType = "video_note"
|
||||
UploaderThumbnailType UploaderFileType = "thumbnail"
|
||||
)
|
||||
|
||||
type UploaderFile struct {
|
||||
filename string
|
||||
data []byte
|
||||
field UploaderFileType
|
||||
}
|
||||
|
||||
func NewUploaderFile(name string, data []byte) UploaderFile {
|
||||
t := uploaderTypeByExt(name)
|
||||
return UploaderFile{filename: name, data: data, field: t}
|
||||
}
|
||||
|
||||
// SetType used when auto-detect failed. I.e. you sending a voice message, but it detects as audio, or if you send audio with thumbnail
|
||||
func (f UploaderFile) SetType(t UploaderFileType) UploaderFile {
|
||||
f.field = t
|
||||
return f
|
||||
}
|
||||
|
||||
type UploaderRequest[R, P any] struct {
|
||||
method string
|
||||
files []UploaderFile
|
||||
params P
|
||||
}
|
||||
|
||||
func NewUploaderRequest[R, P any](method string, params P, files ...UploaderFile) UploaderRequest[R, P] {
|
||||
return UploaderRequest[R, P]{method, files, params}
|
||||
}
|
||||
func (u UploaderRequest[R, P]) DoWithContext(ctx context.Context, up *Uploader) (R, error) {
|
||||
var zero R
|
||||
url := fmt.Sprintf("https://api.telegram.org/bot%s/%s", up.api.token, u.method)
|
||||
|
||||
buf := bytes.NewBuffer(nil)
|
||||
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 {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, buf)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("Laniakea/%s", utils.VersionString))
|
||||
|
||||
up.logger.Debugln("UPLOADER REQ", u.method)
|
||||
res, err := up.api.client.Do(req)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
up.logger.Debugln("UPLOADER RES", u.method, string(body))
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return zero, fmt.Errorf("[%d] %s", res.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var response ApiResponse[R]
|
||||
err = json.Unmarshal(body, &response)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if !response.Ok {
|
||||
return zero, fmt.Errorf("[%d] %s", response.ErrorCode, response.Description)
|
||||
}
|
||||
return response.Result, nil
|
||||
}
|
||||
func (u UploaderRequest[R, P]) Do(up *Uploader) (R, error) {
|
||||
ctx := context.Background()
|
||||
return u.DoWithContext(ctx, up)
|
||||
}
|
||||
|
||||
type UploadPhotoP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -157,13 +23,13 @@ type UploadPhotoP struct {
|
||||
}
|
||||
|
||||
func (u *Uploader) UploadPhoto(params UploadPhotoP, file UploaderFile) (Message, error) {
|
||||
req := NewUploaderRequest[Message]("sendPhoto", params, file)
|
||||
req := NewUploaderRequestWithChatID[Message]("sendPhoto", params, params.ChatID, file)
|
||||
return req.Do(u)
|
||||
}
|
||||
|
||||
type UploadAudioP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -186,13 +52,13 @@ type UploadAudioP struct {
|
||||
}
|
||||
|
||||
func (u *Uploader) UploadAudio(params UploadAudioP, files ...UploaderFile) (Message, error) {
|
||||
req := NewUploaderRequest[Message]("sendAudio", params, files...)
|
||||
req := NewUploaderRequestWithChatID[Message]("sendAudio", params, params.ChatID, files...)
|
||||
return req.Do(u)
|
||||
}
|
||||
|
||||
type UploadDocumentP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -218,7 +84,7 @@ func (u *Uploader) UploadDocument(params UploadDocumentP, files ...UploaderFile)
|
||||
|
||||
type UploadVideoP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -251,7 +117,7 @@ func (u *Uploader) UploadVideo(params UploadVideoP, files ...UploaderFile) (Mess
|
||||
|
||||
type UploadAnimationP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -282,7 +148,7 @@ func (u *Uploader) UploadAnimation(params UploadAnimationP, files ...UploaderFil
|
||||
|
||||
type UploadVoiceP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -308,7 +174,7 @@ func (u *Uploader) UploadVoice(params UploadVoiceP, files ...UploaderFile) (Mess
|
||||
|
||||
type UploadVideoNoteP struct {
|
||||
BusinessConnectionID string `json:"business_connection_id,omitempty"`
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
MessageThreadID int `json:"message_thread_id,omitempty"`
|
||||
DirectMessagesTopicID int `json:"direct_messages_topic_id,omitempty"`
|
||||
|
||||
@@ -330,28 +196,11 @@ func (u *Uploader) UploadVideoNote(params UploadVideoNoteP, files ...UploaderFil
|
||||
return req.Do(u)
|
||||
}
|
||||
|
||||
// setChatPhoto https://core.telegram.org/bots/api#setchatphoto
|
||||
type UploadChatPhotoP struct {
|
||||
ChatID int `json:"chat_id"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
}
|
||||
|
||||
func (u *Uploader) UploadChatPhoto(params UploadChatPhotoP, photo UploaderFile) (Message, error) {
|
||||
req := NewUploaderRequest[Message]("sendChatPhoto", params, photo)
|
||||
return req.Do(u)
|
||||
}
|
||||
|
||||
func uploaderTypeByExt(filename string) UploaderFileType {
|
||||
ext := filepath.Ext(filename)
|
||||
switch ext {
|
||||
case ".jpg", ".jpeg", ".png", ".webp", ".bmp":
|
||||
return UploaderPhotoType
|
||||
case ".mp4":
|
||||
return UploaderVideoType
|
||||
case ".mp3", ".m4a":
|
||||
return UploaderAudioType
|
||||
case ".ogg":
|
||||
return UploaderVoiceType
|
||||
default:
|
||||
return UploaderDocumentType
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ type GetUserProfilePhotosP struct {
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetUserProfilePhotos(params GetUserProfilePhotosP) (UserProfilePhotos, error) {
|
||||
func (api *API) GetUserProfilePhotos(params GetUserProfilePhotosP) (UserProfilePhotos, error) {
|
||||
req := NewRequest[UserProfilePhotos]("getUserProfilePhotos", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -17,7 +17,7 @@ type GetUserProfileAudiosP struct {
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetUserProfileAudios(params GetUserProfileAudiosP) (UserProfileAudios, error) {
|
||||
func (api *API) GetUserProfileAudios(params GetUserProfileAudiosP) (UserProfileAudios, error) {
|
||||
req := NewRequest[UserProfileAudios]("getUserProfileAudios", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -28,7 +28,7 @@ type SetUserEmojiStatusP struct {
|
||||
ExpirationDate int `json:"emoji_status_expiration_date,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) SetUserEmojiStatus(params SetUserEmojiStatusP) (bool, error) {
|
||||
func (api *API) SetUserEmojiStatus(params SetUserEmojiStatusP) (bool, error) {
|
||||
req := NewRequest[bool]("setUserEmojiStatus", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ type GetUserGiftsP struct {
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Api) GetUserGifts(params GetUserGiftsP) (OwnedGifts, error) {
|
||||
func (api *API) GetUserGifts(params GetUserGiftsP) (OwnedGifts, error) {
|
||||
req := NewRequest[OwnedGifts]("getUserGifts", params)
|
||||
return req.Do(api)
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package tgapi
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"git.nix13.pw/scuroneko/slog"
|
||||
)
|
||||
|
||||
func GetLoggerLevel() slog.LogLevel {
|
||||
level := slog.FATAL
|
||||
if os.Getenv("DEBUG") == "true" {
|
||||
level = slog.DEBUG
|
||||
}
|
||||
return level
|
||||
}
|
||||
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
|
||||
|
||||
204
utils/limiter.go
Normal file
204
utils/limiter.go
Normal file
@@ -0,0 +1,204 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
var ErrDropOverflow = errors.New("drop overflow limit")
|
||||
|
||||
// RateLimiter implements per-chat and global rate limiting with optional blocking.
|
||||
// It supports two modes:
|
||||
// - "drop" mode: immediately reject if limits are exceeded.
|
||||
// - "wait" mode: block until capacity is available.
|
||||
type RateLimiter struct {
|
||||
globalLockUntil time.Time // global cooldown timestamp (set by API errors)
|
||||
globalLimiter *rate.Limiter // global token bucket (30 req/sec)
|
||||
globalMu sync.RWMutex // protects globalLockUntil and globalLimiter
|
||||
|
||||
chatLocks map[int64]time.Time // per-chat cooldown timestamps
|
||||
chatLimiters map[int64]*rate.Limiter // per-chat token buckets (1 req/sec)
|
||||
chatMu sync.Mutex // protects chatLocks and chatLimiters
|
||||
}
|
||||
|
||||
// NewRateLimiter creates a new RateLimiter with default limits.
|
||||
// Global: 30 requests per second, burst 30.
|
||||
// Per-chat: 1 request per second, burst 1.
|
||||
func NewRateLimiter() *RateLimiter {
|
||||
return &RateLimiter{
|
||||
globalLimiter: rate.NewLimiter(30, 30),
|
||||
chatLimiters: make(map[int64]*rate.Limiter),
|
||||
chatLocks: make(map[int64]time.Time),
|
||||
}
|
||||
}
|
||||
|
||||
// SetGlobalLock sets a global cooldown period (e.g., after receiving 429 from Telegram).
|
||||
// If retryAfter <= 0, no lock is applied.
|
||||
func (rl *RateLimiter) SetGlobalLock(retryAfter int) {
|
||||
if retryAfter <= 0 {
|
||||
return
|
||||
}
|
||||
rl.globalMu.Lock()
|
||||
defer rl.globalMu.Unlock()
|
||||
rl.globalLockUntil = time.Now().Add(time.Duration(retryAfter) * time.Second)
|
||||
}
|
||||
|
||||
// SetChatLock sets a cooldown for a specific chat (e.g., after 429 for that chat).
|
||||
// If retryAfter <= 0, no lock is applied.
|
||||
func (rl *RateLimiter) SetChatLock(chatID int64, retryAfter int) {
|
||||
if retryAfter <= 0 {
|
||||
return
|
||||
}
|
||||
rl.chatMu.Lock()
|
||||
defer rl.chatMu.Unlock()
|
||||
rl.chatLocks[chatID] = time.Now().Add(time.Duration(retryAfter) * time.Second)
|
||||
}
|
||||
|
||||
// GlobalWait blocks until a global request can be made.
|
||||
// Waits for both global cooldown and token bucket availability.
|
||||
func (rl *RateLimiter) GlobalWait(ctx context.Context) error {
|
||||
if err := rl.waitForGlobalUnlock(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return rl.globalLimiter.Wait(ctx)
|
||||
}
|
||||
|
||||
// Wait blocks until a request for the given chat can be made.
|
||||
// Waits for: chat cooldown → global cooldown → chat token bucket.
|
||||
// Note: Global limit is checked *before* chat limit to avoid overloading upstream.
|
||||
func (rl *RateLimiter) Wait(ctx context.Context, chatID int64) error {
|
||||
if err := rl.waitForChatUnlock(ctx, chatID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rl.waitForGlobalUnlock(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
limiter := rl.getChatLimiter(chatID)
|
||||
return limiter.Wait(ctx)
|
||||
}
|
||||
|
||||
// GlobalAllow checks if a global request can be made without blocking.
|
||||
// Returns false if either global cooldown is active or token bucket is exhausted.
|
||||
func (rl *RateLimiter) GlobalAllow() bool {
|
||||
rl.globalMu.RLock()
|
||||
until := rl.globalLockUntil
|
||||
rl.globalMu.RUnlock()
|
||||
|
||||
if !until.IsZero() && time.Now().Before(until) {
|
||||
return false
|
||||
}
|
||||
return rl.globalLimiter.Allow()
|
||||
}
|
||||
|
||||
// Allow checks if a request for the given chat can be made without blocking.
|
||||
// Returns false if: global cooldown, chat cooldown, global limiter, or chat limiter denies.
|
||||
// Note: Global limiter is checked before chat limiter — upstream limits take priority.
|
||||
func (rl *RateLimiter) Allow(chatID int64) bool {
|
||||
// Check global cooldown
|
||||
rl.globalMu.RLock()
|
||||
globalUntil := rl.globalLockUntil
|
||||
rl.globalMu.RUnlock()
|
||||
if !globalUntil.IsZero() && time.Now().Before(globalUntil) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check chat cooldown
|
||||
rl.chatMu.Lock()
|
||||
chatUntil, ok := rl.chatLocks[chatID]
|
||||
rl.chatMu.Unlock()
|
||||
if ok && !chatUntil.IsZero() && time.Now().Before(chatUntil) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check global token bucket
|
||||
if !rl.globalLimiter.Allow() {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check chat token bucket
|
||||
limiter := rl.getChatLimiter(chatID)
|
||||
return limiter.Allow()
|
||||
}
|
||||
|
||||
// Check applies rate limiting based on configuration.
|
||||
// If dropOverflow is true:
|
||||
// - Immediately returns ErrDropOverflow if either global or chat limit is exceeded.
|
||||
//
|
||||
// Else:
|
||||
// - If chatID != 0: waits for chat-specific capacity (including global limit).
|
||||
// - If chatID == 0: waits for global capacity only.
|
||||
//
|
||||
// chatID == 0 means no specific chat context (e.g., inline query, webhook without chat).
|
||||
func (rl *RateLimiter) Check(ctx context.Context, dropOverflow bool, chatID int64) error {
|
||||
if dropOverflow {
|
||||
if chatID != 0 && !rl.Allow(chatID) {
|
||||
return ErrDropOverflow
|
||||
}
|
||||
if !rl.GlobalAllow() {
|
||||
return ErrDropOverflow
|
||||
}
|
||||
} else if chatID != 0 {
|
||||
if err := rl.Wait(ctx, chatID); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := rl.GlobalWait(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitForGlobalUnlock blocks until global cooldown expires or context is done.
|
||||
// Does not check token bucket — only cooldown.
|
||||
func (rl *RateLimiter) waitForGlobalUnlock(ctx context.Context) error {
|
||||
rl.globalMu.RLock()
|
||||
until := rl.globalLockUntil
|
||||
rl.globalMu.RUnlock()
|
||||
|
||||
if until.IsZero() || time.Now().After(until) {
|
||||
return nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-time.After(time.Until(until)):
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// waitForChatUnlock blocks until the specified chat's cooldown expires or context is done.
|
||||
// Does not check token bucket — only cooldown.
|
||||
func (rl *RateLimiter) waitForChatUnlock(ctx context.Context, chatID int64) error {
|
||||
rl.chatMu.Lock()
|
||||
until, ok := rl.chatLocks[chatID]
|
||||
rl.chatMu.Unlock()
|
||||
|
||||
if !ok || until.IsZero() || time.Now().After(until) {
|
||||
return nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-time.After(time.Until(until)):
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// getChatLimiter returns the rate limiter for the given chat, creating it if needed.
|
||||
// Uses 1 request per second with burst of 1 — conservative for per-user limits.
|
||||
// Must be called with rl.chatMu held.
|
||||
func (rl *RateLimiter) getChatLimiter(chatID int64) *rate.Limiter {
|
||||
if lim, ok := rl.chatLimiters[chatID]; ok {
|
||||
return lim
|
||||
}
|
||||
lim := rate.NewLimiter(1, 1)
|
||||
rl.chatLimiters[chatID] = lim
|
||||
return lim
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
@@ -26,33 +25,31 @@ func Encode[T any](w *multipart.Writer, req T) error {
|
||||
field := v.Field(i)
|
||||
fieldType := t.Field(i)
|
||||
|
||||
formTags := strings.Split(fieldType.Tag.Get("json"), ",")
|
||||
fieldName := ""
|
||||
if len(formTags) == 0 {
|
||||
formTags = strings.Split(fieldType.Tag.Get("json"), ",")
|
||||
jsonTag := fieldType.Tag.Get("json")
|
||||
if jsonTag == "" {
|
||||
jsonTag = fieldType.Name
|
||||
}
|
||||
|
||||
if len(formTags) > 0 {
|
||||
fieldName = formTags[0]
|
||||
if fieldName == "-" {
|
||||
continue
|
||||
}
|
||||
if slices.Index(formTags, "omitempty") >= 0 {
|
||||
if field.IsZero() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fieldName = strings.ToLower(fieldType.Name)
|
||||
parts := strings.Split(jsonTag, ",")
|
||||
fieldName := parts[0]
|
||||
if fieldName == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle omitempty
|
||||
isEmpty := field.IsZero()
|
||||
if slices.Contains(parts, "omitempty") && isEmpty {
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
fw io.Writer
|
||||
err error
|
||||
)
|
||||
|
||||
switch field.Kind() {
|
||||
case reflect.String:
|
||||
if field.String() != "" {
|
||||
if !isEmpty {
|
||||
fw, err = w.CreateFormField(fieldName)
|
||||
if err == nil {
|
||||
_, err = fw.Write([]byte(field.String()))
|
||||
@@ -80,45 +77,47 @@ func Encode[T any](w *multipart.Writer, req T) error {
|
||||
}
|
||||
case reflect.Slice:
|
||||
if field.Type().Elem().Kind() == reflect.Uint8 && !field.IsNil() {
|
||||
// Handle []byte as file upload (e.g., thumbnail)
|
||||
filename := fieldType.Tag.Get("filename")
|
||||
if filename == "" {
|
||||
filename = fieldName
|
||||
}
|
||||
|
||||
ext := ""
|
||||
filename = filename + ext
|
||||
|
||||
fw, err = w.CreateFormFile(fieldName, filename)
|
||||
if err == nil {
|
||||
_, err = fw.Write(field.Bytes())
|
||||
}
|
||||
} else if !field.IsNil() {
|
||||
// Handle slice of primitive values (as multiple form fields with the same name)
|
||||
// Handle []string, []int, etc. — send as multiple fields with same name
|
||||
for j := 0; j < field.Len(); j++ {
|
||||
elem := field.Index(j)
|
||||
fw, err = w.CreateFormField(fieldName)
|
||||
if err == nil {
|
||||
switch elem.Kind() {
|
||||
case reflect.String:
|
||||
_, err = fw.Write([]byte(elem.String()))
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
_, err = fw.Write([]byte(strconv.FormatInt(elem.Int(), 10)))
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
_, err = fw.Write([]byte(strconv.FormatUint(elem.Uint(), 10)))
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch elem.Kind() {
|
||||
case reflect.String:
|
||||
_, err = fw.Write([]byte(elem.String()))
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
_, err = fw.Write([]byte(strconv.FormatInt(elem.Int(), 10)))
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
_, err = fw.Write([]byte(strconv.FormatUint(elem.Uint(), 10)))
|
||||
case reflect.Bool:
|
||||
_, err = fw.Write([]byte(strconv.FormatBool(elem.Bool())))
|
||||
case reflect.Float32, reflect.Float64:
|
||||
_, err = fw.Write([]byte(strconv.FormatFloat(elem.Float(), 'f', -1, 64)))
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case reflect.Struct:
|
||||
var jsonData []byte
|
||||
jsonData, err = json.Marshal(field.Interface())
|
||||
if err == nil {
|
||||
fw, err = w.CreateFormField(fieldName)
|
||||
if err == nil {
|
||||
_, err = fw.Write(jsonData)
|
||||
}
|
||||
}
|
||||
// Don't serialize structs as JSON — flatten them!
|
||||
// Telegram doesn't support nested JSON in form-data.
|
||||
// If you need nested data, use separate fields (e.g., ParseMode, CaptionEntities)
|
||||
// This is a design choice — you should avoid nested structs in params.
|
||||
return fmt.Errorf("nested structs are not supported in params — use flat fields")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
@@ -17,73 +15,7 @@ func GetLoggerLevel() slog.LogLevel {
|
||||
return level
|
||||
}
|
||||
|
||||
func Cast[A, B any](src A) (*B, error) {
|
||||
m, err := StructToMap(src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out := new(B)
|
||||
err = MapToStruct(m, out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MapToStruct unsafe function
|
||||
func MapToStruct(m map[string]any, s any) error {
|
||||
data, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal(data, s)
|
||||
return err
|
||||
}
|
||||
|
||||
// SliceToStruct unsafe function
|
||||
func SliceToStruct(sl []any, s any) error {
|
||||
data, err := json.Marshal(sl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal(data, s)
|
||||
return err
|
||||
}
|
||||
|
||||
// AnyToStruct unsafe function
|
||||
func AnyToStruct(src, dest any) error {
|
||||
data, err := json.Marshal(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal(data, dest)
|
||||
return err
|
||||
}
|
||||
|
||||
func MapToJson(m map[string]any) (string, error) {
|
||||
data, err := json.Marshal(m)
|
||||
return string(data), err
|
||||
}
|
||||
|
||||
func StructToMap(s any) (map[string]any, error) {
|
||||
data, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := make(map[string]any)
|
||||
err = json.Unmarshal(data, &m)
|
||||
return m, err
|
||||
}
|
||||
|
||||
func Map[T, V any](ts []T, fn func(T) V) []V {
|
||||
result := make([]V, len(ts))
|
||||
for i, t := range ts {
|
||||
result[i] = fn(t)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// EscapeMarkdown Deprecated. Use MarkdownV2
|
||||
func EscapeMarkdown(s string) string {
|
||||
s = strings.ReplaceAll(s, "_", `\_`)
|
||||
s = strings.ReplaceAll(s, "*", `\*`)
|
||||
@@ -91,10 +23,20 @@ func EscapeMarkdown(s string) string {
|
||||
return strings.ReplaceAll(s, "`", "\\`")
|
||||
}
|
||||
|
||||
// EscapeHTML escapes special characters for Telegram HTML parse mode.
|
||||
func EscapeHTML(s string) string {
|
||||
s = strings.ReplaceAll(s, "&", "&")
|
||||
s = strings.ReplaceAll(s, "<", "<")
|
||||
s = strings.ReplaceAll(s, ">", ">")
|
||||
return s
|
||||
}
|
||||
|
||||
// EscapeMarkdownV2 escapes special characters for Telegram MarkdownV2.
|
||||
// https://core.telegram.org/bots/api#markdownv2-style
|
||||
func EscapeMarkdownV2(s string) string {
|
||||
symbols := []string{"_", "*", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||
symbols := []string{"_", "*", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!", "\\"}
|
||||
for _, symbol := range symbols {
|
||||
s = strings.ReplaceAll(s, symbol, fmt.Sprintf("\\%s", symbol))
|
||||
s = strings.ReplaceAll(s, symbol, "\\"+symbol)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package utils
|
||||
|
||||
const (
|
||||
VersionString = "0.5.0"
|
||||
VersionMajor = 0
|
||||
VersionMinor = 5
|
||||
VersionString = "1.0.0-beta.10"
|
||||
VersionMajor = 1
|
||||
VersionMinor = 0
|
||||
VersionPatch = 0
|
||||
Beta = 10
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user