[template] Add functions parseDuration, parseDurationToSeconds

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2024-11-25 00:40:17 +01:00
parent 096657bcee
commit 0d76c58ede
Signed by: luzifer
SSH key fingerprint: SHA256:/xtE5lCgiRDQr8SLxHMS92ZBlACmATUmF1crK16Ks4E
2 changed files with 62 additions and 1 deletions

View file

@ -392,6 +392,32 @@ Example:
< @user @user @user < @user @user @user
``` ```
### `parseDuration`
Parses a duration (i.e. 1h25m10s) into a time.Duration
Syntax: `parseDuration <duration>`
Example:
```
# {{ parseDuration "1h30s" }}
< 1h0m30s
```
### `parseDurationToSeconds`
Parses a duration (i.e. 1h25m10s) into a number of seconds
Syntax: `parseDurationToSeconds <duration>`
Example:
```
# {{ parseDurationToSeconds "1h25m10s" }}
< 5110
```
### `pow` ### `pow`
Returns float from calculation: `float1 ** float2` Returns float from calculation: `float1 ** float2`
@ -480,7 +506,7 @@ Example:
``` ```
# Your int this hour: {{ printf "%.0f" (mulf (seededRandom (list "int" .username (now | date "2006-01-02 15") | join ":")) 100) }}% # Your int this hour: {{ printf "%.0f" (mulf (seededRandom (list "int" .username (now | date "2006-01-02 15") | join ":")) 100) }}%
< Your int this hour: 23% < Your int this hour: 24%
``` ```
### `spotifyCurrentPlaying` ### `spotifyCurrentPlaying`

View file

@ -2,6 +2,9 @@
package date package date
import ( import (
"fmt"
"time"
"github.com/Luzifer/twitch-bot/v3/plugins" "github.com/Luzifer/twitch-bot/v3/plugins"
) )
@ -27,5 +30,37 @@ func Register(args plugins.RegistrationArguments) error {
}, },
}) })
args.RegisterTemplateFunction("parseDuration", plugins.GenericTemplateFunctionGetter(func(duration string) (time.Duration, error) {
d, err := time.ParseDuration(duration)
if err != nil {
return 0, fmt.Errorf("parsing duration: %w", err)
}
return d, nil
}), plugins.TemplateFuncDocumentation{
Description: `Parses a duration (i.e. 1h25m10s) into a time.Duration`,
Syntax: "parseDuration <duration>",
Example: &plugins.TemplateFuncDocumentationExample{
Template: `{{ parseDuration "1h30s" }}`,
ExpectedOutput: "1h0m30s",
},
})
args.RegisterTemplateFunction("parseDurationToSeconds", plugins.GenericTemplateFunctionGetter(func(duration string) (int64, error) {
d, err := time.ParseDuration(duration)
if err != nil {
return 0, fmt.Errorf("parsing duration: %w", err)
}
return int64(d / time.Second), nil
}), plugins.TemplateFuncDocumentation{
Description: `Parses a duration (i.e. 1h25m10s) into a number of seconds`,
Syntax: "parseDurationToSeconds <duration>",
Example: &plugins.TemplateFuncDocumentationExample{
Template: `{{ parseDurationToSeconds "1h25m10s" }}`,
ExpectedOutput: "5110",
},
})
return nil return nil
} }