refactor
This commit is contained in:
89
tg_bot/main.go
Normal file
89
tg_bot/main.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/NicoNex/echotron/v3"
|
||||
"github.com/TelegramExchange/pkg/logger"
|
||||
"github.com/TelegramExchange/tgex-backend/tg_bot/backend"
|
||||
"github.com/TelegramExchange/tgex-backend/tg_bot/bot"
|
||||
"github.com/TelegramExchange/tgex-backend/tg_bot/screens"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger.Init(logger.Config{
|
||||
PrettyConsole: true,
|
||||
})
|
||||
|
||||
botToken := mustEnv("TELEGRAM__TOKEN")
|
||||
loginURL := mustEnv("LOGIN_URL")
|
||||
baseURL := os.Getenv("BACKEND__BASE_URL")
|
||||
|
||||
backendClient := backend.New(backend.Config{
|
||||
BaseURL: baseURL,
|
||||
LoginURL: loginURL,
|
||||
})
|
||||
|
||||
var commandRouter = func(command string) bot.State {
|
||||
switch command {
|
||||
case "/start":
|
||||
return &screens.MainMenu{}
|
||||
case "/start login":
|
||||
return &screens.Login{}
|
||||
}
|
||||
panic("Unknown command: " + command)
|
||||
}
|
||||
|
||||
var handleGlobalCallback = func(callbackData string) bot.State {
|
||||
id, ok := strings.CutPrefix(callbackData, "pending_channel:")
|
||||
if ok {
|
||||
return &screens.SelectWorkspace{ChannelID: id, BackState: &screens.MainMenu{}}
|
||||
}
|
||||
|
||||
id, ok = strings.CutPrefix(callbackData, "workspace_invite_accept:")
|
||||
if ok {
|
||||
return &screens.AcceptWorkspaceInvite{InviteID: id}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
newBot := func(chatID int64) echotron.Bot {
|
||||
return bot.NewBot(chatID, botToken, commandRouter, backendClient, handleGlobalCallback)
|
||||
}
|
||||
|
||||
dsp := echotron.NewDispatcher(botToken, newBot)
|
||||
|
||||
log.Info().Msg("bot starting...")
|
||||
|
||||
updateOpts := echotron.UpdateOptions{
|
||||
AllowedUpdates: []echotron.UpdateType{
|
||||
echotron.MessageUpdate,
|
||||
echotron.CallbackQueryUpdate,
|
||||
echotron.MyChatMemberUpdate,
|
||||
echotron.ChatMemberUpdate,
|
||||
echotron.UpdateType("chat_join_request"),
|
||||
},
|
||||
}
|
||||
|
||||
for {
|
||||
if err := dsp.PollOptions(false, updateOpts); err != nil {
|
||||
log.Error().Err(err).Msg("dsp.Poll failed, retrying in 5 seconds...")
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func mustEnv(key string) string {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
log.Fatal().Str("env", key).Msg("missing required environment variable")
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
Reference in New Issue
Block a user