go-twitch/api/extensions/send_extension_chat_message.go

65 lines
1.9 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 extensions
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
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 (c *Extensions) SendExtensionChatMessage(ctx context.Context, broadcasterID string, body *SendExtensionChatMessageRequest) error {
endpoint := c.baseUrl.ResolveReference(&url.URL{Path: "extensions/chat", RawQuery: "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.String(), r)
if err != nil {
return err
}
res, err := c.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
}