discord

package module
v0.0.0-...-d7ed7a3 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2022 License: MIT Imports: 16 Imported by: 0

README

discord

Quick Example

package main

import (
	"fmt"
	"github.com/jnsougata/discord"
	"os"
)

func main() {

	bot := discord.New(discord.Intents())
	bot.Cached = true
	bot.Presence = discord.Presence{
          Since:  0,
          Status: discord.Online,
          Activity: discord.Activity{
                Name: "/ping",
                Type: discord.Listening,
          },
    }
	bot.Listeners = listeners
	bot.Commands(avatar)
	bot.Run(os.Getenv("DISCORD_TOKEN"))
}

var listeners = discord.Listeners{
    OnReady: func(bot discord.Bot) {
    	fmt.Println(fmt.Sprintf("Running %s#%s (Id: %s)", bot.Username, bot.Discriminator, bot.Id))
    	fmt.Println("-------")
    },
    // add more built-in listeners here
}

var avatar = discord.Command{
	Name:        "avatar",
	Description: "shows the avatar of the invoker",
	Execute: func(bot discord.Bot, ctx discord.Context, options discord.ResolvedOptions) {
		ctx.Send(discord.Response{Embed: discord.Embed{Image: discord.EmbedImage{Url: ctx.Author.Avatar.URL()}}})
	},
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	OptionTypes = optionKind{
		String:      3,
		Integer:     4,
		Boolean:     5,
		User:        6,
		Channel:     7,
		Role:        8,
		Mentionable: 9,
		Number:      10,
		Attachment:  11,
	}

	ChannelTypes = channelTypes{
		Text:          0,
		DM:            1,
		Voice:         2,
		GroupDM:       3,
		Category:      4,
		News:          5,
		NewsThread:    10,
		PublicThread:  11,
		PrivateThread: 12,
		StageVoice:    13,
		Directory:     14,
		Forum:         15,
	}

	CommandTypes = commandTypes{
		Slash:   1,
		User:    2,
		Message: 3,
	}

	ButtonStyles = buttonStyles{
		Blue:  1,
		Grey:  2,
		Green: 3,
		Red:   4,
		Link:  5,
	}
)
View Source
var Intents = intents{
	Members:   intent(1 << 1),
	Contents:  intent(1 << 15),
	Presences: intent(1 << 8),
}
View Source
var Permissions = perms()

Functions

func New

func New(intent intent) *connection

New is a function that represents a connection to discord.

Types

type Activity

type Activity struct {
	Name string       `json:"name"`
	Type ActivityType `json:"type"`
	URL  string       `json:"url"` // "url" for ActivityType Streaming
}

func (*Activity) Marshal

func (a *Activity) Marshal() map[string]interface{}

type ActivityType

type ActivityType int
const (
	Playing   ActivityType = 0
	Streaming ActivityType = 1
	Listening ActivityType = 2
	Watching  ActivityType = 3
	Competing ActivityType = 5
)

type Asset

type Asset struct {
	Hash   string
	Size   int64
	Format string
	Extras string
}

func (Asset) CustomURL

func (a Asset) CustomURL(size int64, format string) string

func (Asset) URL

func (a Asset) URL() string

type Attachment

type Attachment struct {
	ID          string `json:"id"`
	Filename    string `json:"filename"`
	Description string `json:"description"`
	ContentType string `json:"content_type"`
	Size        int    `json:"size"`
	URL         string `json:"url"`
	ProxyURL    string `json:"proxy_url"`
	Width       int    `json:"width"`
	Height      int    `json:"height"`
	Ephemeral   bool   `json:"ephemeral"`
}

Attachment represents a base Discord attachment

type Bot

type Bot struct {
	Id            string `json:"id"`
	Username      string `json:"username"`
	Discriminator string `json:"discriminator"`
	Avatar        string `json:"avatar"`
	MfaEnabled    bool   `json:"mfa_enabled"`
	Banner        string `json:"banner"`
	Color         int    `json:"accent_color"`
	Locale        string `json:"locale"`
	Verified      bool   `json:"verified"`
	Flags         int    `json:"flags"`
	PublicFlags   int    `json:"public_flags"`
	Latency       int64  `json:"latency"`
	Guilds        map[string]*Guild
	Users         map[string]*User
}

type Button

type Button struct {
	Style    int
	Label    string
	Emoji    PartialEmoji
	URL      string
	Disabled bool
	OnClick  func(bot Bot, ctx Context)
	// contains filtered or unexported fields
}

type Channel

type Channel struct {
	Id                         string        `json:"id"`
	Type                       int           `json:"type"`
	GuildId                    string        `json:"guild_id"`
	Position                   int           `json:"position"`
	Overwrites                 []interface{} `json:"permission_overwrites"`
	Name                       string        `json:"name"`
	Topic                      string        `json:"topic"`
	NSFW                       bool          `json:"nsfw"`
	LastMessageId              string        `json:"last_message_id"`
	Bitrate                    int           `json:"bitrate"`
	UserLimit                  int           `json:"user_limit"`
	RateLimitPerUser           int           `json:"rate_limit_per_user"`
	Recipients                 []interface{} `json:"recipients"`
	Icon                       string        `json:"icon"`
	OwnerId                    string        `json:"owner_id"`
	ApplicationId              string        `json:"application_id"`
	ParentId                   string        `json:"parent_id"`
	LastPinTime                int           `json:"last_pin_timestamp"`
	RTCRegion                  string        `json:"rtc_region"`
	VideoQualityMode           int           `json:"video_quality_mode"`
	MessageCount               int           `json:"message_count"`
	ThreadMetaData             interface{}   `json:"thread_metadata"`
	Member                     interface{}   `json:"member"`
	DefaultAutoArchiveDuration int           `json:"default_auto_archive_days"`
	Permissions                string        `json:"permissions"`
	Flags                      int           `json:"flags"`
	TotalMessages              int           `json:"total_messages"`
	// contains filtered or unexported fields
}

Channel represents a Discord channel of any type

func (*Channel) Send

func (c *Channel) Send(draft *ChannelMessage) (Message, error)

type ChannelMessage

type ChannelMessage struct {
	Content        string
	Embed          Embed
	Embeds         []Embed
	TTS            bool
	View           View
	File           File
	Files          []File
	SuppressEmbeds bool
	Reference      any
	DeleteAfter    float64
}

type Choice

type Choice struct {
	Name  string      `json:"name"`
	Value interface{} `json:"Value"` // same type as type of Option
}

type Command

type Command struct {
	Type         int    // defaults to chat input
	Name         string // must be less than 32 characters
	Description  string // must be less than 100 characters
	Options      []Option
	DMPermission bool         // default: false
	Permissions  []Permission // default: send_messages
	GuildId      int64

	Execute          func(bot Bot, ctx Context, options ResolvedOptions)
	AutocompleteTask func(bot Bot, ctx Context, choices ...Choice)
	// contains filtered or unexported fields
}

Command is a base type for all discord application commands

func (*Command) SubCommand

func (cmd *Command) SubCommand(subcommand SubCommand)

func (*Command) SubcommandGroups

func (cmd *Command) SubcommandGroups(subcommandGroups ...SubcommandGroup)

type Context

type Context struct {
	Id             string `json:"id"`
	ApplicationId  string `json:"application_id"`
	Type           int    `json:"type"`
	Data           Data   `json:"data"`
	GuildId        string `json:"guild_id"`
	ChannelId      string `json:"channel_id"`
	User           User   `json:"user"`
	Token          string `json:"token"`
	Version        int    `json:"version"`
	AppPermissions string `json:"app_permissions"`
	Locale         string `json:"locale"`
	GuildLocale    string `json:"guild_locale"`
	TargetUser     User
	TargetMessage  Message
	Channel        Channel
	Guild          Guild
	Author         Member
	// contains filtered or unexported fields
}

func (*Context) DeferResponse

func (c *Context) DeferResponse(ephemeral bool)

func (*Context) DeleteResponse

func (c *Context) DeleteResponse()

func (*Context) EditResponse

func (c *Context) EditResponse(response *Response) error

func (*Context) FollowupResponse

func (c *Context) FollowupResponse(response *Response) (Message, error)

func (*Context) ModalResponse

func (c *Context) ModalResponse(modal *Modal) error

func (*Context) OriginalResponse

func (c *Context) OriginalResponse() Message

func (*Context) SendResponse

func (c *Context) SendResponse(response *Response) error

type Data

type Data struct {
	Id       string                 `json:"id"`
	Name     string                 `json:"name"`
	Type     int                    `json:"type"`
	Resolved map[string]interface{} `json:"resolved"`
	Options  []Option               `json:"Options"`
	GuildId  string                 `json:"guild_id"`
	TargetId string                 `json:"target_id"`
}

type Embed

type Embed struct {
	Title       string       `json:"title"`
	Description string       `json:"description"`
	URL         string       `json:"url"`
	Timestamp   string       `json:"timestamp"`
	Color       int          `json:"color"`
	Footer      embedFooter  `json:"footer"`
	Author      embedAuthor  `json:"author"`
	Image       embedImage   `json:"image"`
	Thumbnail   embedImage   `json:"thumbnail"`
	Fields      []embedField `json:"fields"`
}

func (*Embed) SetAuthor

func (e *Embed) SetAuthor(name string, iconURL string) error

func (*Embed) SetField

func (e *Embed) SetField(name string, value string, inline bool) error

func (*Embed) SetFooter

func (e *Embed) SetFooter(text string, iconURL string) error

func (*Embed) SetImage

func (e *Embed) SetImage(url string) error

func (*Embed) SetThumbnail

func (e *Embed) SetThumbnail(url string) error

type Emoji

type Emoji struct {
	Id            int64    `json:"id,string"`
	Name          string   `json:"name"`
	Roles         []string `json:"roles"`
	Managed       bool     `json:"managed"`
	Animated      bool     `json:"animated"`
	Available     bool     `json:"available"`
	RequireColons bool     `json:"require_colons"`
}

type File

type File struct {
	Name        string
	Content     []byte
	Description string
}

func (*File) Write

func (f *File) Write(path string) error

type Guild

type Guild struct {
	Id                          string                   `json:"id"`
	Name                        string                   `json:"name"`
	Owner                       bool                     `json:"owner"`
	OwnerID                     string                   `json:"owner_id"`
	Permissions                 string                   `json:"permissions"`
	Region                      string                   `json:"region"`
	AfkChannelID                string                   `json:"afk_channel_id"`
	AfkTimeout                  int                      `json:"afk_timeout"`
	WidgetEnabled               bool                     `json:"widget_enabled"`
	WidgetChannelID             string                   `json:"widget_channel_id"`
	VerificationLevel           int                      `json:"verification_level"`
	DefaultMessageNotifications int                      `json:"default_message_notifications"`
	ExplicitContentFilter       int                      `json:"explicit_content_filter"`
	Emojis                      []Emoji                  `json:"emojis"`
	Features                    []string                 `json:"features"`
	MFALevel                    int                      `json:"mfa_level"`
	ApplicationID               string                   `json:"application_id"`
	SystemChannelID             string                   `json:"system_channel_id"`
	SystemChannelFlags          int                      `json:"system_channel_flags"`
	RulesChannelID              string                   `json:"rules_channel_id"`
	MaxPresences                int                      `json:"max_presences"`
	MaxMembers                  int                      `json:"max_members"`
	VanityURLCode               string                   `json:"vanity_url_code"`
	Description                 string                   `json:"description"`
	PremiumTier                 int                      `json:"premium_tier"`
	PremiumSubscriptionCount    int                      `json:"premium_subscription_count"`
	PreferredLocale             string                   `json:"preferred_locale"`
	PublicUpdatesChannelID      string                   `json:"public_updates_channel_id"`
	MaxVideoChannelUsers        int                      `json:"max_video_channel_users"`
	ApproximateMemberCount      int                      `json:"approximate_member_count"`
	ApproximatePresenceCount    int                      `json:"approximate_presence_count"`
	WelcomeScreen               map[string]interface{}   `json:"welcome_screen_enabled"`
	NSFWLevel                   int                      `json:"nsfw_level"`
	Stickers                    map[string]interface{}   `json:"stickers"`
	PremiumProgressBarEnabled   bool                     `json:"premium_progress_bar_enabled"`
	JoinedAT                    string                   `json:"joined_at"`
	Large                       bool                     `json:"large"`
	MemberCount                 int                      `json:"member_count"`
	VoiceStates                 []map[string]interface{} `json:"voice_states"`
	Presences                   []map[string]interface{} `json:"presences"`
	Threads                     []map[string]interface{} `json:"threads"`
	StageInstances              []map[string]interface{} `json:"stage_instances"`
	Unavailable                 bool                     `json:"unavailable"`
	GuildScheduledEvents        []map[string]interface{} `json:"guild_scheduled_events"`

	Icon            Asset
	Banner          Asset
	Splash          Asset //    `json:"splash"`
	DiscoverySplash Asset //    `json:"discovery_splash"`
	Me              *Member
	Roles           map[string]*Role
	Members         map[string]*Member
	Channels        map[string]*Channel
	// contains filtered or unexported fields
}

type Interaction

type Interaction struct {
	Id             string                 `json:"id"`
	ApplicationId  string                 `json:"application_id"`
	Type           int                    `json:"type"`
	Data           map[string]interface{} `json:"data"`
	GuildId        string                 `json:"guild_id"`
	ChannelId      string                 `json:"channel_id"`
	User           User                   `json:"user"`
	Token          string                 `json:"token"`
	Version        int                    `json:"version"`
	AppPermissions string                 `json:"app_permissions"`
	Locale         string                 `json:"locale"`
	GuildLocale    string                 `json:"guild_locale"`
	TargetUser     User
	TargetMessage  Message
	Channel        Channel
	Guild          Guild
	Author         Member
	// contains filtered or unexported fields
}

func (*Interaction) DeferResponse

func (i *Interaction) DeferResponse(ephemeral bool)

func (*Interaction) DeleteResponse

func (i *Interaction) DeleteResponse()

func (*Interaction) EditResponse

func (i *Interaction) EditResponse(response *Response) error

func (*Interaction) FollowupResponse

func (i *Interaction) FollowupResponse(response *Response) (Message, error)

func (*Interaction) ModalResponse

func (i *Interaction) ModalResponse(modal *Modal) error

func (*Interaction) OriginalResponse

func (i *Interaction) OriginalResponse() Message

func (*Interaction) SendResponse

func (i *Interaction) SendResponse(response *Response) error

type ListenerType

type ListenerType string
const (
	OnReady             ListenerType = "READY"
	OnMessage           ListenerType = "MESSAGE_CREATE"
	OnGuildJoin         ListenerType = "GUILD_CREATE"
	OnGuildLeave        ListenerType = "GUILD_DELETE"
	OnInteraction       ListenerType = "INTERACTION_CREATE"
	OnGuildMembersChunk ListenerType = "GUILD_MEMBERS_CHUNK"
)

type Listeners

type Listeners struct {
	OnReady         func(bot Bot)
	OnMessage       func(bot Bot, message Message)
	OnGuildJoin     func(bot Bot, guild Guild)
	OnGuildLeave    func(bot Bot, guild Guild)
	OnInteraction   func(bot Bot, interaction Interaction)
	OnSocketReceive func(payload interface{})
}

type Member

type Member struct {
	Nickname      string           `json:"nick"`
	AvatarHash    string           `json:"avatar"`
	JoinedAt      string           `json:"joined_at"`
	PremiumSince  string           `json:"premium_since"`
	Deaf          bool             `json:"deaf"`
	Mute          bool             `json:"mute"`
	Pending       bool             `json:"pending"`
	Permissions   string           `json:"permissions"`
	TimeoutExpiry string           `json:"communication_disabled_until"`
	GuildId       string           `json:"guild_id"`
	Roles         map[string]*Role `json:"roles"`

	Id            string
	Name          string
	Discriminator string
	Avatar        Asset
	Bot           bool
	System        bool
	MfaEnabled    bool
	Banner        Asset
	Color         int
	Locale        string
	Verified      bool
	Email         string
	Flags         int
	PremiumType   int
	PublicFlags   int
	// contains filtered or unexported fields
}

func (*Member) HasPermissions

func (m *Member) HasPermissions(permissions ...Permission) bool

type Message

type Message struct {
	Id                 string                   `json:"id"`
	ChannelId          string                   `json:"channel_id"`
	Author             User                     `json:"author"`
	Content            string                   `json:"content"`
	Timestamp          string                   `json:"timestamp"`
	EditedTimestamp    string                   `json:"edited_timestamp"`
	TTS                bool                     `json:"tts"`
	MentionEveryone    bool                     `json:"mention_everyone"`
	Mentions           []map[string]interface{} `json:"mentions"`
	RoleMentions       []string                 `json:"role_mentions"`
	ChannelMentions    []string                 `json:"channel_mentions"`
	Attachments        []map[string]interface{} `json:"attachments"`
	Embeds             []Embed                  `json:"embeds"`
	Reactions          []map[string]interface{} `json:"reactions"`
	Pinned             bool                     `json:"pinned"`
	WebhookId          string                   `json:"webhook_id"`
	Type               int                      `json:"types"`
	Activity           map[string]interface{}   `json:"activity"`
	Application        map[string]interface{}   `json:"application"`
	ApplicationId      string                   `json:"application_id"`
	MessageReference   map[string]interface{}   `json:"message_reference"`
	Flags              int                      `json:"flags"`
	ReferencedMessages map[string]interface{}   `json:"reference"`
	Interaction        map[string]interface{}   `json:"interaction"`
	Thread             map[string]interface{}   `json:"thread"`
	Components         []map[string]interface{} `json:"components"`
	Stickers           []map[string]interface{} `json:"sticker_items"`
	// contains filtered or unexported fields
}

func (*Message) Delete

func (m *Message) Delete()

func (*Message) Reply

func (m *Message) Reply(message ChannelMessage) (Message, error)
type Modal struct {
	Title       string
	Fields      []TextInput
	SelectMenus []SelectMenu
	OnSubmit    func(bot Bot, ctx Context)
	// contains filtered or unexported fields
}

type Option

type Option struct {
	Name         string `json:"name"`
	Type         int    `json:"type"`
	Description  string
	Required     bool
	MinLength    int      // allowed for: string Option Range(0-6000)
	MaxLength    int      // allowed for: string Option Range(1-6000)
	MinValue     int      // allowed for: integer Option
	MaxValue     int      // allowed for: integer Option
	MaxValueNum  float64  // allowed for: number Option
	MinValueNum  float64  // allowed for: number Option
	AutoComplete bool     // allowed for: string Option, number Option, integer Option
	ChannelTypes []int    // allowed for: channel Option
	Choices      []Choice // allowed for: string Option, number Option, integer Option
	Value        any      `json:"Value"`   // do not use this field
	Focused      bool     `json:"focused"` // do not use this field
}

type PartialAttachment

type PartialAttachment struct {
	Id          string `json:"id"`
	Filename    string `json:"filename"`
	Description string `json:"description"`
}

PartialAttachment represents a partial Discord attachment

type PartialEmoji

type PartialEmoji struct {
	Id       string `json:"id"`
	Name     string `json:"name"`
	Animated bool   `json:"animated,omitempty"`
}

type Permission

type Permission int

type Presence

type Presence struct {
	Since    int64
	Status   Status
	AFK      bool
	Activity Activity // base activity object
	OnMobile bool
}

func (*Presence) Marshal

func (p *Presence) Marshal() map[string]interface{}

type ResolvedOptions

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

func (*ResolvedOptions) Attachment

func (ro *ResolvedOptions) Attachment(name string) (Attachment, bool)

func (*ResolvedOptions) Boolean

func (ro *ResolvedOptions) Boolean(name string) (bool, bool)

func (*ResolvedOptions) Channel

func (ro *ResolvedOptions) Channel(name string) (Channel, bool)

func (*ResolvedOptions) Integer

func (ro *ResolvedOptions) Integer(name string) (int64, bool)

func (*ResolvedOptions) Mentionable

func (ro *ResolvedOptions) Mentionable(name string) (interface{}, bool)

func (*ResolvedOptions) Number

func (ro *ResolvedOptions) Number(name string) (float64, bool)

func (*ResolvedOptions) Role

func (ro *ResolvedOptions) Role(name string) (Role, bool)

func (*ResolvedOptions) String

func (ro *ResolvedOptions) String(name string) (string, bool)

func (*ResolvedOptions) User

func (ro *ResolvedOptions) User(name string) (User, bool)

type Response

type Response struct {
	Content        string
	Embed          Embed
	Embeds         []Embed
	TTS            bool
	Ephemeral      bool
	SuppressEmbeds bool
	View           View
	File           File
	Files          []File
}

type Role

type Role struct {
	Id           string `json:"id"`
	Name         string `json:"name"`
	Color        int    `json:"color"`
	Hoist        bool   `json:"hoist"`
	Icon         string `json:"icon"`
	UnicodeEmoji bool   `json:"unicode_emoji"`
	Position     int    `json:"position"`
	Permissions  string `json:"permissions"`
	Managed      bool   `json:"managed"`
	Mentionable  bool   `json:"mentionable"`
	Tags         string `json:"tags"`
	GuildId      string `json:"guild_id"`
	// contains filtered or unexported fields
}

type SelectMenu

type SelectMenu struct {
	Options     []SelectOption // max 25 Options
	Placeholder string         // max 100 characters
	MinValues   int            // default: 0
	MaxValues   int            // default: 1
	Disabled    bool
	OnSelection func(bot Bot, ctx Context, values ...string)
	// contains filtered or unexported fields
}

type SelectOption

type SelectOption struct {
	Label       string // max 100 characters
	Value       string // default: ""
	Description string // max 100 characters
	Emoji       PartialEmoji
	Default     bool // default: false
}

type Status

type Status string
const (
	Online       Status = "online"
	Idle         Status = "idle"
	DoNotDisturb Status = "dnd"
	Invisible    Status = "invisible"
	Offline      Status = "offline"
)

type SubCommand

type SubCommand struct {
	Name        string
	Description string
	Options     []Option
	Execute     func(bot Bot, ctx Context, options ResolvedOptions)
}

type SubcommandGroup

type SubcommandGroup struct {
	Name        string
	Description string
	// contains filtered or unexported fields
}

func (*SubcommandGroup) Subcommands

func (scg *SubcommandGroup) Subcommands(subcommands ...SubCommand)

type TextInput

type TextInput struct {
	CustomId    string `json:"custom_id"`
	Label       string `json:"label"`       // required default: "Text Input"
	Style       int    `json:"style"`       // 1 for short, 2 for long default: 1
	Value       string `json:"value"`       // default: ""
	Placeholder string `json:"placeholder"` // max 100 chars
	MinLength   int    `json:"min_length"`  // default: 0 upto 4000
	MaxLength   int    `json:"max_length"`  // default: 0 upto 4000
	Required    bool   `json:"required"`    // default: false
}

type User

type User struct {
	Id            string `json:"id"`
	Username      string `json:"username"`
	Discriminator string `json:"discriminator"`
	Bot           bool   `json:"bot"`
	System        bool   `json:"system"`
	MfaEnabled    bool   `json:"mfa_enabled"`
	Color         int    `json:"accent_color"`
	Locale        string `json:"locale"`
	Verified      bool   `json:"verified"`
	Email         string `json:"email"`
	Flags         int    `json:"flags"`
	PremiumType   int    `json:"premium_type"`
	PublicFlags   int    `json:"public_flags"`

	Avatar Asset
	Banner Asset
	// contains filtered or unexported fields
}

type View

type View struct {
	Timeout   float64 // default: 15 * 60 seconds
	OnTimeout func(bot Bot, ctx Context)
	// contains filtered or unexported fields
}

func (*View) AddButtons

func (v *View) AddButtons(buttons ...Button) error

func (*View) AddSelectMenu

func (v *View) AddSelectMenu(menu SelectMenu) error

Jump to

Keyboard shortcuts

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