github.com/wtfutil/wtf@v0.43.0/modules/twitch/client.go (about) 1 package twitch 2 3 import ( 4 helix "github.com/nicklaw5/helix/v2" 5 ) 6 7 type Twitch struct { 8 client *helix.Client 9 UserRefreshToken string 10 UserID string 11 Streams string 12 } 13 14 type ClientOpts struct { 15 ClientID string 16 ClientSecret string 17 AppAccessToken string 18 UserAccessToken string 19 UserRefreshToken string 20 RedirectURI string 21 Streams string 22 UserID string 23 } 24 25 func NewClient(opts *ClientOpts) (*Twitch, error) { 26 client, err := helix.NewClient(&helix.Options{ 27 ClientID: opts.ClientID, 28 ClientSecret: opts.ClientSecret, 29 AppAccessToken: opts.AppAccessToken, 30 RedirectURI: opts.RedirectURI, 31 }) 32 if err != nil { 33 return nil, err 34 } 35 36 // Only set user access token if user has selected followed streams. Otherwise it will supercede app access token. 37 // https://github.com/nicklaw5/helix/pull/131 Seems like it should be fixed in this PR of the helix API, but it hasnt been merged for a long time. 38 if opts.Streams == "followed" { 39 client.SetUserAccessToken(opts.UserAccessToken) 40 } 41 42 t := &Twitch{client: client} 43 t.UserRefreshToken = opts.UserRefreshToken 44 t.UserID = opts.UserID 45 t.Streams = opts.Streams 46 if opts.AppAccessToken == "" && opts.ClientSecret != "" { 47 if err := t.RefreshOAuthToken(); err != nil { 48 return nil, err 49 } 50 } 51 52 return t, nil 53 } 54 55 func (t *Twitch) RefreshOAuthToken() error { 56 if t.Streams == "followed" { 57 userResp, err := t.client.RefreshUserAccessToken(t.UserRefreshToken) 58 if err != nil { 59 return err 60 } 61 t.client.SetUserAccessToken(userResp.Data.AccessToken) 62 t.UserRefreshToken = userResp.Data.RefreshToken 63 } else if t.Streams == "top" { 64 appResp, err := t.client.RequestAppAccessToken([]string{}) 65 if err != nil { 66 return err 67 } 68 t.client.SetAppAccessToken(appResp.Data.AccessToken) 69 } 70 71 return nil 72 } 73 74 func (t *Twitch) TopStreams(params *helix.StreamsParams) (*helix.StreamsResponse, error) { 75 if params == nil { 76 params = &helix.StreamsParams{} 77 } 78 return t.client.GetStreams(params) 79 } 80 81 func (t *Twitch) FollowedStreams(params *helix.FollowedStreamsParams) (*helix.StreamsResponse, error) { 82 if params == nil { 83 params = &helix.FollowedStreamsParams{} 84 } 85 return t.client.GetFollowedStream(params) 86 }