From 1226bffa0ca76c8845ffd6435a46ce23e942205b Mon Sep 17 00:00:00 2001 From: haveachin Date: Fri, 26 Jan 2024 19:02:46 +0100 Subject: [PATCH 1/4] feat: add custom ppa support --- .github/workflows/ci.yml | 52 ++++ .github/workflows/lint.yml | 46 ++++ .github/workflows/release.yml | 49 ++++ .gitignore | 12 +- .golangci.yml | 328 ++++++++++++++++++++++++ .goreleaser.yml | 95 +++++++ README.md | 48 +++- build/package/Dockerfile | 12 +- build/package/Dockerfile.cuda | 12 + build/package/Dockerfile.goreleaser | 5 + cmd/reddit-bot/config.go | 46 ++++ discord.go => cmd/reddit-bot/discord.go | 29 ++- cmd/reddit-bot/main.go | 151 +++++++++++ configs/config.yml | 20 ++ configs/embed.go | 6 + configs/reddit-bot.service | 12 + deployments/docker-compose.build.yml | 5 +- deployments/docker-compose.yml | 4 +- go.mod | 7 +- go.sum | 42 +-- main.go | 84 ------ reddit/post.go | 31 +-- reddit/video.go | 33 ++- 23 files changed, 960 insertions(+), 169 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/release.yml create mode 100644 .golangci.yml create mode 100644 .goreleaser.yml create mode 100644 build/package/Dockerfile.cuda create mode 100644 build/package/Dockerfile.goreleaser create mode 100644 cmd/reddit-bot/config.go rename discord.go => cmd/reddit-bot/discord.go (88%) create mode 100644 cmd/reddit-bot/main.go create mode 100644 configs/config.yml create mode 100644 configs/embed.go create mode 100644 configs/reddit-bot.service delete mode 100644 main.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..007e7e7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,52 @@ +name: CI + +on: + push: + branches: + - master + - main + pull_request: + +permissions: + contents: read + +env: + GO_VERSION: 1.21 + +jobs: + test: + name: Test + strategy: + matrix: + os: [ ubuntu-latest, macos-latest, windows-latest ] + runs-on: ${{ matrix.os }} + steps: + - name: Install Go + uses: actions/setup-go@v3 + with: + go-version: ${{ env.GO_VERSION }} + - name: Checkout code + uses: actions/checkout@v3 + - name: Test + run: make test + + build: + name: Build + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: ${{ env.GO_VERSION }} + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v5 + with: + # either 'goreleaser' (default) or 'goreleaser-pro' + distribution: goreleaser + args: build --snapshot \ No newline at end of file diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..c5ea5b9 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,46 @@ +name: Lint + +on: + push: + branches: + - master + - main + pull_request: + +permissions: + contents: read + pull-requests: read + checks: write + +env: + GO_VERSION: 1.21 + +jobs: + golangci: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: ${{ env.GO_VERSION }} + cache: false + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + # Require: The version of golangci-lint to use. + # When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version. + # When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit. + version: v1.55.2 + + # Optional: working directory, useful for monorepos + # working-directory: somedir + + # Optional: golangci-lint command line arguments. + # + # Note: By default, the `.golangci.yml` file should be at the root of the repository. + # The location of the configuration file can be changed by using `--config=` + # args: --timeout=30m --config=/my/path/.golangci.yml --issues-exit-code=0 + + # Optional: show only new issues if it's a pull request. The default value is `false`. + only-new-issues: true \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..1d1a421 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,49 @@ +name: Release + +on: + push: + tags: + - "*" + +permissions: + contents: write + packages: write + +env: + GO_VERSION: 1.21 + +jobs: + release: + name: Build & Release + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: ${{ env.GO_VERSION }} + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Login to GitHub Container Registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v5 + with: + # either 'goreleaser' (default) or 'goreleaser-pro' + distribution: goreleaser + version: latest + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index d6a4bf9..4692977 100644 --- a/.gitignore +++ b/.gitignore @@ -14,9 +14,11 @@ # Dependency directories (remove the comment below to include it) # vendor/ -config.json -/logs -*.mp4 -/.idea +# IDEs +.idea/ .vscode/ -__debug_bin* \ No newline at end of file + +# Debug +*.mp4 +__debug_bin* +.dev/ \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..caf8fb2 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,328 @@ +# This code is licensed under the terms of the MIT license https://opensource.org/license/mit +# Copyright (c) 2021 Marat Reymers + +## Golden config for golangci-lint v1.55.2 +# +# This is the best config for golangci-lint based on my experience and opinion. +# It is very strict, but not extremely strict. +# Feel free to adapt and change it for your needs. + +run: + # Timeout for analysis, e.g. 30s, 5m. + # Default: 1m + timeout: 3m + + +# This file contains only configs which differ from defaults. +# All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml +linters-settings: + cyclop: + # The maximal code complexity to report. + # Default: 10 + max-complexity: 30 + # The maximal average package complexity. + # If it's higher than 0.0 (float) the check is enabled + # Default: 0.0 + package-average: 10.0 + + errcheck: + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions: true + + exhaustive: + # Program elements to check for exhaustiveness. + # Default: [ switch ] + check: + - switch + - map + + exhaustruct: + # List of regular expressions to exclude struct packages and names from check. + # Default: [] + exclude: + # std libs + - "^net/http.Client$" + - "^net/http.Cookie$" + - "^net/http.Request$" + - "^net/http.Response$" + - "^net/http.Server$" + - "^net/http.Transport$" + - "^net/url.URL$" + - "^os/exec.Cmd$" + - "^reflect.StructField$" + # public libs + - "^github.com/Shopify/sarama.Config$" + - "^github.com/Shopify/sarama.ProducerMessage$" + - "^github.com/mitchellh/mapstructure.DecoderConfig$" + - "^github.com/prometheus/client_golang/.+Opts$" + - "^github.com/spf13/cobra.Command$" + - "^github.com/spf13/cobra.CompletionOptions$" + - "^github.com/stretchr/testify/mock.Mock$" + - "^github.com/testcontainers/testcontainers-go.+Request$" + - "^github.com/testcontainers/testcontainers-go.FromDockerfile$" + - "^golang.org/x/tools/go/analysis.Analyzer$" + - "^google.golang.org/protobuf/.+Options$" + - "^gopkg.in/yaml.v3.Node$" + + funlen: + # Checks the number of lines in a function. + # If lower than 0, disable the check. + # Default: 60 + lines: 100 + # Checks the number of statements in a function. + # If lower than 0, disable the check. + # Default: 40 + statements: 50 + # Ignore comments when counting lines. + # Default false + ignore-comments: true + + gocognit: + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity: 20 + + gocritic: + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be find in https://go-critic.github.io/overview. + settings: + captLocal: + # Whether to restrict checker to params only. + # Default: true + paramsOnly: false + underef: + # Whether to skip (*x).method() calls where x is a pointer receiver. + # Default: true + skipRecvDeref: false + + gomnd: + # List of function patterns to exclude from analysis. + # Values always ignored: `time.Date`, + # `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`, + # `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`. + # Default: [] + ignored-functions: + - flag.Arg + - flag.Duration.* + - flag.Float.* + - flag.Int.* + - flag.Uint.* + - os.Chmod + - os.Mkdir.* + - os.OpenFile + - os.WriteFile + - prometheus.ExponentialBuckets.* + - prometheus.LinearBuckets + + gomodguard: + blocked: + # List of blocked modules. + # Default: [] + modules: + - github.com/golang/protobuf: + recommendations: + - google.golang.org/protobuf + reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules" + - github.com/satori/go.uuid: + recommendations: + - github.com/google/uuid + reason: "satori's package is not maintained" + - github.com/gofrs/uuid: + recommendations: + - github.com/google/uuid + reason: "gofrs' package is not go module" + + govet: + # Enable all analyzers. + # Default: false + enable-all: true + # Disable analyzers by name. + # Run `go tool vet help` to see all analyzers. + # Default: [] + disable: + - fieldalignment # too strict + # Settings per analyzer. + settings: + shadow: + # Whether to be strict about shadowing; can be noisy. + # Default: false + strict: true + + nakedret: + # Make an issue if func has more lines of code than this setting, and it has naked returns. + # Default: 30 + max-func-lines: 0 + + nolintlint: + # Exclude following linters from requiring an explanation. + # Default: [] + allow-no-explanation: [ funlen, gocognit, lll ] + # Enable to require an explanation of nonzero length after each nolint directive. + # Default: false + require-explanation: true + # Enable to require nolint directives to mention the specific linter being suppressed. + # Default: false + require-specific: true + + rowserrcheck: + # database/sql is always checked + # Default: [] + packages: + - github.com/jmoiron/sqlx + + tenv: + # The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures. + # Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked. + # Default: false + all: true + + +linters: + disable-all: true + enable: + ## enabled by default + - errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases + - gosimple # specializes in simplifying a code + - govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string + - ineffassign # detects when assignments to existing variables are not used + - staticcheck # is a go vet on steroids, applying a ton of static analysis checks + - typecheck # like the front-end of a Go compiler, parses and type-checks Go code + - unused # checks for unused constants, variables, functions and types + ## disabled by default + - asasalint # checks for pass []any as any in variadic func(...any) + - asciicheck # checks that your code does not contain non-ASCII identifiers + - bidichk # checks for dangerous unicode character sequences + - bodyclose # checks whether HTTP response body is closed successfully + - cyclop # checks function and package cyclomatic complexity + - dupl # tool for code clone detection + - durationcheck # checks for two durations multiplied together + - errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error + - errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13 + - execinquery # checks query string in Query function which reads your Go src files and warning it finds + - exhaustive # checks exhaustiveness of enum switch statements + - exportloopref # checks for pointers to enclosing loop variables + - forbidigo # forbids identifiers + - funlen # tool for detection of long functions + - gocheckcompilerdirectives # validates go compiler directive comments (//go:) + - gochecknoglobals # checks that no global variables exist + - gochecknoinits # checks that no init functions are present in Go code + - gochecksumtype # checks exhaustiveness on Go "sum types" + - gocognit # computes and checks the cognitive complexity of functions + - goconst # finds repeated strings that could be replaced by a constant + - gocritic # provides diagnostics that check for bugs, performance and style issues + - gocyclo # computes and checks the cyclomatic complexity of functions + - godot # checks if comments end in a period + - goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt + - gomnd # detects magic numbers + - gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod + - gomodguard # allow and block lists linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations + - goprintffuncname # checks that printf-like functions are named with f at the end + - gosec # inspects source code for security problems + - lll # reports long lines + - loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap) + - makezero # finds slice declarations with non-zero initial length + - mirror # reports wrong mirror patterns of bytes/strings usage + - musttag # enforces field tags in (un)marshaled structs + - nakedret # finds naked returns in functions greater than a specified function length + - nestif # reports deeply nested if statements + - nilerr # finds the code that returns nil even if it checks that the error is not nil + - nilnil # checks that there is no simultaneous return of nil error and an invalid value + - noctx # finds sending http request without context.Context + - nolintlint # reports ill-formed or insufficient nolint directives + - nonamedreturns # reports all named returns + - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL + - perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative + - predeclared # finds code that shadows one of Go's predeclared identifiers + - promlinter # checks Prometheus metrics naming via promlint + - protogetter # reports direct reads from proto message fields when getters should be used + - reassign # checks that package variables are not reassigned + - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint + - rowserrcheck # checks whether Err of rows is checked successfully + - sloglint # ensure consistent code style when using log/slog + - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed + - stylecheck # is a replacement for golint + - tenv # detects using os.Setenv instead of t.Setenv since Go1.17 + - testableexamples # checks if examples are testable (have an expected output) + - testifylint # checks usage of github.com/stretchr/testify + - testpackage # makes you use a separate _test package + - tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes + - unconvert # removes unnecessary type conversions + - unparam # reports unused function parameters + - usestdlibvars # detects the possibility to use variables/constants from the Go standard library + - wastedassign # finds wasted assignment statements + - whitespace # detects leading and trailing whitespace + + ## you may want to enable + #- decorder # checks declaration order and count of types, constants, variables and functions + #- exhaustruct # [highly recommend to enable] checks if all structure fields are initialized + #- gci # controls golang package import order and makes it always deterministic + #- ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega + #- godox # detects FIXME, TODO and other comment keywords + #- goheader # checks is file header matches to pattern + #- inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters + #- interfacebloat # checks the number of methods inside an interface + #- ireturn # accept interfaces, return concrete types + #- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated + #- tagalign # checks that struct tags are well aligned + #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope + #- wrapcheck # checks that errors returned from external packages are wrapped + #- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event + + ## disabled + #- containedctx # detects struct contained context.Context field + #- contextcheck # [too many false positives] checks the function whether use a non-inherited context + #- depguard # [replaced by gomodguard] checks if package imports are in a list of acceptable packages + #- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) + #- dupword # [useless without config] checks for duplicate words in the source code + #- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted + #- forcetypeassert # [replaced by errcheck] finds forced type assertions + #- goerr113 # [too strict] checks the errors handling expressions + #- gofmt # [replaced by goimports] checks whether code was gofmt-ed + #- gofumpt # [replaced by goimports, gofumports is not available yet] checks whether code was gofumpt-ed + #- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase + #- grouper # analyzes expression groups + #- importas # enforces consistent import aliases + #- maintidx # measures the maintainability index of each function + #- misspell # [useless] finds commonly misspelled English words in comments + #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity + #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test + #- tagliatelle # checks the struct tags + #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers + #- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines + + ## deprecated + #- deadcode # [deprecated, replaced by unused] finds unused code + #- exhaustivestruct # [deprecated, replaced by exhaustruct] checks if all struct's fields are initialized + #- golint # [deprecated, replaced by revive] golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes + #- ifshort # [deprecated] checks that your code uses short syntax for if-statements whenever possible + #- interfacer # [deprecated] suggests narrower interface types + #- maligned # [deprecated, replaced by govet fieldalignment] detects Go structs that would take less memory if their fields were sorted + #- nosnakecase # [deprecated, replaced by revive var-naming] detects snake case of variable naming and function name + #- scopelint # [deprecated, replaced by exportloopref] checks for unpinned variables in go programs + #- structcheck # [deprecated, replaced by unused] finds unused struct fields + #- varcheck # [deprecated, replaced by unused] finds unused global variables and constants + + +issues: + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 50 + + exclude-rules: + - source: "(noinspection|TODO)" + linters: [ godot ] + - source: "//noinspection" + linters: [ gocritic ] + - path: "_test\\.go" + linters: + - bodyclose + - dupl + - funlen + - goconst + - gosec + - noctx + - wrapcheck \ No newline at end of file diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..677d496 --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,95 @@ +# Make sure to check the documentation at https://goreleaser.com + +version: 1 + +env: + - REPO_URL=https://github.com/haveachin/reddit-bot + - DOCKER_IMAGE_NAME=haveachin/reddit-bot + +before: + hooks: + - go mod tidy + +builds: + - main: ./cmd/reddit-bot + env: + - CGO_ENABLED=0 + binary: reddit-bot + goos: + - linux + - windows + - darwin + +archives: + - format: tar.gz + # this name template makes the OS and Arch compatible with the results of `uname`. + name_template: >- + {{ .ProjectName }}_ + {{- title .Os }}_ + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i386 + {{- else }}{{ .Arch }}{{ end }} + {{- if .Arm }}v{{ .Arm }}{{ end }} + # use zip for windows archives + format_overrides: + - goos: windows + format: zip + +dockers: + - image_templates: + - "docker.io/{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-amd64" + - "docker.io/{{ .Env.DOCKER_IMAGE_NAME }}:latest-amd64" + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:latest-amd64" + use: buildx + dockerfile: Dockerfile.goreleaser + build_flag_templates: + - "--pull" + - "--platform=linux/amd64" + - "--label=org.opencontainers.image.created={{ .Date }}" + - "--label=org.opencontainers.image.title={{ .ProjectName }}" + - "--label=org.opencontainers.image.revision={{ .FullCommit }}" + - "--label=org.opencontainers.image.version={{ .Version }}" + - "--label=org.opencontainers.image.source={{ .Env.REPO_URL }}" + - image_templates: + - "docker.io/{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-arm64v8" + - "docker.io/{{ .Env.DOCKER_IMAGE_NAME }}:latest-arm64v8" + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-arm64v8" + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:latest-arm64v8" + use: buildx + goarch: arm64 + dockerfile: Dockerfile.goreleaser + build_flag_templates: + - "--pull" + - "--platform=linux/arm64/v8" + - "--label=org.opencontainers.image.created={{ .Date }}" + - "--label=org.opencontainers.image.title={{ .ProjectName }}" + - "--label=org.opencontainers.image.revision={{ .FullCommit }}" + - "--label=org.opencontainers.image.version={{ .Version }}" + - "--label=org.opencontainers.image.source={{ .Env.REPO_URL }}" + +docker_manifests: + - name_template: "{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}" + image_templates: + - "{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-amd64" + - "{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-arm64v8" + - name_template: "{{ .Env.DOCKER_IMAGE_NAME }}:latest" + image_templates: + - "{{ .Env.DOCKER_IMAGE_NAME }}:latest-amd64" + - "{{ .Env.DOCKER_IMAGE_NAME }}:latest-arm64v8" + - name_template: "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}" + image_templates: + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:{{ .Version }}-arm64v8" + - name_template: "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:latest" + image_templates: + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:latest-amd64" + - "ghcr.io/{{ .Env.DOCKER_IMAGE_NAME }}:latest-arm64v8" + +changelog: + sort: asc + filters: + exclude: + - "^docs:" + - "^test:" + - "^chore:" diff --git a/README.md b/README.md index ffce71c..847e32e 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,50 @@ A discord bot that replaces image/gif, text, and video posts with a rich preview ## Build -Requires Go 1.15+ +Requires Go 1.21+ -`make all` or `CGO_ENABLED=0 go build -ldflags "-s -w" ./cmd/reddit-bot` \ No newline at end of file +`make all` or `CGO_ENABLED=0 go build -ldflags "-s -w" ./cmd/reddit-bot` + +## Configuration + +See the [default configuration file](configs/config.yml) for more information. + +### Post Processing for Videos + +The Reddit Bot uses yt-dlp for downloading and processing videos. This allows you to customize the post processing args for your hardware. + +#### Intel Hardware Accelleration with VAAPI (i965) + +```yml +postProcessingArgs: + - >- + Merger+ffmpeg_o: + -vaapi_device /dev/dri/renderD128 + -vcodec h264_vaapi + -vf 'format=nv12,hwupload,scale_vaapi=iw/2:ih/2' + -qp 28 + -fpsmax 24 + -c:a libopus + -b:a 64k +``` +#### Nvidia Hardware Accelleration with CUDA + +```yml +postProcessingArgs: + - >- + Merger+ffmpeg_i1: + -hwaccel cuda + -hwaccel_output_format cuda + - >- + Merger+ffmpeg_o: + -vf 'hwupload,scale_cuda=iw/2:ih/2' + -c:v h264_nvenc + -rc constqp + -qp 28 + -fpsmax 24 + -c:a libopus + -b:a 64k +``` +yt-dlp -o out.mp4 -v --ppa "ffmpeg_i:-hwaccel cuda -hwaccel_output_format cuda -vf 'hwupload,scale_cuda=iw/2:ih/2' -c:v h264_nvenc -rc constqp -qp 28 -fpsmax 24 -c:a libopus -b:a 64k" https://www.reddit.com/1abbkcx + +Hey, I'm trying t \ No newline at end of file diff --git a/build/package/Dockerfile b/build/package/Dockerfile index c212e57..b6bc245 100644 --- a/build/package/Dockerfile +++ b/build/package/Dockerfile @@ -3,13 +3,11 @@ LABEL stage=intermediate COPY . /reddit-bot WORKDIR /reddit-bot ENV GO111MODULE=on -RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /main . +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o reddit-bot . FROM alpine:latest -LABEL maintainer="haveachin " -LABEL org.opencontainers.image.source https://github.com/haveachin/reddit-bot RUN apk --no-cache add ca-certificates ffmpeg yt-dlp -WORKDIR /reddit-bot -COPY --from=builder /main ./ -RUN chmod +x ./main -ENTRYPOINT [ "./main" ] \ No newline at end of file +COPY --from=builder /reddit-bot/reddit-bot /usr/bin/reddit-bot +RUN chmod +x /usr/bin/reddit-bot +RUN mkdir /etc/reddit-bot +ENTRYPOINT [ "/usr/bin/reddit-bot", "-c", "/etc/reddit-bot/config.yml" ] \ No newline at end of file diff --git a/build/package/Dockerfile.cuda b/build/package/Dockerfile.cuda new file mode 100644 index 0000000..9bdb293 --- /dev/null +++ b/build/package/Dockerfile.cuda @@ -0,0 +1,12 @@ +FROM golang:latest AS builder +LABEL stage=intermediate +COPY . /reddit-bot +WORKDIR /reddit-bot +ENV GO111MODULE=on +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o reddit-bot . + +FROM nvidia/cuda:10.2-base +COPY --from=builder /reddit-bot/reddit-bot /usr/bin/reddit-bot +RUN chmod +x /usr/bin/reddit-bot +RUN mkdir /etc/reddit-bot +ENTRYPOINT [ "/usr/bin/reddit-bot", "-c", "/etc/reddit-bot/config.yml" ] \ No newline at end of file diff --git a/build/package/Dockerfile.goreleaser b/build/package/Dockerfile.goreleaser new file mode 100644 index 0000000..89e3b43 --- /dev/null +++ b/build/package/Dockerfile.goreleaser @@ -0,0 +1,5 @@ +FROM alpine:latest +RUN apk --no-cache add ca-certificates ffmpeg yt-dlp +COPY reddit-bot /usr/bin/reddit-bot +RUN mkdir /etc/reddit-bot +ENTRYPOINT [ "/usr/bin/reddit-bot", "-c", "/etc/reddit-bot/config.yml" ] \ No newline at end of file diff --git a/cmd/reddit-bot/config.go b/cmd/reddit-bot/config.go new file mode 100644 index 0000000..84420d3 --- /dev/null +++ b/cmd/reddit-bot/config.go @@ -0,0 +1,46 @@ +package main + +import ( + "errors" + "os" + + "github.com/haveachin/reddit-bot/configs" + "gopkg.in/yaml.v3" +) + +type config struct { + DiscordToken string `yaml:"discordToken"` + PostProcessingArgs []string `yaml:"postProcessingArgs"` +} + +func createConfigIfNotExist() error { + info, err := os.Stat(configPath) + if errors.Is(err, os.ErrNotExist) { + return createDefaultConfigFile() + } + + if info.IsDir() { + return errors.New("is a directory") + } + + return nil +} + +func createDefaultConfigFile() error { + bb := configs.DefaultConfig + return os.WriteFile(configPath, bb, 0664) +} + +func readAndParseConfig() (config, error) { + f, err := os.Open(configPath) + if err != nil { + return config{}, err + } + defer f.Close() + + var cfg config + if err := yaml.NewDecoder(f).Decode(&cfg); err != nil { + return cfg, err + } + return cfg, err +} diff --git a/discord.go b/cmd/reddit-bot/discord.go similarity index 88% rename from discord.go rename to cmd/reddit-bot/discord.go index 8e75efb..8453e5b 100644 --- a/discord.go +++ b/cmd/reddit-bot/discord.go @@ -28,11 +28,12 @@ const ( ) type redditBot struct { - redditPostPattern regex.Pattern - embedder embed.Embedder + redditPostPattern regex.Pattern + embedder embed.Embedder + postProcessingArgs []string } -func newRedditBot() redditBot { +func newRedditBot(ppas []string) redditBot { return redditBot{ redditPostPattern: regex.MustCompile( `(?s)(?P<%s>.*)https:\/\/(?:www.|new.)?reddit.com\/r\/(?P<%s>.+)\/(?P<%s>comments|s)\/(?P<%s>[^\s\n\/]+)\/?[^\s\n]*\s?(?P<%s>.*)`, @@ -42,7 +43,8 @@ func newRedditBot() redditBot { captureNamePostID, captureNameSuffixMsg, ), - embedder: embed.NewEmbedder(), + embedder: embed.NewEmbedder(), + postProcessingArgs: ppas, } } @@ -133,9 +135,12 @@ func (rb redditBot) onRedditLinkMessage(s *discord.Session, m *discord.MessageCr if post.IsVideo { s.MessageReactionAdd(m.ChannelID, m.ID, emojiIDWorkingOnIt) logger.Info().Msg("Processing post video") + post.PostProcessingArgs = rb.postProcessingArgs file, err := post.DownloadVideo() if err != nil && file == nil { - logger.Error().Err(err).Msg("ffmpeg error") + logger.Error(). + Err(err). + Msg("ffmpeg error") _, _ = s.ChannelMessageSendReply(m.ChannelID, "Oh, no! Something went wrong while processing your video", m.Reference()) _ = s.MessageReactionAdd(m.ChannelID, m.ID, emojiIDErrorFFMPEG) return @@ -153,14 +158,18 @@ func (rb redditBot) onRedditLinkMessage(s *discord.Session, m *discord.MessageCr } else if post.IsImage { logger.Info().Msg("Embedding image url") msg.Embed.Image = &discord.MessageEmbedImage{ - URL: post.MediaURL, + URL: post.URL, } } else if post.IsEmbed { url, err := rb.embedder.Embed(&post) if err == embed.ErrorNotImplemented { - logger.Warn().Err(err).Msg("embedded website (source) is not yet implemented") + logger.Warn(). + Err(err). + Msg("embedded website (source) is not yet implemented") } else if err != nil { - logger.Error().Err(err).Msg("something went wrong while analyzing embedded content") + logger.Error(). + Err(err). + Msg("something went wrong while analyzing embedded content") } _, _ = s.ChannelMessageSend(m.ChannelID, url) logger.Info().Msg("Sending embedded YouTube video") @@ -168,7 +177,9 @@ func (rb redditBot) onRedditLinkMessage(s *discord.Session, m *discord.MessageCr _, err = s.ChannelMessageSendComplex(m.ChannelID, msg) if err != nil { - logger.Error().Err(err).Msg("Could not send embed") + logger.Error(). + Err(err). + Msg("Could not send embed") _, _ = s.ChannelMessageSendReply(m.ChannelID, "The video is too big", m.Reference()) _ = s.MessageReactionAdd(m.ChannelID, m.ID, emojiIDTooBig) return diff --git a/cmd/reddit-bot/main.go b/cmd/reddit-bot/main.go new file mode 100644 index 0000000..ed5be27 --- /dev/null +++ b/cmd/reddit-bot/main.go @@ -0,0 +1,151 @@ +package main + +import ( + "fmt" + "os" + "os/signal" + "syscall" + "time" + + discord "github.com/bwmarrin/discordgo" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/spf13/pflag" +) + +const ( + envVarPrefix = "REDDITBOT_" +) + +var ( + discordToken string + configPath = "config.yml" + logLevel = "info" + + cfg config +) + +func envVarStringVar(p *string, name string) { + key := envVarPrefix + "_" + name + v := os.Getenv(key) + if v == "" { + return + } + *p = v +} + +func initEnvVars() { + envVarStringVar(&discordToken, "DISCORD_TOKEN") + envVarStringVar(&configPath, "CONFIG") + envVarStringVar(&logLevel, "LOG_LEVEL") +} + +func initFlags() { + pflag.StringVarP(&configPath, "config", "c", configPath, "path to the config file") + pflag.StringVarP(&logLevel, "log-level", "l", logLevel, "log level [debug, info, warn, error]") + pflag.Parse() +} + +func initConfig() { + if err := createConfigIfNotExist(); err != nil { + log.Error(). + Err(err). + Msg("Failed to create config if not exist") + return + } + + var err error + cfg, err = readAndParseConfig() + if err != nil { + log.Error(). + Err(err). + Msg("Failed to read and parse config") + return + } + + if cfg.DiscordToken != "" { + discordToken = cfg.DiscordToken + } +} + +func initLogger() { + log.Logger = log.Output(zerolog.ConsoleWriter{ + Out: os.Stdout, + TimeFormat: time.RFC3339, + }) + + var level zerolog.Level + switch logLevel { + case "debug": + level = zerolog.DebugLevel + case "info": + level = zerolog.InfoLevel + case "warn": + level = zerolog.WarnLevel + case "error": + level = zerolog.ErrorLevel + default: + log.Warn(). + Str("logLevel", logLevel). + Msg("invalid log level; defaulting to info") + } + + zerolog.SetGlobalLevel(level) +} + +func main() { + initLogger() + initEnvVars() + initFlags() + initConfig() + + if err := run(); err != nil { + log.Error(). + Err(err). + Msg("Failed to run") + } +} + +func run() error { + tempDir, err := os.MkdirTemp(os.TempDir(), "reddit-bot") + if err != nil { + return err + } + defer os.RemoveAll(tempDir) + + if err := os.Chdir(tempDir); err != nil { + return err + } + + log.Info().Msg("Connecting to Discord") + discordSession, err := discord.New("Bot " + discordToken) + if err != nil { + return fmt.Errorf("create session: %w", err) + } + defer discordSession.Close() + + rb := newRedditBot(cfg.PostProcessingArgs) + + rmReddidLinkMsg := discordSession.AddHandler(rb.onRedditLinkMessage) + defer rmReddidLinkMsg() + + if err := discordSession.Open(); err != nil { + return fmt.Errorf("connect to discord: %w", err) + } + + status := fmt.Sprintf("Reddit for %d Servers", len(discordSession.State.Guilds)) + if err := discordSession.UpdateWatchStatus(0, status); err != nil { + log.Warn(). + Err(err). + Msg("Failed to update status") + } + + log.Info().Msg("Bot is online") + + // Wait for exit signal form OS + sc := make(chan os.Signal, 1) + signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) + <-sc + + return nil +} diff --git a/configs/config.yml b/configs/config.yml new file mode 100644 index 0000000..6ea263f --- /dev/null +++ b/configs/config.yml @@ -0,0 +1,20 @@ +# Go to https://discord.com/developers/applications +# Click or create your applicaiton. Then go to the "Bot" tab and click "Reset Token" +# Insert this token here. +# +discordToken: "" + +# This are the ffmpeg args that are used as post processing args for yt-dlp. +# By default videos are transcoded to H.264 24 FPS with Opus 64kbps audio. +# The video is also downscaled to half the resolution and lossy compressed. +# +postProcessingArgs: + - >- + Merger+ffmpeg_o: + -vf 'format=nv12,scale=iw/2:ih/2' + -c:v libx264 + -crf 28 + -fpsmax 24 + -c:a libopus + -b:a 64k + -preset faster diff --git a/configs/embed.go b/configs/embed.go new file mode 100644 index 0000000..93eb458 --- /dev/null +++ b/configs/embed.go @@ -0,0 +1,6 @@ +package configs + +import _ "embed" + +//go:embed config.yml +var DefaultConfig []byte diff --git a/configs/reddit-bot.service b/configs/reddit-bot.service new file mode 100644 index 0000000..b80f508 --- /dev/null +++ b/configs/reddit-bot.service @@ -0,0 +1,12 @@ +[Unit] +Description=A Discord Bot that replaces links with rich previews. +After=network.target + +[Service] +ExecStart=/usr/bin/reddit-bot -c /etc/reddit-bot/config.yml +Type=simple +Restart=always + +[Install] +WantedBy=default.target +RequiredBy=network.target \ No newline at end of file diff --git a/deployments/docker-compose.build.yml b/deployments/docker-compose.build.yml index e34b9b5..f1922e4 100644 --- a/deployments/docker-compose.build.yml +++ b/deployments/docker-compose.build.yml @@ -9,6 +9,7 @@ services: container_name: reddit-bot restart: always volumes: - - "./data/logs:/reddit-bot/logs" + - ./data/reddit-bot/etc:/etc/reddit-bot environment: - - REDDITBOT_DISCORD_TOKEN=${DISCORD_TOKEN} \ No newline at end of file + - REDDITBOT_DISCORD_TOKEN=${DISCORD_TOKEN} + - REDDITBOT_LOG_LEVEL=info \ No newline at end of file diff --git a/deployments/docker-compose.yml b/deployments/docker-compose.yml index 3910c1c..3518d44 100644 --- a/deployments/docker-compose.yml +++ b/deployments/docker-compose.yml @@ -4,8 +4,8 @@ services: reddit-bot: image: reddit-bot:${IMAGE_TAG} container_name: reddit-bot - restart: unless-stopped + restart: always volumes: - - "./data/logs:/reddit-bot/logs" + - ./data/reddit-bot/etc:/etc/reddit-bot environment: - REDDITBOT_DISCORD_TOKEN=${DISCORD_TOKEN} diff --git a/go.mod b/go.mod index fc44c36..194d936 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,19 @@ module github.com/haveachin/reddit-bot -go 1.15 +go 1.21 require ( github.com/bwmarrin/discordgo v0.27.1 github.com/rs/zerolog v1.31.0 + github.com/spf13/pflag v1.0.5 + gopkg.in/yaml.v3 v3.0.1 ) require ( github.com/gorilla/websocket v1.5.1 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + golang.org/x/crypto v0.18.0 // indirect golang.org/x/net v0.20.0 // indirect + golang.org/x/sys v0.16.0 // indirect ) diff --git a/go.sum b/go.sum index f7bc4cd..544c850 100644 --- a/go.sum +++ b/go.sum @@ -15,54 +15,24 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A= github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= -golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go deleted file mode 100644 index 5048dc7..0000000 --- a/main.go +++ /dev/null @@ -1,84 +0,0 @@ -package main - -import ( - "fmt" - "os" - "os/signal" - "syscall" - - discord "github.com/bwmarrin/discordgo" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -const ( - envVarPrefix = "REDDITBOT_" -) - -var ( - discordToken string -) - -func envVarStringVar(p *string, name, value string) { - key := envVarPrefix + name - if v := os.Getenv(key); v != "" { - *p = v - } else { - *p = value - } -} - -func initEnvVars() { - envVarStringVar(&discordToken, "DISCORD_TOKEN", discordToken) -} - -func initLogger() { - log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) - zerolog.SetGlobalLevel(zerolog.DebugLevel) -} - -func main() { - initEnvVars() - initLogger() - - if err := run(); err != nil { - log.Error(). - Err(err). - Msg("Failed to run") - } -} - -func run() error { - log.Info().Msg("Connecting to Discord") - discordSession, err := discord.New("Bot " + discordToken) - if err != nil { - return fmt.Errorf("create session: %w", err) - } - defer discordSession.Close() - - rb := newRedditBot() - - rmReddidLinkMsg := discordSession.AddHandler(rb.onRedditLinkMessage) - defer rmReddidLinkMsg() - - if err := discordSession.Open(); err != nil { - return fmt.Errorf("connect to discord: %w", err) - } - - status := fmt.Sprintf("Reddit for %d Servers", len(discordSession.State.Guilds)) - if err := discordSession.UpdateWatchStatus(0, status); err != nil { - log.Warn(). - Err(err). - Msg("Failed to update status") - } - - log.Info(). - Msg("Bot is online") - - // Wait for exit signal form OS - sc := make(chan os.Signal, 1) - signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) - <-sc - - return nil -} diff --git a/reddit/post.go b/reddit/post.go index 4477fdf..ed5370e 100644 --- a/reddit/post.go +++ b/reddit/post.go @@ -19,21 +19,22 @@ const ( // Post is a very simplified variation of a JSON response given from the reddit api type Post struct { - ID string - Title string - Text string - Subreddit string - Author string - Permalink string - MediaURL string - IsImage bool - IsVideo bool - IsEmbed bool - WasRemoved bool - Embed Embed + ID string + Title string + Text string + Subreddit string + Author string + Permalink string + URL string + IsImage bool + IsVideo bool + IsEmbed bool + WasRemoved bool + Embed Embed + PostProcessingArgs []string } -func (p Post) URL() string { +func (p Post) ShortURL() string { return "https://www.reddit.com/" + p.ID } @@ -132,7 +133,7 @@ func PostByID(postID string) (Post, error) { isEmbed := data.PostHint == string(PostTypeVideoEmbed) // TODO: change this isImage := data.PostHint == string(PostTypeImage) isImage = isImage || (!isEmbed && !isVideo && data.URL != "") - wasRemoved := data.RemovedByCategory != "" + wasRemoved := data.RemovedByCategory != "" && data.URL == "" return Post{ ID: postID, Title: data.Title, @@ -140,7 +141,7 @@ func PostByID(postID string) (Post, error) { Subreddit: data.Subreddit, Author: data.Author, Permalink: data.Permalink, - MediaURL: data.URL, + URL: data.URL, IsImage: isImage, IsVideo: isVideo, IsEmbed: isEmbed, diff --git a/reddit/video.go b/reddit/video.go index 73ce7d3..3d573dd 100644 --- a/reddit/video.go +++ b/reddit/video.go @@ -3,11 +3,13 @@ package reddit import ( "os" "os/exec" + + "github.com/rs/zerolog/log" ) func (p Post) DownloadVideo() (*os.File, error) { path := p.ID + ".mp4" - if err := downloadVideo(path, p.URL()); err != nil { + if err := p.downloadAndProcessVideo(path, p.ShortURL()); err != nil { return nil, err } @@ -19,12 +21,31 @@ func (p Post) DownloadVideo() (*os.File, error) { return file, nil } -func downloadVideo(filepath string, url string) error { - cmd := exec.Command("yt-dlp", +func (p Post) downloadAndProcessVideo(filepath string, url string) error { + args := []string{ "--no-continue", - "--postprocessor-args", "-c:v libx264 -c:a aac -crf 32 -preset faster", "-o", filepath, - url, - ) + } + + if len(p.PostProcessingArgs) != 0 { + for _, ppas := range p.PostProcessingArgs { + args = append(args, "--postprocessor-args", ppas) + } + } + + cmd := exec.Command("yt-dlp") + + if log.Debug().Enabled() { + cmd.Stdout = log.Logger + cmd.Stderr = log.Logger + args = append(args, "-v") + } + + cmd.Args = append(args, url) + + log.Debug(). + Str("cmd", cmd.String()). + Msg("yt-dlp cmd") + return cmd.Run() } From 096790ed9bc432a83f28a7a8487c0d6d2e42e4fc Mon Sep 17 00:00:00 2001 From: haveachin Date: Fri, 26 Jan 2024 19:48:51 +0100 Subject: [PATCH 2/4] fix: env var name --- .golangci.yml | 6 ++++-- build/package/Dockerfile.cuda | 12 ------------ cmd/reddit-bot/config.go | 2 +- cmd/reddit-bot/main.go | 2 +- deployments/docker-compose.yml | 1 + reddit/video.go | 3 ++- 6 files changed, 9 insertions(+), 17 deletions(-) delete mode 100644 build/package/Dockerfile.cuda diff --git a/.golangci.yml b/.golangci.yml index caf8fb2..216dda0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -207,7 +207,6 @@ linters: - forbidigo # forbids identifiers - funlen # tool for detection of long functions - gocheckcompilerdirectives # validates go compiler directive comments (//go:) - - gochecknoglobals # checks that no global variables exist - gochecknoinits # checks that no init functions are present in Go code - gochecksumtype # checks exhaustiveness on Go "sum types" - gocognit # computes and checks the cognitive complexity of functions @@ -270,6 +269,7 @@ linters: #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope #- wrapcheck # checks that errors returned from external packages are wrapped #- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event + #- gochecknoglobals # checks that no global variables exist ## disabled #- containedctx # detects struct contained context.Context field @@ -325,4 +325,6 @@ issues: - goconst - gosec - noctx - - wrapcheck \ No newline at end of file + - wrapcheck + - text: 'shadow: declaration of "(err|ctx)" shadows declaration at' + linters: [ govet ] \ No newline at end of file diff --git a/build/package/Dockerfile.cuda b/build/package/Dockerfile.cuda deleted file mode 100644 index 9bdb293..0000000 --- a/build/package/Dockerfile.cuda +++ /dev/null @@ -1,12 +0,0 @@ -FROM golang:latest AS builder -LABEL stage=intermediate -COPY . /reddit-bot -WORKDIR /reddit-bot -ENV GO111MODULE=on -RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o reddit-bot . - -FROM nvidia/cuda:10.2-base -COPY --from=builder /reddit-bot/reddit-bot /usr/bin/reddit-bot -RUN chmod +x /usr/bin/reddit-bot -RUN mkdir /etc/reddit-bot -ENTRYPOINT [ "/usr/bin/reddit-bot", "-c", "/etc/reddit-bot/config.yml" ] \ No newline at end of file diff --git a/cmd/reddit-bot/config.go b/cmd/reddit-bot/config.go index 84420d3..4babad4 100644 --- a/cmd/reddit-bot/config.go +++ b/cmd/reddit-bot/config.go @@ -28,7 +28,7 @@ func createConfigIfNotExist() error { func createDefaultConfigFile() error { bb := configs.DefaultConfig - return os.WriteFile(configPath, bb, 0664) + return os.WriteFile(configPath, bb, 0600) } func readAndParseConfig() (config, error) { diff --git a/cmd/reddit-bot/main.go b/cmd/reddit-bot/main.go index ed5be27..77b2dc8 100644 --- a/cmd/reddit-bot/main.go +++ b/cmd/reddit-bot/main.go @@ -14,7 +14,7 @@ import ( ) const ( - envVarPrefix = "REDDITBOT_" + envVarPrefix = "REDDITBOT" ) var ( diff --git a/deployments/docker-compose.yml b/deployments/docker-compose.yml index 3518d44..62d9622 100644 --- a/deployments/docker-compose.yml +++ b/deployments/docker-compose.yml @@ -9,3 +9,4 @@ services: - ./data/reddit-bot/etc:/etc/reddit-bot environment: - REDDITBOT_DISCORD_TOKEN=${DISCORD_TOKEN} + - REDDITBOT_LOG_LEVEL=info diff --git a/reddit/video.go b/reddit/video.go index 3d573dd..289023b 100644 --- a/reddit/video.go +++ b/reddit/video.go @@ -41,7 +41,8 @@ func (p Post) downloadAndProcessVideo(filepath string, url string) error { args = append(args, "-v") } - cmd.Args = append(args, url) + args = append(args, url) + cmd.Args = args log.Debug(). Str("cmd", cmd.String()). From a4a31f2213e1bb38d0134ceb4d7ef8644539c3ec Mon Sep 17 00:00:00 2001 From: haveachin Date: Fri, 26 Jan 2024 20:36:20 +0100 Subject: [PATCH 3/4] fix: Dockerfile --- build/package/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/package/Dockerfile b/build/package/Dockerfile index b6bc245..ec7fe78 100644 --- a/build/package/Dockerfile +++ b/build/package/Dockerfile @@ -3,7 +3,7 @@ LABEL stage=intermediate COPY . /reddit-bot WORKDIR /reddit-bot ENV GO111MODULE=on -RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o reddit-bot . +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o reddit-bot ./cmd/reddit-bot FROM alpine:latest RUN apk --no-cache add ca-certificates ffmpeg yt-dlp From a6730da188481c2b5d63dd43ba08649723c21cb5 Mon Sep 17 00:00:00 2001 From: haveachin Date: Fri, 26 Jan 2024 23:24:17 +0100 Subject: [PATCH 4/4] fix: intel gpu support --- Makefile | 4 +++- README.md | 21 ++++++++++++++++++--- build/package/Dockerfile | 4 ++-- cmd/reddit-bot/main.go | 9 ++++++--- 4 files changed, 29 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index e7a8bc5..5f07e03 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,5 @@ +.PHONY: build + test: go test -race -timeout 10s ./... @@ -7,4 +9,4 @@ build: all: test build run: build - ./out/reddit-bot -w .dev/reddit-bot + ./out/reddit-bot -c .dev/reddit-bot/config.yml diff --git a/README.md b/README.md index 847e32e..e890630 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,23 @@ postProcessingArgs: -c:a libopus -b:a 64k ``` + +When using Docker Compose you need to add this: + +```docker-compose +version: '3' + +services: + reddit-bot: + ... + group_add: + # Change this to match your "render" host group id. + # Use: getent group render | cut -d: -f3 + - "989" + devices: + - /dev/dri/renderD128:/dev/dri/renderD128 +``` + #### Nvidia Hardware Accelleration with CUDA ```yml @@ -59,6 +76,4 @@ postProcessingArgs: -c:a libopus -b:a 64k ``` -yt-dlp -o out.mp4 -v --ppa "ffmpeg_i:-hwaccel cuda -hwaccel_output_format cuda -vf 'hwupload,scale_cuda=iw/2:ih/2' -c:v h264_nvenc -rc constqp -qp 28 -fpsmax 24 -c:a libopus -b:a 64k" https://www.reddit.com/1abbkcx - -Hey, I'm trying t \ No newline at end of file +Docker setup not done yet. Contributions are welcome. diff --git a/build/package/Dockerfile b/build/package/Dockerfile index ec7fe78..d5e91b4 100644 --- a/build/package/Dockerfile +++ b/build/package/Dockerfile @@ -6,8 +6,8 @@ ENV GO111MODULE=on RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o reddit-bot ./cmd/reddit-bot FROM alpine:latest -RUN apk --no-cache add ca-certificates ffmpeg yt-dlp +RUN apk --no-cache add ca-certificates ffmpeg yt-dlp mesa-dri-gallium mesa-va-gallium intel-media-driver libva-intel-driver linux-firmware-i915 COPY --from=builder /reddit-bot/reddit-bot /usr/bin/reddit-bot RUN chmod +x /usr/bin/reddit-bot RUN mkdir /etc/reddit-bot -ENTRYPOINT [ "/usr/bin/reddit-bot", "-c", "/etc/reddit-bot/config.yml" ] \ No newline at end of file +ENTRYPOINT [ "/usr/bin/reddit-bot", "-c", "/etc/reddit-bot/config.yml" ] diff --git a/cmd/reddit-bot/main.go b/cmd/reddit-bot/main.go index 77b2dc8..4b6b86a 100644 --- a/cmd/reddit-bot/main.go +++ b/cmd/reddit-bot/main.go @@ -86,17 +86,20 @@ func initLogger() { level = zerolog.ErrorLevel default: log.Warn(). - Str("logLevel", logLevel). - Msg("invalid log level; defaulting to info") + Str("level", logLevel). + Msg("Invalid log level; defaulting to info") } zerolog.SetGlobalLevel(level) + log.Info(). + Str("level", logLevel). + Msg("Log level set") } func main() { - initLogger() initEnvVars() initFlags() + initLogger() initConfig() if err := run(); err != nil {