diff --git a/.env-example b/.env-example index 5fa8463..0160f93 100644 --- a/.env-example +++ b/.env-example @@ -15,7 +15,8 @@ TELEGRAM_VOTE_BOT_TOKEN=replace-me TELEGRAM_AUTHORIZATION_BOT_TOKEN=replace-me DISCORD_AUTHORIZATION_BOT_TOKEN=replace-me -DISCORD_AUTHORIZATION_CHANNEL_ID=replace-me +DISCORD_SERVER_ID=replace-me +DISCORD_MEMBER_ROLE_ID=replace-me VOTE_API_URL=replace-me diff --git a/.github/workflows/docker.yaml b/.github/workflows/docker.yaml index 621b066..ffa5303 100644 --- a/.github/workflows/docker.yaml +++ b/.github/workflows/docker.yaml @@ -58,7 +58,7 @@ jobs: push: true tags: ghcr.io/beniamiiin/access-governance-system:pss - - name: Build and push AuthorizationBot + - name: Build and push TelegramAuthorizationBot uses: docker/build-push-action@v4 with: context: . @@ -70,6 +70,20 @@ jobs: DB_URL=${{ secrets.DB_URL }} TELEGRAM_AUTHORIZATION_BOT_TOKEN=${{ secrets.TELEGRAM_AUTHORIZATION_BOT_TOKEN }} DISCORD_AUTHORIZATION_BOT_TOKEN=${{ secrets.DISCORD_AUTHORIZATION_BOT_TOKEN }} - DISCORD_AUTHORIZATION_CHANNEL_ID=${{ secrets.DISCORD_AUTHORIZATION_CHANNEL_ID }} + DISCORD_SERVER_ID=${{ secrets.DISCORD_SERVER_ID }} + DISCORD_MEMBER_ROLE_ID=${{ secrets.DISCORD_MEMBER_ROLE_ID }} push: true - tags: ghcr.io/beniamiiin/access-governance-system:ab + tags: ghcr.io/beniamiiin/access-governance-system:tab + + - name: Build and push DiscordAuthorizationBot + uses: docker/build-push-action@v4 + with: + context: . + file: ./deployments/authorization_bot/Dockerfile + build-args: | + ENVIRONMENT=${{ vars.ENVIRONMENT }} + COMMUNITY_NAME=${{ vars.COMMUNITY_NAME }} + LOKI_URL=${{ secrets.LOKI_URL }} + DISCORD_AUTHORIZATION_BOT_TOKEN=${{ secrets.DISCORD_AUTHORIZATION_BOT_TOKEN }} + push: true + tags: ghcr.io/beniamiiin/access-governance-system:dab diff --git a/Taskfile.prod.yml b/Taskfile.prod.yml index 47e860f..cba4242 100644 --- a/Taskfile.prod.yml +++ b/Taskfile.prod.yml @@ -138,18 +138,27 @@ tasks: deps: - install-docker-plugins vars: - URL: ghcr.io/beniamiiin/access-governance-system:ab - SERVICE_NAME: authorization-bot + TELEGRAM_BOT_URL: ghcr.io/beniamiiin/access-governance-system:tab + TELEGRAM_SERVICE_NAME: authorization-bot-telegram + DISCORD_BOT_URL: ghcr.io/beniamiiin/access-governance-system:dab + DISCORD_SERVICE_NAME: authorization-bot-discord cmds: - - docker pull {{.URL}} - - docker image tag {{.URL}} {{.SERVICE_NAME}} - - docker rmi {{.URL}} - - docker run --detach --interactive --tty --net {{.NETWORK_NAME}} --name {{.SERVICE_NAME}} {{.SERVICE_NAME}} + - docker pull {{.TELEGRAM_BOT_URL}} + - docker image tag {{.TELEGRAM_BOT_URL}} {{.TELEGRAM_SERVICE_NAME}} + - docker rmi {{.TELEGRAM_BOT_URL}} + - docker run --detach --interactive --tty --net {{.NETWORK_NAME}} --name {{.TELEGRAM_SERVICE_NAME}} {{.TELEGRAM_SERVICE_NAME}} + - docker pull {{.DISCORD_BOT_URL}} + - docker image tag {{.DISCORD_BOT_URL}} {{.DISCORD_SERVICE_NAME}} + - docker rmi {{.DISCORD_BOT_URL}} + - docker run --detach --interactive --tty --net {{.NETWORK_NAME}} --name {{.DISCORD_SERVICE_NAME}} {{.DISCORD_SERVICE_NAME}} authorization-bot-down: desc: Stop authorization bot vars: - SERVICE_NAME: authorization-bot + TELEGRAM_SERVICE_NAME: authorization-bot-telegram + DISCORD_SERVICE_NAME: authorization-bot-discord cmds: - - docker rm -f {{.SERVICE_NAME}} - - docker rmi -f {{.SERVICE_NAME}} + - docker rm -f {{.TELEGRAM_SERVICE_NAME}} + - docker rmi -f {{.TELEGRAM_SERVICE_NAME}} + - docker rm -f {{.DISCORD_SERVICE_NAME}} + - docker rmi -f {{.DISCORD_SERVICE_NAME}} diff --git a/Taskfile.yml b/Taskfile.yml index 981edf0..84809c7 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -87,14 +87,20 @@ tasks: up --detach --build - authorization-bot + authorization-bot-telegram authorization-bot-down: desc: Stop authorization bot cmds: - docker-compose - --env-file .env --file ./deployments/docker-compose.yml - --project-name authorization-bot down - authorization-bot + authorization-bot-telegram + - docker-compose + --file ./deployments/docker-compose.yml + down + authorization-bot-discord + - docker-compose + --file ./deployments/docker-compose.yml + down + database diff --git a/cmd/authorization_bot/discord/main.go b/cmd/authorization_bot/discord/main.go new file mode 100644 index 0000000..efbc2d2 --- /dev/null +++ b/cmd/authorization_bot/discord/main.go @@ -0,0 +1,111 @@ +package main + +import ( + "access_governance_system/configs" + "access_governance_system/internal/di" + "context" + "errors" + "fmt" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/bwmarrin/discordgo" + "go.uber.org/zap" +) + +var ( + config configs.DiscordAuthrozationBotConfig + logger *zap.SugaredLogger +) + +func main() { + config, err := configs.LoadDiscordAuthrozationBotConfig() + logger := di.NewLogger(config.Logger.AppName, config.App.Environment, config.Logger.URL) + + if err != nil { + logger.Fatalw("failed to load config", "error", err) + } + logger.Info("config loaded") + + go func() { + logger.Info("setting up health check server") + settingUpHealthCheckServer(logger) + }() + + logger.Info("starting bot") + + discord, err := discordgo.New("Bot " + config.AuthrozationBot.Token) + if err != nil { + logger.Fatalw("failed to create discord session", "error", err) + } + + discord.AddHandler(authorization) + + discord.Identify.Intents = discordgo.IntentsGuildMessages + + err = discord.Open() + if err != nil { + logger.Fatalw("error opening connection", "error", err) + return + } + + stop := make(chan os.Signal, 1) + signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + <-stop + + discord.Close() +} + +func authorization(s *discordgo.Session, m *discordgo.MessageCreate) { + if m.Author.ID == s.State.User.ID { + return + } + + if m.Content == "!authorize" { + tgBotLink := fmt.Sprintf("https://t.me/S16AuthorizationBot?start=%s", m.Author.ID) + message := fmt.Sprintf("Привет, для авторизации в сообществе %s перейди по ссылке %s", config.App.CommunityName, tgBotLink) + + channel, err := s.UserChannelCreate(m.Author.ID) + if err != nil { + fmt.Println("failed to create author channel", "error", err) + } + + _, err = s.ChannelMessageSend(channel.ID, message) + if err != nil { + fmt.Println("failed to send message", "error", err) + } + } +} + +func settingUpHealthCheckServer(logger *zap.SugaredLogger) { + mux := http.NewServeMux() + mux.HandleFunc("/authorization-bot-discord/healthcheck", healthCheckHandler) + + server := &http.Server{Addr: ":8080", Handler: mux} + + if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + logger.Errorw("failed to start http server", "error", err) + } + + stop := make(chan os.Signal, 1) + signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + <-stop + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + err := server.Shutdown(ctx) + if err != nil { + logger.Errorw("failed to shutdown http server", "error", err) + return + } + + logger.Info("shutting down") +} + +func healthCheckHandler(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("I'm alive")) +} diff --git a/cmd/authorization_bot/main.go b/cmd/authorization_bot/telegram/main.go similarity index 93% rename from cmd/authorization_bot/main.go rename to cmd/authorization_bot/telegram/main.go index f687bdb..0e2c53c 100644 --- a/cmd/authorization_bot/main.go +++ b/cmd/authorization_bot/telegram/main.go @@ -21,7 +21,7 @@ import ( ) func main() { - config, err := configs.LoadAuthrozationBotConfig() + config, err := configs.LoadTelegramAuthrozationBotConfig() logger := di.NewLogger(config.Logger.AppName, config.App.Environment, config.Logger.URL) if err != nil { @@ -55,7 +55,7 @@ func main() { func settingUpHealthCheckServer(logger *zap.SugaredLogger) { mux := http.NewServeMux() - mux.HandleFunc("/authorization-bot/healthcheck", healthCheckHandler) + mux.HandleFunc("/authorization-bot-telegram/healthcheck", healthCheckHandler) server := &http.Server{Addr: ":8080", Handler: mux} diff --git a/configs/app.go b/configs/app.go index 9f330d8..19b04e4 100644 --- a/configs/app.go +++ b/configs/app.go @@ -8,7 +8,3 @@ type App struct { InitialSeeders []string `env:"INITIAL_SEEDERS" envSeparator:","` MembersChatID int64 `env:"MEMBERS_CHAT_ID,notEmpty"` } - -func (c App) IsDevEnvironment() bool { - return c.Environment == "development" -} diff --git a/configs/telegram.go b/configs/bot.go similarity index 58% rename from configs/telegram.go rename to configs/bot.go index 538d844..06cfc58 100644 --- a/configs/telegram.go +++ b/configs/bot.go @@ -1,5 +1,5 @@ package configs -type Telegram struct { +type Bot struct { Token string } diff --git a/configs/config.go b/configs/config.go index 68446f8..90ac6d3 100644 --- a/configs/config.go +++ b/configs/config.go @@ -11,8 +11,8 @@ type AccessGovernanceBotConfig struct { App App DB DB Logger Logger - AccessGovernanceBot Telegram - VoteBot Telegram + AccessGovernanceBot Bot + VoteBot Bot VoteAPI VoteAPI } @@ -34,7 +34,7 @@ type ProposalStateServiceConfig struct { App App DB DB Logger Logger - AccessGovernanceBot Telegram + AccessGovernanceBot Bot VoteAPI VoteAPI Quorum float64 `env:"QUORUM"` // 30% initial parameter for quorum @@ -55,23 +55,42 @@ func LoadProposalStateServiceConfig() (ProposalStateServiceConfig, error) { return config, nil } -type AuthrozationBotConfig struct { +type TelegramAuthrozationBotConfig struct { App App DB DB Logger Logger DiscordAuthrozationBot Discord - TelegramAuthrozationBot Telegram + TelegramAuthrozationBot Bot } -func LoadAuthrozationBotConfig() (AuthrozationBotConfig, error) { - var config AuthrozationBotConfig +func LoadTelegramAuthrozationBotConfig() (TelegramAuthrozationBotConfig, error) { + var config TelegramAuthrozationBotConfig if err := env.Parse(&config); err != nil { - return AuthrozationBotConfig{}, fmt.Errorf("failed to parse config: %w", err) + return TelegramAuthrozationBotConfig{}, fmt.Errorf("failed to parse config: %w", err) } config.TelegramAuthrozationBot.Token = os.Getenv("TELEGRAM_AUTHORIZATION_BOT_TOKEN") - config.Logger.AppName = "authorization-bot" + config.Logger.AppName = "authorization-bot-telegram" + + return config, nil +} + +type DiscordAuthrozationBotConfig struct { + App App + Logger Logger + AuthrozationBot Bot +} + +func LoadDiscordAuthrozationBotConfig() (DiscordAuthrozationBotConfig, error) { + var config DiscordAuthrozationBotConfig + + if err := env.Parse(&config); err != nil { + return DiscordAuthrozationBotConfig{}, fmt.Errorf("failed to parse config: %w", err) + } + + config.AuthrozationBot.Token = os.Getenv("DISCORD_AUTHORIZATION_BOT_TOKEN") + config.Logger.AppName = "authorization-bot-discord" return config, nil } diff --git a/configs/discord.go b/configs/discord.go index 978ae6b..ccdc4bf 100644 --- a/configs/discord.go +++ b/configs/discord.go @@ -1,6 +1,7 @@ package configs type Discord struct { - Token string `env:"DISCORD_AUTHORIZATION_BOT_TOKEN,notEmpty"` - AuthorizationChannelID string `env:"DISCORD_AUTHORIZATION_CHANNEL_ID,notEmpty"` + Token string `env:"DISCORD_AUTHORIZATION_BOT_TOKEN"` + ChannelID string `env:"DISCORD_SERVER_ID"` + MemberRoleID string `env:"DISCORD_MEMBER_ROLE_ID"` } diff --git a/deployments/authorization_bot/discord/Dockerfile b/deployments/authorization_bot/discord/Dockerfile new file mode 100644 index 0000000..517f3c4 --- /dev/null +++ b/deployments/authorization_bot/discord/Dockerfile @@ -0,0 +1,28 @@ +FROM golang:1.21 + +ARG ENVIRONMENT +ENV ENVIRONMENT=$ENVIRONMENT + +ARG LOKI_URL +ENV LOKI_URL=$LOKI_URL + +ARG DISCORD_AUTHORIZATION_BOT_TOKEN +ENV DISCORD_AUTHORIZATION_BOT_TOKEN=$DISCORD_AUTHORIZATION_BOT_TOKEN + +ARG DISCORD_SERVER_ID +ENV DISCORD_SERVER_ID=$DISCORD_SERVER_ID + +ARG DISCORD_MEMBER_ROLE_ID +ENV DISCORD_MEMBER_ROLE_ID=$DISCORD_MEMBER_ROLE_ID + +WORKDIR /opt/src + +COPY ./go.mod . +COPY ./go.sum . +RUN go mod download + +ADD . . + +RUN go build -o /go/bin/app ./cmd/authorization_bot/discord + +CMD ["/go/bin/app"] \ No newline at end of file diff --git a/deployments/authorization_bot/Dockerfile b/deployments/authorization_bot/telegram/Dockerfile similarity index 75% rename from deployments/authorization_bot/Dockerfile rename to deployments/authorization_bot/telegram/Dockerfile index 83caba7..d927d3d 100644 --- a/deployments/authorization_bot/Dockerfile +++ b/deployments/authorization_bot/telegram/Dockerfile @@ -18,9 +18,6 @@ ENV TELEGRAM_AUTHORIZATION_BOT_TOKEN=$TELEGRAM_AUTHORIZATION_BOT_TOKEN ARG DISCORD_AUTHORIZATION_BOT_TOKEN ENV DISCORD_AUTHORIZATION_BOT_TOKEN=$DISCORD_AUTHORIZATION_BOT_TOKEN -ARG DISCORD_AUTHORIZATION_CHANNEL_ID -ENV DISCORD_AUTHORIZATION_CHANNEL_ID=$DISCORD_AUTHORIZATION_CHANNEL_ID - WORKDIR /opt/src COPY ./go.mod . @@ -29,6 +26,6 @@ RUN go mod download ADD . . -RUN go build -o /go/bin/app ./cmd/authorization_bot/ +RUN go build -o /go/bin/app ./cmd/authorization_bot/telegram CMD ["/go/bin/app"] \ No newline at end of file diff --git a/deployments/docker-compose.yml b/deployments/docker-compose.yml index 0486722..f32d86d 100644 --- a/deployments/docker-compose.yml +++ b/deployments/docker-compose.yml @@ -22,18 +22,29 @@ services: depends_on: - database - authorization-bot: + authorization-bot-telegram: build: context: .. - dockerfile: ./deployments/authorization_bot/Dockerfile + dockerfile: ./deployments/authorization_bot/telegram/Dockerfile restart: on-failure:5 env_file: - ../.env ports: - 8080:8080 depends_on: + - authorization-bot-discord - database + authorization-bot-discord: + build: + context: .. + dockerfile: ./deployments/authorization_bot/discord/Dockerfile + restart: on-failure:5 + env_file: + - ../.env + ports: + - 8081:8081 + database: image: postgres:15.3 restart: always diff --git a/internal/tg_bot/commands/access_governance_bot/add_comment.go b/internal/tg_bot/commands/access_governance_bot/add_comment.go index 541286c..0f3c83d 100644 --- a/internal/tg_bot/commands/access_governance_bot/add_comment.go +++ b/internal/tg_bot/commands/access_governance_bot/add_comment.go @@ -23,14 +23,14 @@ const ( type addCommentCommand struct { userRepository repositories.UserRepository proposalRepository repositories.ProposalRepository - voteBotConfig configs.Telegram + voteBotConfig configs.Bot logger *zap.SugaredLogger } func NewAddCommentCommand( userRepository repositories.UserRepository, proposalRepository repositories.ProposalRepository, - voteBotConfig configs.Telegram, + voteBotConfig configs.Bot, logger *zap.SugaredLogger, ) commands.Command { return &addCommentCommand{ @@ -45,7 +45,7 @@ func (c *addCommentCommand) CanHandle(command string) bool { return command == addCommentCommandName } -func (c *addCommentCommand) Handle(command string, user *models.User, chatID int64) []tgbotapi.Chattable { +func (c *addCommentCommand) Handle(command, arguments string, user *models.User, chatID int64) []tgbotapi.Chattable { switch user.TelegramState.LastCommandState { case "": return []tgbotapi.Chattable{c.handleAddCommentCommand(command, user, chatID)} diff --git a/internal/tg_bot/commands/access_governance_bot/approved_proposals.go b/internal/tg_bot/commands/access_governance_bot/approved_proposals.go index 129eda3..dc62d88 100644 --- a/internal/tg_bot/commands/access_governance_bot/approved_proposals.go +++ b/internal/tg_bot/commands/access_governance_bot/approved_proposals.go @@ -32,7 +32,7 @@ func (c *approvedProposalsCommand) CanHandle(command string) bool { return command == approvedProposalsCommandName } -func (c *approvedProposalsCommand) Handle(text string, user *models.User, chatID int64) []tgbotapi.Chattable { +func (c *approvedProposalsCommand) Handle(text, arguments string, user *models.User, chatID int64) []tgbotapi.Chattable { proposals, err := c.proposalRepository.GetManyByStatus(models.ProposalStatusApproved, models.ProposalStatusRejected) if err != nil { c.logger.Errorw("failed to get proposals", "error", err) diff --git a/internal/tg_bot/commands/access_governance_bot/cancel_proposal.go b/internal/tg_bot/commands/access_governance_bot/cancel_proposal.go index 17d1c46..682b5f3 100644 --- a/internal/tg_bot/commands/access_governance_bot/cancel_proposal.go +++ b/internal/tg_bot/commands/access_governance_bot/cancel_proposal.go @@ -31,7 +31,7 @@ func (c *cancelProposalCommand) CanHandle(command string) bool { return command == cancelProposalCommandName } -func (c *cancelProposalCommand) Handle(text string, user *models.User, chatID int64) []tgbotapi.Chattable { +func (c *cancelProposalCommand) Handle(text, arguments string, user *models.User, chatID int64) []tgbotapi.Chattable { user.TempProposal = models.Proposal{} user.TelegramState = models.TelegramState{} _, err := c.userRepository.Update(user) diff --git a/internal/tg_bot/commands/access_governance_bot/create_proposal.go b/internal/tg_bot/commands/access_governance_bot/create_proposal.go index 1dad2f8..40bbcdd 100644 --- a/internal/tg_bot/commands/access_governance_bot/create_proposal.go +++ b/internal/tg_bot/commands/access_governance_bot/create_proposal.go @@ -64,7 +64,7 @@ func (c *createProposalCommand) CanHandle(command string) bool { return command == createProposalCommandName } -func (c *createProposalCommand) Handle(command string, user *models.User, chatID int64) []tgbotapi.Chattable { +func (c *createProposalCommand) Handle(command, arguments string, user *models.User, chatID int64) []tgbotapi.Chattable { var message tgbotapi.Chattable if command == createProposalCommandName { diff --git a/internal/tg_bot/commands/access_governance_bot/pending_proposals.go b/internal/tg_bot/commands/access_governance_bot/pending_proposals.go index f590ace..dea4182 100644 --- a/internal/tg_bot/commands/access_governance_bot/pending_proposals.go +++ b/internal/tg_bot/commands/access_governance_bot/pending_proposals.go @@ -32,7 +32,7 @@ func (c *pendingProposalsCommand) CanHandle(command string) bool { return command == pendingProposalsCommandName } -func (c *pendingProposalsCommand) Handle(text string, user *models.User, chatID int64) []tgbotapi.Chattable { +func (c *pendingProposalsCommand) Handle(text, arguments string, user *models.User, chatID int64) []tgbotapi.Chattable { proposals, err := c.proposalRepository.GetManyByStatus(models.ProposalStatusCreated) if err != nil { c.logger.Errorw("failed to get proposals", "error", err) diff --git a/internal/tg_bot/commands/access_governance_bot/start.go b/internal/tg_bot/commands/access_governance_bot/start.go index 6180692..e9823e0 100644 --- a/internal/tg_bot/commands/access_governance_bot/start.go +++ b/internal/tg_bot/commands/access_governance_bot/start.go @@ -32,7 +32,7 @@ func (c *startCommand) CanHandle(command string) bool { return command == startCommandName } -func (c *startCommand) Handle(text string, user *models.User, chatID int64) []tgbotapi.Chattable { +func (c *startCommand) Handle(text, arguments string, user *models.User, chatID int64) []tgbotapi.Chattable { parseMode := tgbotapi.ModeMarkdownV2 messageText := tgbotapi.EscapeText(parseMode, fmt.Sprintf(` diff --git a/internal/tg_bot/commands/authorization_bot/start.go b/internal/tg_bot/commands/authorization_bot/start.go index e34383e..a6f9ff1 100644 --- a/internal/tg_bot/commands/authorization_bot/start.go +++ b/internal/tg_bot/commands/authorization_bot/start.go @@ -5,7 +5,8 @@ import ( "access_governance_system/internal/db/models" "access_governance_system/internal/db/repositories" "access_governance_system/internal/tg_bot/commands" - "fmt" + "access_governance_system/internal/tg_bot/extension" + "strconv" "github.com/bwmarrin/discordgo" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" @@ -16,20 +17,20 @@ const startCommandName = "start" type startCommand struct { discord *discordgo.Session - discordConfig configs.Discord + config configs.Discord userRepository repositories.UserRepository logger *zap.SugaredLogger } -func NewStartCommand(discordConfig configs.Discord, userRepository repositories.UserRepository, logger *zap.SugaredLogger) commands.Command { - discord, err := discordgo.New("Bot " + discordConfig.Token) +func NewStartCommand(config configs.Discord, userRepository repositories.UserRepository, logger *zap.SugaredLogger) commands.Command { + discord, err := discordgo.New("Bot " + config.Token) if err != nil { logger.Fatalw("failed to create discord session", "error", err) } return &startCommand{ discord: discord, - discordConfig: discordConfig, + config: config, userRepository: userRepository, logger: logger, } @@ -39,15 +40,25 @@ func (c *startCommand) CanHandle(command string) bool { return command == startCommandName } -func (c *startCommand) Handle(text string, user *models.User, chatID int64) []tgbotapi.Chattable { +func (c *startCommand) Handle(text, discordID string, user *models.User, chatID int64) []tgbotapi.Chattable { if user.Role == models.UserRoleMember || user.Role == models.UserRoleSeeder { return []tgbotapi.Chattable{ tgbotapi.NewMessage(chatID, "Привет, ты уже авторизован."), } } - c.discord.ChannelMessageSend(c.discordConfig.AuthorizationChannelID, fmt.Sprintf("Пользователь с Telegram ID %d has started authorization.", user.TelegramID)) + err := c.discord.GuildMemberRoleAdd(c.config.ChannelID, discordID, c.config.MemberRoleID) + if err != nil { + c.logger.Errorw("failed to update user role", err) + return []tgbotapi.Chattable{extension.DefaultErrorMessage(chatID)} + } + + user.DiscordID, err = strconv.Atoi(discordID) + if err != nil { + c.logger.Errorw("failed to parse discord id", "error", err) + return []tgbotapi.Chattable{extension.DefaultErrorMessage(chatID)} + } - message := tgbotapi.NewMessage(chatID, "Привет, cпасибо, ты авторизован, можешь возвращаться в Discord") + message := tgbotapi.NewMessage(chatID, "Привет, ты успешно авторизован, можешь возвращаться в Discord") return []tgbotapi.Chattable{message} } diff --git a/internal/tg_bot/commands/command.go b/internal/tg_bot/commands/command.go index f9e5bf2..9921401 100644 --- a/internal/tg_bot/commands/command.go +++ b/internal/tg_bot/commands/command.go @@ -8,5 +8,5 @@ import ( type Command interface { CanHandle(command string) bool - Handle(text string, user *models.User, chatID int64) []tgbotapi.Chattable + Handle(text, arguments string, user *models.User, chatID int64) []tgbotapi.Chattable } diff --git a/internal/tg_bot/handlers/access_governance_bot/command_handler.go b/internal/tg_bot/handlers/access_governance_bot/command_handler.go index 0ce45eb..30748c9 100644 --- a/internal/tg_bot/handlers/access_governance_bot/command_handler.go +++ b/internal/tg_bot/handlers/access_governance_bot/command_handler.go @@ -145,7 +145,7 @@ func (h *accessGovernanceBotCommandHandler) tryToHandleCommand(command string, c h.logger.Errorw("failed to update user", "error", err) } - return handler.Handle(command, user, chatID) + return handler.Handle(command, "", user, chatID) } } @@ -158,7 +158,7 @@ func (h *accessGovernanceBotCommandHandler) tryToHandleSubCommand(command, subCo for _, handler := range commands { if handler.CanHandle(command) { - responseMessage := handler.Handle(subCommand, user, chatID) + responseMessage := handler.Handle(subCommand, "", user, chatID) if responseMessage == nil { h.logger.Errorw("failed to handle subcommand", "subCommand", subCommand) break @@ -190,7 +190,7 @@ func (h *accessGovernanceBotCommandHandler) tryToHandleQueryCallback(query strin h.logger.Errorw("failed to update user", "error", err) } - return handler.Handle(query, user, chatID) + return handler.Handle(query, "", user, chatID) } } diff --git a/internal/tg_bot/handlers/authorization_bot/command_handler.go b/internal/tg_bot/handlers/authorization_bot/command_handler.go index fdb8d50..636332a 100644 --- a/internal/tg_bot/handlers/authorization_bot/command_handler.go +++ b/internal/tg_bot/handlers/authorization_bot/command_handler.go @@ -63,7 +63,7 @@ func (h *authorizationBotCommandHandler) Handle(update tgbotapi.Update) []tgbota if message.IsCommand() { h.logger.Infow("received command", "command", message.Command()) - return h.tryToHandleCommand(message.Command(), h.commands, user, chatID) + return h.tryToHandleCommand(message, h.commands, user, chatID) } } @@ -71,10 +71,13 @@ func (h *authorizationBotCommandHandler) Handle(update tgbotapi.Update) []tgbota return []tgbotapi.Chattable{} } -func (h *authorizationBotCommandHandler) tryToHandleCommand(command string, commands []commands.Command, user *models.User, chatID int64) []tgbotapi.Chattable { +func (h *authorizationBotCommandHandler) tryToHandleCommand(message *tgbotapi.Message, commands []commands.Command, user *models.User, chatID int64) []tgbotapi.Chattable { + command := message.Command() + arguments := message.CommandArguments() + for _, handler := range commands { if handler.CanHandle(command) { - return handler.Handle(command, user, chatID) + return handler.Handle(command, arguments, user, chatID) } }