Files
tgex-backend/pkg/telegram/telegram.go
Artem Tsyrulnikov b212b6c22f фиксы
2026-02-01 11:10:22 +03:00

91 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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")
}
// Получаем информацию о текущем пользователе
self, err := tg.Self(ctx)
if err != nil {
log.Warn().Err(err).Msg("Failed to get user info")
} else {
log.Info().
Int64("id", self.ID).
Str("username", "@"+self.Username).
Str("first_name", self.FirstName).
Str("last_name", self.LastName).
Str("phone", self.Phone).
Msg("Authorized as user")
}
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
}