Files
tg_exporter/internal/client_channel.go
2024-09-02 14:50:51 +08:00

99 lines
2.5 KiB
Go

package internal
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/gotd/td/telegram/downloader"
"github.com/gotd/td/tg"
"github.com/pkg/errors"
"github.com/samber/lo"
)
func (t *TClient) Channel(ctx context.Context, channel *tg.Channel, offset int) error {
inputPeer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
messages, err := t.api.MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{
Peer: inputPeer,
Limit: 10,
OffsetID: offset,
})
if err != nil {
return errors.Wrap(err, "messages.getHistory")
}
downloader := downloader.NewDownloader()
lo.ForEach(messages.(*tg.MessagesChannelMessages).GetMessages(), func(item tg.MessageClass, index int) {
msg, ok := item.(*tg.Message)
if !ok {
fmt.Println("ID: get failed")
return
}
if !t.downloadMedia {
return
}
if mediaClass, ok := msg.GetMedia(); ok {
if photoClass, ok := mediaClass.(*tg.MessageMediaPhoto).GetPhoto(); ok {
photo := photoClass.(*tg.Photo)
thumbSize := ""
if len(photo.Sizes) > 1 {
thumbSize = photo.Sizes[len(photo.Sizes)-1].GetType()
}
location := &tg.InputPhotoFileLocation{
ID: photo.GetID(),
AccessHash: photo.GetAccessHash(),
FileReference: photo.GetFileReference(),
ThumbSize: thumbSize,
}
saveTo := lo.Must(filepath.Abs(fmt.Sprintf("./photos/%d.jpg", photo.GetID())))
storage, err := downloader.Download(t.api, location).ToPath(ctx, saveTo)
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Downloaded : ", storage)
}
}
}
})
return nil
}
type ChannelConfig struct {
ID int64 `json:"id"`
Offset int `json:"offset"`
}
func (t *TClient) SaveChannelConfig(ctx context.Context, channelID int64, offset int) (*ChannelConfig, error) {
channelConfigFile := fmt.Sprintf("outputs/%d/config.json", channelID)
// if file not exists then create it
if _, err := os.Stat(channelConfigFile); os.IsNotExist(err) {
// create config file
data, _ := json.Marshal(&ChannelConfig{ID: channelID})
if err := os.WriteFile(channelConfigFile, data, 0o644); err != nil {
return nil, errors.Wrap(err, "write channel config")
}
}
// read config file
data, err := os.ReadFile(channelConfigFile)
if err != nil {
return nil, errors.Wrap(err, "read channel config")
}
var config *ChannelConfig
if err := json.Unmarshal(data, config); err != nil {
return nil, errors.Wrap(err, "unmarshal channel config")
}
return config, nil
}