go-twitch/api/extensions/send_extension_chat_message.go

67 lines
1.9 KiB
Go
Raw Permalink 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 extensions
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"go.fifitido.net/twitch/api/endpoint"
)
type SendExtensionChatMessageRequest struct {
// The message. The message may contain a maximum of 280 characters.
Text string `json:"text"`
// The ID of the extension thats sending the chat message.
ExtensionID string `json:"extension_id"`
// The extensions version number.
ExtensionVersion string `json:"extension_version"`
}
// Sends a message to the specified broadcasters chat room.
// The extensions name is used as the username for the message in the chat room.
// To send a chat message, your extension must enable Chat Capabilities (under your extensions Capabilities tab).
//
// Rate Limits: You may send a maximum of 12 messages per minute per channel.
//
// 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).
// The role field must be set to external.
func (e *Extensions) SendExtensionChatMessage(ctx context.Context, broadcasterID string, body *SendExtensionChatMessageRequest) error {
v := url.Values{"broadcaster_id": {broadcasterID}}
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/chat", v), 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 chat message (%d)", res.StatusCode)
}
return nil
}