chore: import clean Agent Desk snapshot (2/7)
This commit is contained in:
139
internal/discord/client.go
Normal file
139
internal/discord/client.go
Normal file
@@ -0,0 +1,139 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultBaseURL = "https://discord.com/api/v10"
|
||||
|
||||
type Client struct {
|
||||
botToken string
|
||||
baseURL string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func NewClient(botToken string) *Client {
|
||||
return &Client{
|
||||
botToken: strings.TrimSpace(botToken),
|
||||
baseURL: defaultBaseURL,
|
||||
httpClient: &http.Client{Timeout: 15 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) SetBaseURL(url string) {
|
||||
if strings.TrimSpace(url) != "" {
|
||||
c.baseURL = strings.TrimRight(strings.TrimSpace(url), "/")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) GetMe(ctx context.Context) (*User, error) {
|
||||
var user User
|
||||
if err := c.doRequest(ctx, http.MethodGet, "/users/@me", nil, &user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (c *Client) CreateDMChannel(ctx context.Context, recipientID string) (*Channel, error) {
|
||||
if strings.TrimSpace(recipientID) == "" {
|
||||
return nil, fmt.Errorf("recipient_id is required")
|
||||
}
|
||||
req := CreateDMRequest{RecipientID: strings.TrimSpace(recipientID)}
|
||||
var channel Channel
|
||||
if err := c.doRequest(ctx, http.MethodPost, "/users/@me/channels", req, &channel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &channel, nil
|
||||
}
|
||||
|
||||
func (c *Client) SendMessage(ctx context.Context, channelID string, content string) (*Message, error) {
|
||||
channelID = strings.TrimSpace(channelID)
|
||||
if channelID == "" {
|
||||
return nil, fmt.Errorf("channel_id is required")
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return nil, fmt.Errorf("content is required")
|
||||
}
|
||||
|
||||
req := SendMessageRequest{Content: content}
|
||||
var msg Message
|
||||
endpoint := fmt.Sprintf("/channels/%s/messages", channelID)
|
||||
if err := c.doRequest(ctx, http.MethodPost, endpoint, req, &msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
func (c *Client) SendEmbedMessage(ctx context.Context, channelID string, content string, embeds []Embed) (*Message, error) {
|
||||
channelID = strings.TrimSpace(channelID)
|
||||
if channelID == "" {
|
||||
return nil, fmt.Errorf("channel_id is required")
|
||||
}
|
||||
|
||||
req := SendMessageRequest{
|
||||
Content: content,
|
||||
Embeds: embeds,
|
||||
}
|
||||
var msg Message
|
||||
endpoint := fmt.Sprintf("/channels/%s/messages", channelID)
|
||||
if err := c.doRequest(ctx, http.MethodPost, endpoint, req, &msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
func (c *Client) doRequest(ctx context.Context, method, path string, payload any, result any) error {
|
||||
if c.botToken == "" {
|
||||
return fmt.Errorf("discord bot token is required")
|
||||
}
|
||||
|
||||
endpoint := fmt.Sprintf("%s%s", c.baseURL, path)
|
||||
|
||||
var bodyReader io.Reader
|
||||
if payload != nil {
|
||||
bodyBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal discord request failed: %w", err)
|
||||
}
|
||||
bodyReader = bytes.NewBuffer(bodyBytes)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, endpoint, bodyReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create discord request failed: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", "Bot "+c.botToken)
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
res, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("discord http request failed: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
bodyBytes, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read discord response failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode < 200 || res.StatusCode >= 300 {
|
||||
return fmt.Errorf("discord api error (%d): %s", res.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
if err := json.Unmarshal(bodyBytes, result); err != nil {
|
||||
return fmt.Errorf("unmarshal discord response failed: %w (body: %s)", err, string(bodyBytes))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
90
internal/discord/client_test.go
Normal file
90
internal/discord/client_test.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDiscordSendMessage(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bot test_token" {
|
||||
t.Errorf("expected Bot test_token, got %s", r.Header.Get("Authorization"))
|
||||
}
|
||||
if r.URL.Path != "/channels/789/messages" {
|
||||
t.Errorf("expected path /channels/789/messages, got %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":"123456","channel_id":"789","content":"hello"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewClient("test_token")
|
||||
client.SetBaseURL(server.URL)
|
||||
|
||||
resp, err := client.SendMessage(context.Background(), "789", "hello")
|
||||
if err != nil {
|
||||
t.Fatalf("SendMessage failed: %v", err)
|
||||
}
|
||||
if resp.ID != "123456" {
|
||||
t.Errorf("expected ID 123456, got %s", resp.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscordSendEmbedMessage(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bot test_token" {
|
||||
t.Errorf("expected Bot test_token, got %s", r.Header.Get("Authorization"))
|
||||
}
|
||||
if r.URL.Path != "/channels/789/messages" {
|
||||
t.Errorf("expected path /channels/789/messages, got %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":"embed_123","channel_id":"789","content":"Check image"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewClient("test_token")
|
||||
client.SetBaseURL(server.URL)
|
||||
|
||||
embed := Embed{
|
||||
Title: "Screenshot",
|
||||
Image: &EmbedMedia{URL: "https://example.com/img.png"},
|
||||
}
|
||||
resp, err := client.SendEmbedMessage(context.Background(), "789", "Check image", []Embed{embed})
|
||||
if err != nil {
|
||||
t.Fatalf("SendEmbedMessage failed: %v", err)
|
||||
}
|
||||
if resp.ID != "embed_123" {
|
||||
t.Errorf("expected ID embed_123, got %s", resp.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscordCreateDMChannel(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bot test_token" {
|
||||
t.Errorf("expected Bot test_token, got %s", r.Header.Get("Authorization"))
|
||||
}
|
||||
if r.URL.Path != "/users/@me/channels" {
|
||||
t.Errorf("expected path /users/@me/channels, got %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"id":"dm_chan_123","type":1}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewClient("test_token")
|
||||
client.SetBaseURL(server.URL)
|
||||
|
||||
resp, err := client.CreateDMChannel(context.Background(), "user_999")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateDMChannel failed: %v", err)
|
||||
}
|
||||
if resp.ID != "dm_chan_123" {
|
||||
t.Errorf("expected ID dm_chan_123, got %s", resp.ID)
|
||||
}
|
||||
}
|
||||
80
internal/discord/types.go
Normal file
80
internal/discord/types.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package discord
|
||||
|
||||
// User represents a Discord user.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Discriminator string `json:"discriminator,omitempty"`
|
||||
GlobalName string `json:"global_name,omitempty"`
|
||||
Avatar string `json:"avatar,omitempty"`
|
||||
Bot bool `json:"bot,omitempty"`
|
||||
}
|
||||
|
||||
// Channel represents a Discord channel (Guild Text, DM, Thread, etc.).
|
||||
type Channel struct {
|
||||
ID string `json:"id"`
|
||||
Type int `json:"type"`
|
||||
GuildID string `json:"guild_id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// Attachment represents a file or image uploaded to Discord.
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
Filename string `json:"filename"`
|
||||
URL string `json:"url"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// EmbedMedia represents an image/video/thumbnail inside an Embed.
|
||||
type EmbedMedia struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// Embed represents a Discord rich embed object.
|
||||
type Embed struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Color int `json:"color,omitempty"`
|
||||
Image *EmbedMedia `json:"image,omitempty"`
|
||||
}
|
||||
|
||||
// Message represents a Discord message.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChannelID string `json:"channel_id"`
|
||||
GuildID string `json:"guild_id,omitempty"`
|
||||
Author User `json:"author"`
|
||||
Content string `json:"content"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Attachments []Attachment `json:"attachments,omitempty"`
|
||||
Embeds []Embed `json:"embeds,omitempty"`
|
||||
}
|
||||
|
||||
// SendMessageRequest represents payload for Discord create message API.
|
||||
type SendMessageRequest struct {
|
||||
Content string `json:"content,omitempty"`
|
||||
Embeds []Embed `json:"embeds,omitempty"`
|
||||
}
|
||||
|
||||
// CreateDMRequest represents payload for Discord create DM channel API.
|
||||
type CreateDMRequest struct {
|
||||
RecipientID string `json:"recipient_id"`
|
||||
}
|
||||
|
||||
// WebhookPayload represents an incoming message/event from Discord Gateway or Webhook.
|
||||
type WebhookPayload struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Type int `json:"type,omitempty"`
|
||||
GuildID string `json:"guild_id,omitempty"`
|
||||
ChannelID string `json:"channel_id,omitempty"`
|
||||
Author *User `json:"author,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
Timestamp string `json:"timestamp,omitempty"`
|
||||
Attachments []Attachment `json:"attachments,omitempty"`
|
||||
Embeds []Embed `json:"embeds,omitempty"`
|
||||
Message *Message `json:"message,omitempty"`
|
||||
}
|
||||
Reference in New Issue
Block a user