67 lines
1.9 KiB
Go
67 lines
1.9 KiB
Go
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 that’s sending the chat message.
|
||
ExtensionID string `json:"extension_id"`
|
||
|
||
// The extension’s version number.
|
||
ExtensionVersion string `json:"extension_version"`
|
||
}
|
||
|
||
// Sends a message to the specified broadcaster’s chat room.
|
||
// The extension’s 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 extension’s 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
|
||
}
|