diff --git a/docs/content/configuration/templating.md b/docs/content/configuration/templating.md index 9801884..ffabb0b 100644 --- a/docs/content/configuration/templating.md +++ b/docs/content/configuration/templating.md @@ -392,6 +392,32 @@ Example: < @user @user @user ``` +### `parseDuration` + +Parses a duration (i.e. 1h25m10s) into a time.Duration + +Syntax: `parseDuration ` + +Example: + +``` +# {{ parseDuration "1h30s" }} +< 1h0m30s +``` + +### `parseDurationToSeconds` + +Parses a duration (i.e. 1h25m10s) into a number of seconds + +Syntax: `parseDurationToSeconds ` + +Example: + +``` +# {{ parseDurationToSeconds "1h25m10s" }} +< 5110 +``` + ### `pow` 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: 23% +< Your int this hour: 24% ``` ### `spotifyCurrentPlaying` diff --git a/internal/template/date/date.go b/internal/template/date/date.go index c916ead..0b48694 100644 --- a/internal/template/date/date.go +++ b/internal/template/date/date.go @@ -2,6 +2,9 @@ package date import ( + "fmt" + "time" + "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 ", + 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 ", + Example: &plugins.TemplateFuncDocumentationExample{ + Template: `{{ parseDurationToSeconds "1h25m10s" }}`, + ExpectedOutput: "5110", + }, + }) + return nil }