Files
tgex-backend/tg_parser/pkg/telegram/telegram.go
Artem Tsyrulnikov 2c0ae2dfc3 парсер
2026-01-06 21:06:21 +03:00

77 lines
1.4 KiB
Go

package telegram
import (
"context"
"fmt"
"github.com/rs/zerolog/log"
"github.com/gotd/td/session"
"github.com/gotd/td/telegram"
)
type Config struct {
ApiID int `envconfig:"TELEGRAM__API_ID" required:"true"`
ApiHash string `envconfig:"TELEGRAM__API_HASH" required:"true"`
SessionFile string `envconfig:"TELEGRAM__SESSION_FILE" required:"true"`
}
type Client struct {
*telegram.Client
cancel context.CancelFunc
done chan struct{}
}
func New(cfg Config) (*Client, error) {
ctx := context.Background()
tg := telegram.NewClient(cfg.ApiID, cfg.ApiHash, telegram.Options{
SessionStorage: &session.FileStorage{Path: cfg.SessionFile},
})
runCtx, cancel := context.WithCancel(ctx)
ready := make(chan struct{})
done := make(chan struct{})
client := &Client{
Client: tg,
cancel: cancel,
done: done,
}
go func() {
err := tg.Run(runCtx, func(ctx context.Context) error {
status, err := tg.Auth().Status(ctx)
if err != nil {
close(ready)
return fmt.Errorf("telegram.Auth error: %w", err)
}
if !status.Authorized {
close(ready)
return fmt.Errorf("session not authorized")
}
close(ready)
<-ctx.Done()
return ctx.Err()
})
if err != nil {
log.Error().Err(err).Msg("telegram client stopped")
}
close(done)
}()
<-ready
return client, nil
}
func (c *Client) Close() {
c.cancel()
<-c.done
}