summaryrefslogtreecommitdiff
path: root/main.go
blob: 6c770339402ab80c5e7b353768e2de4bb5c63f41 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
}