summaryrefslogblamecommitdiff
path: root/main.go
blob: 6c770339402ab80c5e7b353768e2de4bb5c63f41 (plain) (tree)

























































































                                                                                                                                                                   
package main

import (
	"log"
	"net/url"
	"os"
	"strings"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/kkdai/youtube/v2"
)

func main() {
	bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_TOKEN"))
	bot.SetAPIEndpoint("https://tg.neonxp.ru/bot%s/%s")
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message != nil { // If we got a message

			message := update.Message
			link, err := url.Parse(message.Text)
			if err != nil {
				continue
			}

			go func(message *tgbotapi.Message) {
				if link.Host == "youtube.com" && link.Query().Get("v") != "" {
					if err := download(bot, message, link.Query().Get("v")); err != nil {
						msg := tgbotapi.NewMessage(message.Chat.ID, "Ошибка: "+err.Error())
						log.Println(err)
						msg.ReplyToMessageID = message.MessageID
						bot.Send(msg)
					}
				} else if link.Host == "youtu.be" && link.Path != "" {
					pathParts := strings.SplitN(link.Path, "?", 2)
					if err := download(bot, message, pathParts[0]); err != nil {
						msg := tgbotapi.NewMessage(message.Chat.ID, "Ошибка: "+err.Error())
						log.Println(err)
						msg.ReplyToMessageID = message.MessageID
						bot.Send(msg)
					}
				}
			}(message)
		}
	}
}

func download(bot *tgbotapi.BotAPI, message *tgbotapi.Message, videoID string) error {

	client := youtube.Client{}

	video, err := client.GetVideo(videoID)
	if err != nil {
		return err
	}

	formats := video.Formats.WithAudioChannels()
	stream, _, err := client.GetStream(video, &formats[0])
	if err != nil {
		return err
	}
	defer stream.Close()

	msg := tgbotapi.NewMessage(message.Chat.ID, "Начинаю скачивать: "+video.Title+"\n<a href=\""+formats[0].URL+"\">Адрес файла</a>")
	msg.ParseMode = "html"
	msg.ReplyToMessageID = message.MessageID
	if _, err := bot.Send(msg); err != nil {
		return err
	}

	file := tgbotapi.FileReader{
		Name:   "video.mp4",
		Reader: stream,
	}
	_, err = bot.Send(tgbotapi.NewVideo(message.From.ID, file))

	return err
}