discord

package module
v0.0.0-...-8a1bf6a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

discord-api-go

個人用途のために作成された、 Go 言語向けの Discord API クライアントライブラリです。REST API と Gateway WebSocket を統合サポートします。

インストール

go get github.com/sikigasa/discord-api-go

概要

モジュール構成

このライブラリは以下の主要コンポーネントで構成されます:

  • API - Discord REST API クライアント
    • Gateway Bot URL 取得
    • グローバルコマンド登録
    • インタラクションレスポンス
  • Gateway - Discord Gateway WebSocket 接続管理
    • WebSocket 接続・切断
    • イベントハンドラー登録
    • ハートビート管理
    • READY 状態確認
  • Client - 統合クライアント
    • REST API と Gateway を一つのインターフェースで提供
    • インタラクション処理
    • コマンド登録

使用例

基本的な使い方
package main

import (
 "context"
 "log/slog"
 "os"

 "github.com/sikigasa/discord-api-go"
)

func main() {
 // ロガーとクライアント初期化
 logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
 client := discord.NewClient(os.Getenv("DISCORD_BOT_TOKEN"), logger)

 // インタラクションハンドラー登録
 client.OnInteraction(func(inter *discord.Interaction) {
  if inter.Type == discord.InteractionTypeApplicationCommand {
   response := &discord.InteractionResponse{
    Type: discord.InteractionCallbackChannelMessageWithSource,
    Data: &discord.InteractionResponseData{
     Content: "Pong!",
    },
   }
   client.RespondToInteraction(inter.ID, inter.Token, response)
  }
 })

 // Gateway に接続
 if err := client.Open(); err != nil {
  logger.Error("Failed to open client", "error", err)
  return
 }
 defer client.Close()

 // コマンド登録例
 commands := []*discord.ApplicationCommand{
  {
   Name:        "ping",
   Description: "Ping コマンド",
  },
 }
 if err := client.RegisterCommands(commands); err != nil {
  logger.Error("Failed to register commands", "error", err)
  return
 }

 // イベント処理中...
 <-client.Gateway.Done()
}

API 仕様

Client
NewClient(token string, logger *slog.Logger) *Client

新しい統合クライアントを作成します。

パラメータ:

  • token - Discord Bot Token
  • logger - slog.Logger インスタンス

戻り値:

  • 初期化された Client インスタンス
func (c *Client) OnInteraction(handler func(*Interaction))

インタラクションハンドラーを登録します。

func (c *Client) Open() error

Gateway に接続し、イベント購読を開始します。

func (c *Client) Close() error

Gateway 接続を閉じます。

func (c *Client) BotUser() *User

Bot 自身のユーザー情報を返します(接続後)。

func (c *Client) RegisterCommands(commands []*ApplicationCommand) error

スラッシュコマンドを一括登録します。

func (c *Client) RespondToInteraction(interactionID, interactionToken string, response *InteractionResponse) error

インタラクションに応答します。

API
NewAPI(token string, logger *slog.Logger) *API

新しい Discord REST API クライアントを作成します。

func (a *API) GetGatewayBot() (*GatewayBotResponse, error)

Gateway Bot URL とシャード情報を取得します。

func (a *API) BulkOverwriteGlobalCommands(appID string, commands []*ApplicationCommand) ([]*ApplicationCommand, error)

グローバルコマンドを一括登録します。

func (a *API) CreateInteractionResponse(interactionID, interactionToken string, response *InteractionResponse) error

インタラクションに応答します。

Gateway
NewGateway(token string, intents int, logger *slog.Logger) *Gateway

新しい Gateway 接続を作成します。

パラメータ:

  • token - Discord Bot Token
  • intents - Gateway Intents フラグ(通常は 0)
  • logger - slog.Logger インスタンス
func (g *Gateway) On(event string, handler func(json.RawMessage))

イベントハンドラーを登録します。

対応イベント:

  • READY - 接続準備完了
  • INTERACTION_CREATE - インタラクション受信
func (g *Gateway) Connect(gatewayURL string) error

Gateway に接続します。

func (g *Gateway) Close() error

Gateway 接続を切断します。

func (g *Gateway) BotUser() *User

Bot 自身のユーザー情報を返します。

func (g *Gateway) Done() <-chan struct{}

接続が閉じられたときに閉じるチャネルを返します。

型定義

Interaction

Discord インタラクション構造です。

type Interaction struct {
 ID        string           // インタラクション ID
 Type      int              // InteractionType 定数
 Token     string           // インタラクショントークン
 GuildID   string           // ギルド ID(オプション)
 ChannelID string           // チャネル ID(オプション)
 Data      *InteractionData // インタラクションデータ
 AppID     string           // アプリケーション ID(オプション)
}
InteractionResponse

インタラクションレスポンス構造です。

type InteractionResponse struct {
 Type int                      // InteractionCallback* 定数
 Data *InteractionResponseData // レスポンスデータ
}
ApplicationCommand

スラッシュコマンド定義です。

type ApplicationCommand struct {
 ID          string                      // コマンド ID(取得時のみ)
 Name        string                      // コマンド名
 Description string                      // コマンド説明
 Options     []*ApplicationCommandOption // オプション(オプション)
}

Documentation

Index

Constants

View Source
const (
	OpcodeDispatch            = 0
	OpcodeHeartbeat           = 1
	OpcodeIdentify            = 2
	OpcodePresenceUpdate      = 3
	OpcodeVoiceStateUpdate    = 4
	OpcodeResume              = 6
	OpcodeReconnect           = 7
	OpcodeRequestGuildMembers = 8
	OpcodeInvalidSession      = 9
	OpcodeHello               = 10
	OpcodeHeartbeatACK        = 11
)
View Source
const (
	InteractionTypePing               = 1
	InteractionTypeApplicationCommand = 2
	InteractionTypeMessageComponent   = 3
	InteractionTypeAutocomplete       = 4
	InteractionTypeModalSubmit        = 5
)

InteractionType 定数

View Source
const (
	InteractionCallbackPong                     = 1
	InteractionCallbackChannelMessageWithSource = 4
	InteractionCallbackDeferredChannelMessage   = 5
	InteractionCallbackDeferredUpdateMessage    = 6
	InteractionCallbackUpdateMessage            = 7
)

InteractionCallbackType 定数

View Source
const (
	OptionTypeSubCommand      = 1
	OptionTypeSubCommandGroup = 2
	OptionTypeString          = 3
	OptionTypeInteger         = 4
	OptionTypeBoolean         = 5
	OptionTypeUser            = 6
	OptionTypeChannel         = 7
	OptionTypeRole            = 8
	OptionTypeMentionable     = 9
	OptionTypeNumber          = 10
)

ApplicationCommandOptionType 定数

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API はDiscord APIクライアント

func NewAPI

func NewAPI(token string, logger *slog.Logger) *API

NewAPI は新しいDiscord APIクライアントを作成する

func (*API) BulkOverwriteGlobalCommands

func (r *API) BulkOverwriteGlobalCommands(appID string, commands []*ApplicationCommand) ([]*ApplicationCommand, error)

BulkOverwriteGlobalCommands はグローバルコマンドを一括登録する

func (*API) CreateInteractionResponse

func (r *API) CreateInteractionResponse(interactionID, interactionToken string, response *InteractionResponse) error

CreateInteractionResponse はインタラクションに応答する

func (*API) GetGatewayBot

func (r *API) GetGatewayBot() (*GatewayBotResponse, error)

GetGatewayBot は Gateway Bot URL を取得する

type ApplicationCommand

type ApplicationCommand struct {
	ID          string                      `json:"id,omitempty"`
	Name        string                      `json:"name"`
	Description string                      `json:"description"`
	Options     []*ApplicationCommandOption `json:"options,omitempty"`
}

ApplicationCommand はスラッシュコマンド定義

type ApplicationCommandOption

type ApplicationCommandOption struct {
	Name        string                            `json:"name"`
	Description string                            `json:"description"`
	Type        int                               `json:"type"`
	Required    bool                              `json:"required,omitempty"`
	Options     []*ApplicationCommandOption       `json:"options,omitempty"`
	Choices     []*ApplicationCommandOptionChoice `json:"choices,omitempty"`
}

ApplicationCommandOption はコマンドオプション定義

type ApplicationCommandOptionChoice

type ApplicationCommandOptionChoice struct {
	Name  string      `json:"name"`
	Value interface{} `json:"value"`
}

ApplicationCommandOptionChoice はオプションの選択肢

type Client

type Client struct {
	API     *API
	Gateway *Gateway
	// contains filtered or unexported fields
}

Client はDiscord API統合クライアント

func NewClient

func NewClient(token string, logger *slog.Logger) *Client

NewClient は新しいDiscord Clientを作成する

func (*Client) BotUser

func (c *Client) BotUser() *User

BotUser はBot自身のユーザー情報を返す

func (*Client) Close

func (c *Client) Close() error

Close はGateway接続を閉じる

func (*Client) OnInteraction

func (c *Client) OnInteraction(handler func(*Interaction))

OnInteraction はインタラクションハンドラーを登録する

func (*Client) Open

func (c *Client) Open() error

Open はGatewayに接続し、イベント購読を開始する

func (*Client) RegisterCommands

func (c *Client) RegisterCommands(commands []*ApplicationCommand) error

RegisterCommands はスラッシュコマンドを一括登録する

func (*Client) RespondToInteraction

func (c *Client) RespondToInteraction(interactionID, interactionToken string, response *InteractionResponse) error

RespondToInteraction はインタラクションに応答する

type Gateway

type Gateway struct {
	// contains filtered or unexported fields
}

Gateway はDiscord Gateway WebSocket接続を管理する

func NewGateway

func NewGateway(token string, intents int, logger *slog.Logger) *Gateway

NewGateway は新しいGatewayを作成する

func (*Gateway) BotUser

func (g *Gateway) BotUser() *User

BotUser はBot自身のユーザー情報を返す

func (*Gateway) Close

func (g *Gateway) Close() error

Close はGateway接続を閉じる

func (*Gateway) Connect

func (g *Gateway) Connect(gatewayURL string) error

Connect はGatewayに接続する

func (*Gateway) Done

func (g *Gateway) Done() <-chan struct{}

Done は接続が閉じられたときに閉じるチャネルを返す

func (*Gateway) On

func (g *Gateway) On(event string, handler func(json.RawMessage))

On はイベントハンドラーを登録する

type GatewayBotResponse

type GatewayBotResponse struct {
	URL    string `json:"url"`
	Shards int    `json:"shards"`
}

GatewayBotResponse は GET /gateway/bot のレスポンス

type GatewayPayload

type GatewayPayload struct {
	Op int             `json:"op"`
	D  json.RawMessage `json:"d,omitempty"`
	S  *int64          `json:"s,omitempty"`
	T  string          `json:"t,omitempty"`
}

GatewayPayload はGateway WebSocketのメッセージ

type HelloData

type HelloData struct {
	HeartbeatInterval int `json:"heartbeat_interval"`
}

HelloData は opcode 10 (Hello) のデータ

type IdentifyData

type IdentifyData struct {
	Token      string             `json:"token"`
	Intents    int                `json:"intents"`
	Properties IdentifyProperties `json:"properties"`
}

IdentifyData は opcode 2 (Identify) のデータ

type IdentifyProperties

type IdentifyProperties struct {
	OS      string `json:"os"`
	Browser string `json:"browser"`
	Device  string `json:"device"`
}

IdentifyProperties はIdentifyのプロパティ

type Interaction

type Interaction struct {
	ID        string           `json:"id"`
	Type      int              `json:"type"`
	Token     string           `json:"token"`
	GuildID   string           `json:"guild_id,omitempty"`
	ChannelID string           `json:"channel_id,omitempty"`
	Data      *InteractionData `json:"data,omitempty"`
	AppID     string           `json:"application_id,omitempty"`
}

Interaction はDiscordインタラクションを表す

type InteractionData

type InteractionData struct {
	ID      string                   `json:"id"`
	Name    string                   `json:"name"`
	Options []*InteractionDataOption `json:"options,omitempty"`
}

InteractionData はインタラクションのデータ

type InteractionDataOption

type InteractionDataOption struct {
	Name    string                   `json:"name"`
	Type    int                      `json:"type"`
	Value   interface{}              `json:"value,omitempty"`
	Options []*InteractionDataOption `json:"options,omitempty"`
}

InteractionDataOption はインタラクションオプション

func (*InteractionDataOption) IntValue

func (o *InteractionDataOption) IntValue() int64

IntValue はオプションの整数値を返す

func (*InteractionDataOption) StringValue

func (o *InteractionDataOption) StringValue() string

StringValue はオプションの文字列値を返す

type InteractionResponse

type InteractionResponse struct {
	Type int                      `json:"type"`
	Data *InteractionResponseData `json:"data,omitempty"`
}

InteractionResponse はインタラクションレスポンス

type InteractionResponseData

type InteractionResponseData struct {
	Content string          `json:"content,omitempty"`
	Embeds  []*MessageEmbed `json:"embeds,omitempty"`
}

InteractionResponseData はインタラクションレスポンスのデータ

type MessageEmbed

type MessageEmbed struct {
	Title       string               `json:"title,omitempty"`
	Description string               `json:"description,omitempty"`
	Color       int                  `json:"color,omitempty"`
	Fields      []*MessageEmbedField `json:"fields,omitempty"`
	Footer      *MessageEmbedFooter  `json:"footer,omitempty"`
}

MessageEmbed はメッセージ埋め込み

type MessageEmbedField

type MessageEmbedField struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Inline bool   `json:"inline,omitempty"`
}

MessageEmbedField は埋め込みフィールド

type MessageEmbedFooter

type MessageEmbedFooter struct {
	Text string `json:"text"`
}

MessageEmbedFooter は埋め込みフッター

type ReadyData

type ReadyData struct {
	V         int    `json:"v"`
	User      User   `json:"user"`
	SessionID string `json:"session_id"`
	ResumeURL string `json:"resume_gateway_url"`
}

ReadyData は READY イベントのデータ

type ResumeData

type ResumeData struct {
	Token     string `json:"token"`
	SessionID string `json:"session_id"`
	Seq       int64  `json:"seq"`
}

ResumeData は opcode 6 (Resume) のデータ

type User

type User struct {
	ID            string `json:"id"`
	Username      string `json:"username"`
	Discriminator string `json:"discriminator"`
	GlobalName    string `json:"global_name,omitempty"`
	Bot           bool   `json:"bot,omitempty"`
}

User はDiscordユーザーを表す

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址