Files
tg_exporter/internal/cmd_channel_add.go
2024-09-05 15:12:53 +08:00

72 lines
1.5 KiB
Go

package internal
import (
"context"
"log"
"exporter/config"
"github.com/gotd/td/tg"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var (
channelID int64
channelAlias string
exportMedia bool
)
func ChannelAddCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Aliases: []string{"a"},
Short: "add a new channel",
PreRunE: func(cmd *cobra.Command, args []string) error {
log.Println("init client")
defer log.Println("init client done")
return InitClient(config.C)
},
RunE: func(cmd *cobra.Command, args []string) error {
return channelAddCmd(context.Background())
},
}
cmd.Flags().Int64Var(&channelID, "channel", 0, "channel id")
cmd.Flags().StringVar(&channelAlias, "alias", "", "channel alias")
cmd.Flags().BoolVar(&exportMedia, "media", false, "export media")
return cmd
}
func channelAddCmd(ctx context.Context) error {
if channelID == 0 && channelAlias == "" {
return errors.New("channel id or alias is required")
}
var channel *tg.Channel
var err error
if channelAlias != "" {
channel, err = client.ChannelInfoByAlias(ctx, channelAlias)
if err != nil {
return err
}
} else {
channel, err = client.ChannelInfoByID(ctx, channelID)
if err != nil {
return err
}
}
if channel.GetID() == 0 {
return errors.New("channel not found")
}
cfg := NewDBChannel(channel.GetID(), channel.Username, channel.Title)
cfg.ExportMedia = exportMedia
if err := cfg.GetOrCreate(ctx); err != nil {
return err
}
return client.Channel(ctx, channel, cfg, true)
}