[templating] Add usernameForID function

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2023-09-03 12:09:33 +02:00
parent 0a53863b69
commit fb57cb9304
Signed by: luzifer
GPG Key ID: D91C3E91E4CAD6F5
2 changed files with 46 additions and 0 deletions

View File

@ -103,6 +103,15 @@ func init() {
FakedOutput: "3 hours, 56 minutes", FakedOutput: "3 hours, 56 minutes",
}, },
}) })
tplFuncs.Register("usernameForID", plugins.GenericTemplateFunctionGetter(tplTwitchUsernameForID), plugins.TemplateFuncDocumentation{
Description: "Returns the currente login name of an user-id",
Syntax: "usernameForID <user-id>",
Example: &plugins.TemplateFuncDocumentationExample{
Template: `{{ usernameForID "12826" }}`,
FakedOutput: "twitch",
},
})
} }
func tplTwitchDisplayName(username string, v ...string) (string, error) { func tplTwitchDisplayName(username string, v ...string) (string, error) {
@ -225,3 +234,7 @@ func tplTwitchStreamUptime(username string) (time.Duration, error) {
} }
return time.Since(si.StartedAt), nil return time.Since(si.StartedAt), nil
} }
func tplTwitchUsernameForID(id string) (string, error) {
return twitchClient.GetUsernameForID(context.Background(), id)
}

View File

@ -159,6 +159,39 @@ func (c *Client) GetIDForUsername(username string) (string, error) {
return payload.Data[0].ID, nil return payload.Data[0].ID, nil
} }
// GetUsernameForID retrieves the login name (not the display name)
// for the given user ID
func (c *Client) GetUsernameForID(ctx context.Context, id string) (string, error) {
cacheKey := []string{"usernameForID", id}
if d := c.apiCache.Get(cacheKey); d != nil {
return d.(string), nil
}
var payload struct {
Data []User `json:"data"`
}
if err := c.Request(ClientRequestOpts{
AuthType: AuthTypeAppAccessToken,
Context: ctx,
Method: http.MethodGet,
OKStatus: http.StatusOK,
Out: &payload,
URL: fmt.Sprintf("https://api.twitch.tv/helix/users?id=%s", id),
}); err != nil {
return "", errors.Wrap(err, "request channel info")
}
if l := len(payload.Data); l != 1 {
return "", errors.Errorf("unexpected number of users returned: %d", l)
}
// The username for an ID will not change (often), cache for a long time
c.apiCache.Set(cacheKey, timeDay, payload.Data[0].Login)
return payload.Data[0].Login, nil
}
func (c *Client) GetUserInformation(user string) (*User, error) { func (c *Client) GetUserInformation(user string) (*User, error) {
user = strings.TrimLeft(user, "#@") user = strings.TrimLeft(user, "#@")