From 9eed838eadadfabd2b7d99cae69deac85625dbe1 Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Sun, 3 Mar 2024 15:50:12 -0500 Subject: [PATCH] Add Predictions endpoints to API --- api/api.go | 3 + api/predictions/create_prediction.go | 63 +++++++++++++++++ api/predictions/end_prediction.go | 66 +++++++++++++++++ api/predictions/get_predictions.go | 69 ++++++++++++++++++ api/predictions/models.go | 101 +++++++++++++++++++++++++++ api/predictions/predictions.go | 18 +++++ 6 files changed, 320 insertions(+) create mode 100644 api/predictions/create_prediction.go create mode 100644 api/predictions/end_prediction.go create mode 100644 api/predictions/get_predictions.go create mode 100644 api/predictions/models.go create mode 100644 api/predictions/predictions.go diff --git a/api/api.go b/api/api.go index dac2aa9..df13f66 100644 --- a/api/api.go +++ b/api/api.go @@ -22,6 +22,7 @@ import ( "go.fifitido.net/twitch/api/hypetrain" "go.fifitido.net/twitch/api/moderation" "go.fifitido.net/twitch/api/polls" + "go.fifitido.net/twitch/api/predictions" ) const HelixBaseUrl = "https://api.twitch.tv/helix" @@ -48,6 +49,7 @@ type API struct { Hypetrain *hypetrain.Hypetrain Moderation *moderation.Moderation Polls *polls.Polls + Predictions *predictions.Predictions } func New() *API { @@ -76,5 +78,6 @@ func New() *API { Hypetrain: hypetrain.New(client, baseUrl), Moderation: moderation.New(client, baseUrl), Polls: polls.New(client, baseUrl), + Predictions: predictions.New(client, baseUrl), } } diff --git a/api/predictions/create_prediction.go b/api/predictions/create_prediction.go new file mode 100644 index 0000000..19175de --- /dev/null +++ b/api/predictions/create_prediction.go @@ -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 that’s 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 it’s 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 +} diff --git a/api/predictions/end_prediction.go b/api/predictions/end_prediction.go new file mode 100644 index 0000000..c9119a3 --- /dev/null +++ b/api/predictions/end_prediction.go @@ -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 that’s 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 +} diff --git a/api/predictions/get_predictions.go b/api/predictions/get_predictions.go new file mode 100644 index 0000000..7a69f33 --- /dev/null +++ b/api/predictions/get_predictions.go @@ -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 cursor’s value. + // Read More: https://dev.twitch.tv/docs/api/guide#pagination + After *types.Cursor `url:"after,omitempty"` +} + +type GetPredictionsResponse struct { + // The broadcaster’s 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 hasn’t 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 +} diff --git a/api/predictions/models.go b/api/predictions/models.go new file mode 100644 index 0000000..5041cef --- /dev/null +++ b/api/predictions/models.go @@ -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 broadcaster’s display name. + BroadcasterName string `json:"broadcaster_name"` + + // The broadcaster’s 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 prediction’s 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 outcome’s 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 viewer’s display name. + UserName string `json:"user_name"` + + // The viewer’s 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" +) diff --git a/api/predictions/predictions.go b/api/predictions/predictions.go new file mode 100644 index 0000000..b8a3c66 --- /dev/null +++ b/api/predictions/predictions.go @@ -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, + } +}