2024-03-02 22:45:59 -05:00
|
|
|
|
package extensions
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"encoding/json"
|
2024-03-07 19:41:05 -05:00
|
|
|
|
"fmt"
|
2024-03-02 22:45:59 -05:00
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
|
|
|
|
"net/url"
|
2024-03-07 20:52:42 -05:00
|
|
|
|
|
|
|
|
|
"go.fifitido.net/twitch/api/endpoint"
|
2024-03-02 22:45:59 -05:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
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.
|
2024-03-07 20:52:42 -05:00
|
|
|
|
func (e *Extensions) SendExtensionChatMessage(ctx context.Context, broadcasterID string, body *SendExtensionChatMessageRequest) error {
|
|
|
|
|
v := url.Values{"broadcaster_id": {broadcasterID}}
|
2024-03-02 22:45:59 -05:00
|
|
|
|
|
|
|
|
|
r, w := io.Pipe()
|
|
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
if err := json.NewEncoder(w).Encode(body); err != nil {
|
|
|
|
|
w.CloseWithError(err)
|
|
|
|
|
} else {
|
|
|
|
|
w.Close()
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
2024-03-07 20:52:42 -05:00
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.Make(e.baseUrl, "extensions/chat", v), r)
|
2024-03-02 22:45:59 -05:00
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-07 20:52:42 -05:00
|
|
|
|
res, err := e.client.Do(req)
|
2024-03-02 22:45:59 -05:00
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
|
2024-03-07 19:41:05 -05:00
|
|
|
|
statusOK := res.StatusCode >= 200 && res.StatusCode < 300
|
|
|
|
|
if !statusOK {
|
|
|
|
|
return fmt.Errorf("failed to send extension chat message (%d)", res.StatusCode)
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-02 22:45:59 -05:00
|
|
|
|
return nil
|
|
|
|
|
}
|