summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
Diffstat (limited to 'main.go')
-rw-r--r--main.go90
1 files changed, 90 insertions, 0 deletions
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..6c77033
--- /dev/null
+++ b/main.go
@@ -0,0 +1,90 @@
+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
+}