diff options
author | Alexander Neonxp Kiryukhin <i@neonxp.ru> | 2024-08-14 18:32:51 +0300 |
---|---|---|
committer | Alexander Neonxp Kiryukhin <i@neonxp.ru> | 2024-08-14 18:32:51 +0300 |
commit | 9f4fbd85cd138820e4cf0f87b77a2c80ae770b1a (patch) | |
tree | 11d9f3a0d41eb17a98e02087760541fd46fb70d0 /main.go |
initial
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 90 |
1 files changed, 90 insertions, 0 deletions
@@ -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 +} |