repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
BetterOCR
github_2023
python
3
junhoyeo
junhoyeo
@@ -70,9 +70,14 @@ def detect_text( print("=====") print(prompt) - api_key = os.environ["OPENAI_API_KEY"] - if "API_KEY" in options["openai"] and options["openai"]["API_KEY"] != "": - api_key = options["openai"]["API_KEY"] + # Prioritize user-specified API_KEY + api_key = options["openai"].get("API_KEY", os.environ.get("OPENAI_API_KEY"))
wtf i was too javascript these days and forgot about `dictionary.get` lol thx 👍
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -127,6 +129,30 @@ Exceptions are not thrown unless calling gum itself does, the status code is int All of the rest of the options and usecases _should work_ ™. Please raise issues/PRs for any improvements. Much appreciated! +## Simplified AP
Lets call it `Higher Level` API than Simplified. I think that signals intention better?
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -127,6 +129,30 @@ Exceptions are not thrown unless calling gum itself does, the status code is int All of the rest of the options and usecases _should work_ ™. Please raise issues/PRs for any improvements. Much appreciated! +## Simplified AP +You can also use the gum like this: + +```clojure-version +(require '[bblgum.core :as b]) + +;; Calling command without any args or opts: +(b/gum :file) + +;; Calling a command with args only:
can remove the escapes here.
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -1,7 +1,7 @@ (ns bblgum.core (:require [bblgum.impl :as i])) -(defn gum +(defn- gumv1
lets call it `gum*` and change the docstrings.
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -33,3 +33,67 @@ :result (case as :bool (zero? exit) out)})) + +(defn- prepare-cmd-map + ([cmd] + (if (map? cmd) + cmd + (prepare-cmd-map cmd [] {}))) + ([cmd args-or-opts] + (if (map? args-or-opts) + (prepare-cmd-map cmd [] args-or-opts) + (prepare-cmd-map cmd args-or-opts {})) +) + ([cmd args options] + (merge {:cmd cmd :args args} options))) + +(comment
lets move the comment at the end.
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -21,15 +21,52 @@ Add this to your `bb.edn` or `deps.edn`: Sample babashka usage: ```console $ bb -Sdeps '{:deps {io.github.lispyclouds/bblgum {:git/sha "7ebae0e2231899fe2a6ad44bc9ef5fca64099fcd"}}}' \ - -e "(require '[bblgum.core :as b]) (b/gum {:cmd :input :opts {:placeholder \"User name:\"}})" + -e "(require '[bblgum.core :as b]) (b/gum :input :placeholder \"User name:\")" ``` ## Interaction This follows the same [section](https://github.com/charmbracelet/gum#interaction) on the gum repo and all params should work verbatim. Run `gum <cmd> --help` to discover all the params and args. -This lib only has _one_ public fn: `bblgum.core/gum`. This is possibly the tiniest clojure lib! +This lib only has _two_ public fns: `bblgum.core/gum*` (low-level API) and `bblgum.core/gum` (high-level API). + +## gum (high-level API)
now that i think of it, we might as well adapt the usual `gum` fn to support this. this change is still non-breaking and not much reason to expose `gum*`
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -127,6 +166,30 @@ Exceptions are not thrown unless calling gum itself does, the status code is int All of the rest of the options and usecases _should work_ ™. Please raise issues/PRs for any improvements. Much appreciated! +## Simplified AP
Lets merge this with the usual examples and not call it differently
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -127,6 +166,30 @@ Exceptions are not thrown unless calling gum itself does, the status code is int All of the rest of the options and usecases _should work_ ™. Please raise issues/PRs for any improvements. Much appreciated! +## Simplified AP +You can also use the gum like this: + +```clojure-version +(require '[bblgum.core :as b]) + +;; Calling command without any args or opts: +(b/gum :file) + +;; Calling a command with args only: +(b/gum :choose [\"foo\" \"bar\"]) + +;; Calling a command with args and opts: +(b/gum :choose [\"foo\" \"bar\"] {:header \"select a foo\"})
still needs the removal of the escaped `\"`
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -33,3 +33,78 @@ :result (case as :bool (zero? exit) out)})) + +(defn- prepare-options [m] + (let [fmted-keys [:opts :in :as :gum-path] + fmted (select-keys m fmted-keys) + opts (apply dissoc m fmted-keys)] + (update fmted :opts merge opts))) + +(defn- prepare-cmd-map + "Prepares command map to be passed to `gum*`. Tries to be smart and figure out what user wants." + ([cmd] + (if (map? cmd) + cmd + (prepare-cmd-map cmd [] nil))) + ([cmd args-or-opts] + (if (vector? args-or-opts) + (prepare-cmd-map cmd args-or-opts nil) + (prepare-cmd-map cmd [] args-or-opts))) + ([cmd args & options] + (let [args* (if (vector? args) args []) + foptions (filter some? options) + options* (if (keyword? args) (conj foptions args) foptions)] + (merge {:cmd cmd :args args*} (if (seq options*) (prepare-options (apply hash-map options*)) {}))))) + +(defn gum
inline the `gum*` here and remove it.
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -33,3 +33,78 @@ :result (case as :bool (zero? exit) out)})) + +(defn- prepare-options [m]
lets move these 2 fns to the impl ns and add some tests
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -1,8 +1,8 @@ (ns bblgum.core (:require [bblgum.impl :as i])) -(defn gum - "Main driver fn for using gum: https://github.com/charmbracelet/gum +(defn- gum*
we can merge this and the `gum` right? move this logic to the end of the multi-arity dispatch and remove `gum*`?
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -2,34 +2,52 @@ (:require [bblgum.impl :as i])) (defn gum - "Main driver fn for using gum: https://github.com/charmbracelet/gum + "High level gum API. Simpler in usage then `gum*`, but uses it under the hood.
can remove the mention of `gum*` from here
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -2,34 +2,52 @@ (:require [bblgum.impl :as i])) (defn gum - "Main driver fn for using gum: https://github.com/charmbracelet/gum + "High level gum API. Simpler in usage then `gum*`, but uses it under the hood. - Options map: - cmd: The interaction command. Can be a keyword. Required - opts: A map of options to be passed as optional params to gum - args: A vec of args to be passed as positional params to gum - in: An input stream than can be passed to gum - as: Coerce the output. Currently supports :bool, :ignored or defaults to a seq of strings - gum-path: Path to the gum binary. Defaults to gum + You can call `gum` like this: + + (gum :command [\"args vector\"] :opt \"value\" :opt2 \"value2\") + + There are several special opts, that are handled by the library: + :in - An input stream than can be passed to gum + :as - Coerce the output. Currently supports :bool, :ignored or defaults to a seq of strings + :gum-path - Path to the gum binary. Defaults to gum + + All other opts are passed to the `gum` CLI. Consult `gum CMD --help` to see available options. + To pass flags like `--directory` use `:directory true`. Always use full names of the options. + + Usage examples + -------------- + Command only: + (gum :file) + + Command with args: + (gum :choose [\"arg\" \"arg2\"]) + + Command with opts: + (gum :file :directory true) + + Command with arguments and options: + (gum :choose [\"arg1\" \"arg2\"] :header \"Choose an option\") Returns a map of: status: The exit code from gum result: The output from the execution: seq of lines or coerced via :as." - [{:keys [cmd opts args in as gum-path]}] - (when-not cmd - (throw (IllegalArgumentException. ":cmd must be provided or non-nil"))) - - (let [gum-path (or gum-path "gum") - with-opts (->> opts - (map (fn [[opt value]] - (str "--" (i/->str opt) "=" (i/multi-opt value)))) - (into [gum-path (i/->str cmd)])) - out (if (= :ignored as) :inherit :string) - args (if (or (empty? args) (= "--" (first args))) - args - (cons "--" args)) - {:keys [exit out]} (i/exec (into with-opts args) in out)] - {:status exit - :result (case as - :bool (zero? exit) - out)})) + [cmd & [args & opts]] + (let [{:keys [cmd opts args in as gum-path]} (apply i/prepare-cmd-map cmd args opts)] + (when-not cmd + (throw (IllegalArgumentException. ":cmd must be provided or non-nil")))
can we improve this message? maybe something like `:cmd must be provided in the map or as a first arg?`
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -2,24 +2,43 @@ (:require [bblgum.impl :as i])) (defn gum - "Main driver fn for using gum: https://github.com/charmbracelet/gum + "Main driver of bblgum. - Options map: - cmd: The interaction command. Can be a keyword. Required - opts: A map of options to be passed as optional params to gum - args: A vec of args to be passed as positional params to gum - in: An input stream than can be passed to gum - as: Coerce the output. Currently supports :bool, :ignored or defaults to a seq of strings - gum-path: Path to the gum binary. Defaults to gum + You can call `gum` like this: + + (gum :command [\"args vector\"] :opt \"value\" :opt2 \"value2\") + + There are several special opts, that are handled by the library: + :in - An input stream than can be passed to gum + :as - Coerce the output. Currently supports :bool, :ignored or defaults to a seq of strings + :gum-path - Path to the gum binary. Defaults to gum + + All other opts are passed to the `gum` CLI. Consult `gum CMD --help` to see available options. + To pass flags like `--directory` use `:directory true`. Always use full names of the options. + + Usage examples + -------------- + Command only: + (gum :file) + + Command with args: + (gum :choose [\"arg\" \"arg2\"]) + + Command with opts: + (gum :file :directory true) + + Command with arguments and options: + (gum :choose [\"arg1\" \"arg2\"] :header \"Choose an option\") Returns a map of: status: The exit code from gum result: The output from the execution: seq of lines or coerced via :as." - [{:keys [cmd opts args in as gum-path]}] - (when-not cmd - (throw (IllegalArgumentException. ":cmd must be provided or non-nil"))) - - (let [gum-path (or gum-path "gum") + [cmd & [args & opts]] + (when-not + (or (keyword? cmd)
wouldnt this fail with the old direct map invocation then? `(gum {...})`
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -30,3 +30,107 @@ str/trim str/split-lines (filter seq)))))) + +(defn gum*
lets call this exec, simplify the docstring.
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -30,3 +30,107 @@ str/trim str/split-lines (filter seq)))))) + +(defn gum* + "Low level API. If you don't know why you are using `gum*` then you're probably looking for `gum` + Options map: + cmd: The interaction command. Can be a keyword. Required + opts: A map of options to be passed as optional params to gum + args: A vec of args to be passed as positional params to gum + in: An input stream than can be passed to gum + as: Coerce the output. Currently supports :bool, :ignored or defaults to a seq of strings + gum-path: Path to the gum binary. Defaults to gum + Returns a map of: + status: The exit code from gum + result: The output from the execution: seq of lines or coerced via :as." + [{:keys [cmd opts args in as gum-path]}] + (when-not cmd + (throw (IllegalArgumentException. ":cmd must be provided or non-nil"))) + (let [gum-path (or gum-path "gum") + with-opts (->> opts + (map (fn [[opt value]] + (str "--" (i/->str opt) "=" (i/multi-opt value)))) + (into [gum-path (i/->str cmd)])) + out (if (= :ignored as) :inherit :string) + args (if (or (empty? args) (= "--" (first args))) + args + (cons "--" args)) + {:keys [exit out]} (i/exec (into with-opts args) in out)] + {:status exit + :result (case as + :bool (zero? exit) + out)})) + +(defn prepare-options [m] + (let [fmted-keys [:opts :in :as :gum-path] + fmted (select-keys m fmted-keys) + opts (apply dissoc m fmted-keys)] + (update fmted :opts merge opts))) + +(defn prepare-cmd-map + "Prepares command map to be passed to `gum*`. Tries to be smart and figure out what user wants." + ([cmd] + (if (map? cmd) + cmd + (prepare-cmd-map cmd [] nil))) + ([cmd args-or-opts] + (if (vector? args-or-opts) + (prepare-cmd-map cmd args-or-opts nil) + (prepare-cmd-map cmd [] args-or-opts))) + ([cmd args & options] + (let [args* (if (vector? args) args []) + foptions (filter some? options) + options* (if (keyword? args) (conj foptions args) foptions)] + (merge {:cmd cmd :args args*} (if (seq options*) (prepare-options (apply hash-map options*)) {}))))) + +(defn gum
this can be in core tbh
bblgum
github_2023
others
3
lispyclouds
lispyclouds
@@ -21,108 +21,103 @@ Add this to your `bb.edn` or `deps.edn`: Sample babashka usage: ```console $ bb -Sdeps '{:deps {io.github.lispyclouds/bblgum {:git/sha "7ebae0e2231899fe2a6ad44bc9ef5fca64099fcd"}}}' \ - -e "(require '[bblgum.core :as b]) (b/gum {:cmd :input :opts {:placeholder \"User name:\"}})" + -e "(require '[bblgum.core :as b]) (b/gum :input :placeholder \"User name:\")" ``` ## Interaction This follows the same [section](https://github.com/charmbracelet/gum#interaction) on the gum repo and all params should work verbatim. Run `gum <cmd> --help` to discover all the params and args. -This lib only has _one_ public fn: `bblgum.core/gum`. This is possibly the tiniest clojure lib!
bit sad about this going away, but will make my peace with it 🙏🏽
basset
github_2023
php
120
Laravel-Backpack
promatik
@@ -67,7 +70,12 @@ public function write(string $path, array $attributes = []): void */ public function assetPath(string $path): string { - $asset = Str::of(asset($path.$this->cachebusting)); + // if path is not a url or it's local url, we will append the cachebusting + if (! Str::startsWith($path, ['http://', 'https://']) || Str::startsWith($path, url(''))) {
```suggestion if (! Str::startsWith($path, ['http://', 'https://', '://']) || Str::startsWith($path, url(''))) { ```
basset
github_2023
php
96
Laravel-Backpack
pxpm
@@ -4,6 +4,9 @@ // development mode, assets will not be internalized 'dev_mode' => env('BASSET_DEV_MODE', env('APP_ENV') === 'local'), + // verify ssl certificate while fetching assets + 'verify_ssl_certificate' => true,
Wasn't the initial intention of this to provide a way of skip the cert. validation in some envs ? In that case I think we need a env variable right ? ```suggestion 'verify_ssl_certificate' => env('BASSET_VERIFY_SSL_CERTIFICATE', true), ```
basset
github_2023
php
96
Laravel-Backpack
pxpm
@@ -512,4 +512,17 @@ public function bassetDirectory(string $asset, string $output): StatusEnum return $this->loader->finish(StatusEnum::INTERNALIZED); } + + /** + * Fetch the content body of an url. + * + * @param string $url + * @return string
```suggestion ```
basset
github_2023
others
85
Laravel-Backpack
pxpm
@@ -1 +1 @@ -@basset('resources/sample.js') \ No newline at end of file +@bassetInstance('resources/sample.js')
shouldn't the directive be @basset ?
basset
github_2023
php
58
Laravel-Backpack
tabacitu
@@ -5,11 +5,11 @@ 'dev_mode' => env('BASSET_DEV_MODE', env('APP_ENV') === 'local'), // disk and path where to store bassets - 'disk' => 'public', + 'disk' => env('BASSET_DISK', 'public'),
Let's document these new .ENV variables please. And ideally also create a section in the README called "How to use on Laravel Vapor"
basset
github_2023
others
72
Laravel-Backpack
pxpm
@@ -220,6 +220,23 @@ But what if your `script.js` file is not only loaded by `card.blade.php`, but al That's where this package comes to the rescue. It will load the asset just ONCE, even if it's loaded from multiple blade files. +## FAQ + +#### Basset is not working, what may be wrong? + +Before making any changes, you can run the command `php artisan basset:check`. It will perform a basic test to initialize, write, and read an asset, giving you better insights into any errors. + +The most common reasons for Basset to fail are: + +1) **Incorrect APP_URL in the `.env` file.** +Ensure that APP_URL in your `.env` matches your server configuration, including the hostname, protocol, and port number. Incorrect settings can lead to asset loading issues. + +2) **Improperly configured disk.** +By default, Basset uses the public disk since its files must be public. For new Laravel projects, the configuration is usually correct. If you're upgrading from an older version, check `config/backpack/basset.php`. Make sure your `config/filesystems.php` public disk looks like: https://github.com/laravel/laravel/blob/10.x/config/filesystems.php#L39-L45.
```suggestion By default, Basset uses the Laravel `public` disk. For new Laravel projects, the configuration is usually correct. If you're upgrading a project and/or changed the `public` disk configuration, it's advised that you change the basset disk in `config/backpack/basset.php` to `basset`. The `basset` disk is a copy of the original Laravel `public` with working configurations. ``` I think we should mention here that changing the disk is the solution if you have changed configurations in your public disk.
basset
github_2023
others
72
Laravel-Backpack
pxpm
@@ -220,6 +220,23 @@ But what if your `script.js` file is not only loaded by `card.blade.php`, but al That's where this package comes to the rescue. It will load the asset just ONCE, even if it's loaded from multiple blade files. +## FAQ + +#### Basset is not working, what may be wrong? + +Before making any changes, you can run the command `php artisan basset:check`. It will perform a basic test to initialize, write, and read an asset, giving you better insights into any errors. + +The most common reasons for Basset to fail are: + +1) **Incorrect APP_URL in the `.env` file.** +Ensure that APP_URL in your `.env` matches your server configuration, including the hostname, protocol, and port number. Incorrect settings can lead to asset loading issues. + +2) **Improperly configured disk.** +By default, Basset uses the public disk since its files must be public. For new Laravel projects, the configuration is usually correct. If you're upgrading from an older version, check `config/backpack/basset.php`. Make sure your `config/filesystems.php` public disk looks like: https://github.com/laravel/laravel/blob/10.x/config/filesystems.php#L39-L45. + +3) **Missing or broken storage symlink.** +If you use the default disk, Basset requires the `php artisan storage:link` command to work properly. During installation, Basset attempts to create the symlink. If it fails, manually create it with `php artisan storage:link`. If you encounter issues (e.g., after moving the project), recreating the symlink should resolve them.
```suggestion 3) **Missing or broken storage symlink.** If you use the default `public` disk, Basset requires that the symlink between the storage and the public accessible folder to be created with `php artisan storage:link` command. During installation, Basset attempts to create the symlink. If it fails, you will need to manually create it with `php artisan storage:link`. If you encounter issues (e.g., after moving the project), recreating the symlink should resolve them. Note for Homestead users: the symlink can't be created inside the virtual machine. You should stop your instance with: `vagrant down`, create the symlink in your local application folder and then `vagrant up` to bring the system back up. ```
basset
github_2023
php
72
Laravel-Backpack
pxpm
@@ -0,0 +1,147 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Backpack\Basset\BassetManager; +use Backpack\Basset\Enums\StatusEnum; +use Exception; +use Illuminate\Console\Command; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Http; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetCheck extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:check + {--installing} : Does this call comes from installing command.'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Check Backpack Basset installation.'; + + private string $filepath; + private BassetManager $basset; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $message = ''; + if (! $this->option('installing')) { + $this->components->info('Checking Backpack Basset installation'); + } + + try { + // init check + $message = 'Initializing basset check'; + $this->init(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // checking storage + $message = 'Checking cache storage'; + $this->testCache(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // fetching a basset + $message = 'Fetching a basset'; + $this->testFetch(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>');
```suggestion if (! $this->option('installing')) { $this->components->info('Checking Backpack Basset installation'); } try { // init check $this->init(); $this->components->twoColumnDetail('Initializing basset check', '<fg=green;options=bold>DONE</>'); // checking storage $this->testCache(); $this->components->twoColumnDetail('Checking cache storage', '<fg=green;options=bold>DONE</>'); // fetching a basset $this->testFetch(); $this->components->twoColumnDetail('Fetching a basset', '<fg=green;options=bold>DONE</>'); ```
basset
github_2023
php
72
Laravel-Backpack
pxpm
@@ -0,0 +1,147 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Backpack\Basset\BassetManager; +use Backpack\Basset\Enums\StatusEnum; +use Exception; +use Illuminate\Console\Command; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Http; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetCheck extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:check + {--installing} : Does this call comes from installing command.'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Check Backpack Basset installation.'; + + private string $filepath; + private BassetManager $basset; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $message = ''; + if (! $this->option('installing')) { + $this->components->info('Checking Backpack Basset installation'); + } + + try { + // init check + $message = 'Initializing basset check'; + $this->init(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // checking storage + $message = 'Checking cache storage'; + $this->testCache(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // fetching a basset + $message = 'Fetching a basset'; + $this->testFetch(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // clear temporary file + File::delete($this->filepath); + } catch (Exception $e) { + $this->components->twoColumnDetail($message, '<fg=red;options=bold>ERROR</>'); + $this->newLine(); + $this->components->error($e->getMessage()); + $this->line(' <fg=gray>│ Backpack Basset failed to check it\'s working properly.</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ This may be due to multiple issues. Please ensure:</>'); + $this->line(' <fg=gray>│ 1) APP_URL is correctly set in the <fg=white>.env</> file.</>'); + $this->line(' <fg=gray>│ 2) Your server is running and accessible at <fg=white>'.url('').'</>.</>'); + $this->line(' <fg=gray>│ 3) Your disk is properly configured in <fg=white>config/filesystems.php</>.</>');
```suggestion $this->line(' <fg=gray>│ 3) The <fg=white>'.config('backpack.basset.disk').'</> disk is properly configured in <fg=white>config/filesystems.php</>.</>'); ```
basset
github_2023
php
72
Laravel-Backpack
pxpm
@@ -0,0 +1,147 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Backpack\Basset\BassetManager; +use Backpack\Basset\Enums\StatusEnum; +use Exception; +use Illuminate\Console\Command; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Http; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetCheck extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:check + {--installing} : Does this call comes from installing command.'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Check Backpack Basset installation.'; + + private string $filepath; + private BassetManager $basset; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $message = ''; + if (! $this->option('installing')) { + $this->components->info('Checking Backpack Basset installation'); + } + + try { + // init check + $message = 'Initializing basset check'; + $this->init(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // checking storage + $message = 'Checking cache storage'; + $this->testCache(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // fetching a basset + $message = 'Fetching a basset'; + $this->testFetch(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // clear temporary file + File::delete($this->filepath); + } catch (Exception $e) { + $this->components->twoColumnDetail($message, '<fg=red;options=bold>ERROR</>'); + $this->newLine(); + $this->components->error($e->getMessage()); + $this->line(' <fg=gray>│ Backpack Basset failed to check it\'s working properly.</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ This may be due to multiple issues. Please ensure:</>'); + $this->line(' <fg=gray>│ 1) APP_URL is correctly set in the <fg=white>.env</> file.</>'); + $this->line(' <fg=gray>│ 2) Your server is running and accessible at <fg=white>'.url('').'</>.</>'); + $this->line(' <fg=gray>│ 3) Your disk is properly configured in <fg=white>config/filesystems.php</>.</>'); + $this->line(' <fg=gray>│ 4) The storage symlink exists and is valid (public/storage).</>');
```suggestion $this->line(' <fg=gray>│ 4) The storage symlink exists and is valid (by default: public/storage).</>'); ```
basset
github_2023
php
72
Laravel-Backpack
pxpm
@@ -0,0 +1,147 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Backpack\Basset\BassetManager; +use Backpack\Basset\Enums\StatusEnum; +use Exception; +use Illuminate\Console\Command; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Http; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetCheck extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:check + {--installing} : Does this call comes from installing command.'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Check Backpack Basset installation.'; + + private string $filepath; + private BassetManager $basset; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $message = ''; + if (! $this->option('installing')) { + $this->components->info('Checking Backpack Basset installation'); + } + + try { + // init check + $message = 'Initializing basset check'; + $this->init(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // checking storage + $message = 'Checking cache storage'; + $this->testCache(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // fetching a basset + $message = 'Fetching a basset'; + $this->testFetch(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // clear temporary file + File::delete($this->filepath); + } catch (Exception $e) { + $this->components->twoColumnDetail($message, '<fg=red;options=bold>ERROR</>'); + $this->newLine(); + $this->components->error($e->getMessage()); + $this->line(' <fg=gray>│ Backpack Basset failed to check it\'s working properly.</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ This may be due to multiple issues. Please ensure:</>'); + $this->line(' <fg=gray>│ 1) APP_URL is correctly set in the <fg=white>.env</> file.</>'); + $this->line(' <fg=gray>│ 2) Your server is running and accessible at <fg=white>'.url('').'</>.</>'); + $this->line(' <fg=gray>│ 3) Your disk is properly configured in <fg=white>config/filesystems.php</>.</>'); + $this->line(' <fg=gray>│ 4) The storage symlink exists and is valid (public/storage).</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ For more information and solutions, please visit the Backpack Basset FAQ at:</>'); + $this->line(' <fg=gray>│ https://github.com/laravel-backpack/basset#faq</>'); + $this->newLine(); + exit(1); + } + + if (! $this->option('installing')) { + $this->newLine(); + } + } + + /** + * Initialize the test. + * + * @return void + */ + private function init(): void + { + $this->basset = app('basset'); + + // create a local temporary file + $path = storage_path('app/tmp/'); + $file = 'backpack-test.js'; + $this->filepath = $path.$file; + + File::ensureDirectoryExists($path); + File::put($this->filepath, 'test'); + + if (! File::exists($this->filepath)) { + throw new Exception('Error accessing the filesystem, the check can not run.'); + } + } + + /** + * Test cache the asset. + * + * @return void + */ + private function testCache(): void + { + // cache it with basset + $result = $this->basset->basset($this->filepath, false); + + if (! in_array($result, [StatusEnum::INTERNALIZED, StatusEnum::IN_CACHE])) { + throw new Exception('Error caching the file.'); + } + } + + /** + * Test fetch the asset with Http. + * + * @return void + */ + private function testFetch(): void + { + // cache it with basset + $url = $this->basset->getUrl($this->filepath); + + if (! str_contains($url, '://')) {
Something is triggering my spidey sense here ... when would `getUrl()` don't return a url ?
basset
github_2023
php
72
Laravel-Backpack
pxpm
@@ -0,0 +1,147 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Backpack\Basset\BassetManager; +use Backpack\Basset\Enums\StatusEnum; +use Exception; +use Illuminate\Console\Command; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Http; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetCheck extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:check + {--installing} : Does this call comes from installing command.'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Check Backpack Basset installation.'; + + private string $filepath; + private BassetManager $basset; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $message = ''; + if (! $this->option('installing')) { + $this->components->info('Checking Backpack Basset installation'); + } + + try { + // init check + $message = 'Initializing basset check'; + $this->init(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // checking storage + $message = 'Checking cache storage'; + $this->testCache(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // fetching a basset + $message = 'Fetching a basset'; + $this->testFetch(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // clear temporary file + File::delete($this->filepath); + } catch (Exception $e) { + $this->components->twoColumnDetail($message, '<fg=red;options=bold>ERROR</>'); + $this->newLine(); + $this->components->error($e->getMessage()); + $this->line(' <fg=gray>│ Backpack Basset failed to check it\'s working properly.</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ This may be due to multiple issues. Please ensure:</>'); + $this->line(' <fg=gray>│ 1) APP_URL is correctly set in the <fg=white>.env</> file.</>'); + $this->line(' <fg=gray>│ 2) Your server is running and accessible at <fg=white>'.url('').'</>.</>'); + $this->line(' <fg=gray>│ 3) Your disk is properly configured in <fg=white>config/filesystems.php</>.</>'); + $this->line(' <fg=gray>│ 4) The storage symlink exists and is valid (public/storage).</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ For more information and solutions, please visit the Backpack Basset FAQ at:</>'); + $this->line(' <fg=gray>│ https://github.com/laravel-backpack/basset#faq</>'); + $this->newLine(); + exit(1); + } + + if (! $this->option('installing')) { + $this->newLine(); + } + } + + /** + * Initialize the test. + * + * @return void + */ + private function init(): void + { + $this->basset = app('basset'); + + // create a local temporary file + $path = storage_path('app/tmp/');
I am thinking if we really should create the file, or use an already existing file in backpack core, like `common.js`. Why ? I don't want the "check" to fail if it's not able to create a dummy file. That's not what we are testing here, and I really don't care if user is able to create a file in a random directory or not. I just want to know if basset is able to internalize a file in a configured disk, and get the file url to display. What you think ? Am I dreaming here or does it make sense ?
basset
github_2023
php
72
Laravel-Backpack
pxpm
@@ -0,0 +1,141 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Backpack\Basset\BassetManager; +use Backpack\Basset\Enums\StatusEnum; +use Exception; +use Illuminate\Console\Command; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Http; +use Illuminate\Support\Str; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetCheck extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:check + {--installing} : Does this call comes from installing command.'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Check Backpack Basset installation.'; + + private string $filepath; + private BassetManager $basset; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $message = ''; + if (! $this->option('installing')) { + $this->components->info('Checking Backpack Basset installation'); + } + + try { + // init check + $message = 'Initializing basset check'; + $this->init(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // checking storage + $message = 'Checking cache storage'; + $this->testCache(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + + // fetching a basset + $message = 'Fetching a basset'; + $this->testFetch(); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + } catch (Exception $e) { + $this->components->twoColumnDetail($message, '<fg=red;options=bold>ERROR</>'); + $this->newLine(); + $this->components->error($e->getMessage()); + $this->line(' <fg=gray>│ Backpack Basset failed to check it\'s working properly.</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ This may be due to multiple issues. Please ensure:</>'); + $this->line(' <fg=gray>│ 1) APP_URL is correctly set in the <fg=white>.env</> file.</>'); + $this->line(' <fg=gray>│ 2) Your server is running and accessible at <fg=white>'.url('').'</>.</>'); + $this->line(' <fg=gray>│ 3) The <fg=white>'.config('backpack.basset.disk').'</> disk is properly configured in <fg=white>config/filesystems.php</>.</>'); + $this->line(' <fg=gray>│ Optionally, basset provides a disk named "basset", you can use it instead.</>'); + $this->line(' <fg=gray>│ 4) The storage symlink exists and is valid (by default: public/storage).</>'); + $this->line(' <fg=gray>│</>'); + $this->line(' <fg=gray>│ For more information and solutions, please visit the Backpack Basset FAQ at:</>'); + $this->line(' <fg=gray>│ https://github.com/laravel-backpack/basset#faq</>');
```suggestion $this->line(' <fg=gray>│ <fg=white>https://github.com/laravel-backpack/basset#faq</></>'); ```
basset
github_2023
php
72
Laravel-Backpack
tabacitu
@@ -160,6 +164,29 @@ public function terminate(): void $basset->cacheMap->save(); } + /** + * Loads needed basset disks. + * + * @return void + */ + public function loadDisk(): void
I thought we talked about adding the disk only if `config('backpack.basset.disk') == 'basset'`. Did we forget or decide against that?
basset
github_2023
php
72
Laravel-Backpack
pxpm
@@ -160,6 +164,29 @@ public function terminate(): void $basset->cacheMap->save(); } + /** + * Loads needed basset disks. + * + * @return void + */ + public function loadDisk(): void + { + // ignore if the disk exists + if (app()->config['filesystems.disks.basset']) {
```suggestion if (app()->config['filesystems.disks.basset'] || app()->config['backpack.basset.disk'] !== 'basset') { ```
basset
github_2023
php
72
Laravel-Backpack
tabacitu
@@ -160,6 +164,29 @@ public function terminate(): void $basset->cacheMap->save(); } + /** + * Loads needed basset disks. + * + * @return void + */ + public function loadDisk(): void + { + // ignore if the disk exists + if (app()->config['filesystems.disks.basset'] || app()->config['backpack.basset.disk'] !== 'basset') { + return; + }
```suggestion // if the basset disk already exists, don't override it if (app()->config['filesystems.disks.basset']) { return; } // if the basset disk isn't being used at all, don't even bother to add it if (app()->config['backpack.basset.disk'] !== 'basset') { return; } ```
basset
github_2023
php
74
Laravel-Backpack
tabacitu
@@ -161,6 +164,23 @@ public function terminate(): void $basset->cacheMap->save(); } + /** + * Loads needed basset disks. + * + * @return void + */ + public function loadDisks(): void
```suggestion public function loadDisk(): void ```
basset
github_2023
php
74
Laravel-Backpack
tabacitu
@@ -36,6 +36,9 @@ public function boot(): void $this->bootForConsole(); } + // Load basset disk + $this->loadDisks(); +
Can we only do this if the config is set to use the "basset" disk?
basset
github_2023
php
74
Laravel-Backpack
tabacitu
@@ -161,6 +164,23 @@ public function terminate(): void $basset->cacheMap->save(); } + /** + * Loads needed basset disks. + * + * @return void + */ + public function loadDisks(): void + { + // add the basset disk to filesystem configuration + app()->config['filesystems.disks.basset'] = [ + 'driver' => 'local', + 'root' => storage_path('app/public'), + 'url' => '/storage', + 'visibility' => 'public', + 'throw' => false, + ];
What happens if someone already has a disk named `basset`?
basset
github_2023
others
74
Laravel-Backpack
pxpm
@@ -232,7 +232,8 @@ The most common reasons for Basset to fail are: Ensure that APP_URL in your `.env` matches your server configuration, including the hostname, protocol, and port number. Incorrect settings can lead to asset loading issues. 2) **Improperly configured disk.** -By default, Basset uses the public disk since its files must be public. For new Laravel projects, the configuration is usually correct. If you're upgrading from an older version, check `config/backpack/basset.php`. Make sure your `config/filesystems.php` public disk looks like: https://github.com/laravel/laravel/blob/10.x/config/filesystems.php#L39-L45. +By default, Basset uses the public disk since its files must be public. For new Laravel projects, the configuration is usually correct. If you're upgrading from an older version, check `config/backpack/basset.php`. Make sure your `config/filesystems.php` public disk looks like: https://github.com/laravel/laravel/blob/10.x/config/filesystems.php#L39-L45. +If you prefer not to change your public disk, you can create your own disk and set it in the Basset config, or you can use the provided disk named `basset` by setting it in the `config/backpack/basset.php`.
I already added a comment in the other PR regarding this, maybe we remove this from this PR and make the full readme change in the `check-command` branch.
basset
github_2023
others
73
Laravel-Backpack
pxpm
@@ -16,7 +16,7 @@ "analyse": "./vendor/bin/phpstan analyse --level 5 src" }, "require": { - "laravel/framework": "^10.1|^9.0", + "laravel/framework": "^10.1",
AFAIK the pipe functionality we use here was added in L10.7 https://github.com/laravel/framework/commit/58269047e7a39d4a5f157b645205666c689e0ce5
basset
github_2023
php
57
Laravel-Backpack
promatik
@@ -5,11 +5,11 @@ 'dev_mode' => env('BASSET_DEV_MODE', env('APP_ENV') === 'local'), // disk and path where to store bassets - 'disk' => 'public', + 'disk' => env('BASSET_DISK')??'public',
```suggestion 'disk' => env('BASSET_DISK', 'public'), ```
basset
github_2023
php
57
Laravel-Backpack
promatik
@@ -5,11 +5,11 @@ 'dev_mode' => env('BASSET_DEV_MODE', env('APP_ENV') === 'local'), // disk and path where to store bassets - 'disk' => 'public', + 'disk' => env('BASSET_DISK')??'public', 'path' => 'basset', // use cache map file (.basset) - 'cache_map' => true, + 'cache_map' => env('BASSET_CACHE_MAP')??true,
```suggestion 'cache_map' => env('BASSET_CACHE_MAP', true), ```
basset
github_2023
others
53
Laravel-Backpack
tabacitu
@@ -32,8 +32,11 @@ composer require backpack/basset php artisan basset:install ``` -> **Note** -> By default Basset relies on the public disk, you may change it if you want to, but if you stick to the defaults, make sure your disk is properly setup on `config/filsystems.php`, make sure it [looks like the default one](https://github.com/laravel/laravel/blob/10.x/config/filesystems.php#L39-L45). +#### Storage Symlink +The installation command will create the storage symlink in your system and it will also add the command to `composer.json` file, which will most probably make it work on your development/staging/production servers. If that's not the case, make sure you create the links manually wherever you need them, with the command `php artisan storage:link`. + +#### Disk +By default Basset relies on the public disk, you may change it if you want to, but if you stick to the defaults, make sure your disk is properly setup on `config/filsystems.php`, make sure it [looks like the default one](https://github.com/laravel/laravel/blob/10.x/config/filesystems.php#L39-L45).
```suggestion #### Storage Symlink Basset uses the `public` disk to store cached assets in a directory that is publicly-accesible. So it needs you to run `php artisan storage:link` to create the symlink. The installation command will create ask to run that, and to add that command to your `composer.json`. That will most likely make it work on your development/staging/production servers. If that's not the case, make sure you create the links manually wherever you need them, with the command `php artisan storage:link`. #### Disk By default Basset uses the `public` disk. If you're having trouble with the assets not showing up on page, you might have an old Laravel configuration for it. Please make sure your disk is properly setup on `config/filsystems.php` - it should look like [the default one](https://github.com/laravel/laravel/blob/10.x/config/filesystems.php#L39-L45). ```
basset
github_2023
php
51
Laravel-Backpack
tabacitu
@@ -0,0 +1,90 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Illuminate\Console\Command; +use Illuminate\Support\Str; +use Symfony\Component\Process\Process; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetInstall extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:install'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Install Backpack Basset.'; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $this->components->info('Installing Basset'); + + // create symlink + $this->createSymLink(); + + // check if artisan storage:link command exists + $this->addComposerCommand(); + + $this->newLine(); + $this->info(' Done'); + } + + /** + * Create symlink logic. + * + * @return void + */ + private function createSymLink(): void + { + $message = 'Creating symlink'; + + if (file_exists(public_path('storage'))) { + $this->components->twoColumnDetail($message, '<fg=yellow;options=bold>SKIPPING</>');
I think this provides a little more clarity as to WHY the directory wasn't created: ```suggestion $this->components->twoColumnDetail($message, '<fg=yellow;options=bold>ALREADY EXISTED</>'); ```
basset
github_2023
php
51
Laravel-Backpack
tabacitu
@@ -0,0 +1,90 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Illuminate\Console\Command; +use Illuminate\Support\Str; +use Symfony\Component\Process\Process; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetInstall extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:install'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Install Backpack Basset.'; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $this->components->info('Installing Basset'); + + // create symlink + $this->createSymLink(); + + // check if artisan storage:link command exists + $this->addComposerCommand(); + + $this->newLine(); + $this->info(' Done'); + } + + /** + * Create symlink logic. + * + * @return void + */ + private function createSymLink(): void + { + $message = 'Creating symlink'; + + if (file_exists(public_path('storage'))) { + $this->components->twoColumnDetail($message, '<fg=yellow;options=bold>SKIPPING</>'); + + return; + } + + $this->call('storage:link'); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + } + + /** + * Add storage:link command to composer logic. + * + * @return void + */ + private function addComposerCommand(): void + { + $message = 'Adding storage:link command to composer'; + + if (Str::of(file_get_contents('composer.json'))->contains('php artisan storage:link')) { + $this->components->twoColumnDetail($message, '<fg=yellow;options=bold>SKIPPING</>'); + + return; + } + + if ($this->components->confirm('Do you wish to add symlink creation command to composer.json post install script?', true)) { + $this->components->task($message, function () { + $process = new Process(['composer', 'config', 'scripts.post-install-cmd.-1', 'php artisan storage:link']);
Ooooh this is so elegant! 👏👏👏
basset
github_2023
php
51
Laravel-Backpack
tabacitu
@@ -0,0 +1,90 @@ +<?php + +namespace Backpack\Basset\Console\Commands; + +use Illuminate\Console\Command; +use Illuminate\Support\Str; +use Symfony\Component\Process\Process; + +/** + * Basset Cache command. + * + * @property object $output + */ +class BassetInstall extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'basset:install'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Install Backpack Basset.'; + + /** + * Execute the console command. + * + * @return void + */ + public function handle(): void + { + $this->components->info('Installing Basset'); + + // create symlink + $this->createSymLink(); + + // check if artisan storage:link command exists + $this->addComposerCommand(); + + $this->newLine(); + $this->info(' Done'); + } + + /** + * Create symlink logic. + * + * @return void + */ + private function createSymLink(): void + { + $message = 'Creating symlink'; + + if (file_exists(public_path('storage'))) { + $this->components->twoColumnDetail($message, '<fg=yellow;options=bold>SKIPPING</>'); + + return; + } + + $this->call('storage:link'); + $this->components->twoColumnDetail($message, '<fg=green;options=bold>DONE</>'); + } + + /** + * Add storage:link command to composer logic. + * + * @return void + */ + private function addComposerCommand(): void + { + $message = 'Adding storage:link command to composer'; + + if (Str::of(file_get_contents('composer.json'))->contains('php artisan storage:link')) { + $this->components->twoColumnDetail($message, '<fg=yellow;options=bold>SKIPPING</>'); + + return; + } + + if ($this->components->confirm('Do you wish to add symlink creation command to composer.json post install script?', true)) {
```suggestion if ($this->components->confirm('You will need to run `php artisan storage:link` on every server you deploy the app to. Do you wish to add that command to composer.json' post-install-script, to make that automatic?', true)) { ```
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -0,0 +1,113 @@ +<?php + +namespace Backpack\Basset\Helpers; + +use Illuminate\Support\Facades\File; +use PharData; +use ZipArchive; + +class Unarchiver +{ + /** + * Unarchive files. + * + * @param string $file source file + * @param string $output output destination + * @return bool result + */ + public function unarchiveFile(string $file, string $output): bool + { + $mimeType = File::mimeType($file); + + switch ($mimeType) { + // zip + case 'application/zip': + return $this->unarchiveZip($file, $output); + + // tar.gz + case 'application/gzip': + case 'application/x-gzip': + case 'application/bzip2': + case 'application/x-bzip2': + return $this->unarchiveGz($file, $output); + + // tar + case 'application/x-tar': + return $this->unarchiveTar($file, $output); + } + + return false; + } + + /** + * Unarchive zip files. + * + * @param string $file source file + * @param string $output output destination + * @return bool result + */ + private function unarchiveZip(string $file, string $output): bool + { + $zip = new ZipArchive(); + $zip->open($file); + $result = $zip->extractTo($output); + $zip->close(); + + return $result; + } + + /** + * Unarchive gz files. + * + * @param string $file source file + * @param string $output output destination + * @return bool result + */ + private function unarchiveGz(string $file, string $output): bool + { + $phar = new PharData($file); + $tar = $phar->decompress()->getPath(); + + $result = $this->unarchiveTar($tar, $output); + unlink($tar); + + return $result; + } + + /** + * Unarchive tar files. + * + * @param string $file source file + * @param string $output output destination + * @return bool result + */ + private function unarchiveTar(string $file, string $output): bool + { + $phar = new PharData($file); + + return $phar->extractTo($output); + } + + /** + * Returns a temporary file path. + * + * @return string + */ + public function getTemporaryFilePath(): string + { + return tempnam(sys_get_temp_dir(), ''); + } + + /** + * Returns a temporary directory path. + * + * @return string + */ + public function getTemporaryDirectoryPath(): string + { + $dir = storage_path('app/tmp/'.mt_rand().'/'); + File::ensureDirectoryExists($dir); + + return $dir; + }
Let's move this to the top of the file. It's easier to "read" a class if you start with `public` methods, then `private`. I also find it easier to read if you start with getters, then setters/doers.
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -0,0 +1,74 @@ +<?php + +namespace Backpack\Basset\Helpers; + +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Storage; + +class CacheMap +{ + private $map = []; + private $path; + private $active = false; + private $dirty = false;
Maybe we add a verb here to make the call more fluent? I think I like `cachemap->isDirty` more than `cachemap->dirty()`, how about you? ```suggestion private $isActive = false; private $isDirty = false; ```
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -0,0 +1,74 @@ +<?php + +namespace Backpack\Basset\Helpers; + +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Storage; + +class CacheMap +{ + private $map = []; + private $path; + private $active = false; + private $dirty = false; + + public function __construct() + { + $this->active = config('backpack.basset.cache_map', false); + $this->path = Storage::disk(config('backpack.basset.disk'))->path('.basset'); + + if (! $this->active) { + return; + } + + // Load map + $this->map = File::exists($this->path) ? json_decode(File::get($this->path), true) : []; + } + + /** + * Saves the cache map to the .basset file. + * + * @return void + */ + public function save(): void + { + if (! $this->dirty || ! $this->active) { + return; + } + + // save file + File::put($this->path, json_encode($this->map, JSON_PRETTY_PRINT)); + } + + /** + * Adds an asset to the cache map. + * + * @param string $asset + * @param string $path + * @return void + */ + public function add(string $asset, string|bool $path = true): void
Hmm... I don't think `$cacheMap->add()` is very expressive... In previous PRs I was suggesting we remove the `asset` from the function name, because the `asset` was already present in the class name, but in this case, when you write `$cacheMap->add()`... I don't think it's very clear what you're adding... This is nitpicking of course but I think it'd read more clearly if it were: ```suggestion public function addAsset(string $asset, string|bool $path = true): void ```
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -0,0 +1,74 @@ +<?php + +namespace Backpack\Basset\Helpers; + +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Storage; + +class CacheMap +{ + private $map = []; + private $path; + private $active = false; + private $dirty = false; + + public function __construct() + { + $this->active = config('backpack.basset.cache_map', false); + $this->path = Storage::disk(config('backpack.basset.disk'))->path('.basset'); + + if (! $this->active) { + return; + } + + // Load map + $this->map = File::exists($this->path) ? json_decode(File::get($this->path), true) : []; + } + + /** + * Saves the cache map to the .basset file. + * + * @return void + */ + public function save(): void + { + if (! $this->dirty || ! $this->active) { + return; + } + + // save file + File::put($this->path, json_encode($this->map, JSON_PRETTY_PRINT)); + } + + /** + * Adds an asset to the cache map. + * + * @param string $asset + * @param string $path + * @return void + */ + public function add(string $asset, string|bool $path = true): void + { + if (! $this->active) { + return; + } + + $this->map[$asset] = $path; + $this->dirty = true; + } + + /** + * Gets the asset url from map. + * + * @param string $asset + * @return string | false + */ + public function get(string $asset): string|false
Similarly: ```suggestion public function getAsset(string $asset): string|false ```
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -42,6 +42,7 @@ public function handle(): void $disk->deleteDirectory($path); $disk->makeDirectory($path); + $disk->delete('.basset');
So this is something I wanted to talk to you about... Should we use the _singular_ name everywhere in the file paths... OR the _plural_? 👀 🤷‍♂️ Would it make more sense to be: - `storage/app/public/basset` (or) - `storage/app/public/bassets` I mean... are we storing - "_things that Basset uses_" (or) - "_backed up assets (aka bassets)_" Which one sounds more intuitive to you?
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -30,6 +36,10 @@ public function __construct() $this->cachebusting = $cachebusting ? (string) Str::of($cachebusting)->start('?') : ''; $this->basePath = (string) Str::of(config('backpack.basset.path'))->finish('/'); + $this->cacheMap = new CacheMap(); + $this->loading = new LoadingTime();
Hmm I found this a bit weird... "loading" is not a noun so it's weird to do stuff to it, right? 😀 ```suggestion $this->loader = new LoadingTime(); ```
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -153,29 +163,39 @@ public function getUrl(string $asset): string */ public function basset(string $asset, bool|string $output = true, array $attributes = []): StatusEnum { + $this->loading->start();
Yup, there we go... this is a bit weird, right? Wouldn't it make more sense as: ```suggestion $this->loader->start(); ```
basset
github_2023
php
27
Laravel-Backpack
tabacitu
@@ -0,0 +1,77 @@ +<?php + +namespace Backpack\Basset\Helpers; + +use Illuminate\Filesystem\FilesystemAdapter; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Storage; + +class CacheMap +{ + private $map = []; + private $path; + private $isActive = false; + private $isDirty = false; + + public function __construct() + { + $this->isActive = config('backpack.basset.cache_map', false); + if (! $this->isActive) { + return; + } + + /** @var FilesystemAdapter */ + $disk = Storage::disk(config('backpack.basset.disk')); + $this->path = $disk->path('.basset'); + + // Load map + $this->map = File::exists($this->path) ? json_decode(File::get($this->path), true) : []; + } + + /** + * Saves the cache map to the .basset file. + * + * @return void + */ + public function save(): void + { + if (! $this->isDirty || ! $this->isActive) { + return; + } + + // save file + File::put($this->path, json_encode($this->map, JSON_PRETTY_PRINT)); + } + + /** + * Adds an asset to the cache map. + * + * @param string $asset + * @param string $path + * @return void + */ + public function addAsset(string $asset, string|bool $path = true): void
I notice the assets get their ABSOLUTE paths added: <img width="1512" alt="CleanShot 2023-04-21 at 11 45 54@2x" src="https://user-images.githubusercontent.com/1032474/233590288-d07e40ad-0b54-4d21-88a5-f0479c2f6a1b.png"> Doesn't this mean that... if something changes, like the protocol (HTTP/HTTPS) or app name (unlikely)... the whole bassets cache file is useless? Is that a real problem... or not? 🤷‍♂️ I'm genuinely asking.
basset
github_2023
php
23
Laravel-Backpack
tabacitu
@@ -1,6 +1,9 @@ <?php return [ + // development mode, assets will not be internalized + 'dev_mode' => false,
We should probably have an ENV variable for this. That way, most devs wouldn't need to publish the config file at all. Do you have a better name than this? ```suggestion 'dev_mode' => env('BASSET_DEV_MODE', false), ```
lume
github_2023
others
232
lumehq
yukibtc
@@ -449,7 +449,8 @@ pub async fn publish( // Create unsigned event let unsigned_event = match difficulty { - Some(num) => EventBuilder::text_note(content, tags).to_unsigned_pow_event(public_key, num), + Some(num) => EventBuilder::pow(EventBuilder::text_note(content, tags), num) + .to_unsigned_event(public_key),
You can rewrite this to: ```rust EventBuilder::text_note(content, tags).pow(num).to_unsigned_event(public_key) ``` (so is more readable)
lume
github_2023
others
232
lumehq
yukibtc
@@ -382,7 +382,7 @@ pub async fn copy_friend(npub: &str, state: State<'_, Nostr>) -> Result<bool, St .await { for event in contact_list_events.into_iter() { - for tag in event.into_iter_tags() { + for tag in event.tags {
It's not mandatory but if you call `iter` or `into_iter` on a list/collection, it will be faster.
lume
github_2023
others
202
lumehq
reyamir
@@ -469,11 +469,13 @@ pub async fn zap_event( #[tauri::command] #[specta::specta] pub async fn get_following( - client: &Client, - public_key: &PublicKey, + state: State<'_, Nostr>, + public_key: &str, timeout: Option<std::time::Duration>, ) -> Result<Vec<String>, String> { - let filter = Filter::new().kind(Kind::ContactList).author(*public_key); + let client = &state.client; + let public_key = PublicKey::from_str(public_key).unwrap();
I think we should have a simple validate for pubkey, because whole app will crash if pubkey is not valid here
lume
github_2023
others
166
lumehq
yukibtc
@@ -0,0 +1,147 @@ +use crate::Nostr; +use nostr_sdk::prelude::*; +use std::{str::FromStr, time::Duration}; +use tauri::State; + +#[tauri::command(async)] +pub async fn get_event(id: &str, nostr: State<'_, Nostr>) -> Result<String, ()> { + let client = &nostr.client; + let event_id; + + if id.starts_with("note1") { + event_id = EventId::from_bech32(id).unwrap(); + } else if id.starts_with("nevent1") { + event_id = EventId::from_bech32(id).unwrap(); + } else if id.starts_with("naddr1") { + event_id = EventId::from_bech32(id).unwrap(); + } else { + event_id = EventId::from_hex(id).unwrap(); + }
The event ID has "note" as bech32 prefix, the "nevent" is for events and "naddr" for coordinates. Try to use this: ```rust let event_id: EventId = match Nip19::from_bech32(..) { Ok(val) => match val { Nip19::EventId(id) => id, Nip19::Event(e) => e.event_id, _ => // return error }, Err(_) => EventId::from_hex(..)? } ``` The coordinate (naddr) not contains an event ID. If you prefer to use `starts_with(..)`, remove the "naddr" and replace `EventId` with `Nip19Event` in the "nevent" block condition.
lume
github_2023
others
166
lumehq
yukibtc
@@ -4,35 +4,73 @@ )] pub mod commands; +pub mod nostr; +use age::secrecy::ExposeSecret; +use keyring::Entry; +use nostr_sdk::prelude::*; +use tauri::Manager; use tauri_plugin_autostart::MacosLauncher; -use tauri_plugin_sql::{Migration, MigrationKind}; -use tauri_plugin_theme::ThemePlugin; +use tokio::sync::Mutex; + +pub struct Nostr { + client: Mutex<Client>,
Is the `Mutex` required for `tauri`? Or another specific feature? Because the `Client` has no mutable method (to be compatible by default with multi-threaded env, so not require to be wrapped in `Arc` and/or `Mutex`), so if you not need to completely replace it (or something else that I missed), the `Mutex` isn't needed. ```rust pub struct Nostr { client: Client, contact_list: Mutex<Option<Vec<PublicKey>>>, } ```
lume
github_2023
typescript
167
lumehq
reyamir
@@ -3,6 +3,7 @@ export const FETCH_LIMIT = 20; export const LANGUAGES = [ { label: "English", code: "en" }, { label: "Japanese", code: "ja" }, + { label: "French", code: "fr" },
`Français` seems better for recognize
org-timeblock
github_2023
others
20
ichernyshovvv
alphapapa
@@ -1413,6 +1415,30 @@ When called from Lisp, DATE should be a date as returned by (ot-show-context) (recenter)))) +(defun ot-clock-in () + "Jump to the org heading of selected timeblock."
The docstring needs to be updated to match what the command does. :)
org-timeblock
github_2023
others
20
ichernyshovvv
alphapapa
@@ -1413,6 +1415,30 @@ When called from Lisp, DATE should be a date as returned by (ot-show-context) (recenter)))) +(defun ot-clock-in () + "Jump to the org heading of selected timeblock." + (interactive) + (unless (eq major-mode 'org-timeblock-mode) + (user-error "Not in *org-timeblock* buffer")) + (goto-char (point-min))
Probably `save-excursion` should be used around the body of the function.
org-timeblock
github_2023
others
20
ichernyshovvv
alphapapa
@@ -1413,6 +1415,30 @@ When called from Lisp, DATE should be a date as returned by (ot-show-context) (recenter)))) +(defun ot-clock-in () + "Jump to the org heading of selected timeblock." + (interactive) + (unless (eq major-mode 'org-timeblock-mode) + (user-error "Not in *org-timeblock* buffer")) + (goto-char (point-min)) + (search-forward "</rect>" nil t)
Generally, searching for XML with a regexp seems like something to be avoided. If possible, text-properties should be used instead, to mark the boundaries of entries. (Maybe that would be out-of-scope for this PR, but something to consider.)
org-timeblock
github_2023
others
20
ichernyshovvv
alphapapa
@@ -1413,6 +1415,30 @@ When called from Lisp, DATE should be a date as returned by (ot-show-context) (recenter)))) +(defun ot-clock-in () + "Jump to the org heading of selected timeblock." + (interactive) + (unless (eq major-mode 'org-timeblock-mode) + (user-error "Not in *org-timeblock* buffer")) + (goto-char (point-min)) + (search-forward "</rect>" nil t) + (when (re-search-forward (format "<rect .*? id=\"\\([^\"]+\\)\" fill=\"%s\"" ot-sel-block-color) nil t)
It would be good to use `rx-to-string` instead of a raw string and `format` here.
org-timeblock
github_2023
others
20
ichernyshovvv
alphapapa
@@ -1413,6 +1415,30 @@ When called from Lisp, DATE should be a date as returned by (ot-show-context) (recenter)))) +(defun ot-clock-in () + "Jump to the org heading of selected timeblock." + (interactive) + (unless (eq major-mode 'org-timeblock-mode) + (user-error "Not in *org-timeblock* buffer")) + (goto-char (point-min)) + (search-forward "</rect>" nil t) + (when (re-search-forward (format "<rect .*? id=\"\\([^\"]+\\)\" fill=\"%s\"" ot-sel-block-color) nil t) + (when-let ((inhibit-read-only t) + (id (match-string-no-properties 1)) + (m (cadr (seq-find (lambda (x) (string= (car x) id)) ot-data))))
This indentation is off.
org-timeblock
github_2023
others
20
ichernyshovvv
alphapapa
@@ -1413,6 +1415,30 @@ When called from Lisp, DATE should be a date as returned by (ot-show-context) (recenter)))) +(defun ot-clock-in () + "Jump to the org heading of selected timeblock." + (interactive) + (unless (eq major-mode 'org-timeblock-mode) + (user-error "Not in *org-timeblock* buffer")) + (goto-char (point-min)) + (search-forward "</rect>" nil t) + (when (re-search-forward (format "<rect .*? id=\"\\([^\"]+\\)\" fill=\"%s\"" ot-sel-block-color) nil t) + (when-let ((inhibit-read-only t) + (id (match-string-no-properties 1)) + (m (cadr (seq-find (lambda (x) (string= (car x) id)) ot-data)))) + (switch-to-buffer-other-window (marker-buffer m))
You'll likely want to use `save-window-excursion`, unless you want the user to actually switch away from the timeblock view.
org-timeblock
github_2023
others
3
ichernyshovvv
ichernyshovvv
@@ -683,7 +683,7 @@ commands" (quit-window t)) (defun ot--schedule-time (marker eventp) - "Change the timestamp of the org entry at MARKER to a specified time(range) interactively. + "Interactively change Org entry timestamp at MARKER to a specified time-range.
Please change to "Interactively change time for Org entry timestamp at MARKER."
org-timeblock
github_2023
others
3
ichernyshovvv
ichernyshovvv
@@ -683,7 +683,7 @@ commands" (quit-window t)) (defun ot--schedule-time (marker eventp) - "Change the timestamp of the org entry at MARKER to a specified time(range) interactively. + "Interactively change Org entry timestamp at MARKER to a specified time-range. If EVENTP is non-nil, change timestamp of the event. Schedule or event date won't be changed.
I think, we need to clarify here that the time might be a timerange which depends on user interactive choice.
org-timeblock
github_2023
others
3
ichernyshovvv
ichernyshovvv
@@ -787,7 +787,8 @@ PROMPT can overwrite the default prompt." (defun ot-construct-id (&optional marker eventp) "Construct identifier for the org entry at MARKER. -If MARKER is nil, use entry at point." +If MARKER is nil, use entry at point. +If EVENTP is non-nil use entry's TIMESTAMP property."
Please add a comma after 'non-nil'
efficiency-nodes-comfyui
github_2023
python
55
LucianoCirino
LucianoCirino
@@ -89,12 +89,20 @@ def efficientloader(self, ckpt_name, vae_name, clip_skip, lora_name, lora_model_ vae_cache, ckpt_cache, lora_cache = get_cache_numbers("Efficient Loader") if lora_name != "None" or lora_stack is not None:
This line should actually be: ``` if lora_name != "None" or lora_stack: ``` So we take into account both when lora_stack is not connected (value = None) and when its an empty list [ ]. The current version you posted will give an error if you connect the LoRA Stacker and set all the LoRA names on both Efficient Loader and LoRA Stacker to "None".
efficiency-nodes-comfyui
github_2023
python
55
LucianoCirino
LucianoCirino
@@ -89,12 +89,20 @@ def efficientloader(self, ckpt_name, vae_name, clip_skip, lora_name, lora_model_ vae_cache, ckpt_cache, lora_cache = get_cache_numbers("Efficient Loader") if lora_name != "None" or lora_stack is not None: + # Initialize an empty list to store LoRa parameters. lora_params = [] + + # Check if lora_name is not the string "None" and if so, add its parameters. if lora_name != "None": lora_params.append((lora_name, lora_model_strength, lora_clip_strength)) - if lora_stack is not None: + + # If lora_stack is not None or an empty list, extend lora_params with its items. + if lora_stack: lora_params.extend(lora_stack) - model, clip = load_lora(lora_params, ckpt_name, my_unique_id, cache=lora_cache, ckpt_cache=ckpt_cache, cache_overwrite=True) + + # If there are any parameters in lora_params, load the LoRa with them. + if lora_params:
Checking for lora_params being None or an empty list at this point might not be necessary, because we are only entering this part of the logic if 'lora_name' or 'lora_stack' is valid, and if they are valid, so will 'lora_params'. So it would just turn to this. ``` model, clip = load_lora(lora_params, ckpt_name, my_unique_id, cache=lora_cache, ckpt_cache=ckpt_cache, cache_overwrite=True) ```
insights-bot
github_2023
go
206
nekomeowww
LemonNekoGH
@@ -218,7 +218,7 @@ func (m *AutoRecapService) summarize(chatID int64, options *ent.TelegramChatReca logID, summarizations, err := m.chathistories.SummarizeChatHistories(chatID, chatType, histories) if err != nil { - m.logger.Error("failed to summarize last six hour chat histories", + m.logger.Error(fmt.Sprintf("failed to summarize last %d hour chat histories", hours),
Maybe we need `Errorf` function?
insights-bot
github_2023
go
206
nekomeowww
nekomeowww
@@ -403,14 +403,61 @@ func (m *AutoRecapService) summarize(chatID int64, options *ent.TelegramChatReca msg.ReplyMarkup = inlineKeyboardMarkup } - _, err = m.botService.Send(msg) + sent_msg, err := m.botService.Send(msg) if err != nil { m.logger.Error("failed to send chat histories recap", zap.Int64("chat_id", chatID), zap.Int("auto_recap_rates", options.AutoRecapRatesPerDay), zap.Error(err), ) } + + // Check whether the first message of the batch needs to be pinned + if i != 0 || !options.PinAutoRecapMessage { + err = m.chathistories.SaveOneTelegramSentMessage(&sent_msg, false) + if err != nil { + m.logger.Error("failed to save one telegram sent message", + zap.Int64("chat_id", chatID), + zap.Error(err)) + } + + return + } + + // Unpin the last pinned message + lastPinnedMessage, err := m.chathistories.FindLastTelegramPinnedMessage(chatID) + if err != nil { + m.logger.Error("failed to find last pinned message", + zap.Int64("chat_id", chatID), + zap.Error(err), + ) + } + + if err = m.botService.UnpinChatMessage(tgbot.NewUnpinChatMessageConfig(chatID, lastPinnedMessage.MessageID)); err != nil { + m.logger.Error("failed to unpin chat message", + zap.Int64("chat_id", chatID), + zap.Error(err), + ) + } + + if err = m.chathistories.UpdatePinnedMessage(lastPinnedMessage.ChatID, lastPinnedMessage.MessageID, false); err != nil { + m.logger.Error("failed to save one telegram sent message", + zap.Int64("chat_id", chatID), + zap.Error(err)) + } + + if err = m.botService.PinChatMessage(tgbot.NewPinChatMessageConfig(chatID, sent_msg.MessageID)); err != nil { + m.logger.Error("failed to pin chat message", + zap.Int64("chat_id", chatID), + zap.Error(err), + ) + } + + if err = m.chathistories.SaveOneTelegramSentMessage(&sent_msg, true); err != nil { + m.logger.Error("failed to save one telegram sent message", + zap.Int64("chat_id", chatID), + zap.Error(err)) + }
You can use the similar technic like what you have written with https://github.com/nekomeowww/insights-bot/pull/206/files#diff-99fbab3f020962dc5770c6e55c402059116a0a019d7c9a243de8db596ed8b6afR256-R260 as well as https://github.com/nekomeowww/insights-bot/blob/0ec307bb387b3cf3f28fc623d36d57fa7376667c/internal/services/autorecap/autorecap.go#L91-L120 with https://github.com/nekomeowww/fo?tab=readme-ov-file#may0-6 to better handle the errors like this: ```suggestion may := fo.NewMay0().Use(func(err error, messageArgs ...any) { if len(messageArgs) == 0 { m.logger.Error(err.Error()) return } prefix, _ := messageArgs[0].(string) if len(messageArgs) == 1 { m.logger.Error(prefix, zap.Error(err)) return } fields := make([]zap.Field, 0) fields = append(fields, zap.Error(err)) for i, v := range messageArgs[1:] { field, ok := v.(zap.Field) if !ok { fields = append(fields, zap.Any(fmt.Sprintf("error_field_%d", i), field)) } else { fields = append(fields, field) } } m.logger.Error(prefix, fields...) }) // Unpin the last pinned message lastPinnedMessage, err := m.chathistories.FindLastTelegramPinnedMessage(chatID) if err != nil { m.logger.Error("failed to find last pinned message", zap.Int64("chat_id", chatID), zap.Error(err), ) } may.Invoke(m.botService.UnpinChatMessage(tgbot.NewUnpinChatMessageConfig(chatID, lastPinnedMessage.MessageID)), "failed to unpin chat message", zap.Int64("chat_id", chatID), zap.Int("message_id", lastPinnedMessage.MessageID)) may.Invoke(m.chathistories.UpdatePinnedMessage(lastPinnedMessage.ChatID, lastPinnedMessage.MessageID, false), "failed to save one telegram sent message", zap.Int64("chat_id", lastPinnedMessage.ChatID), zap.Int("message_id", lastPinnedMessage.MessageID)) may.Invoke(m.botService.PinChatMessage(tgbot.NewPinChatMessageConfig(chatID, sentMsg.MessageID)), "failed to pin chat message", zap.Int64("chat_id", chatID), zap.Int("message_id", sentMsg.MessageID)) may.Invoke(m.chathistories.SaveOneTelegramSentMessage(&sentMsg, true), "failed to save one telegram sent message") ``` In fact I think a universal and general implementation for middleware of `fo.NewMay0()` can be extracted later and contribute to [github.com/nekomeowww/fo](github.com/nekomeowww/fo) since I think this might be a pretty straightforward way to handle the optional errors with logs. What do you think?
insights-bot
github_2023
go
206
nekomeowww
nekomeowww
@@ -403,14 +403,61 @@ func (m *AutoRecapService) summarize(chatID int64, options *ent.TelegramChatReca msg.ReplyMarkup = inlineKeyboardMarkup } - _, err = m.botService.Send(msg) + sent_msg, err := m.botService.Send(msg) if err != nil { m.logger.Error("failed to send chat histories recap", zap.Int64("chat_id", chatID), zap.Int("auto_recap_rates", options.AutoRecapRatesPerDay), zap.Error(err), ) } + + // Check whether the first message of the batch needs to be pinned + if i != 0 || !options.PinAutoRecapMessage { + err = m.chathistories.SaveOneTelegramSentMessage(&sent_msg, false)
```suggestion sentMsg, err := m.botService.Send(msg) if err != nil { m.logger.Error("failed to send chat histories recap", zap.Int64("chat_id", chatID), zap.Int("auto_recap_rates", options.AutoRecapRatesPerDay), zap.Error(err), ) } // Check whether the first message of the batch needs to be pinned if i != 0 || !options.PinAutoRecapMessage { err = m.chathistories.SaveOneTelegramSentMessage(&sentMsg, false) ``` Use camelCase please.
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -21,84 +21,141 @@ system: modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has upgraded your group to a <b>supergroup</b>, resulting in a change of group ID. <b>We have automatically migrated all historical records and data to the new group ID</b>. All previous settings will remain in effect. However, due to Telegram's restrictions, message IDs from before the migration won't match those sent afterwards. This means messages sent before the upgrade won't be included in future summaries. We apologize for any inconvenience.
``` {{.Name}} @{{.Username}} has upgraded ``` Should not be `has upgraded`, shouldn't it be `has detected that your group has been upgraded to`?
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -21,84 +21,141 @@ system: modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has upgraded your group to a <b>supergroup</b>, resulting in a change of group ID. <b>We have automatically migrated all historical records and data to the new group ID</b>. All previous settings will remain in effect. However, due to Telegram's restrictions, message IDs from before the migration won't match those sent afterwards. This means messages sent before the upgrade won't be included in future summaries. We apologize for any inconvenience. - welcome: - messageSuperGroup: | - 🤗 欢迎使用 @{{.Username}}! +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - For web page article reading, use the command /smr@{{.Username}} <code>article link</code>. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - To summarize this group's chat history, set me as this group's admin (permissions can be off) under a <b>recognizable identity</b> (recommended to avoid permission errors), then send /configure_recap@{{.Username}} to activate the chat recap feature. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - To delete all messages recorded by the bot, simply revoke my admin rights. This will trigger an automatic cleanup of the bot’s historical data (unless this feature has been altered by another bot maintainer). - 如果还有疑问的话可以通过 + For questions: - 1. 执行帮助命令 /help@{{.Username}} 来查看支持的命令; - 2. 前往 Bot 所在的<a href="https://github.com/nekomeowww/insights-bot">开源仓库</a>提交 Issue 问询开发者。 + 1. Use /help@{{.Username}} to view supported commands. + 2. Visit the bot's <a href="https://github.com/nekomeowww/insights-bot">GitHub repository</a> to ask the developer. - 祝你使用愉快! - messageNormalGroup: | - 🤗 欢迎使用 @{{.Username}}! + Enjoy your use! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + messageNormalGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For web page article reading, use the command /smr@{{.Username}} <code>article link</code>. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - To summarize this group's chat history, set me as this group's admin (permissions can be off) under a <b>recognizable identity</b> (recommended to avoid permission errors), then send /configure_recap@{{.Username}} to activate the chat recap feature. - ⚠️ 警告:你的群组尚未是超级群组(supergroup)。<b>普通群组的消息链接引用功能无法正常工作。</b> + - To delete all messages recorded by the bot, simply revoke my admin rights. This triggers an automatic cleanup of the bot’s historical data (unless altered by another maintainer). - 如果你希望使用消息链接引用功能,请通过下面任意操作使其正常运作: + ⚠️ Your group is not a supergroup yet, which means the message link reference feature won't work properly. - - 短时间内将群组开放为公共群组并快速还原回私有群组; - - 通过其他操作将本群组升级为超级群组; + To enable message linking: - 如果还有疑问的话可以通过 + - Temporarily set your group to public, then revert it to private. + - Upgrade to a supergroup through other methods. - 1. 执行帮助命令 /help@{{.Username}} 来查看支持的命令; - 2. 前往 Bot 所在的<a href="https://github.com/nekomeowww/insights-bot">开源仓库</a>提交 Issue 问询开发者。 + For questions: + + 1. Use /help@{{.Username}} to view commands. + 2. Visit the bot's <a href="https://github.com/nekomeowww/insights-bot">GitHub repository</a> for developer queries. + + Enjoy your use! - 祝你使用愉快! commands: groups: summarization: - name: 量子速读 + name: Quantum Speed-Reading commands: smr: - help: 量子速读网页文章(也支持在频道中使用) 用法:/smr <code>&lt;链接&gt;</code> + help: Streamline your reading process with Quantum Speed-Reading. This feature allows you to quickly digest web articles and is also channel-compatible. To initiate, use the command :/smr <code>&lt;链接&gt;</code> noLinksFound: - telegram: 没有找到链接,可以发送一个有效的链接吗?用法:<code>/smr &lt;链接&gt;</code> - slackOrDiscord: 你发来的链接无法被理解,可以重新发一个试试。用法:`/smr <链接>` + telegram: It appears no link was detected. Could you kindly provide a valid URL? For usage:<code>/smr &lt;link&gt;</code>. + slackOrDiscord: It appears no link was detected. Could you kindly provide a valid URL? For usage:`/smr <link>` invalidLink: - telegram: 你发来的链接无法被理解,可以重新发一个试试。用法:<code>/smr &lt;链接&gt;</code> - slackOrDiscord: 你发来的链接无法被理解,可以重新发一个试试。用法:`/smr <链接>` - reading: 请稍等,量子速读中... - rateLimitExceeded: 很抱歉,您的操作触发了我们的限制机制,为了保证系统的可用性,本命令每最多 {{ .Seconds }} 秒使用一次,请您耐心等待 {{ .SecondsToBeWaited }} 秒后再试,感谢您的理解和支持。 - failedToRead: 量子速读失败了,可以再试试? - failedToReadDueToFailedToFetch: 量子速读的链接读取失败了哦。可以再试试? - contentNotSupported: 暂时不支持量子速读这样的内容呢,可以换个别的链接试试。 + telegram: We were unable to process the link you provided. Please ensure the URL is correct and try again. Usage:<code>/smr &lt;link&gt;</code>. + slackOrDiscord: We were unable to process the link you provided. Please ensure the URL is correct and try again. Usage:`/smr <link>` + reading: Quantum Speed-Reading is currently in action, please hold on for a moment... + rateLimitExceeded: Our apologies, but your recent action has has reached the rate limit maintain due to maintain service stability. This command may be utilized once every {{ .Seconds }} seconds. We kindly ask you to wait {{ .SecondsToBeWaited }} seconds before your next attempt. Your understanding and cooperation are greatly appreciated. + failedToRead: Unfortunately, Quantum Speed-Reading was unsuccessful. Would you like to attempt it once more? + failedToReadDueToFailedToFetch: We encountered an issue retrieving the content for Quantum Speed-Reading. Perhaps another try might yield success? + contentNotSupported: The content provided does not currently support Quantum Speed-Reading. Considering another link may be beneficial. permissionDenied: No permission to send message, please try to reinstall this APP +prompts: + smr: + - role: system + content: | + You are my web article reading assistant. I will provide you with the title, author, and the main text from the webpage I've captured, and then you will summarize the article. Please meet the following requirements when summarizing: + 1. First, if the article's title is not in Chinese, translate it into simplified Chinese in a faithful, expressive, and elegant manner and place it on the first line. + 2. Then, summarize the article in under 300 words based on the information I've provided. + 3. Lastly, using your existing knowledge and experience, propose 3 questions that are creative and involve divergent thinking based on the information I've provided about the article. + 4. Please reply in simplified Chinese. + The format of your reply should be like this example (where the double curly braces need to be replaced):\n + {{Simplified Chinese title, can be omitted}}\n\nSummary: {{Summary of the article}}\n\nRelated Questions:\n1. {{Related Question 1}}\n2. {{Related Question 2}}\n3. {{Related Question 3}} +- role: user + content: | + The information related to my first request is as follows: + Article Title: {{ .Title }} + Article Author: {{ .By }} + Article Content: {{ .Content }} + Please complete the task as requested. + +system: + commands: + groups: + basic: + name: Basic Commands + commands: + start: + help: Start interacting with the bot + help: + help: Get help + message: | + Hi! 👋 Welcome to using Insights Bot! + + I currently support these commands: + + {{ .Commands }} + cancel: + help: Cancel the current activated operation + alreadyCancelledAll: There is no activated operation to cancel + +commands: + groups: + summarization: + name: Quantum Speed-Reading + commands: + smr: + help: Streamline your reading process with Quantum Speed-Reading. This feature allows you to quickly digest web articles and is also channel-compatible. To initiate, use the command: /smr <code>&lt;link&gt;</code>. + noLinksFound: It appears no link was detected. Could you kindly provide a valid URL? For usage: <code>/smr &lt;link&gt;</code>. + invalidLink: We were unable to process the link you provided. Please ensure the URL is correct and try again. Usage: <code>/smr &lt;link&gt;</code>. + reading: Quantum Speed-Reading is currently in action, please hold on for a moment... + rateLimitExceeded: Our apologies, but your recent action has has reached the rate limit maintain due to maintain service stability. This command may be utilized once every {{ .Seconds }} seconds. We kindly ask you to wait {{ .SecondsToBeWaited }} seconds before your next attempt. Your understanding and cooperation are greatly appreciated. + failedToRead: Unfortunately, Quantum Speed-Reading was unsuccessful. Would you like to attempt it once more? + failedToReadDueToFailedToFetch: We encountered an issue retrieving the content for Quantum Speed-Reading. Perhaps another try might yield success? + contentNotSupported: The content provided does not currently support Quantum Speed-Reading. Considering another link may be beneficial. + + + prompts: smr: - role: system content: | - 你是我的网页文章阅读助理。我将为你提供文章的标题、作 - 者、所抓取的网页中的正文等信息,然后你将对文章做出总结。\n请你在总结时满足以下要求: - 1. 首先如果文章的标题不是中文的请依据上下文将标题信达雅的翻译为简体中文并放在第一行 - 2. 然后从我提供的文章信息中总结出一个三百字以内的文章的摘要 - 3. 最后,你将利用你已有的知识和经验,对我提供的文章信息提出 3 个具有创造性和发散思维的问题 - 4. 请用简体中文进行回复 - 最终你回复的消息格式应像这个例句一样(例句中的双花括号为需要替换的内容):\n - {{简体中文标题,可省略}}\n\n摘要:{{文章的摘要}}\n\n关联提问:\n1. {{关联提问 1}}\n2. {{关联提问 2}}\n2. {{关联提问 3}} + You are my web article reading assistant. I will provide you with the article's title, author, and the main content captured from the web page, and then you will summarize the article. \nPlease meet the following requirements when summarizing: + 1. First, if the article's title is not in Chinese, please translate it into simplified Chinese elegantly according to the context and place it at the first line + 2. Then, summarize the article in no more than 300 words based on the information I provided + 3. Lastly, using your existing knowledge and experience, propose 3 creative and divergent questions regarding the information I provided + 4. Please reply in Simplified Chinese + The format of your reply should be like this example (where double curly braces need to be replaced): \n + {{Simplified Chinese title, optional}}\n\nSummary: {{Summary of the article}}\n\nRelated Questions:\n1. {{Related Question 1}}\n2. {{Related Question 2}}\n3. {{Related Question 3}} - role: user content: | - 我的第一个要求相关的信息如下: - 文章标题:{{ .Title }} - 文章作者:{{ .By }} - 文章正文:{{ .Content }} - 接下来请你完成我所要求的任务。 + The information related to my first request is as follows: + Article title: {{ .Title }} + Article author: {{ .By }} + Article content: {{ .Content }} + Please complete the task I requested.
Please add one extra empty line at the end of the file.
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -15,90 +15,150 @@ system: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Cancel the current operation + alreadyCancelledAll: There is no operation to cancel modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has noticed your group's upgrade to a <b>supergroup</b>, which has resulted in a change of the group ID. Rest assured, we have seamlessly migrated all historical data to the new ID, with all your settings preserved intact. Due to Telegram's restrictions, however, message IDs from before the upgrade will not correspond with those sent afterwards, meaning they will be omitted from future summaries. We apologize for any inconvenience this adjustment may cause.
Why choose the word `adjustment`? ``` Due to Telegram's restrictions, message IDs sent before the upgrade will not correspond with those sent afterwards. ``` And why so many commas.
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -15,90 +15,150 @@ system: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Cancel the current operation + alreadyCancelledAll: There is no operation to cancel modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has noticed your group's upgrade to a <b>supergroup</b>, which has resulted in a change of the group ID. Rest assured, we have seamlessly migrated all historical data to the new ID, with all your settings preserved intact. Due to Telegram's restrictions, however, message IDs from before the upgrade will not correspond with those sent afterwards, meaning they will be omitted from future summaries. We apologize for any inconvenience this adjustment may cause. + +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! + + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. + + - For chat history summaries, assign me as admin (with or without permissions) using a <b>recognizable identity</b> to avoid errors. Then, initiate /configure_recap@{{.Username}} to set up chat recap.
```suggestion - For chat history summaries, assign me as admin (with or without permissions) using a <b>non-anonymous identity</b> to avoid permission detection errors. Then, initiate /configure_recap@{{.Username}} to set up chat recap. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -15,90 +15,150 @@ system: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Cancel the current operation + alreadyCancelledAll: There is no operation to cancel modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has noticed your group's upgrade to a <b>supergroup</b>, which has resulted in a change of the group ID. Rest assured, we have seamlessly migrated all historical data to the new ID, with all your settings preserved intact. Due to Telegram's restrictions, however, message IDs from before the upgrade will not correspond with those sent afterwards, meaning they will be omitted from future summaries. We apologize for any inconvenience this adjustment may cause. + +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! + + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. + + - For chat history summaries, assign me as admin (with or without permissions) using a <b>recognizable identity</b> to avoid errors. Then, initiate /configure_recap@{{.Username}} to set up chat recap. + + - Revoking my admin rights will erase all recorded messages, cleaning historical data unless modified by another bot manager.
```suggestion - Revoking my admin role will trigger myself to clean up erase all recorded messages, as well as historical data and logs (only when the actual implemented haven't modified by the other operators of bot instances). ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -15,90 +15,150 @@ system: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Cancel the current operation + alreadyCancelledAll: There is no operation to cancel modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has noticed your group's upgrade to a <b>supergroup</b>, which has resulted in a change of the group ID. Rest assured, we have seamlessly migrated all historical data to the new ID, with all your settings preserved intact. Due to Telegram's restrictions, however, message IDs from before the upgrade will not correspond with those sent afterwards, meaning they will be omitted from future summaries. We apologize for any inconvenience this adjustment may cause. + +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! + + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. + + - For chat history summaries, assign me as admin (with or without permissions) using a <b>recognizable identity</b> to avoid errors. Then, initiate /configure_recap@{{.Username}} to set up chat recap. + + - Revoking my admin rights will erase all recorded messages, cleaning historical data unless modified by another bot manager. + + Questions? + + 1. Type /help@{{.Username}} for commands. + 2. Check our <a href="https://github.com/nekomeowww/insights-bot">GitHub</a> for more info.
```suggestion 2. Raise an issue at the <a href="https://github.com/nekomeowww/insights-bot">open sourced repository</a> for more info from the developers. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -15,90 +15,150 @@ system: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Cancel the current operation + alreadyCancelledAll: There is no operation to cancel modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has noticed your group's upgrade to a <b>supergroup</b>, which has resulted in a change of the group ID. Rest assured, we have seamlessly migrated all historical data to the new ID, with all your settings preserved intact. Due to Telegram's restrictions, however, message IDs from before the upgrade will not correspond with those sent afterwards, meaning they will be omitted from future summaries. We apologize for any inconvenience this adjustment may cause. + +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! + + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. + + - For chat history summaries, assign me as admin (with or without permissions) using a <b>recognizable identity</b> to avoid errors. Then, initiate /configure_recap@{{.Username}} to set up chat recap. + + - Revoking my admin rights will erase all recorded messages, cleaning historical data unless modified by another bot manager. + + Questions? + + 1. Type /help@{{.Username}} for commands. + 2. Check our <a href="https://github.com/nekomeowww/insights-bot">GitHub</a> for more info. - welcome: - messageSuperGroup: | - 🤗 欢迎使用 @{{.Username}}! + Happy to assist! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + messageNormalGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - Use /smr@{{.Username}} <code>article link</code> for reading articles. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - To get chat summaries, make me an admin (permissions optional) under a <b>recognizable identity</b> for error-free setup, then trigger /configure_recap@{{.Username}}.
```suggestion - For chat history summaries, assign me as admin (with or without permissions) using a <b>non-anonymous identity</b> to avoid permission detection errors. Then, initiate /configure_recap@{{.Username}} to set up chat recap. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -2,103 +2,100 @@ system: commands: groups: basic: - name: 基础命令 + name: Basic Commands commands: start: - help: Start interacting with the bot + help: Begin interacting with the bot help: - help: Get help + help: Obtain assistance message: | - Hi! 👋 Welcome using Insights Bot! + Greetings! 👋 Welcome to using Insights Bot! I currently support these commands: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Terminate the current operation
```suggestion help: Cancel any ongoing operations. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -2,103 +2,100 @@ system: commands: groups: basic: - name: 基础命令 + name: Basic Commands commands: start: - help: Start interacting with the bot + help: Begin interacting with the bot help: - help: Get help + help: Obtain assistance message: | - Hi! 👋 Welcome using Insights Bot! + Greetings! 👋 Welcome to using Insights Bot! I currently support these commands: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Terminate the current operation + alreadyCancelledAll: No ongoing operations to terminate
```suggestion alreadyCancelledAll: No ongoing operations to cancel ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -2,103 +2,100 @@ system: commands: groups: basic: - name: 基础命令 + name: Basic Commands commands: start: - help: Start interacting with the bot + help: Begin interacting with the bot help: - help: Get help + help: Obtain assistance message: | - Hi! 👋 Welcome using Insights Bot! + Greetings! 👋 Welcome to using Insights Bot! I currently support these commands: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Terminate the current operation + alreadyCancelledAll: No ongoing operations to terminate modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has observed your group's transition to a <b>supergroup</b>, leading to a change in the group ID. Rest assured, we've smoothly transitioned all historical data to the new ID, maintaining all your settings unaltered. Due to Telegram's limitations, message IDs from before the upgrade won't match those sent after, and will thus be excluded from future summaries. We regret any inconvenience caused by this adjustment.
```suggestion {{.Name}} @{{.Username}} has observed your group's upgrading to a <b>supergroup</b>, where the group ID will change. Rest assured, we've smoothly transitioned all historical data to the new group ID, while maintaining all your settings unaltered. However, due to Telegram's limitations, message IDs from before the upgrade won't match those sent after and will thus be excluded from future summaries. We regret any inconvenience caused by such migrations. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -2,103 +2,100 @@ system: commands: groups: basic: - name: 基础命令 + name: Basic Commands commands: start: - help: Start interacting with the bot + help: Begin interacting with the bot help: - help: Get help + help: Obtain assistance message: | - Hi! 👋 Welcome using Insights Bot! + Greetings! 👋 Welcome to using Insights Bot! I currently support these commands: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Terminate the current operation + alreadyCancelledAll: No ongoing operations to terminate modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has observed your group's transition to a <b>supergroup</b>, leading to a change in the group ID. Rest assured, we've smoothly transitioned all historical data to the new ID, maintaining all your settings unaltered. Due to Telegram's limitations, message IDs from before the upgrade won't match those sent after, and will thus be excluded from future summaries. We regret any inconvenience caused by this adjustment. - welcome: - messageSuperGroup: | - 🤗 欢迎使用 @{{.Username}}! +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For chat history summaries, appoint me as admin (with or without permissions) using a <b>non-anonymous identity</b> to bypass permission detection issues. Then, start /configure_recap@{{.Username}} to configure chat recap.
```suggestion - For chat history summaries, please assign me as admin (all permissions can be omitted) using a <b>non-anonymous identity</b> (recommended, otherwise permission validation may fail. Then, start /configure_recap@{{.Username}} to configure chat recap. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -2,103 +2,100 @@ system: commands: groups: basic: - name: 基础命令 + name: Basic Commands commands: start: - help: Start interacting with the bot + help: Begin interacting with the bot help: - help: Get help + help: Obtain assistance message: | - Hi! 👋 Welcome using Insights Bot! + Greetings! 👋 Welcome to using Insights Bot! I currently support these commands: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Terminate the current operation + alreadyCancelledAll: No ongoing operations to terminate modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has observed your group's transition to a <b>supergroup</b>, leading to a change in the group ID. Rest assured, we've smoothly transitioned all historical data to the new ID, maintaining all your settings unaltered. Due to Telegram's limitations, message IDs from before the upgrade won't match those sent after, and will thus be excluded from future summaries. We regret any inconvenience caused by this adjustment. - welcome: - messageSuperGroup: | - 🤗 欢迎使用 @{{.Username}}! +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For chat history summaries, appoint me as admin (with or without permissions) using a <b>non-anonymous identity</b> to bypass permission detection issues. Then, start /configure_recap@{{.Username}} to configure chat recap. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - Revoking my admin role will prompt me to delete all recorded messages, along with historical data and logs (only if no modifications have been made by other bot operators). - 如果还有疑问的话可以通过 + Questions? - 1. 执行帮助命令 /help@{{.Username}} 来查看支持的命令; - 2. 前往 Bot 所在的<a href="https://github.com/nekomeowww/insights-bot">开源仓库</a>提交 Issue 问询开发者。 + 1. Enter /help@{{.Username}} for command information. + 2. Submit an issue at the <a href="https://github.com/nekomeowww/insights-bot">open-source repository</a> for further details from the developers. - 祝你使用愉快! - messageNormalGroup: | - 🤗 欢迎使用 @{{.Username}}! + messageNormalGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - Use /smr@{{.Username}} <code>article link</code> for article readings. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For chat history summaries, appoint me as admin (with or without permissions) using a <b>non-anonymous identity</b> to bypass permission detection issues. Then, start /configure_recap@{{.Username}} to configure chat recap.
```suggestion - For chat history summaries, please assign me as admin (all permissions can be omitted) using a <b>non-anonymous identity</b> (recommended, otherwise permission validation may fail. Then, start /configure_recap@{{.Username}} to configure chat recap. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -2,103 +2,100 @@ system: commands: groups: basic: - name: 基础命令 + name: Basic Commands commands: start: - help: Start interacting with the bot + help: Begin interacting with the bot help: - help: Get help + help: Obtain assistance message: | - Hi! 👋 Welcome using Insights Bot! + Greetings! 👋 Welcome to using Insights Bot! I currently support these commands: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Terminate the current operation + alreadyCancelledAll: No ongoing operations to terminate modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has observed your group's transition to a <b>supergroup</b>, leading to a change in the group ID. Rest assured, we've smoothly transitioned all historical data to the new ID, maintaining all your settings unaltered. Due to Telegram's limitations, message IDs from before the upgrade won't match those sent after, and will thus be excluded from future summaries. We regret any inconvenience caused by this adjustment. - welcome: - messageSuperGroup: | - 🤗 欢迎使用 @{{.Username}}! +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For chat history summaries, appoint me as admin (with or without permissions) using a <b>non-anonymous identity</b> to bypass permission detection issues. Then, start /configure_recap@{{.Username}} to configure chat recap. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - Revoking my admin role will prompt me to delete all recorded messages, along with historical data and logs (only if no modifications have been made by other bot operators). - 如果还有疑问的话可以通过 + Questions? - 1. 执行帮助命令 /help@{{.Username}} 来查看支持的命令; - 2. 前往 Bot 所在的<a href="https://github.com/nekomeowww/insights-bot">开源仓库</a>提交 Issue 问询开发者。 + 1. Enter /help@{{.Username}} for command information. + 2. Submit an issue at the <a href="https://github.com/nekomeowww/insights-bot">open-source repository</a> for further details from the developers. - 祝你使用愉快! - messageNormalGroup: | - 🤗 欢迎使用 @{{.Username}}! + messageNormalGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - Use /smr@{{.Username}} <code>article link</code> for article readings. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For chat history summaries, appoint me as admin (with or without permissions) using a <b>non-anonymous identity</b> to bypass permission detection issues. Then, start /configure_recap@{{.Username}} to configure chat recap. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - Removing my admin status is a simple way to delete all bot-recorded messages, automatically purging bot data unless modifications have been made by another maintainer. - ⚠️ 警告:你的群组尚未是超级群组(supergroup)。<b>普通群组的消息链接引用功能无法正常工作。</b> + ⚠️ Your group isn't a supergroup, impacting message link functionality.
```suggestion ⚠️ Your group isn't a supergroup yet; message reference linking will not work. ```
insights-bot
github_2023
others
194
nekomeowww
nekomeowww
@@ -2,103 +2,100 @@ system: commands: groups: basic: - name: 基础命令 + name: Basic Commands commands: start: - help: Start interacting with the bot + help: Begin interacting with the bot help: - help: Get help + help: Obtain assistance message: | - Hi! 👋 Welcome using Insights Bot! + Greetings! 👋 Welcome to using Insights Bot! I currently support these commands: {{ .Commands }} cancel: - help: Cancel the current activated operation - alreadyCancelledAll: There is no activated operation to cancel + help: Terminate the current operation + alreadyCancelledAll: No ongoing operations to terminate modules: telegram: chatMigration: - notification: | - {{.Name}} @{{.Username}} 监测到您的群组已从 <b>群组(group)</b> 升级为了 <b>超级群组(supergroup)</b>,届时,群组的 ID 将会发生变更,<b>现已自动将过去的历史记录和数据留存自动迁移到了新的群组 ID 名下</b>,之前的设置将会保留并继续沿用,不过需要注意的是,由于 Telegram 官方的限制,迁移事件前的消息 ID 将无法与今后发送的消息 ID 相兼容,所以当下一次总结消息时将不会包含在迁移事件发生前所发送的消息,由此带来的不便敬请谅解。 + notification: | + {{.Name}} @{{.Username}} has observed your group's transition to a <b>supergroup</b>, leading to a change in the group ID. Rest assured, we've smoothly transitioned all historical data to the new ID, maintaining all your settings unaltered. Due to Telegram's limitations, message IDs from before the upgrade won't match those sent after, and will thus be excluded from future summaries. We regret any inconvenience caused by this adjustment. - welcome: - messageSuperGroup: | - 🤗 欢迎使用 @{{.Username}}! +welcome: + messageSuperGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - Use /smr@{{.Username}} <code>article link</code> for web article summaries. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For chat history summaries, appoint me as admin (with or without permissions) using a <b>non-anonymous identity</b> to bypass permission detection issues. Then, start /configure_recap@{{.Username}} to configure chat recap. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - Revoking my admin role will prompt me to delete all recorded messages, along with historical data and logs (only if no modifications have been made by other bot operators). - 如果还有疑问的话可以通过 + Questions? - 1. 执行帮助命令 /help@{{.Username}} 来查看支持的命令; - 2. 前往 Bot 所在的<a href="https://github.com/nekomeowww/insights-bot">开源仓库</a>提交 Issue 问询开发者。 + 1. Enter /help@{{.Username}} for command information. + 2. Submit an issue at the <a href="https://github.com/nekomeowww/insights-bot">open-source repository</a> for further details from the developers. - 祝你使用愉快! - messageNormalGroup: | - 🤗 欢迎使用 @{{.Username}}! + messageNormalGroup: | + 🤗 Welcome to @{{.Username}}! - - 如果要让我帮忙阅读网页文章,请直接使用开箱即用的命令 /smr@{{.Username}} <code>要阅读的链接</code>; + - Use /smr@{{.Username}} <code>article link</code> for article readings. - - 如果想要我帮忙总结本群组的聊天记录,请以<b>管理员</b>身份将我配置为本群组的管理员(可以关闭所有权限),然后在<b>非匿名和非其他身份的身份</b>下(推荐,否则容易出现权限识别错误的情况)发送 /configure_recap@{{.Username}} 来开始配置本群组的聊天回顾功能。 + - For chat history summaries, appoint me as admin (with or without permissions) using a <b>non-anonymous identity</b> to bypass permission detection issues. Then, start /configure_recap@{{.Username}} to configure chat recap. - - 如果你在授权 Bot 管理员之后希望 Bot 将已经记录的消息全数移除,可以通过撤销 Bot 的管理员权限来触发 Bot 的历史数据自动清理(如果该部分代码未经其他 Bot 实例维护者修改的话)。 + - Removing my admin status is a simple way to delete all bot-recorded messages, automatically purging bot data unless modifications have been made by another maintainer. - ⚠️ 警告:你的群组尚未是超级群组(supergroup)。<b>普通群组的消息链接引用功能无法正常工作。</b> + ⚠️ Your group isn't a supergroup, impacting message link functionality. - 如果你希望使用消息链接引用功能,请通过下面任意操作使其正常运作: + To enable linking:
```suggestion To enable message reference linking: ```
insights-bot
github_2023
others
190
nekomeowww
nekomeowww
@@ -21,34 +21,35 @@ system: commands: groups: summarization: - name: 量子速读 + name: Quantum Speed Reading
```suggestion name: Quantum Speed-Reading ``` Should we align the name for it?
insights-bot
github_2023
others
190
nekomeowww
nekomeowww
@@ -21,34 +21,35 @@ system: commands: groups: summarization: - name: 量子速读 + name: Quantum Speed Reading commands: smr: - help: 量子速读网页文章(也支持在频道中使用) 用法:/smr <code>&lt;链接&gt;</code> - noLinksFound: 没有找到链接,可以发送一个有效的链接吗?用法:<code>/smr &lt;链接&gt;</code> - invalidLink: 你发来的链接无法被理解,可以重新发一个试试。用法:<code>/smr &lt;链接&gt;</code> - reading: 请稍等,量子速读中... - rateLimitExceeded: 很抱歉,您的操作触发了我们的限制机制,为了保证系统的可用性,本命令每最多 {{ .Seconds }} 秒使用一次,请您耐心等待 {{ .SecondsToBeWaited }} 秒后再试,感谢您的理解和支持。 - failedToRead: 量子速读失败了,可以再试试? - failedToReadDueToFailedToFetch: 量子速读的链接读取失败了哦。可以再试试? - contentNotSupported: 暂时不支持量子速读这样的内容呢,可以换个别的链接试试。 + help: Streamline your reading process with Quantum Speed-Reading. This feature allows you to quickly digest web articles and is also channel-compatible. To initiate, use the command: /smr <code>&lt;link&gt;</code>. + noLinksFound: It appears no link was detected. Could you kindly provide a valid URL? For usage: <code>/smr &lt;link&gt;</code>. + invalidLink: We were unable to process the link you provided. Please ensure the URL is correct and try again. Usage: <code>/smr &lt;link&gt;</code>. + reading: Quantum Speed-Reading is currently in action, please hold on for a moment... + rateLimitExceeded: Our apologies, but your recent action has activated our rate limiting system to maintain service stability. This command may be utilized once every {{ .Seconds }} seconds. We kindly ask you to wait {{ .SecondsToBeWaited }} seconds before your next attempt. Your understanding and cooperation are greatly appreciated.
```suggestion rateLimitExceeded: Our apologies, but your recent action has reached the rate limit maintain due to maintain service stability. This command may be utilized once every {{ .Seconds }} seconds. We kindly ask you to wait {{ .SecondsToBeWaited }} seconds before your next attempt. Your understanding and cooperation are greatly appreciated. ```
insights-bot
github_2023
others
190
nekomeowww
nekomeowww
@@ -66,39 +66,34 @@ modules: commands: groups: summarization: - name: 量子速读 + name: Quantum Speed-Reading commands: smr: - help: 量子速读网页文章(也支持在频道中使用) 用法:/smr <code>&lt;链接&gt;</code> - noLinksFound: - telegram: 没有找到链接,可以发送一个有效的链接吗?用法:<code>/smr &lt;链接&gt;</code> - slackOrDiscord: 你发来的链接无法被理解,可以重新发一个试试。用法:`/smr <链接>` - invalidLink: - telegram: 你发来的链接无法被理解,可以重新发一个试试。用法:<code>/smr &lt;链接&gt;</code> - slackOrDiscord: 你发来的链接无法被理解,可以重新发一个试试。用法:`/smr <链接>`
Should also translate for `telegram` and `slackOrDiscord`.
insights-bot
github_2023
others
161
nekomeowww
PA733
@@ -119,9 +119,9 @@ services: environment: - REDIS_PASSWORD=123456 command: > - ${REDIS_PASSWORD:+--requirepass \"$REDIS_PASSWORD}\"} + /bin/sh -c "redis-server --requirepass $$REDIS_PASSWORD" healthcheck: - test: [ "CMD-SHELL", "redis-cli -e ${REDIS_PASSWORD:+-a \"$REDIS_PASSWORD\"} --no-auth-warning ping" ] + test: [ "CMD-SHELL", "redis-cli -a $$REDIS_PASSWORD --no-auth-warning ping" ]
之前的改动考虑到了空密码和密码含空格的情况。 如果指定了`--requirepass ""`,那么redis将会被锁死(任何登录操作,redis都会返回`NOAUTH Authentication required`信息)。 之前的逻辑是,密码为空时不传入`--requirepass`参数。 `-e`让认证失败或ping失败时,redis-cli返回非零状态码,这样docker就能正确捕获异常。 `--no-auth-warning`去掉了在命令行传入密码时,redis-cli的警告信息
insights-bot
github_2023
others
159
nekomeowww
nekomeowww
@@ -116,11 +116,12 @@ services: redis_local: image: redis:7 restart: unless-stopped - # comment the following line if you don't want to set password for redis + environment: + - REDIS_PASSWORD=123456 command: > - --requirepass 123456 + ${REDIS_PASSWORD:+--requirepass \"$REDIS_PASSWORD}\"}
原来还有这种写法,受教了
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -63,17 +63,17 @@ func TestSlackBot_createNewSlackCredential(t *testing.T) { a := assert.New(t) r := require.New(t) - defer cleanSlackCredential(bot, r) + defer cleanSlackCredential(s, r) expectTeamId := "TEAM_ID"
```suggestion expectTeamID := "TEAM_ID" ```
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -70,3 +81,81 @@ func (cli *Client) SendMessageWithTokenExpirationCheck(channel string, storeFn S return cli.SendMessageWithTokenExpirationCheck(channel, storeFn, options...) } + +var _ healthchecker.HealthChecker = (*BotService)(nil) + +type BotService struct { + logger *logger.Logger + + services *services.Services + serverEngine *gin.Engine + server *http.Server + + started bool +} + +func (s *BotService) SetService(services *services.Services) { + s.services = services +} + +func (s *BotService) GetService() *services.Services { + return s.services +} + +func NewBotService(slackConfig configs.SectionSlack) *BotService { + engine := gin.Default() + server := &http.Server{ + Addr: lo.Ternary(slackConfig.Port == "", ":7070", net.JoinHostPort("", slackConfig.Port)), + Handler: engine, + ReadHeaderTimeout: time.Second * 10, + } + + return &BotService{ + serverEngine: engine, + server: server, + } +} + +func (s *BotService) Handle(method, path string, handler gin.HandlerFunc) { + s.serverEngine.Handle(method, path, handler) +} + +func (s *BotService) SetLogger(logger *logger.Logger) { + s.logger = logger +} + +func (s *BotService) Check(ctx context.Context) error { + return lo.Ternary(s.started, nil, errors.New("slack bot not started yet")) +} + +func (s *BotService) Run() error { + listener, err := net.Listen("tcp", s.server.Addr) + if err != nil { + return err + } + + go func() { + err = s.server.Serve(listener) + if err != nil && err != http.ErrServerClosed { + s.logger.WithField("error", err.Error()).Fatal("slack bot server error") + } + }() + + s.logger.Infof("Slack Bot/App webhook server is listening on %s", s.server.Addr) + s.started = true + + return nil +} + +func (s *BotService) Stop(ctx context.Context) error { + err := s.server.Shutdown(ctx) + + if !errors.Is(err, context.Canceled) { + s.logger.WithField("error", err.Error()).Error("slack bot server shutdown failed") + return err + }
不论如何都打印。cancelled 说明 graceful 耗时太长了,如果是正常情况,是不是要改 stop timeout 阈值?
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -70,3 +81,81 @@ func (cli *Client) SendMessageWithTokenExpirationCheck(channel string, storeFn S return cli.SendMessageWithTokenExpirationCheck(channel, storeFn, options...) } + +var _ healthchecker.HealthChecker = (*BotService)(nil) + +type BotService struct { + logger *logger.Logger + + services *services.Services + serverEngine *gin.Engine + server *http.Server + + started bool +} + +func (s *BotService) SetService(services *services.Services) { + s.services = services +} + +func (s *BotService) GetService() *services.Services { + return s.services +} + +func NewBotService(slackConfig configs.SectionSlack) *BotService { + engine := gin.Default() + server := &http.Server{ + Addr: lo.Ternary(slackConfig.Port == "", ":7070", net.JoinHostPort("", slackConfig.Port)), + Handler: engine, + ReadHeaderTimeout: time.Second * 10, + } + + return &BotService{ + serverEngine: engine, + server: server, + } +} + +func (s *BotService) Handle(method, path string, handler gin.HandlerFunc) { + s.serverEngine.Handle(method, path, handler) +} + +func (s *BotService) SetLogger(logger *logger.Logger) { + s.logger = logger +} + +func (s *BotService) Check(ctx context.Context) error { + return lo.Ternary(s.started, nil, errors.New("slack bot not started yet")) +} + +func (s *BotService) Run() error { + listener, err := net.Listen("tcp", s.server.Addr) + if err != nil { + return err + } + + go func() { + err = s.server.Serve(listener) + if err != nil && err != http.ErrServerClosed { + s.logger.WithField("error", err.Error()).Fatal("slack bot server error") + } + }() + + s.logger.Infof("Slack Bot/App webhook server is listening on %s", s.server.Addr) + s.started = true + + return nil +} + +func (s *BotService) Stop(ctx context.Context) error { + err := s.server.Shutdown(ctx) +
没必要多空一行?
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -0,0 +1,92 @@ +package discordbot + +import ( + "context" + "crypto/ed25519" + "errors" + "net" + + "github.com/disgoorg/disgo" + "github.com/disgoorg/disgo/bot" + "github.com/disgoorg/disgo/httpserver" + "github.com/nekomeowww/insights-bot/internal/configs" + "github.com/nekomeowww/insights-bot/pkg/logger" + "github.com/samber/lo" +) + +type BotService struct { + bot.Client + + logger *logger.Logger + + webhookStarted bool +} + +func NewBotService[E bot.Event]( + f func(e E), + cfg configs.SectionDiscord, + logger *logger.Logger, +) *BotService { + discordBot := &BotService{ + logger: logger, + } + + port := lo.Ternary(cfg.Port == "", "7072", cfg.Port) + + client, err := disgo.New( + cfg.Token, + bot.WithHTTPServerConfigOpts( + cfg.PublicKey, + httpserver.WithAddress(net.JoinHostPort("", port)), + httpserver.WithURL("/discord/command/smr"), + ), + bot.WithEventListenerFunc(f), + ) + if err != nil { + logger.WithField("error", err.Error()).Fatal("discord: failed to create bot instance") + } + + discordBot.Client = client + + return discordBot +} + +func (b *BotService) SetLogger(logger *logger.Logger) { + b.logger = logger +} + +func (b *BotService) Check(ctx context.Context) error { + return lo.Ternary(b.webhookStarted, nil, errors.New("discord bot service is not started yet")) +} + +func (b *BotService) Run() error { + // use custom ed25519 verify implementation. + // this code is from examples of disgoorg/disgo. + httpserver.Verify = func(publicKey httpserver.PublicKey, message, sig []byte) bool { + return ed25519.Verify(publicKey, message, sig) + } + + b.logger.Info("discord: registering commands...") + + _, err := b.Rest().SetGlobalCommands(b.ApplicationID(), commands) + if err != nil { + return err + } + + b.logger.Info("discord: starting webhook server...") + + err = b.OpenHTTPServer() + if err != nil { + return err + } + + b.webhookStarted = true + + return nil +} + +func (b *BotService) Stop(ctx context.Context) { + b.logger.Info("discord: shutting down...") + b.Close(ctx) + b.webhookStarted = false
给 health check 用的没必要设回 false,要不然会触发告警的
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -0,0 +1,23 @@ +package smr + +import ( + "net/url" + + "github.com/samber/lo" +) + +func CheckUrl(urlString string) error { + if urlString == "" { + return ErrNoLink + } + + parsedURL, err2 := url.Parse(urlString) + if err2 != nil { + return ErrParse
```suggestion return fmt.Errorf("%w: %w", err2, ErrParse) ```
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -0,0 +1,23 @@ +package smr + +import ( + "net/url" + + "github.com/samber/lo" +) + +func CheckUrl(urlString string) error { + if urlString == "" { + return ErrNoLink + } + + parsedURL, err2 := url.Parse(urlString) + if err2 != nil { + return ErrParse + } + if parsedURL.Scheme == "" || !lo.Contains([]string{"http", "https"}, parsedURL.Scheme) { + return ErrScheme
```suggestion return fmt.Errorf("%w: %w", err2, ErrScheme) ```
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -0,0 +1,117 @@ +package smr + +import ( + "context" + "encoding/json" + "errors" + + "github.com/nekomeowww/insights-bot/internal/services/smr/types" + "github.com/redis/rueidis" + "github.com/sourcegraph/conc/pool" +) + +func (s *Service) AddTask(taskInfo types.TaskInfo) error { + result, err := json.Marshal(&taskInfo) + if err != nil { + return err + } + + err = s.redisClient.Do(context.Background(), s.redisClient.B().Lpush().Key("smr/task").Element(string(result)).Build()).Error() + if err != nil { + return err + } + + s.logger. + WithField("url", taskInfo.Url). + WithField("platform", taskInfo.Platform). + Info("smr service: task added") + + // TODO: #111 should reject ongoing smr request in the same chat + return nil +} + +func (s *Service) stop() { + if s.alreadyClosed { + return + } + s.closeChan <- struct{}{} + close(s.closeChan) +} + +func (s *Service) getTask() (types.TaskInfo, error) { + var info types.TaskInfo + + res, err := s.redisClient.Do(context.Background(), s.redisClient.B().Brpop().Key("smr/task").Timeout(10).Build()).AsStrSlice() + if err != nil { + return info, err + } + + err = json.Unmarshal([]byte(res[1]), &info)
好像没保证 `res` 有 `len() == 2`?
insights-bot
github_2023
go
119
nekomeowww
nekomeowww
@@ -0,0 +1,117 @@ +package smr + +import ( + "context" + "encoding/json" + "errors" + + "github.com/nekomeowww/insights-bot/internal/services/smr/types" + "github.com/redis/rueidis" + "github.com/sourcegraph/conc/pool" +) + +func (s *Service) AddTask(taskInfo types.TaskInfo) error { + result, err := json.Marshal(&taskInfo) + if err != nil { + return err + } + + err = s.redisClient.Do(context.Background(), s.redisClient.B().Lpush().Key("smr/task").Element(string(result)).Build()).Error() + if err != nil { + return err + } + + s.logger. + WithField("url", taskInfo.Url). + WithField("platform", taskInfo.Platform). + Info("smr service: task added") + + // TODO: #111 should reject ongoing smr request in the same chat + return nil +} + +func (s *Service) stop() { + if s.alreadyClosed { + return + } + s.closeChan <- struct{}{} + close(s.closeChan) +} + +func (s *Service) getTask() (types.TaskInfo, error) {
用 pointer pattern 省去调用方解 err