go-twitch/api/ads/start_commercial.go

76 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package ads
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
)
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 thats 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 thats 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 broadcasters 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 (e *Ads) StartCommercial(ctx context.Context, body *StartCommercialRequest) (*StartCommercialResponse, error) {
endpoint := e.baseUrl.ResolveReference(&url.URL{Path: "channels/commercial"})
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.String(), r)
if err != nil {
return nil, err
}
res, err := e.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var data StartCommercialResponse
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, err
}
return &data, nil
}