Add Predictions endpoints to API

This commit is contained in:
Evan Fiordeliso 2024-03-03 15:50:12 -05:00
parent 11de434482
commit 9eed838ead
6 changed files with 320 additions and 0 deletions

View File

@ -22,6 +22,7 @@ import (
"go.fifitido.net/twitch/api/hypetrain" "go.fifitido.net/twitch/api/hypetrain"
"go.fifitido.net/twitch/api/moderation" "go.fifitido.net/twitch/api/moderation"
"go.fifitido.net/twitch/api/polls" "go.fifitido.net/twitch/api/polls"
"go.fifitido.net/twitch/api/predictions"
) )
const HelixBaseUrl = "https://api.twitch.tv/helix" const HelixBaseUrl = "https://api.twitch.tv/helix"
@ -48,6 +49,7 @@ type API struct {
Hypetrain *hypetrain.Hypetrain Hypetrain *hypetrain.Hypetrain
Moderation *moderation.Moderation Moderation *moderation.Moderation
Polls *polls.Polls Polls *polls.Polls
Predictions *predictions.Predictions
} }
func New() *API { func New() *API {
@ -76,5 +78,6 @@ func New() *API {
Hypetrain: hypetrain.New(client, baseUrl), Hypetrain: hypetrain.New(client, baseUrl),
Moderation: moderation.New(client, baseUrl), Moderation: moderation.New(client, baseUrl),
Polls: polls.New(client, baseUrl), Polls: polls.New(client, baseUrl),
Predictions: predictions.New(client, baseUrl),
} }
} }

View File

@ -0,0 +1,63 @@
package predictions
import (
"context"
"encoding/json"
"net/http"
"net/url"
"github.com/google/go-querystring/query"
)
type CreatePredictionRequest struct {
// The ID of the broadcaster thats running the prediction. This ID must match the user ID in the user access token.
BroadcasterID string `json:"broadcaster_id"`
// The question that the broadcaster is asking. For example, Will I finish this entire pizza?
Title string `json:"title"`
// The list of possible outcomes that the viewers may choose from. The list must contain a minimum of 2 choices and up to a maximum of 10 choices.
Outcomes []CreateOutcome `json:"outcomes"`
// The length of time (in seconds) that the prediction will run for. The minimum is 30 seconds and the maximum is 1800 seconds (30 minutes).
PredictionWindow int `json:"prediction_window"`
}
type CreateOutcome struct {
// The text of one of the outcomes that the viewer may select. The title is limited to a maximum of 25 characters.
Title string `json:"title"`
}
type CreatePredictionResponse struct {
// A list that contains the single prediction that you created.
Data []Prediction `json:"data"`
}
// Creates a Channel Points Prediction.
//
// With a Channel Points Prediction, the broadcaster poses a question and viewers try to predict the outcome.
// The prediction runs as soon as its created. The broadcaster may run only one prediction at a time.
//
// Requires a user access token that includes the channel:manage:predictions scope.
func (c *Predictions) CreatePrediction(ctx context.Context, params *CreatePredictionRequest) (*CreatePredictionResponse, error) {
v, _ := query.Values(params)
endpoint := c.baseUrl.ResolveReference(&url.URL{Path: "predictions", RawQuery: v.Encode()})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), nil)
if err != nil {
return nil, err
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var data CreatePredictionResponse
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, err
}
return &data, nil
}

View File

@ -0,0 +1,66 @@
package predictions
import (
"context"
"encoding/json"
"net/http"
"net/url"
"github.com/google/go-querystring/query"
)
type EndPredictionRequest struct {
// The ID of the broadcaster thats running the prediction. This ID must match the user ID in the user access token.
BroadcasterID string `json:"broadcaster_id"`
// The ID of the prediction to update.
ID string `json:"id"`
// The status to set the prediction to. Possible case-sensitive values are:
//
// RESOLVED — The winning outcome is determined and the Channel Points are distributed to the viewers who predicted the correct outcome.
//
// CANCELED — The broadcaster is canceling the prediction and sending refunds to the participants.
//
// LOCKED — The broadcaster is locking the prediction, which means viewers may no longer make predictions.
//
// The broadcaster can update an active prediction to LOCKED, RESOLVED, or CANCELED; and update a locked prediction to RESOLVED or CANCELED.
//
// The broadcaster has up to 24 hours after the prediction window closes to resolve the prediction.
// If not, Twitch sets the status to CANCELED and returns the points.
Status Status `json:"status"`
// The ID of the winning outcome. You must set this parameter if you set status to RESOLVED.
WinningOutcomeID *string `json:"winning_outcome_id"`
}
type EndPredictionResponse struct {
// A list that contains the single prediction that you updated.
Data []Prediction `json:"data"`
}
// Locks, resolves, or cancels a Channel Points Prediction.
//
// Requires a user access token that includes the channel:manage:predictions scope.
func (c *Predictions) EndPrediction(ctx context.Context, params *EndPredictionRequest) (*EndPredictionResponse, error) {
v, _ := query.Values(params)
endpoint := c.baseUrl.ResolveReference(&url.URL{Path: "predictions", RawQuery: v.Encode()})
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, endpoint.String(), nil)
if err != nil {
return nil, err
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var data EndPredictionResponse
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, err
}
return &data, nil
}

View File

@ -0,0 +1,69 @@
package predictions
import (
"context"
"encoding/json"
"net/http"
"net/url"
"github.com/google/go-querystring/query"
"go.fifitido.net/twitch/api/types"
)
type GetPredictionsParams struct {
// The ID of the broadcaster whose predictions you want to get. This ID must match the user ID in the user access token.
BroadcasterID string `url:"broadcaster_id"`
// The ID of the prediction to get.
// To specify more than one ID, include this parameter for each prediction you want to get. For example, id=1234&id=5678.
// You may specify a maximum of 25 IDs. The endpoint ignores duplicate IDs and those not owned by the broadcaster.
IDs []string `url:"id,omitempty"`
// The maximum number of items to return per page in the response.
// The minimum page size is 1 item per page and the maximum is 25 items per page.
// The default is 20.
First *int `url:"first,omitempty"`
// The cursor used to get the next page of results.
// The Pagination object in the response contains the cursors value.
// Read More: https://dev.twitch.tv/docs/api/guide#pagination
After *types.Cursor `url:"after,omitempty"`
}
type GetPredictionsResponse struct {
// The broadcasters list of Channel Points Predictions.
// The list is sorted in descending ordered by when the prediction began (the most recent prediction is first).
// The list is empty if the broadcaster hasnt created predictions.
Data []Prediction `json:"data"`
// A pagination object that contains the cursor to use to get the next page of results.
// The object is empty if there are no more pages left to page through.
// Read More: https://dev.twitch.tv/docs/api/guide#pagination
Pagination types.Pagination `json:"pagination"`
}
// Gets a list of Channel Points Predictions that the broadcaster created.
//
// Requires a user access token that includes the channel:read:predictions or channel:manage:predictions scope.
func (c *Predictions) GetPredictions(ctx context.Context, params *GetPredictionsParams) (*GetPredictionsResponse, error) {
v, _ := query.Values(params)
endpoint := c.baseUrl.ResolveReference(&url.URL{Path: "predictions", RawQuery: v.Encode()})
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, err
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var data GetPredictionsResponse
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, err
}
return &data, nil
}

101
api/predictions/models.go Normal file
View File

@ -0,0 +1,101 @@
package predictions
import "time"
type Prediction struct {
// An ID that identifies this prediction.
ID string `json:"id"`
// An ID that identifies the broadcaster that created the prediction.
BroadcasterID string `json:"broadcaster_id"`
// The broadcasters display name.
BroadcasterName string `json:"broadcaster_name"`
// The broadcasters login name.
BroadcasterLogin string `json:"broadcaster_login"`
// The question that the prediction asks. For example, Will I finish this entire pizza?
Title string `json:"title"`
// The ID of the winning outcome. Is null unless status is RESOLVED.
WinningOutcomeID string `json:"winning_outcome_id"`
// The list of possible outcomes for the prediction.
Outcomes []Outcome `json:"outcomes"`
// The length of time (in seconds) that the prediction will run for.
PredictionWindow int `json:"prediction_window"`
// The predictions status.
Status Status `json:"status"`
// The UTC date and time of when the Prediction began.
CreatedAt time.Time `json:"created_at"`
// The UTC date and time of when the Prediction ended. If status is ACTIVE, this is set to null.
EndedAt *time.Time `json:"ended_at"`
// The UTC date and time of when the Prediction was locked. If status is not LOCKED, this is set to null.
LockedAt *time.Time `json:"locked_at"`
}
type Outcome struct {
// An ID that identifies this outcome.
ID string `json:"id"`
// The outcomes text.
Title string `json:"title"`
// The number of unique viewers that chose this outcome.
Users int `json:"users"`
// The number of Channel Points spent by viewers on this outcome.
ChannelPoints int `json:"channel_points"`
// A list of viewers who were the top predictors; otherwise, null if none.
TopPredictors []TopPredictor `json:"top_predictors"`
// The color that visually identifies this outcome in the UX.
Color Color `json:"color"`
}
type TopPredictor struct {
// An ID that identifies the viewer.
UserID string `json:"user_id"`
// The viewers display name.
UserName string `json:"user_name"`
// The viewers login name.
UserLogin string `json:"user_login"`
// The number of Channel Points the viewer spent.
ChannelPointsUsed int `json:"channel_points_used"`
// The number of Channel Points distributed to the viewer.
ChannelPointsWon int `json:"channel_points_won"`
}
type Color string
const (
ColorBlue Color = "BLUE"
ColorPink Color = "PINK"
)
type Status string
const (
// The Prediction is running and viewers can make predictions.
StatusActive Status = "ACTIVE"
// The broadcaster canceled the Prediction and refunded the Channel Points to the participants.
StatusCanceled Status = "CANCELED"
// The broadcaster locked the Prediction, which means viewers can no longer make predictions.
StatusLocked Status = "LOCKED"
// The winning outcome was determined and the Channel Points were distributed to the viewers who predicted the correct outcome.
StatusResolved Status = "RESOLVED"
)

View File

@ -0,0 +1,18 @@
package predictions
import (
"net/http"
"net/url"
)
type Predictions struct {
client *http.Client
baseUrl *url.URL
}
func New(client *http.Client, baseUrl *url.URL) *Predictions {
return &Predictions{
client: client,
baseUrl: baseUrl,
}
}