Spaces:
Paused
Paused
| package bot | |
| import ( | |
| "TelegramCloud/tgf/config" | |
| "TelegramCloud/tgf/internal/db" | |
| "context" | |
| "time" | |
| "go.uber.org/zap" | |
| "github.com/celestix/gotgproto" | |
| "github.com/celestix/gotgproto/sessionMaker" | |
| "github.com/glebarez/sqlite" | |
| ) | |
| var Bot *gotgproto.Client | |
| var InstanceMgr *InstanceManager | |
| func StartClient(log *zap.Logger) (*gotgproto.Client, error) { | |
| ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) | |
| defer cancel() | |
| resultChan := make(chan struct { | |
| client *gotgproto.Client | |
| err error | |
| }) | |
| go func(ctx context.Context) { | |
| client, err := gotgproto.NewClient( | |
| int(config.ValueOf.ApiID), | |
| config.ValueOf.ApiHash, | |
| gotgproto.ClientTypeBot(config.ValueOf.BotToken), | |
| &gotgproto.ClientOpts{ | |
| Session: sessionMaker.SqlSession( | |
| sqlite.Open("/tmp/fsb.session"), | |
| ), | |
| DisableCopyright: true, | |
| }, | |
| ) | |
| resultChan <- struct { | |
| client *gotgproto.Client | |
| err error | |
| }{client, err} | |
| }(ctx) | |
| select { | |
| case <-ctx.Done(): | |
| return nil, ctx.Err() | |
| case result := <-resultChan: | |
| if result.err != nil { | |
| return nil, result.err | |
| } | |
| log.Info("Client started", zap.String("username", result.client.Self.Username)) | |
| Bot = result.client | |
| return result.client, nil | |
| } | |
| } | |
| // InitInstanceManager initializes the bot instance manager | |
| func InitInstanceManager(userBotMgr *db.UserBotManager, log *zap.Logger) { | |
| InstanceMgr = NewInstanceManager(userBotMgr, log) | |
| log.Info("Bot instance manager initialized") | |
| } | |
| // GetBotForUser returns the appropriate bot for a user (personal or main bot) | |
| func GetBotForUser(ctx context.Context, userID int64, log *zap.Logger) *gotgproto.Client { | |
| // Try to get user's personal bot first | |
| if InstanceMgr != nil { | |
| userBot, err := InstanceMgr.GetBotForUser(ctx, userID) | |
| if err != nil { | |
| log.Warn("Failed to get user bot, falling back to main bot", | |
| zap.Int64("userID", userID), | |
| zap.Error(err)) | |
| } else { | |
| log.Debug("Using user's personal bot", zap.Int64("userID", userID)) | |
| return userBot | |
| } | |
| } | |
| // Fall back to main bot | |
| log.Debug("Using main bot", zap.Int64("userID", userID)) | |
| return Bot | |
| } |