initial commit
Marco Andronaco andronacomarco@gmail.com
Sun, 26 May 2024 15:32:23 +0200
13 files changed,
335 insertions(+),
0 deletions(-)
A
.github/workflows/publish.yaml
@@ -0,0 +1,48 @@
+# +name: Create and publish a Docker image + +# Configures this workflow to run every time a change is pushed to the branch called `main`. +on: + push: + branches: ['main'] + +# Defines two custom environment variables for the workflow. These are used for the Container registry domain, and a name for the Docker image that this workflow builds. +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +# There is a single job in this workflow. It's configured to run on the latest available version of Ubuntu. +jobs: + build-and-push-image: + runs-on: ubuntu-latest + # Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job. + permissions: + contents: read + packages: write + # + steps: + - name: Checkout repository + uses: actions/checkout@v3 + # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here. + - name: Log in to the Container registry + uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels. + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + # This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages. + # It uses the `context` parameter to define the build's context as the set of files located in the specified path. For more information, see "[Usage](https://github.com/docker/build-push-action#usage)" in the README of the `docker/build-push-action` repository. + # It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step. + - name: Build and push Docker image + uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }}
A
.gitmodules
@@ -0,0 +1,3 @@
+[submodule "telegram-bot-api"] + path = telegram-bot-api + url = https://github.com/OvyFlash/telegram-bot-api
A
Dockerfile
@@ -0,0 +1,36 @@
+# syntax=docker/dockerfile:1 + +FROM golang:alpine AS builder + +WORKDIR /build + +# Download Go modules +COPY ./telegram-bot-api ./telegram-bot-api +COPY go.mod go.su[m] ./ +RUN go mod download + +# Transfer source code + + +COPY *.go ./ + +# Build +RUN CGO_ENABLED=0 go build -trimpath -o /dist/app + +# Test +FROM build-stage AS run-test-stage +RUN go test -v ./... + +FROM alpine:latest AS build-release-stage + +RUN apk update && \ + apk add --no-cache \ + pandoc \ + tectonic + +#COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ +COPY --from=builder /dist /app + +WORKDIR /app + +ENTRYPOINT ["/app/app"]
A
LICENSE
@@ -0,0 +1,21 @@
+MIT License + +Copyright (c) 2024 Marco Andronaco + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.
A
Makefile
@@ -0,0 +1,14 @@
+# Variables +ENV_FILE=.env + +.PHONY: all clean build + +all: build + +# Build the Docker image +build: $(REQUIREMENTS) + docker-compose build + +# Utility target to run the Docker container +run: $(ENV_FILE) + docker-compose up
A
README.md
@@ -0,0 +1,25 @@
+# Albus +A Telegram Bot that converts documents to more readable formats. + +## Usage + +``` +git submodule init +git submodule update +cp .env.example .env +``` + +Put your Telegram Bot Token inside `.env`. + +### Docker +``` +make +make run +``` + +### Poetry +Ensure `pandoc` and `tectonic` are installed. + +``` +go run . +```
A
albus.go
@@ -0,0 +1,96 @@
+package main + +import ( + "os" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/joho/godotenv" +) + +const tokenEnvName = "TELEGRAM_BOT_TOKEN" + +func main() { + godotenv.Load() + + tgToken := os.Getenv(tokenEnvName) + if tgToken == "" { + println("Please set the", tokenEnvName, "environment variable.") + os.Exit(1) + } + + bot, err := tgbotapi.NewBotAPI(tgToken) + if err != nil { + println(err) + os.Exit(1) + } + + bot.Debug = true + + println("Authorized on account", bot.Self.UserName) + + u := tgbotapi.NewUpdate(0) + u.Timeout = 60 + + updates := bot.GetUpdatesChan(u) + + for update := range updates { + if update.Message == nil { // ignore any non-Message updates + continue + } + + msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") + msg.ReplyParameters.MessageID = update.Message.MessageID + + messageDocument := update.Message.Document + if messageDocument == nil { + continue + } + + msgFileNameFull := messageDocument.FileName + msgFileId := messageDocument.FileID + + msgFile, err := bot.GetFile(tgbotapi.FileConfig{FileID: msgFileId}) + if err != nil { + println("Error getting file:", err) + continue + } + + msgFileName, msgFileExtension := SplitFilename(msgFileNameFull) + uniqueFileName := msgFileId + msgFileExtension + + err = DownloadFile(uniqueFileName, msgFile.Link(bot.Token)) + if err != nil { + println("Error downloading file:", err) + continue + } + + outFileName, outExtension := ConvertFile(uniqueFileName) + os.Remove(uniqueFileName) + if outFileName == "" && outExtension == "" { + println("Error converting file:", uniqueFileName) + continue + } + outFileNameFull := JoinFilename(outFileName, outExtension) + finalFileName := JoinFilename(msgFileName, outExtension) + + file, err := os.Open(outFileNameFull) + if err != nil { + println("Error opening new file: ", err) + } + + fileReader := tgbotapi.FileReader{ + Name: finalFileName, + Reader: file, + } + + newMsg := tgbotapi.NewDocument(update.Message.Chat.ID, fileReader) + + if _, err := bot.Send(newMsg); err != nil { + println("Could not send message.") + os.Exit(1) + } + + file.Close() + os.Remove(outFileNameFull) + } +}
A
docker-compose.yaml
@@ -0,0 +1,8 @@
+services: + albus: + container_name: albus-go + image: albus-go + build: + context: . + env_file: .env + restart: unless-stopped
A
go.mod
@@ -0,0 +1,10 @@
+module github.com/BiRabittoh/albus-go + +go 1.22.3 + +require ( + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/joho/godotenv v1.5.1 +) + +replace github.com/go-telegram-bot-api/telegram-bot-api/v5 => ./telegram-bot-api/
A
go.sum
@@ -0,0 +1,4 @@
+github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
A
utils.go
@@ -0,0 +1,68 @@
+package main + +import ( + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" +) + +var conversionMap = map[string]string{ + ".docx": ".pdf", + ".odt": ".pdf", + ".epub": ".html", +} + +func SplitFilename(filename string) (name, ext string) { + ext = strings.ToLower(filepath.Ext(filename)) + name = filename[:len(filename)-len(ext)] + return name, ext +} + +func JoinFilename(name, ext string) string { + if len(ext) > 0 && ext[0] != '.' { + ext = "." + ext + } + return name + ext +} + +func DownloadFile(filePath string, url string) error { + resp, err := http.Get(url) + if err != nil { + return err + } + defer resp.Body.Close() + + out, err := os.Create(filePath) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, resp.Body) + return err +} + +func ConvertFile(inputFile string) (string, string) { + fileName, fileExtension := SplitFilename(inputFile) + + outputExtension, exists := conversionMap[fileExtension] + if !exists { + println("Error. Format not supported:", fileExtension) + return "", "" + } + + outputFile := JoinFilename(fileName, outputExtension) + println("Converting...") + cmd := exec.Command("pandoc", inputFile, "--pdf-engine=tectonic", "-o", outputFile) + + output, err := cmd.CombinedOutput() + if err != nil { + println("Error. Command execution failed:", err) + return "", "" + } + println(output) + return fileName, outputExtension +}