70 lines
2.2 KiB
Go
70 lines
2.2 KiB
Go
package predictions
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"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()
|
||
|
||
statusOK := res.StatusCode >= 200 && res.StatusCode < 300
|
||
if !statusOK {
|
||
return nil, fmt.Errorf("failed to create prediction (%d)", res.StatusCode)
|
||
}
|
||
|
||
var data CreatePredictionResponse
|
||
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
return &data, nil
|
||
}
|