Files
tg_exporter/internal/client.go
2024-09-02 23:39:22 +08:00

87 lines
2.1 KiB
Go

package internal
import (
"context"
"path/filepath"
"exporter/config"
"github.com/gotd/td/telegram"
"github.com/gotd/td/telegram/auth"
"github.com/gotd/td/tg"
"github.com/pkg/errors"
"github.com/samber/lo"
"go.uber.org/zap"
)
type TClient struct {
Config *config.Config
Client *telegram.Client
}
func NewClient(logger *zap.Logger, config *config.Config) *TClient {
c := &TClient{
Config: config,
Client: telegram.NewClient(config.AppID, config.AppHash, telegram.Options{
Logger: logger,
UpdateHandler: nil,
SessionStorage: &telegram.FileSessionStorage{
Path: lo.Must(filepath.Abs(config.SessionFile)),
},
}),
}
return c
}
func (t *TClient) Login(ctx context.Context) error {
logger.Info("login phone", zap.String("phone", t.Config.Phone))
flow := auth.NewFlow(Terminal{PhoneNumber: client.Config.Phone}, auth.SendCodeOptions{})
if err := t.Client.Auth().IfNecessary(context.Background(), flow); err != nil {
return errors.Wrap(err, "auth")
}
self, err := t.Client.Self(ctx)
if err != nil {
return errors.Wrap(err, "call self")
}
logger.Info("Login",
zap.String("first_name", self.FirstName),
zap.String("last_name", self.LastName),
zap.String("username", self.Username),
zap.Int64("id", self.ID),
)
return nil
}
// ChannelInfo
func (t *TClient) ChannelInfoByAlias(ctx context.Context, channelAlias string) (*tg.Channel, error) {
p, err := t.Client.API().ContactsResolveUsername(ctx, channelAlias)
if err != nil {
return nil, errors.Wrap(err, "contacts.resolveUsername")
}
chats := p.GetChats()
if len(chats) == 0 {
return nil, errors.New("chat not found")
}
channel := chats[0].(*tg.Channel)
return channel, nil
}
func (t *TClient) ChannelInfoByID(ctx context.Context, channelID int64) (*tg.Channel, error) {
p, err := t.Client.API().ChannelsGetChannels(ctx, []tg.InputChannelClass{
&tg.InputChannel{ChannelID: channelID},
})
if err != nil {
return nil, errors.Wrap(err, "contacts.resolveUsername")
}
chats := p.GetChats()
if len(chats) == 0 {
return nil, errors.New("chat not found")
}
channel := chats[0].(*tg.Channel)
return channel, nil
}