diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..20e1ef1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "daily" \ No newline at end of file diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml new file mode 100644 index 0000000..675eaaf --- /dev/null +++ b/.github/workflows/build-test.yml @@ -0,0 +1,23 @@ +name: Build & test +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Setup Go + uses: actions/setup-go@v3 + with: + go-version: '>=1.22.0' + - name: Build + run: go build -v ./... + - name: Test with the Go CLI + run: go test ./... \ No newline at end of file diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml new file mode 100644 index 0000000..f3f3b1a --- /dev/null +++ b/.github/workflows/goreleaser.yml @@ -0,0 +1,27 @@ +name: goreleaser + +on: + push: + tags: + - '*' + +jobs: + goreleaser: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: '>=1.20.0' + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v5 + with: + distribution: goreleaser + version: latest + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GH_PAT }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0ec1faf --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib +dist/ +*.test + +# Output of the go coverage tool +*.out + +.idea/ +config.toml \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..89c31ed --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,353 @@ +# 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.60.3 +# +# 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 their names from checks. + # Regular expressions must match complete canonical struct package/name/structname. + # 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 + + 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/gofrs/uuid/v5 + reason: "gofrs' package was not go module before v5" + + 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 + + inamedparam: + # Skips check for interface methods with only a single parameter. + # Default: false + skip-single-param: true + + mnd: + # 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: + - args.Error + - flag.Arg + - flag.Duration.* + - flag.Float.* + - flag.Int.* + - flag.Uint.* + - os.Chmod + - os.Mkdir.* + - os.OpenFile + - os.WriteFile + - prometheus.ExponentialBuckets.* + - prometheus.LinearBuckets + + 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 + + perfsprint: + # Optimizes into strings concatenation. + # Default: true + strconcat: false + + rowserrcheck: + # database/sql is always checked + # Default: [] + packages: + - github.com/jmoiron/sqlx + + sloglint: + # Enforce not using global loggers. + # Values: + # - "": disabled + # - "all": report all global loggers + # - "default": report only the default slog logger + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#no-global + # Default: "" + no-global: "all" + # Enforce using methods that accept a context. + # Values: + # - "": disabled + # - "all": report all contextless calls + # - "scope": report only if a context exists in the scope of the outermost function + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#context-only + # Default: "" + context: "scope" + + 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 + - canonicalheader # checks whether net/http.Header uses canonical header + - copyloopvar # detects places where loop variables are copied (Go 1.22+) + - 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 + - exhaustive # checks exhaustiveness of enum switch statements + - fatcontext # detects nested contexts in loops + - 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 + - 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 + - intrange # finds places where for loops could make use of an integer range + - 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 + - mnd # detects magic numbers + - 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 + - spancheck # checks for mistakes with OpenTelemetry/Census spans + - 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 + #- err113 # [too strict] checks the errors handling expressions + #- 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 + #- execinquery # [deprecated] checks query string in Query function which reads your Go src files and warning it finds + #- exportloopref # [not necessary from Go 1.22] checks for pointers to enclosing loop variables + #- forcetypeassert # [replaced by errcheck] finds forced type assertions + #- 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 + + +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 + - text: 'shadow: declaration of "(ctx|err)" shadows declaration at' + linters: [ govet ] diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..047a765 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,26 @@ +version: 1 + +project_name: hsbot + +builds: + - main: ./ + env: + - CGO_ENABLED=0 + goos: + - linux + - windows + - darwin +archives: + - files: + - config.sample.toml + - README.md +checksum: + name_template: 'checksums.txt' +snapshot: + name_template: "{{ incpatch .Version }}-next" +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..61d1860 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..073eac6 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# hsbot + +A telegram bot for generating LLM responses, manipulating images and transcribing audio. + +## Prerequisites + +- [Telegram bot](https://core.telegram.org/bots) API token +- [Claude](https://www.anthropic.com/api) API key +- [fal.ai](https://fal.ai/docs) API key +- [ImageMagick](https://imagemagick.org/index.php) binary installed + +Copy `config.sample.toml` to `config.toml` and set your keys/options. + +## Handlers + +- `/chat`: Keeping conversation context for a duration defined in the config, this handler uses Claude to generate +chat responses. Also works with replying to images, using Claude's Vision component. +- `/image`: Generating images from a prompt, set to use Flux as default. +- `/scale`: Liquid rescale images with a power factor +- `/transcribe`: Transcribe audio files and voice messages + +## Development + +The base architecture is hexagonal. For business logic and its interfaces, extend the ports side on `internal/core`. +Implementations that talks to something else than the business logic should be created as an adapter in +`internal/adapters`. + +Commands are stored and fetched dynamically, use the `CommandRegistry` to register new commands. After that, you can +create the handler in `main.go`. \ No newline at end of file diff --git a/config.sample.toml b/config.sample.toml new file mode 100644 index 0000000..2efffbf --- /dev/null +++ b/config.sample.toml @@ -0,0 +1,21 @@ +[bot] +# log level, debug/info +log_level = "info" + +[chat] +# Timeout to clear conversation cache per ChatID +context_timeout = "5m" + +[telegram] +bot_token = "4242:telegram-bot-token" + +[claude] +api_key = "sk-api-key" +system_prompt = ''' +You are HSBot, a helpful assistant. +''' + +[fal] +api_key = "4242:1234" +flux_url = "https://fal.run/fal-ai/flux-pro" +whisper_url = "https://fal.run/fal-ai/whisper" \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..88fb2e8 --- /dev/null +++ b/go.mod @@ -0,0 +1,38 @@ +module hsbot + +go 1.22 + +require ( + github.com/go-telegram/bot v1.7.2 + github.com/gofrs/uuid/v5 v5.3.0 + github.com/liushuangls/go-anthropic/v2 v2.6.0 + github.com/rs/zerolog v1.33.0 + github.com/spf13/viper v1.19.0 + github.com/stretchr/testify v1.9.0 +) + +require ( + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 // indirect + golang.org/x/sys v0.24.0 // indirect + golang.org/x/text v0.14.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..da48b71 --- /dev/null +++ b/go.sum @@ -0,0 +1,92 @@ +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/go-telegram/bot v1.7.2 h1:Ml50/XleEvk2h568brw66+gH6cDVh1hIIiDFUUwCvxo= +github.com/go-telegram/bot v1.7.2/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gofrs/uuid/v5 v5.3.0 h1:m0mUMr+oVYUdxpMLgSYCZiXe7PuVPnI94+OMeVBNedk= +github.com/gofrs/uuid/v5 v5.3.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/liushuangls/go-anthropic/v2 v2.6.0 h1:hkgLQPD04wL4lFrV5ZoGlIyy4f6P+brIuRlzn2S8K9s= +github.com/liushuangls/go-anthropic/v2 v2.6.0/go.mod h1:8BKv/fkeTaL5R9R9bGkaknYBueyw2WxY20o7bImbOek= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= +github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= +github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 h1:yixxcjnhBmY0nkL253HFVIm0JsFHwrHdT3Yh6szTnfY= +golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +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/internal/adapters/converter/magick.go b/internal/adapters/converter/magick.go new file mode 100644 index 0000000..6dbdaa9 --- /dev/null +++ b/internal/adapters/converter/magick.go @@ -0,0 +1,73 @@ +package converter + +import ( + "context" + "errors" + "fmt" + "hsbot/internal/adapters/file" + "os/exec" + "path/filepath" + + "github.com/rs/zerolog/log" +) + +const MaxPower = 100 +const PowerFactor = 1.3 + +type MagickConverter struct { + magickBinary []string +} + +func NewMagickConverter() (*MagickConverter, error) { + eh := &MagickConverter{} + commands := [][]string{{"magick", "convert", "-version"}, {"convert", "-version"}} + + for _, command := range commands { + _, err := exec.Command(command[0], command[1:]...).Output() + if err != nil { + log.Debug().Strs("commands", command).Msg("binary not found") + continue + } + + log.Debug().Strs("commands", command).Msg("binary found") + eh.magickBinary = command[:len(command)-1] + break + } + + if len(eh.magickBinary) == 0 { + return nil, errors.New("magick binary not available") + } + + return eh, nil +} + +func (m *MagickConverter) Scale(ctx context.Context, imageURL string, power float32) ([]byte, error) { + f, err := file.Download(ctx, imageURL) + if err != nil { + return nil, err + } + + path, err := file.SaveTemp(f, filepath.Ext(imageURL)) + if err != nil { + return nil, err + } + + size := MaxPower - (power / PowerFactor) + dimensions := fmt.Sprintf("%f%%x%f%%", size, size) + outFilename := fmt.Sprintf("%s%s", path, ".png") + + args := make([]string, 0, len(m.magickBinary)) + copy(args, m.magickBinary) + args = append(args, path, "-liquid-rescale", dimensions, outFilename) + + cmd := exec.Command(args[0], args[1:]...) + out, err := cmd.Output() + if err != nil { + log.Error().Bytes("magickStderr", out).Msg("magick commands failed") + return nil, err + } + + log.Debug().Msg("magick commands finished") + + return file.GetTemp(outFilename) +} diff --git a/internal/adapters/file/file.go b/internal/adapters/file/file.go new file mode 100644 index 0000000..8d14d8b --- /dev/null +++ b/internal/adapters/file/file.go @@ -0,0 +1,86 @@ +package file + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + + "github.com/gofrs/uuid/v5" + "github.com/rs/zerolog/log" +) + +func Download(ctx context.Context, path string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, path, nil) + if err != nil { + log.Error().Err(err).Str("path", path).Msg("") + return nil, errors.New("could build get request") + } + + client := &http.Client{} + res, err := client.Do(req) + if err != nil { + log.Error().Err(err).Str("path", path).Msg("") + return nil, errors.New("could not download file") + } + defer res.Body.Close() + + buf, err := io.ReadAll(res.Body) + + if err != nil { + log.Error().Err(err).Str("path", path).Msg("") + return nil, errors.New("could not write file content") + } + + return buf, nil +} + +func SaveTemp(data []byte, extension string) (string, error) { + id, err := uuid.NewV4() + if err != nil { + return "", err + } + + log.Debug().Int("bytes", len(data)).Str("extension", extension).Msg("creating temp file") + + path := filepath.Join(os.TempDir(), fmt.Sprintf("%s%s", id.String(), extension)) + + f, err := os.Create(path) + if err != nil { + log.Error().Err(err).Msg("could not create temp file") + return "", err + } + + defer f.Close() + + if _, err := f.Write(data); err != nil { + return "", err + } + + log.Debug().Str("path", f.Name()).Msg("created file") + + return f.Name(), nil +} + +func GetTemp(path string) ([]byte, error) { + buf, err := os.ReadFile(path) + if err != nil { + log.Error().Err(err).Msg("") + return nil, err + } + + defer removeTempFile(path) + + return buf, nil +} + +func removeTempFile(path string) { + err := os.Remove(path) + if err != nil { + log.Warn().Str("path", path).Err(err).Msg("could not clean up temp file") + } + log.Debug().Str("path", path).Msg("cleaned up temp file") +} diff --git a/internal/adapters/generator/claude.go b/internal/adapters/generator/claude.go new file mode 100644 index 0000000..0205479 --- /dev/null +++ b/internal/adapters/generator/claude.go @@ -0,0 +1,75 @@ +package generator + +import ( + "context" + "fmt" + "hsbot/internal/adapters/file" + "hsbot/internal/core/domain" + + "github.com/liushuangls/go-anthropic/v2" +) + +const MaxTokens = 5000 + +type ClaudeGenerator struct { + client *anthropic.Client + systemPrompt string +} + +func NewClaudeGenerator(apiKey, systemPrompt string) *ClaudeGenerator { + return &ClaudeGenerator{ + systemPrompt: systemPrompt, + client: anthropic.NewClient(apiKey), + } +} + +func (c *ClaudeGenerator) GenerateFromPrompt(ctx context.Context, prompts []domain.Prompt) (string, error) { + var messages []anthropic.Message + + for _, prompt := range prompts { + if prompt.Author == domain.System { + messages = append(messages, anthropic.NewAssistantTextMessage(prompt.Prompt)) + } else if prompt.Author == domain.User { + message, err := createUserMessage(ctx, prompt) + if err != nil { + return "", err + } + messages = append(messages, message) + } + } + + resp, err := c.client.CreateMessages(ctx, anthropic.MessagesRequest{ + Model: anthropic.ModelClaude3Dot5Sonnet20240620, + System: c.systemPrompt, + Messages: messages, + MaxTokens: MaxTokens, + }) + if err != nil { + return "", fmt.Errorf("claude API error: %w", err) + } + + return resp.Content[0].GetText(), nil +} + +func createUserMessage(ctx context.Context, prompt domain.Prompt) (anthropic.Message, error) { + if prompt.ImageURL != "" { + f, err := file.Download(ctx, prompt.ImageURL) + if err != nil { + return anthropic.Message{}, fmt.Errorf("error downloading image: %w", err) + } + + return anthropic.Message{ + Role: anthropic.RoleUser, + Content: []anthropic.MessageContent{ + anthropic.NewImageMessageContent(anthropic.MessageContentImageSource{ + Type: "base64", + MediaType: "image/jpeg", + Data: f, + }), + anthropic.NewTextMessageContent(prompt.Prompt), + }, + }, nil + } + + return anthropic.NewUserTextMessage(prompt.Prompt), nil +} diff --git a/internal/adapters/generator/fal.go b/internal/adapters/generator/fal.go new file mode 100644 index 0000000..b448861 --- /dev/null +++ b/internal/adapters/generator/fal.go @@ -0,0 +1,131 @@ +package generator + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + + "github.com/rs/zerolog/log" +) + +type FALGenerator struct { + apiKey string + apiURL string +} + +func NewFALGenerator(apiURL, apiKey string) *FALGenerator { + return &FALGenerator{ + apiKey: apiKey, + apiURL: apiURL, + } +} + +type imageRequest struct { + Prompt string `json:"prompt"` + EnableSafetyChecker bool `json:"enable_safety_checker"` + ImageSize string `json:"image_size"` +} + +type imageResponse struct { + Images []struct { + URL string `json:"url"` + ContentType string `json:"content_type"` + } `json:"images"` + Prompt string `json:"prompt"` +} + +func (f *FALGenerator) GenerateFromPrompt(ctx context.Context, prompt string) (string, error) { + falRequest := imageRequest{ + Prompt: prompt, + EnableSafetyChecker: false, + ImageSize: "square", + } + + payloadBuf := new(bytes.Buffer) + err := json.NewEncoder(payloadBuf).Encode(falRequest) + if err != nil { + return "", err + } + + body, err := f.postFALRequest(ctx, payloadBuf) + if err != nil { + return "", err + } + + log.Info().Interface("body", body).Msg("FAL imageResponse") + + var result imageResponse + if err := json.Unmarshal(body, &result); err != nil { + log.Error().Err(err).Msg("error unmarshalling FAL imageResponse") + return "", err + } + + log.Info().Interface("result", result).Msg("FAL imageResponse") + + return result.Images[0].URL, nil +} + +type audioRequest struct { + AudioURL string `json:"audio_url"` +} + +type audioResponse struct { + Text string `json:"text"` +} + +func (f *FALGenerator) GenerateFromAudio(ctx context.Context, url string) (string, error) { + falRequest := audioRequest{ + AudioURL: url, + } + + payloadBuf := new(bytes.Buffer) + err := json.NewEncoder(payloadBuf).Encode(falRequest) + if err != nil { + return "", err + } + + body, err := f.postFALRequest(ctx, payloadBuf) + if err != nil { + return "", err + } + log.Info().Interface("body", body).Msg("FAL audioResponse") + + var result audioResponse + if err := json.Unmarshal(body, &result); err != nil { + log.Error().Err(err).Msg("error unmarshalling FAL audioResponse") + return "", err + } + + log.Info().Interface("result", result).Msg("FAL audioResponse") + + return result.Text, nil +} + +func (f *FALGenerator) postFALRequest(ctx context.Context, payloadBuf *bytes.Buffer) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.apiURL, payloadBuf) + if err != nil { + log.Error().Err(err).Msg("error creating POST request for FAL") + return nil, err + } + + req.Header.Add("Authorization", "Key "+f.apiKey) + req.Header.Add("Content-Type", "application/json") + + client := &http.Client{} + res, err := client.Do(req) + if err != nil { + log.Error().Err(err).Msg("error executing request to FAL") + return nil, err + } + + defer res.Body.Close() + + body, err := io.ReadAll(res.Body) + if err != nil { + log.Error().Err(err).Msg("error parsing FAL response") + return nil, err + } + return body, nil +} diff --git a/internal/adapters/handler/command.go b/internal/adapters/handler/command.go new file mode 100644 index 0000000..7f30f91 --- /dev/null +++ b/internal/adapters/handler/command.go @@ -0,0 +1,125 @@ +package handler + +import ( + "context" + "hsbot/internal/core/domain" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + "github.com/rs/zerolog/log" +) + +type CommandHandler struct { + commandRegistry *domain.CommandRegistry +} + +func NewCommandHandler(commandRegistry *domain.CommandRegistry) *CommandHandler { + return &CommandHandler{commandRegistry: commandRegistry} +} + +func (h *CommandHandler) Handle(ctx context.Context, b *bot.Bot, update *models.Update) { + if update.Message == nil { + return + } + + log.Debug().Str("message", update.Message.Text).Msg("registering chat command handler") + + cmd := domain.ParseCommand(update.Message.Text) + commandHandler, err := h.commandRegistry.Get(cmd) + if err != nil { + log.Debug().Str("commands", cmd).Msg("no handler for commands") + return + } + + replyToMessageID := new(int) + if update.Message.ReplyToMessage != nil { + *replyToMessageID = update.Message.ReplyToMessage.ID + } + + imageURL := make(chan string) + audioURL := make(chan string) + + go getOptionalImage(ctx, b, update, imageURL) + go getOptionalAudio(ctx, b, update, audioURL) + + commandHandler.Respond(ctx, &domain.Message{ + ID: update.Message.ID, + ChatID: update.Message.Chat.ID, + Text: update.Message.Text, + ReplyToMessageID: replyToMessageID, + ImageURL: <-imageURL, + AudioURL: <-audioURL, + }) +} + +func getOptionalImage(ctx context.Context, b *bot.Bot, update *models.Update, url chan string) { + var photos []models.PhotoSize + + if update.Message.Photo != nil { + photos = update.Message.Photo + } + + if update.Message.ReplyToMessage != nil { + if update.Message.ReplyToMessage.Photo != nil { + photos = update.Message.ReplyToMessage.Photo + } + } + + if len(photos) == 0 { + url <- "" + return + } + + f, err := b.GetFile(ctx, &bot.GetFileParams{FileID: findLargestImage(photos)}) + if err != nil { + log.Error().Msg("error getting file from telegram api") + url <- "" + return + } + + url <- b.FileDownloadLink(f) +} + +func getOptionalAudio(ctx context.Context, b *bot.Bot, update *models.Update, url chan string) { + var fileID string + if update.Message.Audio != nil { + fileID = update.Message.Audio.FileID + } + + if update.Message.ReplyToMessage != nil { + if update.Message.ReplyToMessage.Voice != nil { + fileID = update.Message.ReplyToMessage.Voice.FileID + } + + if update.Message.ReplyToMessage.Audio != nil { + fileID = update.Message.ReplyToMessage.Audio.FileID + } + } + + if fileID == "" { + url <- "" + return + } + + f, err := b.GetFile(ctx, &bot.GetFileParams{FileID: fileID}) + if err != nil { + log.Error().Msg("error getting file from telegram api") + url <- "" + return + } + + url <- b.FileDownloadLink(f) +} + +func findLargestImage(photos []models.PhotoSize) string { + maxSize := -1 + var maxID string + for _, photo := range photos { + if photo.FileSize > maxSize { + maxSize = photo.FileSize + maxID = photo.FileID + } + } + + return maxID +} diff --git a/internal/adapters/sender/telegram.go b/internal/adapters/sender/telegram.go new file mode 100644 index 0000000..05a9f77 --- /dev/null +++ b/internal/adapters/sender/telegram.go @@ -0,0 +1,111 @@ +package sender + +import ( + "bytes" + "context" + "fmt" + "hsbot/internal/core/domain" + "time" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + "github.com/rs/zerolog/log" +) + +//go:generate mockery --name TelegramBot + +type TelegramSender struct { + bot *bot.Bot +} + +func NewTelegramSender(bot *bot.Bot) *TelegramSender { + return &TelegramSender{bot: bot} +} + +func (s *TelegramSender) SendMessageReply(ctx context.Context, chatID int64, messageID int, message string) error { + _, err := s.bot.SendMessage(ctx, &bot.SendMessageParams{ + ChatID: chatID, + Text: message, + ReplyParameters: &models.ReplyParameters{ + MessageID: messageID, + ChatID: chatID, + }, + }) + + return err +} + +func (s *TelegramSender) SendImageURLReply(ctx context.Context, chatID int64, messageID int, url string) error { + params := &bot.SendPhotoParams{ + ChatID: chatID, + ReplyParameters: &models.ReplyParameters{ + MessageID: messageID, + ChatID: chatID, + }, + Photo: &models.InputFileString{Data: url}, + } + + _, err := s.bot.SendPhoto(ctx, params) + if err != nil { + log.Error().Err(err).Msg("failed to send photo response") + return err + } + + return nil +} + +func (s *TelegramSender) SendImageFileReply(ctx context.Context, chatID int64, messageID int, file []byte) error { + params := &bot.SendPhotoParams{ + ChatID: chatID, + Photo: &models.InputFileUpload{Filename: fmt.Sprintf("%d.png", messageID), + Data: bytes.NewReader(file)}, + ReplyParameters: &models.ReplyParameters{ + MessageID: messageID, + ChatID: chatID, + }, + } + + _, err := s.bot.SendPhoto(ctx, params) + if err != nil { + log.Error().Err(err).Msg("failed to send photo response") + return err + } + + return nil +} + +const ChatActionRepeatSeconds = 5 + +func (s *TelegramSender) SendChatAction(ctx context.Context, chatID int64, action domain.Action) { + log.Debug().Int64("chatID", chatID).Msg("starting action routine") + for { + select { + case <-ctx.Done(): + log.Debug().Int64("chatID", chatID).Msg("done, stopping action routine") + return + default: + } + + var chatAction models.ChatAction + switch action { + case domain.SendingPhoto: + chatAction = models.ChatActionUploadPhoto + case domain.Typing: + chatAction = models.ChatActionTyping + default: + chatAction = models.ChatActionTyping + } + + log.Debug().Int64("chatID", chatID).Msg("transmitting action") + _, err := s.bot.SendChatAction(ctx, &bot.SendChatActionParams{ + ChatID: chatID, + Action: chatAction, + }) + if err != nil { + log.Err(err).Msg("error sending chat action") + return + } + + time.Sleep(ChatActionRepeatSeconds * time.Second) + } +} diff --git a/internal/core/domain/command.go b/internal/core/domain/command.go new file mode 100644 index 0000000..de36d7c --- /dev/null +++ b/internal/core/domain/command.go @@ -0,0 +1,64 @@ +package domain + +import ( + "context" + "errors" + "strings" + + "github.com/rs/zerolog/log" +) + +type CommandResponder interface { + Respond(ctx context.Context, message *Message) + GetCommand() string +} + +type CommandRegistry struct { + commands map[string]CommandResponder +} + +func (c *CommandRegistry) Register(handler CommandResponder) { + if c.commands == nil { + c.commands = make(map[string]CommandResponder) + } + + log.Info().Str("handler", handler.GetCommand()).Msg("adding command handler to registry") + c.commands[handler.GetCommand()] = handler +} + +func (c *CommandRegistry) Get(command string) (CommandResponder, error) { + log.Debug().Interface("commands", command).Msg("fetching command handler from registry") + + if c.commands == nil { + err := errors.New("can't fetch commands, registry not initialized") + return nil, err + } + + handler, ok := c.commands[command] + if !ok { + return nil, errors.New("commands not found") + } + + return handler, nil +} +func (c *CommandRegistry) ListServices() []string { + keys := make([]string, len(c.commands)) + + i := 0 + for k := range c.commands { + keys[i] = k + i++ + } + + return keys +} + +func ParseCommandArgs(args string) string { + command := strings.Split(args, " ") + return strings.Join(command[1:], " ") +} + +func ParseCommand(args string) string { + command := strings.Split(args, " ") + return command[0] +} diff --git a/internal/core/domain/command_test.go b/internal/core/domain/command_test.go new file mode 100644 index 0000000..98d3382 --- /dev/null +++ b/internal/core/domain/command_test.go @@ -0,0 +1,47 @@ +package domain_test + +import ( + "hsbot/internal/core/domain" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseCommandArgs(t *testing.T) { + type TestCase struct { + description string + args string + want string + } + + testCases := []TestCase{ + { + description: "should discard first word", + args: "/scale 12", + want: "12", + }, + { + description: "should only discard first word", + args: "/scale 12 13", + want: "12 13", + }, + { + description: "empty on no args", + args: "/scale", + want: "", + }, + { + description: "empty on no input", + args: "", + want: "", + }, + } + + for _, testCase := range testCases { + t.Run(testCase.description, func(t *testing.T) { + got := domain.ParseCommandArgs(testCase.args) + + assert.Equal(t, testCase.want, got) + }) + } +} diff --git a/internal/core/domain/commands/chat.go b/internal/core/domain/commands/chat.go new file mode 100644 index 0000000..c696c4c --- /dev/null +++ b/internal/core/domain/commands/chat.go @@ -0,0 +1,131 @@ +package commands + +import ( + "context" + "fmt" + "hsbot/internal/core/domain" + "hsbot/internal/core/port" + "time" + + "github.com/rs/zerolog/log" +) + +type ChatHandler struct { + textGenerator port.TextGenerator + textSender port.TextSender + command string + cache map[int64]*Conversation +} + +type Conversation struct { + timestamp time.Time + messages []domain.Prompt +} + +func NewChatHandler(textGenerator port.TextGenerator, textSender port.TextSender, command string, + cacheDuration time.Duration) *ChatHandler { + h := &ChatHandler{ + textGenerator: textGenerator, + textSender: textSender, + command: command, + } + + go h.clearCache(cacheDuration) + + return h +} + +func (h *ChatHandler) GetCommand() string { + return h.command +} + +func (h *ChatHandler) Respond(ctx context.Context, message *domain.Message) { + l := log.With(). + Int("messageId", message.ID). + Int64("chatId", message.ChatID). + Str("command", h.GetCommand()). + Logger() + + l.Info().Msg("handling request") + + ctx, cancel := context.WithCancel(ctx) + go h.textSender.SendChatAction(ctx, message.ChatID, domain.Typing) + + promptText := domain.ParseCommandArgs(message.Text) + if promptText == "" { + err := h.textSender.SendMessageReply(ctx, message.ChatID, message.ID, "please input a prompt") + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + conversation, ok := h.cache[message.ChatID] + if !ok { + l.Debug().Msg("new conversation") + h.cache = make(map[int64]*Conversation) + + h.cache[message.ChatID] = &Conversation{ + messages: []domain.Prompt{ + { + Author: domain.User, + Prompt: promptText, + ImageURL: message.ImageURL, + }, + }, + } + conversation = h.cache[message.ChatID] + l.Debug().Int("message cache size", len(h.cache[message.ChatID].messages)).Msg("") + } else { + conversation.messages = append(conversation.messages, domain.Prompt{Author: domain.User, + Prompt: promptText, ImageURL: message.ImageURL}) + } + + response, err := h.textGenerator.GenerateFromPrompt(ctx, conversation.messages) + if err != nil { + err := h.textSender.SendMessageReply(ctx, + message.ChatID, + message.ID, + fmt.Sprintf("failed to generate reply: %s", err)) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + conversation.messages = append(conversation.messages, domain.Prompt{Author: domain.System, Prompt: promptText}) + conversation.timestamp = time.Now() + + err = h.textSender.SendMessageReply(ctx, + message.ChatID, + message.ID, + response) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + + cancel() +} + +func (h *ChatHandler) clearCache(timeout time.Duration) { + log.Debug().Msg("gpt cache timer started") + + for range time.Tick(time.Minute) { + for chatID := range h.cache { + log.Debug().Int64("chatID", chatID).Msg("checking timestamp for id") + messageTime := h.cache[chatID].timestamp + if messageTime.Add(timeout).Before(time.Now()) { + log.Debug().Int64("chatID", chatID).Msg("expired chat, resetting") + delete(h.cache, chatID) + } + } + } +} diff --git a/internal/core/domain/commands/image.go b/internal/core/domain/commands/image.go new file mode 100644 index 0000000..387f5b2 --- /dev/null +++ b/internal/core/domain/commands/image.go @@ -0,0 +1,82 @@ +package commands + +import ( + "context" + "fmt" + "hsbot/internal/core/domain" + "hsbot/internal/core/port" + + "github.com/rs/zerolog/log" +) + +type ImageHandler struct { + imageGenerator port.ImageGenerator + imageSender port.ImageSender + textSender port.TextSender + command string +} + +func NewImageHandler(imageGenerator port.ImageGenerator, + imageSender port.ImageSender, + textSender port.TextSender, + command string) *ImageHandler { + return &ImageHandler{imageGenerator: imageGenerator, + imageSender: imageSender, + textSender: textSender, + command: command} +} + +func (h *ImageHandler) GetCommand() string { + return h.command +} + +func (h *ImageHandler) Respond(ctx context.Context, message *domain.Message) { + l := log.With(). + Int("messageId", message.ID). + Int64("chatId", message.ChatID). + Str("imageURL", message.ImageURL). + Str("command", h.GetCommand()). + Logger() + + l.Info().Msg("handling request") + + ctx, cancel := context.WithCancel(ctx) + go h.textSender.SendChatAction(ctx, message.ChatID, domain.SendingPhoto) + + prompt := domain.ParseCommandArgs(message.Text) + if prompt == "" { + err := h.textSender.SendMessageReply(ctx, message.ChatID, message.ID, "missing image prompt") + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + imageURL, err := h.imageGenerator.GenerateFromPrompt(ctx, prompt) + if err != nil { + errMsg := "error getting FAL response" + l.Error().Err(err).Str("imageURL", imageURL).Msg(errMsg) + err := h.textSender.SendMessageReply(ctx, + message.ChatID, + message.ID, + fmt.Sprintf("error getting FAL response: %s", err)) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + err = h.imageSender.SendImageURLReply(ctx, message.ChatID, message.ID, imageURL) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() +} diff --git a/internal/core/domain/commands/scale.go b/internal/core/domain/commands/scale.go new file mode 100644 index 0000000..18d28bb --- /dev/null +++ b/internal/core/domain/commands/scale.go @@ -0,0 +1,95 @@ +package commands + +import ( + "context" + "fmt" + "hsbot/internal/core/domain" + "hsbot/internal/core/port" + "strconv" + + "github.com/rs/zerolog/log" +) + +type ScaleHandler struct { + imageConverter port.ImageConverter + textSender port.TextSender + imageSender port.ImageSender + command string +} + +func NewScaleHandler(imageConverter port.ImageConverter, textSender port.TextSender, imageSender port.ImageSender, + command string) *ScaleHandler { + return &ScaleHandler{imageConverter: imageConverter, textSender: textSender, imageSender: imageSender, + command: command} +} + +func (h *ScaleHandler) GetCommand() string { + return h.command +} + +func (h *ScaleHandler) Respond(ctx context.Context, message *domain.Message) { + l := log.With(). + Int("messageId", message.ID). + Int64("chatId", message.ChatID). + Str("command", h.GetCommand()). + Logger() + + l.Info().Msg("handling request") + + ctx, cancel := context.WithCancel(ctx) + go h.textSender.SendChatAction(ctx, message.ChatID, domain.SendingPhoto) + + if message.ImageURL == "" || message.ReplyToMessageID == nil { + err := h.textSender.SendMessageReply(ctx, message.ChatID, message.ID, + "reply to an image") + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + args := domain.ParseCommandArgs(message.Text) + + var power float64 + var err error + if args == "" { + power = 80 + } else { + power, err = strconv.ParseFloat(args, 32) + if err != nil { + err := h.textSender.SendMessageReply(ctx, message.ChatID, message.ID, + "usage: /scale or /scale , 1-100") + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + } + + rescaled, err := h.imageConverter.Scale(ctx, message.ImageURL, float32(power)) + if err != nil { + err := h.textSender.SendMessageReply(ctx, message.ChatID, message.ID, + fmt.Sprintf("failed to scale image: %s", err)) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + err = h.imageSender.SendImageFileReply(ctx, message.ChatID, *message.ReplyToMessageID, rescaled) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() +} diff --git a/internal/core/domain/commands/transcribe.go b/internal/core/domain/commands/transcribe.go new file mode 100644 index 0000000..a283ca2 --- /dev/null +++ b/internal/core/domain/commands/transcribe.go @@ -0,0 +1,69 @@ +package commands + +import ( + "context" + "fmt" + "hsbot/internal/core/domain" + "hsbot/internal/core/port" + + "github.com/rs/zerolog/log" +) + +type TranscribeHandler struct { + transcriber port.Transcriber + textSender port.TextSender + command string +} + +func NewTranscribeHandler(transcriber port.Transcriber, textSender port.TextSender, command string) *TranscribeHandler { + return &TranscribeHandler{transcriber: transcriber, textSender: textSender, command: command} +} + +func (h *TranscribeHandler) GetCommand() string { + return h.command +} + +func (h *TranscribeHandler) Respond(ctx context.Context, message *domain.Message) { + l := log.With(). + Int("messageId", message.ID). + Int64("chatId", message.ChatID). + Str("audioURL", message.AudioURL). + Str("command", h.GetCommand()). + Logger() + + l.Info().Msg("handling request") + + ctx, cancel := context.WithCancel(ctx) + go h.textSender.SendChatAction(ctx, message.ChatID, domain.Typing) + + if message.AudioURL == "" { + err := h.textSender.SendMessageReply(ctx, message.ChatID, message.ID, "no audio found for transcription") + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + resp, err := h.transcriber.GenerateFromAudio(ctx, message.AudioURL) + if err != nil { + err := h.textSender.SendMessageReply(ctx, message.ChatID, message.ID, fmt.Sprintf("transcription failed: %s", err)) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() + return + } + + err = h.textSender.SendMessageReply(ctx, message.ChatID, *message.ReplyToMessageID, resp) + if err != nil { + l.Error().Err(err).Msg(domain.ErrSendingReplyFailed) + cancel() + return + } + cancel() +} diff --git a/internal/core/domain/constants.go b/internal/core/domain/constants.go new file mode 100644 index 0000000..a2fa988 --- /dev/null +++ b/internal/core/domain/constants.go @@ -0,0 +1,5 @@ +package domain + +const ( + ErrSendingReplyFailed = "failed to send reply" +) diff --git a/internal/core/domain/model.go b/internal/core/domain/model.go new file mode 100644 index 0000000..4f7b8b1 --- /dev/null +++ b/internal/core/domain/model.go @@ -0,0 +1,30 @@ +package domain + +type Author string + +const ( + User Author = "user" + System Author = "system" +) + +type Prompt struct { + Prompt string + ImageURL string + Author Author +} + +type Message struct { + ID int + ChatID int64 + ReplyToMessageID *int + ImageURL string + AudioURL string + Text string +} + +type Action string + +const ( + Typing Action = "typing" + SendingPhoto Action = "sending_photo" +) diff --git a/internal/core/port/converter.go b/internal/core/port/converter.go new file mode 100644 index 0000000..63b57a5 --- /dev/null +++ b/internal/core/port/converter.go @@ -0,0 +1,7 @@ +package port + +import "context" + +type ImageConverter interface { + Scale(ctx context.Context, imageURL string, power float32) ([]byte, error) +} diff --git a/internal/core/port/generator.go b/internal/core/port/generator.go new file mode 100644 index 0000000..4fe3d58 --- /dev/null +++ b/internal/core/port/generator.go @@ -0,0 +1,18 @@ +package port + +import ( + "context" + "hsbot/internal/core/domain" +) + +type TextGenerator interface { + GenerateFromPrompt(ctx context.Context, prompts []domain.Prompt) (string, error) +} + +type Transcriber interface { + GenerateFromAudio(ctx context.Context, url string) (string, error) +} + +type ImageGenerator interface { + GenerateFromPrompt(ctx context.Context, prompt string) (string, error) +} diff --git a/internal/core/port/sender.go b/internal/core/port/sender.go new file mode 100644 index 0000000..206ecf9 --- /dev/null +++ b/internal/core/port/sender.go @@ -0,0 +1,16 @@ +package port + +import ( + "context" + "hsbot/internal/core/domain" +) + +type TextSender interface { + SendMessageReply(ctx context.Context, chatID int64, messageID int, message string) error + SendChatAction(ctx context.Context, chatID int64, action domain.Action) +} + +type ImageSender interface { + SendImageURLReply(ctx context.Context, chatID int64, messageID int, url string) error + SendImageFileReply(ctx context.Context, chatID int64, messageID int, file []byte) error +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..f191628 --- /dev/null +++ b/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "context" + "hsbot/internal/adapters/converter" + "hsbot/internal/adapters/generator" + "hsbot/internal/adapters/handler" + "hsbot/internal/adapters/sender" + "hsbot/internal/core/domain" + "hsbot/internal/core/domain/commands" + "os" + "os/signal" + "time" + + "github.com/rs/zerolog" + + "github.com/go-telegram/bot" + "github.com/rs/zerolog/log" + "github.com/spf13/viper" +) + +func main() { + log.Info().Msg("starting hsbot...") + + viper.AddConfigPath(".") + viper.SetConfigType("toml") + + log.Info().Msg("reading config file...") + err := viper.ReadInConfig() + if err != nil { + log.Fatal().Err(err).Msg("could not read config file") + } + + var logLevel zerolog.Level + + switch viper.GetString("bot.log_level") { + case "info": + logLevel = zerolog.InfoLevel + case "debug": + logLevel = zerolog.DebugLevel + default: + logLevel = zerolog.InfoLevel + } + + zerolog.SetGlobalLevel(logLevel) + + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) + defer cancel() + + token := viper.GetString("telegram.bot_token") + b, err := bot.New(token) + if err != nil { + log.Panic().Err(err).Msg("failed initializing telegram bot") + } + + s := sender.NewTelegramSender(b) + + claudeGenerator := generator.NewClaudeGenerator(viper.GetString("claude.api_key"), + viper.GetString("claude.system_prompt")) + fluxGenerator := generator.NewFALGenerator(viper.GetString("fal.flux_url"), viper.GetString("fal.api_key")) + magickConverter, err := converter.NewMagickConverter() + if err != nil { + log.Panic().Err(err).Msg("failed initializing magick converter") + } + transcriber := generator.NewFALGenerator(viper.GetString("fal.whisper_url"), viper.GetString("fal.api_key")) + + chatConvoDuration, err := time.ParseDuration(viper.GetString("chat.context_timeout")) + if err != nil { + log.Panic().Err(err).Msg("invalid duration for chat context in config") + } + + commandRegistry := &domain.CommandRegistry{} + commandRegistry.Register(commands.NewChatHandler(claudeGenerator, s, "/chat", + chatConvoDuration)) + commandRegistry.Register(commands.NewImageHandler(fluxGenerator, s, s, "/image")) + commandRegistry.Register(commands.NewScaleHandler(magickConverter, s, s, "/scale")) + commandRegistry.Register(commands.NewTranscribeHandler(transcriber, s, "/transcribe")) + + commandHandler := handler.NewCommandHandler(commandRegistry) + + b.RegisterHandler(bot.HandlerTypeMessageText, "/", bot.MatchTypePrefix, commandHandler.Handle) + + log.Info().Msg("bot listening") + b.Start(ctx) +}