package extensions import ( "context" "encoding/json" "fmt" "io" "net/http" "go.fifitido.net/twitch/api/endpoint" ) type SendExtensionPubsubMessageRequest struct { // The target of the message. Possible values are: // // broadcast // global // whisper- // // If is_global_broadcast is true, you must set this field to global. The broadcast and global values are mutually exclusive; specify only one of them. Target []string `json:"target"` // The ID of the broadcaster to send the message to. Don’t include this field if is_global_broadcast is set to true. BroadcasterID *string `json:"broadcaster_id,omitempty"` // A Boolean value that determines whether the message should be sent to all channels where your extension is active. Set to true if the message should be sent to all channels. The default is false. IsGlobalBroadcast *bool `json:"is_global_broadcast,omitempty"` // The message to send. The message can be a plain-text string or a string-encoded JSON object. The message is limited to a maximum of 5 KB. Message string `json:"message"` } // Sends a message to one or more viewers. You can send messages to a specific channel or to all channels where your extension is active. This endpoint uses the same mechanism as the send JavaScript helper function used to send messages. // // Rate Limits: You may send a maximum of 100 messages per minute per combination of extension client ID and broadcaster ID. // // Requires a signed JSON Web Token (JWT) created by an EBS. For signing requirements, // see Signing the JWT: https://dev.twitch.tv/docs/extensions/building/#signing-the-jwt // The signed JWT must include the role, user_id, and exp fields // (see JWT Schema: https://dev.twitch.tv/docs/extensions/reference/#jwt-schema). // along with the channel_id and pubsub_perms fields. The role field must be set to external. // // To send the message to a specific channel, set the channel_id field in the JWT to the channel’s ID and set the pubsub_perms.send array to broadcast. // // To send the message to all channels on which your extension is active, set the channel_id field to all and set the pubsub_perms.send array to global. func (e *Extensions) SendExtensionPubsubMessage(ctx context.Context, body *SendExtensionPubsubMessageRequest) 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(e.baseUrl, "extensions/pubsub"), r) if err != nil { return err } res, err := e.client.Do(req) if err != nil { return err } defer res.Body.Close() statusOK := res.StatusCode >= 200 && res.StatusCode < 300 if !statusOK { return fmt.Errorf("failed to send extension pubsub message (%d)", res.StatusCode) } return nil }