All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 5s
75 lines
2.3 KiB
Go
75 lines
2.3 KiB
Go
package api
|
|
|
|
import (
|
|
"log/slog"
|
|
"slices"
|
|
"strings"
|
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
"github.com/maximotejeda/us_dop_bot/internal/application/command"
|
|
"github.com/maximotejeda/us_dop_bot/internal/application/message"
|
|
"github.com/maximotejeda/us_dop_bot/internal/application/query"
|
|
"github.com/maximotejeda/us_dop_bot/internal/ports"
|
|
)
|
|
|
|
type api struct {
|
|
bot *tgbotapi.BotAPI
|
|
command ports.Tgb
|
|
message ports.Tgb
|
|
query ports.Tgb
|
|
dolar ports.DolarService
|
|
user ports.UserService
|
|
log *slog.Logger
|
|
}
|
|
|
|
func NewApi(bot *tgbotapi.BotAPI) *api {
|
|
log := slog.Default()
|
|
log = log.With("location", "root")
|
|
return &api{bot: bot, log: log}
|
|
}
|
|
|
|
func (a *api) Run(update *tgbotapi.Update, dolar ports.DolarService, user ports.UserService) {
|
|
// check for user in db
|
|
_, err := user.Get(update.SentFrom().ID)
|
|
if err != nil {
|
|
|
|
if strings.Contains(err.Error(), "sql: no rows in result set") {
|
|
a.log.Info("user not in database ")
|
|
a.log.Info("bot not restricted adding user to DB")
|
|
user.Create(update.SentFrom())
|
|
a.log.Info("Adding query permision to user over bot")
|
|
user.AddBot(update.SentFrom().ID, a.bot.Self.UserName)
|
|
}
|
|
a.log.Error("getting user", "error", err)
|
|
a.log.Info("bot not restricted adding user to DB")
|
|
}
|
|
bots, err := user.GetBots(update.SentFrom().ID)
|
|
if err != nil {
|
|
a.log.Error("getting bots", "error", err)
|
|
}
|
|
if !slices.Contains(bots, a.bot.Self.UserName) {
|
|
a.log.Info("bot not found in db for user", "bot", a.bot.Self.UserName)
|
|
a.log.Info("adding bots", "user", update.SentFrom().UserName, "bot", a.bot.Self.UserName)
|
|
_, err := user.AddBot(update.SentFrom().ID, a.bot.Self.UserName)
|
|
if err != nil {
|
|
a.log.Error("adding bots", "user", update.SentFrom().UserName, "bot", a.bot.Self.UserName, "error", err)
|
|
}
|
|
}
|
|
msg := update.Message
|
|
if msg != nil { // message is not nil can be a command or a text message
|
|
if msg.IsCommand() {
|
|
a.command = command.NewCommand(a.bot, update, dolar, user)
|
|
a.command.Handler()
|
|
// is a command
|
|
} else if msg.Text != "" {
|
|
// is a text message
|
|
a.message = message.NewMessage(a.bot, update, dolar, user)
|
|
a.message.Handler()
|
|
}
|
|
} else if update.CallbackQuery != nil {
|
|
// is a cal back query
|
|
a.query = query.NewQuery(a.bot, update, dolar, user)
|
|
a.query.Handler()
|
|
}
|
|
}
|