package ads import ( "context" "encoding/json" "fmt" "io" "net/http" "go.fifitido.net/twitch/api/endpoint" ) type StartCommercialRequest struct { // The ID of the partner or affiliate broadcaster that wants to run the commercial. This ID must match the user ID found in the OAuth token. BroadcasterID string `json:"broadcaster_id"` // The length of the commercial to run, in seconds. // Twitch tries to serve a commercial that’s the requested length, but it may be shorter or longer. // The maximum length you should request is 180 seconds. Duration int `json:"duration"` } type StartCommercialResponse struct { // An array that contains a single object with the status of your start commercial request. Data []StartCommercialData `json:"data"` } type StartCommercialData struct { // The length of the commercial you requested. If you request a commercial that’s longer than 180 seconds, the API uses 180 seconds. Length int `json:"length"` // A message that indicates whether Twitch was able to serve an ad. Message string `json:"message"` // The number of seconds you must wait before running another commercial. RetryAfter int `json:"retry_after"` } // Starts a commercial on the specified channel. // // NOTE: Only partners and affiliates may run commercials and they must be streaming live at the time. // // NOTE: Only the broadcaster may start a commercial; the broadcaster’s editors and moderators may not start commercials on behalf of the broadcaster. // // Requires a user access token that includes the channel:edit:commercial scope. func (a *Ads) StartCommercial(ctx context.Context, body *StartCommercialRequest) (*StartCommercialResponse, error) { r, w := io.Pipe() go func() { if err := json.NewEncoder(w).Encode(body); err != nil { w.CloseWithError(err) } else { w.Close() } }() req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.Make(a.baseUrl, "channels/commercial"), r) if err != nil { return nil, err } res, err := a.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 start commercial (%d)", res.StatusCode) } var data StartCommercialResponse if err := json.NewDecoder(res.Body).Decode(&data); err != nil { return nil, err } return &data, nil }