all repos — albus-go @ main

albus.go (view raw)

 1package main
 2
 3import (
 4	"os"
 5
 6	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
 7	"github.com/joho/godotenv"
 8)
 9
10const tokenEnvName = "TELEGRAM_BOT_TOKEN"
11
12func main() {
13	godotenv.Load()
14
15	tgToken := os.Getenv(tokenEnvName)
16	if tgToken == "" {
17		println("Please set the", tokenEnvName, "environment variable.")
18		os.Exit(1)
19	}
20
21	bot, err := tgbotapi.NewBotAPI(tgToken)
22	if err != nil {
23		println(err)
24		os.Exit(1)
25	}
26
27	bot.Debug = true
28
29	println("Authorized on account", bot.Self.UserName)
30
31	u := tgbotapi.NewUpdate(0)
32	u.Timeout = 60
33
34	updates := bot.GetUpdatesChan(u)
35
36	for update := range updates {
37		if update.Message == nil { // ignore any non-Message updates
38			continue
39		}
40
41		msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
42		msg.ReplyParameters.MessageID = update.Message.MessageID
43
44		messageDocument := update.Message.Document
45		if messageDocument == nil {
46			continue
47		}
48
49		msgFileNameFull := messageDocument.FileName
50		msgFileId := messageDocument.FileID
51
52		msgFile, err := bot.GetFile(tgbotapi.FileConfig{FileID: msgFileId})
53		if err != nil {
54			println("Error getting file:", err)
55			continue
56		}
57
58		msgFileName, msgFileExtension := SplitFilename(msgFileNameFull)
59		uniqueFileName := msgFileId + msgFileExtension
60
61		err = DownloadFile(uniqueFileName, msgFile.Link(bot.Token))
62		if err != nil {
63			println("Error downloading file:", err)
64			continue
65		}
66
67		outFileName, outExtension := ConvertFile(uniqueFileName)
68		os.Remove(uniqueFileName)
69		if outFileName == "" && outExtension == "" {
70			println("Error converting file:", uniqueFileName)
71			continue
72		}
73		outFileNameFull := JoinFilename(outFileName, outExtension)
74		finalFileName := JoinFilename(msgFileName, outExtension)
75
76		file, err := os.Open(outFileNameFull)
77		if err != nil {
78			println("Error opening new file: ", err)
79		}
80
81		fileReader := tgbotapi.FileReader{
82			Name:   finalFileName,
83			Reader: file,
84		}
85
86		newMsg := tgbotapi.NewDocument(update.Message.Chat.ID, fileReader)
87
88		if _, err := bot.Send(newMsg); err != nil {
89			println("Could not send message.")
90			os.Exit(1)
91		}
92
93		file.Close()
94		os.Remove(outFileNameFull)
95	}
96}