mirror of
https://github.com/Luzifer/twitch-bot.git
synced 2024-12-20 11:51:17 +00:00
[templating] Add usernameForID
function
Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
parent
0a53863b69
commit
fb57cb9304
2 changed files with 46 additions and 0 deletions
|
@ -103,6 +103,15 @@ func init() {
|
|||
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) {
|
||||
|
@ -225,3 +234,7 @@ func tplTwitchStreamUptime(username string) (time.Duration, error) {
|
|||
}
|
||||
return time.Since(si.StartedAt), nil
|
||||
}
|
||||
|
||||
func tplTwitchUsernameForID(id string) (string, error) {
|
||||
return twitchClient.GetUsernameForID(context.Background(), id)
|
||||
}
|
||||
|
|
|
@ -159,6 +159,39 @@ func (c *Client) GetIDForUsername(username string) (string, error) {
|
|||
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) {
|
||||
user = strings.TrimLeft(user, "#@")
|
||||
|
||||
|
|
Loading…
Reference in a new issue