From 1eb6f02ccde641171604958475c0f07c4bc28f07 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 2 Jun 2021 12:17:44 +0200 Subject: [PATCH 01/19] pointer refactor & cleanup --- api/action_row.go | 4 +- api/bit.go | 11 - api/button.go | 16 +- api/cache.go | 12 +- api/cache_flags.go | 18 +- api/channels.go | 4 +- api/color.go | 4 - api/command.go | 40 +- api/command_option.go | 28 +- api/command_permission.go | 8 +- api/component.go | 2 +- api/disgo.go | 25 +- api/emote.go | 32 +- api/entity_builder.go | 6 +- api/events/dm_message_reaction_events.go | 2 +- api/events/emote_events.go | 10 +- api/events/guild_message_reaction_events.go | 2 +- api/events/interaction_events.go | 12 +- api/events/listener_adapter.go | 398 +++++++++--------- api/events/message_reaction_events.go | 2 +- api/gateway_intents.go | 18 +- api/guild.go | 18 +- api/interaction.go | 26 +- api/interaction_followup.go | 4 +- api/interaction_response.go | 26 +- api/invite.go | 2 +- api/member.go | 2 +- api/message.go | 10 +- api/message_builder.go | 4 +- api/permissions.go | 36 +- api/restclient.go | 38 +- api/role.go | 16 +- api/self_user.go | 12 + api/user.go | 8 +- api/voice_state.go | 12 +- example/examplebot.go | 49 +-- internal/cache_impl.go | 20 +- internal/disgo_impl.go | 28 +- internal/entity_builder_impl.go | 10 +- internal/event_manager_impl.go | 2 +- .../handlers/interaction_create_handler.go | 2 +- .../interaction_create_webhook_handler.go | 4 +- internal/restclient_impl.go | 38 +- internal/webhook_server_impl.go | 2 +- 44 files changed, 518 insertions(+), 505 deletions(-) delete mode 100644 api/bit.go delete mode 100644 api/color.go create mode 100644 api/self_user.go diff --git a/api/action_row.go b/api/action_row.go index 3b1bd0d4..65dc6cec 100644 --- a/api/action_row.go +++ b/api/action_row.go @@ -1,8 +1,8 @@ package api // NewActionRow creates a new ActionRow holding th provided Component(s) -func NewActionRow(components ...Component) *ActionRow { - return &ActionRow{ +func NewActionRow(components ...Component) ActionRow { + return ActionRow{ ComponentImpl: newComponentImpl(ComponentTypeActionRow), Components: components, } diff --git a/api/bit.go b/api/bit.go deleted file mode 100644 index a1d4682e..00000000 --- a/api/bit.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -// Bit is a utility for interacting with bitfields -type Bit interface { - Add(bits ...Bit) Bit - Remove(bits ...Bit) Bit - HasAll(bits ...Bit) bool - Has(bit Bit) bool - MissingAny(bits ...Bit) bool - Missing(bit Bit) bool -} diff --git a/api/button.go b/api/button.go index 641ea2c5..18fb268c 100644 --- a/api/button.go +++ b/api/button.go @@ -13,8 +13,8 @@ const ( ) // NewButton creates a new Button with the provided parameters. Link Button(s) need a url and other Button(s) need a customID -func NewButton(style ButtonStyle, label *string, customID string, url string, emote *Emote, disabled bool) *Button { - return &Button{ +func NewButton(style ButtonStyle, label *string, customID string, url string, emote *Emoji, disabled bool) Button { + return Button{ ComponentImpl: newComponentImpl(ComponentTypeButton), Style: style, CustomID: customID, @@ -26,27 +26,27 @@ func NewButton(style ButtonStyle, label *string, customID string, url string, em } // NewPrimaryButton creates a new Button with ButtonStylePrimary & the provided parameters -func NewPrimaryButton(label string, customID string, emote *Emote, disabled bool) *Button { +func NewPrimaryButton(label string, customID string, emote *Emoji, disabled bool) Button { return NewButton(ButtonStylePrimary, &label, customID, "", emote, disabled) } // NewSecondaryButton creates a new Button with ButtonStyleSecondary & the provided parameters -func NewSecondaryButton(label string, customID string, emote *Emote, disabled bool) *Button { +func NewSecondaryButton(label string, customID string, emote *Emoji, disabled bool) Button { return NewButton(ButtonStyleSecondary, &label, customID, "", emote, disabled) } // NewSuccessButton creates a new Button with ButtonStyleSuccess & the provided parameters -func NewSuccessButton(label string, customID string, emote *Emote, disabled bool) *Button { +func NewSuccessButton(label string, customID string, emote *Emoji, disabled bool) Button { return NewButton(ButtonStyleSuccess, &label, customID, "", emote, disabled) } // NewDangerButton creates a new Button with ButtonStyleDanger & the provided parameters -func NewDangerButton(label string, customID string, emote *Emote, disabled bool) *Button { +func NewDangerButton(label string, customID string, emote *Emoji, disabled bool) Button { return NewButton(ButtonStyleDanger, &label, customID, "", emote, disabled) } // NewLinkButton creates a new link Button with ButtonStyleLink & the provided parameters -func NewLinkButton(label string, url string, emote *Emote, disabled bool) *Button { +func NewLinkButton(label string, url string, emote *Emoji, disabled bool) Button { return NewButton(ButtonStyleLink, &label, "", url, emote, disabled) } @@ -55,7 +55,7 @@ type Button struct { ComponentImpl Style ButtonStyle `json:"style,omitempty"` Label *string `json:"label,omitempty"` - Emote *Emote `json:"emoji,omitempty"` + Emote *Emoji `json:"emoji,omitempty"` CustomID string `json:"custom_id,omitempty"` URL string `json:"url,omitempty"` Disabled bool `json:"disabled,omitempty"` diff --git a/api/cache.go b/api/cache.go index 16241425..b8fce8aa 100644 --- a/api/cache.go +++ b/api/cache.go @@ -118,11 +118,11 @@ type Cache interface { FindCategory(Snowflake, func(*Category) bool) *Category FindCategories(Snowflake, func(*Category) bool) []*Category - Emote(emoteID Snowflake) *Emote - EmotesByName(guildID Snowflake, name string, ignoreCase bool) []*Emote - Emotes(guildID Snowflake) []*Emote - EmoteCache(guildID Snowflake) map[Snowflake]*Emote - AllEmoteCache() map[Snowflake]map[Snowflake]*Emote - CacheEmote(*Emote) *Emote + Emote(emoteID Snowflake) *Emoji + EmotesByName(guildID Snowflake, name string, ignoreCase bool) []*Emoji + Emotes(guildID Snowflake) []*Emoji + EmoteCache(guildID Snowflake) map[Snowflake]*Emoji + AllEmoteCache() map[Snowflake]map[Snowflake]*Emoji + CacheEmote(*Emoji) *Emoji UncacheEmote(guildID Snowflake, emoteID Snowflake) } diff --git a/api/cache_flags.go b/api/cache_flags.go index 324967b6..dbbc9a0d 100644 --- a/api/cache_flags.go +++ b/api/cache_flags.go @@ -27,27 +27,27 @@ const ( ) // Add allows you to add multiple bits together, producing a new bit -func (c CacheFlags) Add(bits ...Bit) Bit { +func (c CacheFlags) Add(bits ...CacheFlags) CacheFlags { total := CacheFlags(0) for _, bit := range bits { - total |= bit.(CacheFlags) + total |= bit } c |= total return c } // Remove allows you to subtract multiple bits from the first, producing a new bit -func (c CacheFlags) Remove(bits ...Bit) Bit { +func (c CacheFlags) Remove(bits ...CacheFlags) CacheFlags { total := CacheFlags(0) for _, bit := range bits { - total |= bit.(CacheFlags) + total |= bit } c &^= total return c } // HasAll will ensure that the bit includes all of the bits entered -func (c CacheFlags) HasAll(bits ...Bit) bool { +func (c CacheFlags) HasAll(bits ...CacheFlags) bool { for _, bit := range bits { if !c.Has(bit) { return false @@ -57,12 +57,12 @@ func (c CacheFlags) HasAll(bits ...Bit) bool { } // Has will check whether the Bit contains another bit -func (c CacheFlags) Has(bit Bit) bool { - return (c & bit.(CacheFlags)) == bit +func (c CacheFlags) Has(bit CacheFlags) bool { + return (c & bit) == bit } // MissingAny will check whether the bit is missing any one of the bits -func (c CacheFlags) MissingAny(bits ...Bit) bool { +func (c CacheFlags) MissingAny(bits ...CacheFlags) bool { for _, bit := range bits { if !c.Has(bit) { return true @@ -72,6 +72,6 @@ func (c CacheFlags) MissingAny(bits ...Bit) bool { } // Missing will do the inverse of Bit.Has -func (c CacheFlags) Missing(bit Bit) bool { +func (c CacheFlags) Missing(bit CacheFlags) bool { return !c.Has(bit) } diff --git a/api/channels.go b/api/channels.go index cd9f0149..29e473ce 100644 --- a/api/channels.go +++ b/api/channels.go @@ -45,13 +45,13 @@ type MessageChannel struct { } // SendMessage sends a Message to a TextChannel -func (c MessageChannel) SendMessage(message *MessageCreate) (*Message, error) { +func (c MessageChannel) SendMessage(message MessageCreate) (*Message, error) { // Todo: attachments return c.Disgo.RestClient().SendMessage(c.ID, message) } // EditMessage edits a Message in this TextChannel -func (c MessageChannel) EditMessage(messageID Snowflake, message *MessageUpdate) (*Message, error) { +func (c MessageChannel) EditMessage(messageID Snowflake, message MessageUpdate) (*Message, error) { return c.Disgo.RestClient().EditMessage(c.ID, messageID, message) } diff --git a/api/color.go b/api/color.go deleted file mode 100644 index f5012239..00000000 --- a/api/color.go +++ /dev/null @@ -1,4 +0,0 @@ -package api - -// Color is used for specifying colors in an Embed / Role -type Color int diff --git a/api/command.go b/api/command.go index f17a9f3f..4c013c0b 100644 --- a/api/command.go +++ b/api/command.go @@ -8,13 +8,13 @@ var errNoDisgoInstance = errors.New("no disgo instance injected") type Command struct { Disgo Disgo GuildPermissions map[Snowflake]*GuildCommandPermissions - GuildID *Snowflake `json:"guild_id"` - ID Snowflake `json:"id,omitempty"` - ApplicationID Snowflake `json:"application_id,omitempty"` - Name string `json:"name"` - Description string `json:"description"` - DefaultPermission *bool `json:"default_permission,omitempty"` - Options []*CommandOption `json:"options,omitempty"` + GuildID *Snowflake `json:"guild_id"` + ID Snowflake `json:"id,omitempty"` + ApplicationID Snowflake `json:"application_id,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + DefaultPermission bool `json:"default_permission,omitempty"` + Options []CommandOption `json:"options,omitempty"` } // Guild returns the Guild the Command is from from the Cache or nil if it is a global Command @@ -31,8 +31,8 @@ func (c Command) FromGuild() bool { } // ToCreate return the CommandCreate for this Command -func (c *Command) ToCreate() *CommandCreate { - return &CommandCreate{ +func (c *Command) ToCreate() CommandCreate { + return CommandCreate{ Name: c.Name, Description: c.Description, DefaultPermission: c.DefaultPermission, @@ -61,7 +61,7 @@ func (c *Command) Fetch() error { } // Update updates the current Command with the given fields -func (c *Command) Update(command *CommandUpdate) error { +func (c *Command) Update(command CommandUpdate) error { if c.Disgo == nil { return errNoDisgoInstance } @@ -81,8 +81,8 @@ func (c *Command) Update(command *CommandUpdate) error { } // SetPermissions sets the GuildCommandPermissions for a specific Guild. this overrides all existing CommandPermission(s). thx discord for that -func (c *Command) SetPermissions(guildID Snowflake, permissions ...*CommandPermission) error { - _, err := c.Disgo.RestClient().SetGuildCommandPermissions(c.Disgo.ApplicationID(), guildID, c.ID, &SetGuildCommandPermissions{Permissions: permissions}) +func (c *Command) SetPermissions(guildID Snowflake, permissions ...CommandPermission) error { + _, err := c.Disgo.RestClient().SetGuildCommandPermissions(c.Disgo.ApplicationID(), guildID, c.ID, SetGuildCommandPermissions{Permissions: permissions}) if err != nil { return err } @@ -117,16 +117,16 @@ func (c Command) Delete() error { // CommandCreate is used to create an Command. all fields are optional type CommandCreate struct { - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - DefaultPermission *bool `json:"default_permission,omitempty"` - Options []*CommandOption `json:"options,omitempty"` + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + DefaultPermission bool `json:"default_permission,omitempty"` + Options []CommandOption `json:"options,omitempty"` } // CommandUpdate is used to update an existing Command. all fields are optional type CommandUpdate struct { - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - DefaultPermission *bool `json:"default_permission,omitempty"` - Options []*CommandOption `json:"options,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + DefaultPermission *bool `json:"default_permission,omitempty"` + Options []CommandOption `json:"options,omitempty"` } diff --git a/api/command_option.go b/api/command_option.go index 8d883ae4..3b521459 100644 --- a/api/command_option.go +++ b/api/command_option.go @@ -17,8 +17,8 @@ const ( ) // NewCommandOption creates a new CommandOption with the provided params -func NewCommandOption(optionType CommandOptionType, name string, description string, options ...*CommandOption) *CommandOption { - return &CommandOption{ +func NewCommandOption(optionType CommandOptionType, name string, description string, options ...CommandOption) CommandOption { + return CommandOption{ Type: optionType, Name: name, Description: description, @@ -27,42 +27,42 @@ func NewCommandOption(optionType CommandOptionType, name string, description str } // NewSubCommand creates a new CommandOption with CommandOptionTypeSubCommand -func NewSubCommand(name string, description string, options ...*CommandOption) *CommandOption { +func NewSubCommand(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeSubCommand, name, description, options...) } // NewSubCommandGroup creates a new CommandOption with CommandOptionTypeSubCommandGroup -func NewSubCommandGroup(name string, description string, options ...*CommandOption) *CommandOption { +func NewSubCommandGroup(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeSubCommandGroup, name, description, options...) } // NewStringOption creates a new CommandOption with CommandOptionTypeSubCommand -func NewStringOption(name string, description string, options ...*CommandOption) *CommandOption { +func NewStringOption(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeString, name, description, options...) } // NewIntegerOption creates a new CommandOption with CommandOptionTypeSubCommand -func NewIntegerOption(name string, description string, options ...*CommandOption) *CommandOption { +func NewIntegerOption(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeInteger, name, description, options...) } // NewBooleanOption creates a new CommandOption with CommandOptionTypeSubCommand -func NewBooleanOption(name string, description string, options ...*CommandOption) *CommandOption { +func NewBooleanOption(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeBoolean, name, description, options...) } // NewUserOption creates a new CommandOption with CommandOptionTypeSubCommand -func NewUserOption(name string, description string, options ...*CommandOption) *CommandOption { +func NewUserOption(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeUser, name, description, options...) } // NewChannelOption creates a new CommandOption with CommandOptionTypeSubCommand -func NewChannelOption(name string, description string, options ...*CommandOption) *CommandOption { +func NewChannelOption(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeChannel, name, description, options...) } // NewMentionableOption creates a new CommandOption with CommandOptionTypeUser or CommandOptionTypeRole -func NewMentionableOption(name string, description string, options ...*CommandOption) *CommandOption { +func NewMentionableOption(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeMentionable, name, description, options...) } @@ -72,13 +72,13 @@ type CommandOption struct { Name string `json:"name"` Description string `json:"description"` Required bool `json:"required,omitempty"` - Choices []*OptionChoice `json:"choices,omitempty"` - Options []*CommandOption `json:"options,omitempty"` + Choices []OptionChoice `json:"choices,omitempty"` + Options []CommandOption `json:"options,omitempty"` } // AddChoice adds a new choice to the the CommandOption func (o *CommandOption) AddChoice(name string, value interface{}) *CommandOption { - o.Choices = append(o.Choices, &OptionChoice{ + o.Choices = append(o.Choices, OptionChoice{ Name: name, Value: value, }) @@ -86,7 +86,7 @@ func (o *CommandOption) AddChoice(name string, value interface{}) *CommandOption } // AddOptions adds multiple choices to the the CommandOption -func (o *CommandOption) AddOptions(options ...*CommandOption) *CommandOption { +func (o *CommandOption) AddOptions(options ...CommandOption) *CommandOption { o.Options = append(o.Options, options...) return o } diff --git a/api/command_permission.go b/api/command_permission.go index 3c075091..e7170a2f 100644 --- a/api/command_permission.go +++ b/api/command_permission.go @@ -6,7 +6,7 @@ type GuildCommandPermissions struct { ID Snowflake `json:"id"` ApplicationID Snowflake `json:"application_id"` GuildID Snowflake `json:"guild_id"` - Permissions []*CommandPermission `json:"permissions"` + Permissions []CommandPermission `json:"permissions"` } // TODO: add methods to update those @@ -28,10 +28,10 @@ type CommandPermission struct { } // SetGuildCommandsPermissions holds a slice of SetGuildCommandPermissions -type SetGuildCommandsPermissions []*SetGuildCommandPermissions +type SetGuildCommandsPermissions []SetGuildCommandPermissions // SetGuildCommandPermissions is used to update CommandPermission ID should be omitted fro bulk update type SetGuildCommandPermissions struct { - ID Snowflake `json:"id,omitempty"` - Permissions []*CommandPermission `json:"permissions"` + ID Snowflake `json:"id,omitempty"` + Permissions []CommandPermission `json:"permissions"` } diff --git a/api/component.go b/api/component.go index bddaa23c..1340ac62 100644 --- a/api/component.go +++ b/api/component.go @@ -33,7 +33,7 @@ type UnmarshalComponent struct { ComponentType ComponentType `json:"type"` Style ButtonStyle `json:"style"` Label *string `json:"label"` - Emote *Emote `json:"emoji"` + Emote *Emoji `json:"emoji"` CustomID string `json:"custom_id"` URL string `json:"url"` Disabled bool `json:"disabled"` diff --git a/api/disgo.go b/api/disgo.go index bf5e152a..6967d900 100644 --- a/api/disgo.go +++ b/api/disgo.go @@ -23,7 +23,8 @@ type Disgo interface { GatewayIntents() GatewayIntents RawGatewayEventsEnabled() bool ApplicationID() Snowflake - SelfUser() *User + SelfUser() *SelfUser + SelfUserID() Snowflake EntityBuilder() EntityBuilder EventManager() EventManager VoiceDispatchInterceptor() VoiceDispatchInterceptor @@ -35,22 +36,22 @@ type Disgo interface { GetCommand(commandID Snowflake) (*Command, error) GetCommands() ([]*Command, error) - CreateCommand(command *CommandCreate) (*Command, error) - EditCommand(commandID Snowflake, command *CommandUpdate) (*Command, error) + CreateCommand(command CommandCreate) (*Command, error) + EditCommand(commandID Snowflake, command CommandUpdate) (*Command, error) DeleteCommand(commandID Snowflake) error - SetCommands(commands ...*CommandCreate) ([]*Command, error) + SetCommands(commands ...CommandCreate) ([]*Command, error) GetGuildCommand(guildID Snowflake, commandID Snowflake) (*Command, error) - GetGuildCommands(guildID Snowflake, ) ([]*Command, error) - CreateGuildCommand(guildID Snowflake, command *CommandCreate) (*Command, error) - EditGuildCommand(guildID Snowflake, commandID Snowflake, command *CommandUpdate) (*Command, error) + GetGuildCommands(guildID Snowflake) ([]*Command, error) + CreateGuildCommand(guildID Snowflake, command CommandCreate) (*Command, error) + EditGuildCommand(guildID Snowflake, commandID Snowflake, command CommandUpdate) (*Command, error) DeleteGuildCommand(guildID Snowflake, commandID Snowflake) error - SetGuildCommands(guildID Snowflake, commands ...*CommandCreate) ([]*Command, error) + SetGuildCommands(guildID Snowflake, commands ...CommandCreate) ([]*Command, error) GetGuildCommandsPermissions(guildID Snowflake) ([]*GuildCommandPermissions, error) GetGuildCommandPermissions(guildID Snowflake, commandID Snowflake) (*GuildCommandPermissions, error) - SetGuildCommandsPermissions(guildID Snowflake, commandPermissions ...*SetGuildCommandPermissions) ([]*GuildCommandPermissions, error) - SetGuildCommandPermissions(guildID Snowflake, commandID Snowflake, permissions *SetGuildCommandPermissions) (*GuildCommandPermissions, error) + SetGuildCommandsPermissions(guildID Snowflake, commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, error) + SetGuildCommandPermissions(guildID Snowflake, commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, error) } // EventHandler provides info about the EventHandler @@ -68,7 +69,7 @@ type GatewayEventHandler interface { // WebhookEventHandler is used to handle raw webhook events type WebhookEventHandler interface { EventHandler - HandleWebhookEvent(disgo Disgo, eventManager EventManager, replyChannel chan *InteractionResponse, payload interface{}) + HandleWebhookEvent(disgo Disgo, eventManager EventManager, replyChannel chan InteractionResponse, payload interface{}) } // EventListener is used to create new EventListener to listen to events @@ -87,7 +88,7 @@ type EventManager interface { Disgo() Disgo Close() AddEventListeners(eventListeners ...EventListener) - Handle(eventType GatewayEventType, replyChannel chan *InteractionResponse, sequenceNumber int, payload json.RawMessage) + Handle(eventType GatewayEventType, replyChannel chan InteractionResponse, sequenceNumber int, payload json.RawMessage) Dispatch(event Event) } diff --git a/api/emote.go b/api/emote.go index e77ef2d8..491f5772 100644 --- a/api/emote.go +++ b/api/emote.go @@ -1,22 +1,22 @@ package api -// NewEmote creates a new custom Emote with the given parameters -func NewEmote(name string, emoteID Snowflake) *Emote { - return &Emote{Name: name, ID: emoteID, Animated: false} +// NewEmote creates a new custom Emoji with the given parameters +func NewEmote(name string, emoteID Snowflake) *Emoji { + return &Emoji{Name: name, ID: emoteID, Animated: false} } -// NewAnimatedEmote creates a new animated custom Emote with the given parameters -func NewAnimatedEmote(name string, emoteID Snowflake) *Emote { - return &Emote{Name: name, ID: emoteID, Animated: true} +// NewAnimatedEmote creates a new animated custom Emoji with the given parameters +func NewAnimatedEmote(name string, emoteID Snowflake) *Emoji { + return &Emoji{Name: name, ID: emoteID, Animated: true} } // NewEmoji creates a new emoji with the given unicode -func NewEmoji(name string) *Emote { - return &Emote{Name: name} +func NewEmoji(name string) *Emoji { + return &Emoji{Name: name} } -// Emote allows you to interact with emojis & emotes -type Emote struct { +// Emoji allows you to interact with emojis & emotes +type Emoji struct { Disgo Disgo GuildID Snowflake `json:"guild_id,omitempty"` Name string `json:"name,omitempty"` @@ -24,13 +24,13 @@ type Emote struct { Animated bool `json:"animated,omitempty"` } -// Guild returns the Guild of the Emote from the Cache -func (e Emote) Guild() *Guild { +// Guild returns the Guild of the Emoji from the Cache +func (e *Emoji) Guild() *Guild { return e.Disgo.Cache().Guild(e.GuildID) } // Mention returns the string used to send the emoji -func (e Emote) Mention() string { +func (e *Emoji) Mention() string { start := "<:" if e.Animated { start = "" } -// String formats the Emote as string -func (e Emote) String() string { +// String formats the Emoji as string +func (e *Emoji) String() string { return e.Mention() } // Reaction returns the identifier used for adding and removing reactions for messages in discord -func (e Emote) Reaction() string { +func (e *Emoji) Reaction() string { return ":" + e.Name + ":" + e.ID.String() } diff --git a/api/entity_builder.go b/api/entity_builder.go index 41c179a2..7e38cbce 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -15,8 +15,8 @@ var ( type EntityBuilder interface { Disgo() Disgo - CreateButtonInteraction(fullInteraction *FullInteraction, c chan *InteractionResponse, updateCache CacheStrategy) *ButtonInteraction - CreateCommandInteraction(fullInteraction *FullInteraction, c chan *InteractionResponse, updateCache CacheStrategy) *CommandInteraction + CreateButtonInteraction(fullInteraction *FullInteraction, c chan InteractionResponse, updateCache CacheStrategy) *ButtonInteraction + CreateCommandInteraction(fullInteraction *FullInteraction, c chan InteractionResponse, updateCache CacheStrategy) *CommandInteraction CreateGlobalCommand(command *Command, updateCache CacheStrategy) *Command @@ -37,5 +37,5 @@ type EntityBuilder interface { CreateCategory(channel *Channel, updateCache CacheStrategy) *Category CreateDMChannel(channel *Channel, updateCache CacheStrategy) *DMChannel - CreateEmote(guildID Snowflake, emote *Emote, updateCache CacheStrategy) *Emote + CreateEmote(guildID Snowflake, emote *Emoji, updateCache CacheStrategy) *Emoji } diff --git a/api/events/dm_message_reaction_events.go b/api/events/dm_message_reaction_events.go index 470084c6..b03b677c 100644 --- a/api/events/dm_message_reaction_events.go +++ b/api/events/dm_message_reaction_events.go @@ -20,7 +20,7 @@ type DMMessageReactionRemoveEvent struct { GenericDMMessageReactionEvent } -// DMMessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emote from a api.Message in a api.DMChannel(requires the api.GatewayIntentsDirectMessageReactions) +// DMMessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.DMChannel(requires the api.GatewayIntentsDirectMessageReactions) type DMMessageReactionRemoveEmoteEvent struct { GenericDMMessageEvent MessageReaction api.MessageReaction diff --git a/api/events/emote_events.go b/api/events/emote_events.go index bcafda7a..ead85b0d 100644 --- a/api/events/emote_events.go +++ b/api/events/emote_events.go @@ -7,21 +7,21 @@ import ( // GenericEmoteEvent is called upon receiving EmoteCreateEvent, EmoteUpdateEvent or EmoteDeleteEvent(requires api.GatewayIntentsGuildEmojis) type GenericEmoteEvent struct { GenericGuildEvent - Emote *api.Emote + Emote *api.Emoji } -// EmoteCreateEvent indicates that a new api.Emote got created in a api.Guild(requires api.GatewayIntentsGuildEmojis) +// EmoteCreateEvent indicates that a new api.Emoji got created in a api.Guild(requires api.GatewayIntentsGuildEmojis) type EmoteCreateEvent struct { GenericEmoteEvent } -// EmoteUpdateEvent indicates that a api.Emote got updated in a api.Guild(requires api.GatewayIntentsGuildEmojis) +// EmoteUpdateEvent indicates that a api.Emoji got updated in a api.Guild(requires api.GatewayIntentsGuildEmojis) type EmoteUpdateEvent struct { GenericEmoteEvent - OldEmote *api.Emote + OldEmote *api.Emoji } -// EmoteDeleteEvent indicates that a api.Emote got deleted in a api.Guild(requires api.GatewayIntentsGuildEmojis) +// EmoteDeleteEvent indicates that a api.Emoji got deleted in a api.Guild(requires api.GatewayIntentsGuildEmojis) type EmoteDeleteEvent struct { GenericEmoteEvent } diff --git a/api/events/guild_message_reaction_events.go b/api/events/guild_message_reaction_events.go index d9f70104..dd5b4de5 100644 --- a/api/events/guild_message_reaction_events.go +++ b/api/events/guild_message_reaction_events.go @@ -20,7 +20,7 @@ type GuildMessageReactionRemoveEvent struct { GenericGuildMessageReactionEvent } -// GuildMessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emote from a api.Message in a api.TextChannel(requires the api.GatewayIntentsGuildMessageReactions) +// GuildMessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.TextChannel(requires the api.GatewayIntentsGuildMessageReactions) type GuildMessageReactionRemoveEmoteEvent struct { GenericGuildMessageEvent MessageReaction api.MessageReaction diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index 1e18049f..bb1c2fa9 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -11,12 +11,12 @@ type GenericInteractionEvent struct { } // Reply replies to the api.Interaction with the provided api.InteractionResponse -func (e *GenericInteractionEvent) Reply(response *api.InteractionResponse) error { +func (e *GenericInteractionEvent) Reply(response api.InteractionResponse) error { return e.Interaction.Reply(response) } // EditOriginal edits the original api.InteractionResponse -func (e *GenericInteractionEvent) EditOriginal(followupMessage *api.FollowupMessage) (*api.Message, error) { +func (e *GenericInteractionEvent) EditOriginal(followupMessage api.FollowupMessage) (*api.Message, error) { return e.Interaction.EditOriginal(followupMessage) } @@ -26,12 +26,12 @@ func (e *GenericInteractionEvent) DeleteOriginal() error { } // SendFollowup used to send a api.FollowupMessage to an api.Interaction -func (e *GenericInteractionEvent) SendFollowup(followupMessage *api.FollowupMessage) (*api.Message, error) { +func (e *GenericInteractionEvent) SendFollowup(followupMessage api.FollowupMessage) (*api.Message, error) { return e.Interaction.SendFollowup(followupMessage) } // EditFollowup used to edit a api.FollowupMessage from an api.Interaction -func (e *GenericInteractionEvent) EditFollowup(messageID api.Snowflake, followupMessage *api.FollowupMessage) (*api.Message, error) { +func (e *GenericInteractionEvent) EditFollowup(messageID api.Snowflake, followupMessage api.FollowupMessage) (*api.Message, error) { return e.Interaction.EditFollowup(messageID, followupMessage) } @@ -57,7 +57,7 @@ func (e *CommandEvent) DeferReply(ephemeral bool) error { } // ReplyCreate replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.InteractionResponseData -func (e *CommandEvent) ReplyCreate(data *api.InteractionResponseData) error { +func (e *CommandEvent) ReplyCreate(data api.InteractionResponseData) error { return e.CommandInteraction.ReplyCreate(data) } @@ -116,7 +116,7 @@ func (e *ButtonClickEvent) DeferEdit() error { } // ReplyEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.InteractionResponseData which edits the original api.Message -func (e *ButtonClickEvent) ReplyEdit(data *api.InteractionResponseData) error { +func (e *ButtonClickEvent) ReplyEdit(data api.InteractionResponseData) error { return e.ButtonInteraction.ReplyEdit(data) } diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index 635db4a7..aa1ddb3a 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -9,151 +9,151 @@ import ( // ListenerAdapter lets you override the handles for receiving events type ListenerAdapter struct { // Other events - OnGenericEvent func(event *GenericEvent) - OnHeartbeat func(event *HeartbeatEvent) - OnHTTPRequest func(event *HTTPRequestEvent) - OnRawGateway func(event *RawGatewayEvent) - OnReadyEvent func(event *ReadyEvent) + OnGenericEvent func(event GenericEvent) + OnHeartbeat func(event HeartbeatEvent) + OnHTTPRequest func(event HTTPRequestEvent) + OnRawGateway func(event RawGatewayEvent) + OnReadyEvent func(event ReadyEvent) // api.Command Events - OnGenericCommandEvent func(event *GenericCommandEvent) - OnCommandCreate func(event *CommandCreateEvent) - OnCommandUpdate func(event *CommandUpdateEvent) - OnCommandDelete func(event *CommandDeleteEvent) + OnGenericCommandEvent func(event GenericCommandEvent) + OnCommandCreate func(event CommandCreateEvent) + OnCommandUpdate func(event CommandUpdateEvent) + OnCommandDelete func(event CommandDeleteEvent) // api.Channel Events - OnGenericChannelEvent func(event *GenericChannelEvent) + OnGenericChannelEvent func(event GenericChannelEvent) // api.Category Events - OnGenericCategoryEvent func(event *GenericCategoryEvent) - OnCategoryCreate func(event *CategoryCreateEvent) - OnCategoryUpdate func(event *CategoryUpdateEvent) - OnCategoryDelete func(event *CategoryDeleteEvent) + OnGenericCategoryEvent func(event GenericCategoryEvent) + OnCategoryCreate func(event CategoryCreateEvent) + OnCategoryUpdate func(event CategoryUpdateEvent) + OnCategoryDelete func(event CategoryDeleteEvent) // api.DMChannel Events - OnGenericDMChannelEvent func(event *GenericDMChannelEvent) - OnDMChannelCreate func(event *DMChannelCreateEvent) - OnDMChannelUpdate func(event *DMChannelUpdateEvent) - OnDMChannelDelete func(event *DMChannelDeleteEvent) + OnGenericDMChannelEvent func(event GenericDMChannelEvent) + OnDMChannelCreate func(event DMChannelCreateEvent) + OnDMChannelUpdate func(event DMChannelUpdateEvent) + OnDMChannelDelete func(event DMChannelDeleteEvent) // api.DMChannel Reaction Events - OnGenericDMMessageReactionEventEvent func(event *GenericDMMessageReactionEvent) - OnDMMessageReactionAdd func(event *DMMessageReactionAddEvent) - OnDMMessageReactionRemove func(event *DMMessageReactionRemoveEvent) - OnDMMessageReactionRemoveEmote func(event *DMMessageReactionRemoveEmoteEvent) - OnDMMessageReactionRemoveAll func(event *DMMessageReactionRemoveAllEvent) + OnGenericDMMessageReactionEventEvent func(event GenericDMMessageReactionEvent) + OnDMMessageReactionAdd func(event DMMessageReactionAddEvent) + OnDMMessageReactionRemove func(event DMMessageReactionRemoveEvent) + OnDMMessageReactionRemoveEmote func(event DMMessageReactionRemoveEmoteEvent) + OnDMMessageReactionRemoveAll func(event DMMessageReactionRemoveAllEvent) // api.StoreChannel Events - OnGenericStoreChannelEvent func(event *GenericStoreChannelEvent) - OnStoreChannelCreate func(event *StoreChannelCreateEvent) - OnStoreChannelUpdate func(event *StoreChannelUpdateEvent) - OnStoreChannelDelete func(event *StoreChannelDeleteEvent) + OnGenericStoreChannelEvent func(event GenericStoreChannelEvent) + OnStoreChannelCreate func(event StoreChannelCreateEvent) + OnStoreChannelUpdate func(event StoreChannelUpdateEvent) + OnStoreChannelDelete func(event StoreChannelDeleteEvent) // api.TextChannel Events - OnGenericTextChannelEvent func(event *GenericTextChannelEvent) - OnTextChannelCreate func(event *TextChannelCreateEvent) - OnTextChannelUpdate func(event *TextChannelUpdateEvent) - OnTextChannelDelete func(event *TextChannelDeleteEvent) + OnGenericTextChannelEvent func(event GenericTextChannelEvent) + OnTextChannelCreate func(event TextChannelCreateEvent) + OnTextChannelUpdate func(event TextChannelUpdateEvent) + OnTextChannelDelete func(event TextChannelDeleteEvent) // api.VoiceChannel Events - OnGenericVoiceChannelEvent func(event *GenericVoiceChannelEvent) - OnVoiceChannelCreate func(event *VoiceChannelCreateEvent) - OnVoiceChannelUpdate func(event *VoiceChannelUpdateEvent) - OnVoiceChannelDelete func(event *VoiceChannelDeleteEvent) + OnGenericVoiceChannelEvent func(event GenericVoiceChannelEvent) + OnVoiceChannelCreate func(event VoiceChannelCreateEvent) + OnVoiceChannelUpdate func(event VoiceChannelUpdateEvent) + OnVoiceChannelDelete func(event VoiceChannelDeleteEvent) - // api.Emote Events - OnGenericEmoteEvent func(event *GenericEmoteEvent) - OnEmoteCreate func(event *EmoteCreateEvent) - OnEmoteUpdate func(event *EmoteUpdateEvent) - OnEmoteDelete func(event *EmoteDeleteEvent) + // api.Emoji Events + OnGenericEmoteEvent func(event GenericEmoteEvent) + OnEmoteCreate func(event EmoteCreateEvent) + OnEmoteUpdate func(event EmoteUpdateEvent) + OnEmoteDelete func(event EmoteDeleteEvent) // api.GatewayStatus Events - OnGenericGatewayStatusEvent func(event *GenericGatewayStatusEvent) - OnConnected func(event *ConnectedEvent) - OnReconnected func(event *ReconnectedEvent) - OnResumed func(event *ResumedEvent) - OnDisconnected func(event *DisconnectedEvent) + OnGenericGatewayStatusEvent func(event GenericGatewayStatusEvent) + OnConnected func(event ConnectedEvent) + OnReconnected func(event ReconnectedEvent) + OnResumed func(event ResumedEvent) + OnDisconnected func(event DisconnectedEvent) // api.Guild Events - OnGenericGuildEvent func(event *GenericGuildEvent) - OnGuildJoin func(event *GuildJoinEvent) - OnGuildUpdate func(event *GuildUpdateEvent) - OnGuildLeave func(event *GuildLeaveEvent) - OnGuildAvailable func(event *GuildAvailableEvent) - OnGuildUnavailable func(event *GuildUnavailableEvent) - OnGuildReady func(event *GuildReadyEvent) - OnGuildBan func(event *GuildBanEvent) - OnGuildUnban func(event *GuildUnbanEvent) + OnGenericGuildEvent func(event GenericGuildEvent) + OnGuildJoin func(event GuildJoinEvent) + OnGuildUpdate func(event GuildUpdateEvent) + OnGuildLeave func(event GuildLeaveEvent) + OnGuildAvailable func(event GuildAvailableEvent) + OnGuildUnavailable func(event GuildUnavailableEvent) + OnGuildReady func(event GuildReadyEvent) + OnGuildBan func(event GuildBanEvent) + OnGuildUnban func(event GuildUnbanEvent) // api.Guild api.Invite Events - OnGenericGuildInviteEvent func(event *GenericGuildInviteEvent) - OnGuildInviteCreate func(event *GuildInviteCreateEvent) - OnGuildInviteDelete func(event *GuildInviteDeleteEvent) + OnGenericGuildInviteEvent func(event GenericGuildInviteEvent) + OnGuildInviteCreate func(event GuildInviteCreateEvent) + OnGuildInviteDelete func(event GuildInviteDeleteEvent) // api.Guild api.Member Events - OnGenericGuildMemberEvent func(event *GenericGuildMemberEvent) - OnGuildMemberJoin func(event *GuildMemberJoinEvent) - OnGuildMemberUpdate func(event *GuildMemberUpdateEvent) - OnGuildMemberLeave func(event *GuildMemberLeaveEvent) + OnGenericGuildMemberEvent func(event GenericGuildMemberEvent) + OnGuildMemberJoin func(event GuildMemberJoinEvent) + OnGuildMemberUpdate func(event GuildMemberUpdateEvent) + OnGuildMemberLeave func(event GuildMemberLeaveEvent) // api.Guild api.Message Events - OnGenericGuildMessageEvent func(event *GenericGuildMessageEvent) - OnGuildMessageCreate func(event *GuildMessageCreateEvent) - OnGuildMessageUpdate func(event *GuildMessageUpdateEvent) - OnGuildMessageDelete func(event *GuildMessageDeleteEvent) + OnGenericGuildMessageEvent func(event GenericGuildMessageEvent) + OnGuildMessageCreate func(event GuildMessageCreateEvent) + OnGuildMessageUpdate func(event GuildMessageUpdateEvent) + OnGuildMessageDelete func(event GuildMessageDeleteEvent) // api.Guild api.Message Reaction Events - OnGenericGuildMessageReactionEvent func(event *GenericGuildMessageReactionEvent) - OnGuildMessageReactionAdd func(event *GuildMessageReactionAddEvent) - OnGuildMessageReactionRemove func(event *GuildMessageReactionRemoveEvent) - OnGuildMessageReactionRemoveEmote func(event *GuildMessageReactionRemoveEmoteEvent) - OnGuildMessageReactionRemoveAll func(event *GuildMessageReactionRemoveAllEvent) + OnGenericGuildMessageReactionEvent func(event GenericGuildMessageReactionEvent) + OnGuildMessageReactionAdd func(event GuildMessageReactionAddEvent) + OnGuildMessageReactionRemove func(event GuildMessageReactionRemoveEvent) + OnGuildMessageReactionRemoveEmote func(event GuildMessageReactionRemoveEmoteEvent) + OnGuildMessageReactionRemoveAll func(event GuildMessageReactionRemoveAllEvent) // api.Guild Voice Events - OnGenericGuildVoiceEvent func(event *GenericGuildVoiceEvent) - OnGuildVoiceUpdate func(event *GuildVoiceUpdateEvent) - OnGuildVoiceJoin func(event *GuildVoiceJoinEvent) - OnGuildVoiceLeave func(event *GuildVoiceLeaveEvent) + OnGenericGuildVoiceEvent func(event GenericGuildVoiceEvent) + OnGuildVoiceUpdate func(event GuildVoiceUpdateEvent) + OnGuildVoiceJoin func(event GuildVoiceJoinEvent) + OnGuildVoiceLeave func(event GuildVoiceLeaveEvent) // api.Guild api.Role Events - OnGenericRoleEvent func(event *GenericRoleEvent) - OnRoleCreate func(event *RoleCreateEvent) - OnRoleUpdate func(event *RoleUpdateEvent) - OnRoleDelete func(event *RoleDeleteEvent) + OnGenericRoleEvent func(event GenericRoleEvent) + OnRoleCreate func(event RoleCreateEvent) + OnRoleUpdate func(event RoleUpdateEvent) + OnRoleDelete func(event RoleDeleteEvent) // api.Interaction Events - OnGenericInteractionEvent func(event *GenericInteractionEvent) - OnCommand func(event *CommandEvent) - OnButtonClick func(event *ButtonClickEvent) + OnGenericInteractionEvent func(event GenericInteractionEvent) + OnCommand func(event CommandEvent) + OnButtonClick func(event ButtonClickEvent) // api.Message Events - OnGenericMessageEvent func(event *GenericMessageEvent) - OnMessageCreate func(event *MessageCreateEvent) - OnMessageUpdate func(event *MessageUpdateEvent) - OnMessageDelete func(event *MessageDeleteEvent) + OnGenericMessageEvent func(event GenericMessageEvent) + OnMessageCreate func(event MessageCreateEvent) + OnMessageUpdate func(event MessageUpdateEvent) + OnMessageDelete func(event MessageDeleteEvent) // api.Message Reaction Events - OnGenericReactionEvent func(event *GenericReactionEvents) - OnMessageReactionAdd func(event *MessageReactionAddEvent) - OnMessageReactionRemove func(event *MessageReactionRemoveEvent) - OnMessageReactionRemoveEmote func(event *MessageReactionRemoveEmoteEvent) - OnMessageReactionRemoveAll func(event *MessageReactionRemoveAllEvent) + OnGenericReactionEvent func(event GenericReactionEvents) + OnMessageReactionAdd func(event MessageReactionAddEvent) + OnMessageReactionRemove func(event MessageReactionRemoveEvent) + OnMessageReactionRemoveEmote func(event MessageReactionRemoveEmoteEvent) + OnMessageReactionRemoveAll func(event MessageReactionRemoveAllEvent) // Self Events - OnSelfUpdate func(event *SelfUpdateEvent) + OnSelfUpdate func(event SelfUpdateEvent) // api.User Events - OnGenericUserEvent func(event *GenericUserEvent) - OnUserUpdate func(event *UserUpdateEvent) - OnUserTyping func(event *UserTypingEvent) - OnGuildUserTyping func(event *GuildMemberTypingEvent) - OnDMUserTyping func(event *DMUserTypingEvent) + OnGenericUserEvent func(event GenericUserEvent) + OnUserUpdate func(event UserUpdateEvent) + OnUserTyping func(event UserTypingEvent) + OnGuildUserTyping func(event GuildMemberTypingEvent) + OnDMUserTyping func(event DMUserTypingEvent) // api.User api.Activity Events - OnGenericUserActivityEvent func(event *GenericUserActivityEvent) - OnUserActivityStart func(event *UserActivityStartEvent) - OnUserActivityUpdate func(event *UserActivityUpdateEvent) - OnUserActivityEnd func(event *UserActivityEndEvent) + OnGenericUserActivityEvent func(event GenericUserActivityEvent) + OnUserActivityStart func(event UserActivityStartEvent) + OnUserActivityUpdate func(event UserActivityUpdateEvent) + OnUserActivityEnd func(event UserActivityEndEvent) } // OnEvent is getting called everytime we receive an event @@ -161,445 +161,445 @@ func (l ListenerAdapter) OnEvent(event interface{}) { switch e := event.(type) { case GenericEvent: if listener := l.OnGenericEvent; listener != nil { - listener(&e) + listener(e) } case HeartbeatEvent: if listener := l.OnHeartbeat; listener != nil { - listener(&e) + listener(e) } case HTTPRequestEvent: if listener := l.OnHTTPRequest; listener != nil { - listener(&e) + listener(e) } case RawGatewayEvent: if listener := l.OnRawGateway; listener != nil { - listener(&e) + listener(e) } case ReadyEvent: if listener := l.OnReadyEvent; listener != nil { - listener(&e) + listener(e) } // api.Command Events case GenericCommandEvent: if listener := l.OnGenericCommandEvent; listener != nil { - listener(&e) + listener(e) } case CommandCreateEvent: if listener := l.OnCommandCreate; listener != nil { - listener(&e) + listener(e) } case CommandUpdateEvent: if listener := l.OnCommandUpdate; listener != nil { - listener(&e) + listener(e) } case CommandDeleteEvent: if listener := l.OnCommandDelete; listener != nil { - listener(&e) + listener(e) } // api.Channel Events case GenericChannelEvent: if listener := l.OnGenericChannelEvent; listener != nil { - listener(&e) + listener(e) } // api.Category Events case GenericCategoryEvent: if listener := l.OnGenericCategoryEvent; listener != nil { - listener(&e) + listener(e) } case CategoryCreateEvent: if listener := l.OnCategoryCreate; listener != nil { - listener(&e) + listener(e) } case CategoryUpdateEvent: if listener := l.OnCategoryUpdate; listener != nil { - listener(&e) + listener(e) } case CategoryDeleteEvent: if listener := l.OnCategoryDelete; listener != nil { - listener(&e) + listener(e) } // api.DMChannel Events// api.Category Events case GenericDMChannelEvent: if listener := l.OnGenericDMChannelEvent; listener != nil { - listener(&e) + listener(e) } case DMChannelCreateEvent: if listener := l.OnDMChannelCreate; listener != nil { - listener(&e) + listener(e) } case DMChannelUpdateEvent: if listener := l.OnDMChannelUpdate; listener != nil { - listener(&e) + listener(e) } case DMChannelDeleteEvent: if listener := l.OnDMChannelDelete; listener != nil { - listener(&e) + listener(e) } // api.DMChannel Events// api.Category Events case GenericDMMessageReactionEvent: if listener := l.OnGenericDMMessageReactionEventEvent; listener != nil { - listener(&e) + listener(e) } case DMMessageReactionAddEvent: if listener := l.OnDMMessageReactionAdd; listener != nil { - listener(&e) + listener(e) } case DMMessageReactionRemoveEvent: if listener := l.OnDMMessageReactionRemove; listener != nil { - listener(&e) + listener(e) } case DMMessageReactionRemoveEmoteEvent: if listener := l.OnDMMessageReactionRemoveEmote; listener != nil { - listener(&e) + listener(e) } case DMMessageReactionRemoveAllEvent: if listener := l.OnDMMessageReactionRemoveAll; listener != nil { - listener(&e) + listener(e) } // api.StoreChannel Events case GenericStoreChannelEvent: if listener := l.OnGenericStoreChannelEvent; listener != nil { - listener(&e) + listener(e) } case StoreChannelCreateEvent: if listener := l.OnStoreChannelCreate; listener != nil { - listener(&e) + listener(e) } case StoreChannelUpdateEvent: if listener := l.OnStoreChannelUpdate; listener != nil { - listener(&e) + listener(e) } case StoreChannelDeleteEvent: if listener := l.OnStoreChannelDelete; listener != nil { - listener(&e) + listener(e) } // api.TextChannel Events case GenericTextChannelEvent: if listener := l.OnGenericTextChannelEvent; listener != nil { - listener(&e) + listener(e) } case TextChannelCreateEvent: if listener := l.OnTextChannelCreate; listener != nil { - listener(&e) + listener(e) } case TextChannelUpdateEvent: if listener := l.OnTextChannelUpdate; listener != nil { - listener(&e) + listener(e) } case TextChannelDeleteEvent: if listener := l.OnTextChannelDelete; listener != nil { - listener(&e) + listener(e) } // api.VoiceChannel Events case GenericVoiceChannelEvent: if listener := l.OnGenericVoiceChannelEvent; listener != nil { - listener(&e) + listener(e) } case VoiceChannelCreateEvent: if listener := l.OnVoiceChannelCreate; listener != nil { - listener(&e) + listener(e) } case VoiceChannelUpdateEvent: if listener := l.OnVoiceChannelUpdate; listener != nil { - listener(&e) + listener(e) } case VoiceChannelDeleteEvent: if listener := l.OnVoiceChannelDelete; listener != nil { - listener(&e) + listener(e) } // api.emote Events case GenericEmoteEvent: if listener := l.OnGenericEmoteEvent; listener != nil { - listener(&e) + listener(e) } case EmoteCreateEvent: if listener := l.OnEmoteCreate; listener != nil { - listener(&e) + listener(e) } case EmoteUpdateEvent: if listener := l.OnEmoteUpdate; listener != nil { - listener(&e) + listener(e) } case EmoteDeleteEvent: if listener := l.OnEmoteDelete; listener != nil { - listener(&e) + listener(e) } // api.GatewayStatus Events case GenericGatewayStatusEvent: if listener := l.OnGenericGatewayStatusEvent; listener != nil { - listener(&e) + listener(e) } case ConnectedEvent: if listener := l.OnConnected; listener != nil { - listener(&e) + listener(e) } case ReconnectedEvent: if listener := l.OnReconnected; listener != nil { - listener(&e) + listener(e) } case ResumedEvent: if listener := l.OnResumed; listener != nil { - listener(&e) + listener(e) } case DisconnectedEvent: if listener := l.OnDisconnected; listener != nil { - listener(&e) + listener(e) } // api.Guild Events case GenericGuildEvent: if listener := l.OnGenericGuildEvent; listener != nil { - listener(&e) + listener(e) } case GuildJoinEvent: if listener := l.OnGuildJoin; listener != nil { - listener(&e) + listener(e) } case GuildUpdateEvent: if listener := l.OnGuildUpdate; listener != nil { - listener(&e) + listener(e) } case GuildLeaveEvent: if listener := l.OnGuildLeave; listener != nil { - listener(&e) + listener(e) } case GuildAvailableEvent: if listener := l.OnGuildAvailable; listener != nil { - listener(&e) + listener(e) } case GuildUnavailableEvent: if listener := l.OnGuildUnavailable; listener != nil { - listener(&e) + listener(e) } case GuildReadyEvent: if listener := l.OnGuildReady; listener != nil { - listener(&e) + listener(e) } case GuildBanEvent: if listener := l.OnGuildBan; listener != nil { - listener(&e) + listener(e) } case GuildUnbanEvent: if listener := l.OnGuildUnban; listener != nil { - listener(&e) + listener(e) } // api.Guild api.Invite Events case GenericGuildInviteEvent: if listener := l.OnGenericGuildInviteEvent; listener != nil { - listener(&e) + listener(e) } case GuildInviteCreateEvent: if listener := l.OnGuildInviteCreate; listener != nil { - listener(&e) + listener(e) } case GuildInviteDeleteEvent: if listener := l.OnGuildInviteDelete; listener != nil { - listener(&e) + listener(e) } // api.Member Events case GenericGuildMemberEvent: if listener := l.OnGenericGuildMemberEvent; listener != nil { - listener(&e) + listener(e) } case GuildMemberJoinEvent: if listener := l.OnGuildMemberJoin; listener != nil { - listener(&e) + listener(e) } case GuildMemberUpdateEvent: if listener := l.OnGuildMemberUpdate; listener != nil { - listener(&e) + listener(e) } case GuildMemberLeaveEvent: if listener := l.OnGuildMemberLeave; listener != nil { - listener(&e) + listener(e) } // api.Guild api.Message Events case GenericGuildMessageEvent: if listener := l.OnGenericGuildMessageEvent; listener != nil { - listener(&e) + listener(e) } case GuildMessageCreateEvent: if listener := l.OnGuildMessageCreate; listener != nil { - listener(&e) + listener(e) } case GuildMessageUpdateEvent: if listener := l.OnGuildMessageUpdate; listener != nil { - listener(&e) + listener(e) } case GuildMessageDeleteEvent: if listener := l.OnGuildMessageDelete; listener != nil { - listener(&e) + listener(e) } // api.Guild api.Message Reaction Events case GenericGuildMessageReactionEvent: if listener := l.OnGenericGuildMessageReactionEvent; listener != nil { - listener(&e) + listener(e) } case GuildMessageReactionAddEvent: if listener := l.OnGuildMessageReactionAdd; listener != nil { - listener(&e) + listener(e) } case GuildMessageReactionRemoveEvent: if listener := l.OnGuildMessageReactionRemove; listener != nil { - listener(&e) + listener(e) } case GuildMessageReactionRemoveEmoteEvent: if listener := l.OnGuildMessageReactionRemoveEmote; listener != nil { - listener(&e) + listener(e) } case GuildMessageReactionRemoveAllEvent: if listener := l.OnGuildMessageReactionRemoveAll; listener != nil { - listener(&e) + listener(e) } // api.Guild Voice Events case GenericGuildVoiceEvent: if listener := l.OnGenericGuildVoiceEvent; listener != nil { - listener(&e) + listener(e) } case GuildVoiceUpdateEvent: if listener := l.OnGuildVoiceUpdate; listener != nil { - listener(&e) + listener(e) } case GuildVoiceJoinEvent: if listener := l.OnGuildVoiceJoin; listener != nil { - listener(&e) + listener(e) } case GuildVoiceLeaveEvent: if listener := l.OnGuildVoiceLeave; listener != nil { - listener(&e) + listener(e) } // api.Guild api.Role Events case GenericRoleEvent: if listener := l.OnGenericRoleEvent; listener != nil { - listener(&e) + listener(e) } case RoleCreateEvent: if listener := l.OnRoleCreate; listener != nil { - listener(&e) + listener(e) } case RoleUpdateEvent: if listener := l.OnRoleUpdate; listener != nil { - listener(&e) + listener(e) } case RoleDeleteEvent: if listener := l.OnRoleDelete; listener != nil { - listener(&e) + listener(e) } // Interaction Events case GenericInteractionEvent: if listener := l.OnGenericInteractionEvent; listener != nil { - listener(&e) + listener(e) } case CommandEvent: if listener := l.OnCommand; listener != nil { - listener(&e) + listener(e) } case ButtonClickEvent: if listener := l.OnButtonClick; listener != nil { - listener(&e) + listener(e) } // api.Message Events case GenericMessageEvent: if listener := l.OnGenericMessageEvent; listener != nil { - listener(&e) + listener(e) } case MessageCreateEvent: if listener := l.OnMessageCreate; listener != nil { - listener(&e) + listener(e) } case MessageUpdateEvent: if listener := l.OnMessageUpdate; listener != nil { - listener(&e) + listener(e) } case MessageDeleteEvent: if listener := l.OnMessageDelete; listener != nil { - listener(&e) + listener(e) } // api.Message Reaction Events case GenericReactionEvents: if listener := l.OnGenericReactionEvent; listener != nil { - listener(&e) + listener(e) } case MessageReactionAddEvent: if listener := l.OnMessageReactionAdd; listener != nil { - listener(&e) + listener(e) } case MessageReactionRemoveEvent: if listener := l.OnMessageReactionRemove; listener != nil { - listener(&e) + listener(e) } case MessageReactionRemoveEmoteEvent: if listener := l.OnMessageReactionRemoveEmote; listener != nil { - listener(&e) + listener(e) } case MessageReactionRemoveAllEvent: if listener := l.OnMessageReactionRemoveAll; listener != nil { - listener(&e) + listener(e) } // Self Events case SelfUpdateEvent: if listener := l.OnSelfUpdate; listener != nil { - listener(&e) + listener(e) } // api.User Events case GenericUserEvent: if listener := l.OnGenericUserEvent; listener != nil { - listener(&e) + listener(e) } case UserUpdateEvent: if listener := l.OnUserUpdate; listener != nil { - listener(&e) + listener(e) } case UserTypingEvent: if listener := l.OnUserTyping; listener != nil { - listener(&e) + listener(e) } case GuildMemberTypingEvent: if listener := l.OnGuildUserTyping; listener != nil { - listener(&e) + listener(e) } case DMUserTypingEvent: if listener := l.OnDMUserTyping; listener != nil { - listener(&e) + listener(e) } // api.User api.Activity Events case GenericUserActivityEvent: if listener := l.OnGenericUserActivityEvent; listener != nil { - listener(&e) + listener(e) } case UserActivityStartEvent: if listener := l.OnUserActivityStart; listener != nil { - listener(&e) + listener(e) } case UserActivityUpdateEvent: if listener := l.OnUserActivityUpdate; listener != nil { - listener(&e) + listener(e) } case UserActivityEndEvent: if listener := l.OnUserActivityEnd; listener != nil { - listener(&e) + listener(e) } default: diff --git a/api/events/message_reaction_events.go b/api/events/message_reaction_events.go index b8e7da36..25567cca 100644 --- a/api/events/message_reaction_events.go +++ b/api/events/message_reaction_events.go @@ -20,7 +20,7 @@ type MessageReactionRemoveEvent struct { GenericReactionEvents } -// MessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emote from a api.Message in a api.Channel(requires the api.GatewayIntentsGuildMessageReactions and/or api.GatewayIntentsDirectMessageReactions) +// MessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.Channel(requires the api.GatewayIntentsGuildMessageReactions and/or api.GatewayIntentsDirectMessageReactions) type MessageReactionRemoveEmoteEvent struct { GenericMessageEvent MessageReaction api.MessageReaction diff --git a/api/gateway_intents.go b/api/gateway_intents.go index 526bb4a0..fa3eced1 100644 --- a/api/gateway_intents.go +++ b/api/gateway_intents.go @@ -4,27 +4,27 @@ package api type GatewayIntents int64 // Add allows you to add multiple bits together, producing a new bit -func (p GatewayIntents) Add(bits ...Bit) Bit { +func (p GatewayIntents) Add(bits ...GatewayIntents) GatewayIntents { total := GatewayIntents(0) for _, bit := range bits { - total |= bit.(GatewayIntents) + total |= bit } p |= total return p } // Remove allows you to subtract multiple bits from the first, producing a new bit -func (p GatewayIntents) Remove(bits ...Bit) Bit { +func (p GatewayIntents) Remove(bits ...GatewayIntents) GatewayIntents { total := GatewayIntents(0) for _, bit := range bits { - total |= bit.(GatewayIntents) + total |= bit } p &^= total return p } // HasAll will ensure that the bit includes all of the bits entered -func (p GatewayIntents) HasAll(bits ...Bit) bool { +func (p GatewayIntents) HasAll(bits ...GatewayIntents) bool { for _, bit := range bits { if !p.Has(bit) { return false @@ -34,12 +34,12 @@ func (p GatewayIntents) HasAll(bits ...Bit) bool { } // Has will check whether the Bit contains another bit -func (p GatewayIntents) Has(bit Bit) bool { - return (p & bit.(GatewayIntents)) == bit +func (p GatewayIntents) Has(bit GatewayIntents) bool { + return (p & bit) == bit } // MissingAny will check whether the bit is missing any one of the bits -func (p GatewayIntents) MissingAny(bits ...Bit) bool { +func (p GatewayIntents) MissingAny(bits ...GatewayIntents) bool { for _, bit := range bits { if !p.Has(bit) { return true @@ -49,7 +49,7 @@ func (p GatewayIntents) MissingAny(bits ...Bit) bool { } // Missing will do the inverse of Bit.Has -func (p GatewayIntents) Missing(bit Bit) bool { +func (p GatewayIntents) Missing(bit GatewayIntents) bool { return !p.Has(bit) } diff --git a/api/guild.go b/api/guild.go index b6d23d90..01aefc11 100644 --- a/api/guild.go +++ b/api/guild.go @@ -115,14 +115,14 @@ type GuildPreview struct { Description *string `json:"description"` ApproximateMemberCount *int `json:"approximate_member_count"` ApproximatePresenceCount *int `json:"approximate_presence_count"` - Emojis []*Emote `json:"emojis"` + Emojis []*Emoji `json:"emojis"` } // FullGuild represents a Guild objects sent by discord with the GatewayEventGuildCreate type FullGuild struct { *Guild Roles []*Role `json:"roles"` - Emotes []*Emote `json:"emojis"` + Emotes []*Emoji `json:"emojis"` Members []*Member `json:"members"` Channels []*Channel `json:"channels"` VoiceStates []*VoiceState `json:"voice_states"` @@ -178,12 +178,12 @@ func (g *Guild) Disconnect() error { } // CreateRole allows you to create a new Role -func (g *Guild) CreateRole(role *UpdateRole) (*Role, error) { +func (g *Guild) CreateRole(role UpdateRole) (*Role, error) { return g.Disgo.RestClient().CreateRole(g.ID, role) } // AddMember adds a member to the Guild with the oauth2 access token -func (g *Guild) AddMember(userID Snowflake, addGuildMemberData *AddGuildMemberData) (*Member, error) { +func (g *Guild) AddMember(userID Snowflake, addGuildMemberData AddGuildMemberData) (*Member, error) { return g.Disgo.RestClient().AddMember(g.ID, userID, addGuildMemberData) } @@ -216,12 +216,12 @@ func (g *Guild) GetCommands() ([]*Command, error) { } // CreateCommand creates a new Command for this Guild -func (g *Guild) CreateCommand(command *CommandCreate) (*Command, error) { +func (g *Guild) CreateCommand(command CommandCreate) (*Command, error) { return g.Disgo.CreateGuildCommand(g.ID, command) } // EditCommand edits a specific Guild Command -func (g *Guild) EditCommand(commandID Snowflake, command *CommandUpdate) (*Command, error) { +func (g *Guild) EditCommand(commandID Snowflake, command CommandUpdate) (*Command, error) { return g.Disgo.EditGuildCommand(g.ID, commandID, command) } @@ -231,7 +231,7 @@ func (g *Guild) DeleteCommand(commandID Snowflake) error { } // SetCommands overrides all Command(s) for this Guild -func (g *Guild) SetCommands(commands ...*CommandCreate) ([]*Command, error) { +func (g *Guild) SetCommands(commands ...CommandCreate) ([]*Command, error) { return g.Disgo.SetGuildCommands(g.ID, commands...) } @@ -246,11 +246,11 @@ func (g *Guild) GetCommandPermissions(commandID Snowflake) (*GuildCommandPermiss } // SetCommandsPermissions sets the GuildCommandPermissions for a all Command(s) -func (g *Guild) SetCommandsPermissions(commandPermissions ...*SetGuildCommandPermissions) ([]*GuildCommandPermissions, error) { +func (g *Guild) SetCommandsPermissions(commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, error) { return g.Disgo.SetGuildCommandsPermissions(g.ID, commandPermissions...) } // SetCommandPermissions sets the GuildCommandPermissions for a specific Command -func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions *SetGuildCommandPermissions) (*GuildCommandPermissions, error) { +func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, error) { return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } diff --git a/api/interaction.go b/api/interaction.go index ca5b4222..cabf5597 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -18,7 +18,7 @@ const ( // Interaction holds the general parameters of each Interaction type Interaction struct { Disgo Disgo - ResponseChannel chan *InteractionResponse + ResponseChannel chan InteractionResponse Replied bool ID Snowflake `json:"id"` Type InteractionType `json:"type"` @@ -31,7 +31,7 @@ type Interaction struct { } // Reply replies to the api.Interaction with the provided api.InteractionResponse -func (i *Interaction) Reply(response *InteractionResponse) error { +func (i *Interaction) Reply(response InteractionResponse) error { if i.Replied { return errors.New("you already replied to this interaction") } @@ -91,7 +91,7 @@ func (i *Interaction) GuildChannel() *GuildChannel { } // EditOriginal edits the original api.InteractionResponse -func (i *Interaction) EditOriginal(followupMessage *FollowupMessage) (*Message, error) { +func (i *Interaction) EditOriginal(followupMessage FollowupMessage) (*Message, error) { return i.Disgo.RestClient().EditInteractionResponse(i.Disgo.ApplicationID(), i.Token, followupMessage) } @@ -101,12 +101,12 @@ func (i *Interaction) DeleteOriginal() error { } // SendFollowup used to send a api.FollowupMessage to an api.Interaction -func (i *Interaction) SendFollowup(followupMessage *FollowupMessage) (*Message, error) { +func (i *Interaction) SendFollowup(followupMessage FollowupMessage) (*Message, error) { return i.Disgo.RestClient().SendFollowupMessage(i.Disgo.ApplicationID(), i.Token, followupMessage) } // EditFollowup used to edit a api.FollowupMessage from an api.Interaction -func (i *Interaction) EditFollowup(messageID Snowflake, followupMessage *FollowupMessage) (*Message, error) { +func (i *Interaction) EditFollowup(messageID Snowflake, followupMessage FollowupMessage) (*Message, error) { return i.Disgo.RestClient().EditFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID, followupMessage) } @@ -137,16 +137,16 @@ type CommandInteraction struct { // DeferReply replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource and shows a loading state func (i *CommandInteraction) DeferReply(ephemeral bool) error { - var data *InteractionResponseData + var data InteractionResponseData if ephemeral { - data = &InteractionResponseData{Flags: MessageFlagEphemeral} + data = InteractionResponseData{Flags: MessageFlagEphemeral} } - return i.Reply(&InteractionResponse{Type: InteractionResponseTypeDeferredChannelMessageWithSource, Data: data}) + return i.Reply(InteractionResponse{Type: InteractionResponseTypeDeferredChannelMessageWithSource, Data: data}) } // ReplyCreate replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.InteractionResponseData -func (i *CommandInteraction) ReplyCreate(data *InteractionResponseData) error { - return i.Reply(&InteractionResponse{Type: InteractionResponseTypeChannelMessageWithSource, Data: data}) +func (i *CommandInteraction) ReplyCreate(data InteractionResponseData) error { + return i.Reply(InteractionResponse{Type: InteractionResponseTypeChannelMessageWithSource, Data: data}) } // ButtonInteraction is a specific Interaction when CLicked on Button(s) @@ -158,12 +158,12 @@ type ButtonInteraction struct { // DeferEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeDeferredUpdateMessage and cancels the loading state func (i *ButtonInteraction) DeferEdit() error { - return i.Reply(&InteractionResponse{Type: InteractionResponseTypeDeferredUpdateMessage}) + return i.Reply(InteractionResponse{Type: InteractionResponseTypeDeferredUpdateMessage}) } // ReplyEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.InteractionResponseData which edits the original api.Message -func (i *ButtonInteraction) ReplyEdit(data *InteractionResponseData) error { - return i.Reply(&InteractionResponse{Type: InteractionResponseTypeUpdateMessage, Data: data}) +func (i *ButtonInteraction) ReplyEdit(data InteractionResponseData) error { + return i.Reply(InteractionResponse{Type: InteractionResponseTypeUpdateMessage, Data: data}) } // CommandInteractionData is the command data payload diff --git a/api/interaction_followup.go b/api/interaction_followup.go index e56e9798..7405fb4b 100644 --- a/api/interaction_followup.go +++ b/api/interaction_followup.go @@ -127,6 +127,6 @@ func (b *FollowupMessageBuilder) SetEphemeral(ephemeral bool) *FollowupMessageBu } // Build returns your built FollowupMessage -func (b *FollowupMessageBuilder) Build() *FollowupMessage { - return &b.FollowupMessage +func (b *FollowupMessageBuilder) Build() FollowupMessage { + return b.FollowupMessage } diff --git a/api/interaction_response.go b/api/interaction_response.go index faefea89..bda9812a 100644 --- a/api/interaction_response.go +++ b/api/interaction_response.go @@ -18,8 +18,8 @@ const ( // InteractionResponse is how you answer interactions. If an answer is not sent within 3 seconds of receiving it, the interaction is failed, and you will be unable to respond to it. type InteractionResponse struct { - Type InteractionResponseType `json:"type"` - Data *InteractionResponseData `json:"data,omitempty"` + Type InteractionResponseType `json:"type"` + Data InteractionResponseData `json:"data,omitempty"` } // The InteractionResponseData is used to specify the message_events options when creating an InteractionResponse @@ -41,7 +41,19 @@ type InteractionResponseBuilder struct { func NewInteractionResponseBuilder() *InteractionResponseBuilder { return &InteractionResponseBuilder{ InteractionResponse: InteractionResponse{ - Data: &InteractionResponseData{ + Data: InteractionResponseData{ + AllowedMentions: &DefaultInteractionAllowedMentions, + }, + }, + } +} + +// NewInteractionResponseWithTypeBuilder returns a new InteractionResponseBuilder with the given InteractionResponseType +func NewInteractionResponseWithTypeBuilder(responseType InteractionResponseType) *InteractionResponseBuilder { + return &InteractionResponseBuilder{ + InteractionResponse: InteractionResponse{ + Type: responseType, + Data: InteractionResponseData{ AllowedMentions: &DefaultInteractionAllowedMentions, }, }, @@ -50,7 +62,7 @@ func NewInteractionResponseBuilder() *InteractionResponseBuilder { // NewInteractionResponseBuilderByMessage returns a new InteractionResponseBuilder and takes an existing Message func NewInteractionResponseBuilderByMessage(message *Message) *InteractionResponseBuilder { - rs := &InteractionResponseData{ + rs := InteractionResponseData{ TTS: message.TTS, Embeds: message.Embeds, Components: message.Components, @@ -183,11 +195,11 @@ func (b *InteractionResponseBuilder) SetEphemeral(ephemeral bool) *InteractionRe } // Build returns your built InteractionResponse -func (b *InteractionResponseBuilder) Build() *InteractionResponse { - return &b.InteractionResponse +func (b *InteractionResponseBuilder) Build() InteractionResponse { + return b.InteractionResponse } // BuildData returns your built InteractionResponseData -func (b *InteractionResponseBuilder) BuildData() *InteractionResponseData { +func (b *InteractionResponseBuilder) BuildData() InteractionResponseData { return b.Data } diff --git a/api/invite.go b/api/invite.go index ee579990..32654326 100644 --- a/api/invite.go +++ b/api/invite.go @@ -30,7 +30,7 @@ type Invite struct { } // URL returns the invite url in format like https://discord.gg/{code} -func (i Invite) URL() string { +func (i *Invite) URL() string { url, err := restclient.InviteURL.Compile(nil, i.Code) if err != nil { return "" diff --git a/api/member.go b/api/member.go index dec914a7..5c0e5e93 100644 --- a/api/member.go +++ b/api/member.go @@ -41,7 +41,7 @@ func (m Member) IsOwner() bool { } // Update updates the member -func (m Member) Update(updateGuildMemberData *UpdateGuildMemberData) (*Member, error) { +func (m Member) Update(updateGuildMemberData UpdateGuildMemberData) (*Member, error) { return m.Disgo.RestClient().UpdateMember(m.GuildID, m.User.ID, updateGuildMemberData) } diff --git a/api/message.go b/api/message.go index 1e2a8cd5..e8dcb964 100644 --- a/api/message.go +++ b/api/message.go @@ -225,8 +225,8 @@ func (m *Message) Channel() *MessageChannel { return m.Disgo.Cache().MessageChannel(m.ChannelID) } -// AddReactionByEmote allows you to add an Emote to a message_events via reaction -func (m *Message) AddReactionByEmote(emote Emote) error { +// AddReactionByEmote allows you to add an Emoji to a message_events via reaction +func (m *Message) AddReactionByEmote(emote Emoji) error { return m.AddReaction(emote.Reaction()) } @@ -236,7 +236,7 @@ func (m *Message) AddReaction(emoji string) error { } // Edit allows you to edit an existing Message sent by you -func (m *Message) Edit(message *MessageUpdate) (*Message, error) { +func (m *Message) Edit(message MessageUpdate) (*Message, error) { return m.Disgo.RestClient().EditMessage(m.ChannelID, m.ID, message) } @@ -255,7 +255,7 @@ func (m *Message) Crosspost() (*Message, error) { } // Reply allows you to reply to an existing Message -func (m *Message) Reply(message *MessageCreate) (*Message, error) { +func (m *Message) Reply(message MessageCreate) (*Message, error) { message.MessageReference = &MessageReference{ MessageID: &m.ID, } @@ -266,7 +266,7 @@ func (m *Message) Reply(message *MessageCreate) (*Message, error) { type MessageReaction struct { Count int `json:"count"` Me bool `json:"me"` - Emoji Emote `json:"emoji"` + Emoji Emoji `json:"emoji"` } // MessageUpdate is used to edit a Message diff --git a/api/message_builder.go b/api/message_builder.go index 909ee399..bba0fa6c 100644 --- a/api/message_builder.go +++ b/api/message_builder.go @@ -135,6 +135,6 @@ func (b *MessageBuilder) SetMessageReferenceByMessageID(messageID Snowflake) *Me } // Build builds the MessageBuilder to a MessageCreate struct -func (b *MessageBuilder) Build() *MessageCreate { - return &b.MessageCreate +func (b *MessageBuilder) Build() MessageCreate { + return b.MessageCreate } diff --git a/api/permissions.go b/api/permissions.go index 389827e5..d305d0d7 100644 --- a/api/permissions.go +++ b/api/permissions.go @@ -18,8 +18,8 @@ const ( type PermissionOverwrite struct { ID Snowflake `json:"id"` Type PermissionOverwriteType `json:"type"` - Allow Permissions `json:"allow"` - Deny Permissions `json:"deny"` + Allow Permissions `json:"allow,string"` + Deny Permissions `json:"deny,string"` } // Permissions extends the Bit structure, and is used within roles and channels @@ -37,7 +37,7 @@ func (p Permissions) MarshalJSON() ([]byte, error) { return jsonValue, nil } -// UnmarshalJSON unmarshals permissions into an int64 +// UnmarshalJSON unmarshalls permissions into an int64 func (p *Permissions) UnmarshalJSON(b []byte) error { var strPermissions string err := json.Unmarshal(b, &strPermissions) @@ -54,27 +54,27 @@ func (p *Permissions) UnmarshalJSON(b []byte) error { } // Add allows you to add multiple bits together, producing a new bit -func (p Permissions) Add(bits ...Bit) Bit { +func (p Permissions) Add(bits ...Permissions) Permissions { total := Permissions(0) for _, bit := range bits { - total |= bit.(Permissions) + total |= bit } p |= total return p } // Remove allows you to subtract multiple bits from the first, producing a new bit -func (p Permissions) Remove(bits ...Bit) Bit { +func (p Permissions) Remove(bits ...Permissions) Permissions { total := Permissions(0) for _, bit := range bits { - total |= bit.(Permissions) + total |= bit } p &^= total return p } // HasAll will ensure that the bit includes all of the bits entered -func (p Permissions) HasAll(bits ...Bit) bool { +func (p Permissions) HasAll(bits ...Permissions) bool { for _, bit := range bits { if !p.Has(bit) { return false @@ -84,12 +84,12 @@ func (p Permissions) HasAll(bits ...Bit) bool { } // Has will check whether the Bit contains another bit -func (p Permissions) Has(bit Bit) bool { - return (p & bit.(Permissions)) == bit +func (p Permissions) Has(bit Permissions) bool { + return (p & bit) == bit } // MissingAny will check whether the bit is missing any one of the bits -func (p Permissions) MissingAny(bits ...Bit) bool { +func (p Permissions) MissingAny(bits ...Permissions) bool { for _, bit := range bits { if !p.Has(bit) { return true @@ -99,7 +99,7 @@ func (p Permissions) MissingAny(bits ...Bit) bool { } // Missing will do the inverse of Bit.Has -func (p Permissions) Missing(bit Bit) bool { +func (p Permissions) Missing(bit Permissions) bool { return !p.Has(bit) } @@ -148,7 +148,7 @@ const ( PermissionViewAuditLogs PermissionViewChannel Permissions = 1 << (iota + 2) - PermissionAllText = PermissionViewChannel | + PermissionsAllText = PermissionViewChannel | PermissionSendMessages | PermissionSendTTSMessages | PermissionManageMessages | @@ -156,7 +156,7 @@ const ( PermissionAttachFiles | PermissionReadMessageHistory | PermissionMentionEveryone - PermissionAllVoice = PermissionViewChannel | + PermissionsAllVoice = PermissionViewChannel | PermissionVoiceConnect | PermissionVoiceSpeak | PermissionVoiceMuteMembers | @@ -164,14 +164,14 @@ const ( PermissionVoiceMoveMembers | PermissionVoiceUseVAD | PermissionVoicePrioritySpeaker - PermissionAllChannel = PermissionAllText | - PermissionAllVoice | + PermissionsAllChannel = PermissionsAllText | + PermissionsAllVoice | PermissionCreateInstantInvite | PermissionManageRoles | PermissionManageChannels | PermissionAddReactions | PermissionViewAuditLogs - PermissionAll = PermissionAllChannel | + PermissionsAll = PermissionsAllChannel | PermissionKickMembers | PermissionBanMembers | PermissionManageServer | @@ -179,5 +179,5 @@ const ( PermissionManageWebhooks | PermissionManageEmojis - PermissionNone Permissions = 0 + PermissionsNone Permissions = 0 ) diff --git a/api/restclient.go b/api/restclient.go index 4dbf0745..acccd158 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -24,8 +24,8 @@ type RestClient interface { Close() Disgo() Disgo - SendMessage(channelID Snowflake, message *MessageCreate) (*Message, error) - EditMessage(channelID Snowflake, messageID Snowflake, message *MessageUpdate) (*Message, error) + SendMessage(channelID Snowflake, message MessageCreate) (*Message, error) + EditMessage(channelID Snowflake, messageID Snowflake, message MessageUpdate) (*Message, error) DeleteMessage(channelID Snowflake, messageID Snowflake) error BulkDeleteMessages(channelID Snowflake, messageIDs ...Snowflake) error CrosspostMessage(channelID Snowflake, messageID Snowflake) (*Message, error) @@ -37,17 +37,17 @@ type RestClient interface { GetUser(userID Snowflake) (*User, error) GetMember(guildID Snowflake, userID Snowflake) (*Member, error) GetMembers(guildID Snowflake) ([]*Member, error) - AddMember(guildID Snowflake, userID Snowflake, addGuildMemberData *AddGuildMemberData) (*Member, error) + AddMember(guildID Snowflake, userID Snowflake, addGuildMemberData AddGuildMemberData) (*Member, error) KickMember(guildID Snowflake, userID Snowflake, reason *string) error - UpdateMember(guildID Snowflake, userID Snowflake, updateGuildMemberData *UpdateGuildMemberData) (*Member, error) + UpdateMember(guildID Snowflake, userID Snowflake, updateGuildMemberData UpdateGuildMemberData) (*Member, error) MoveMember(guildID Snowflake, userID Snowflake, channelID *Snowflake) (*Member, error) AddMemberRole(guildID Snowflake, userID Snowflake, roleID Snowflake) error RemoveMemberRole(guildID Snowflake, userID Snowflake, roleID Snowflake) error GetRoles(guildID Snowflake) ([]*Role, error) - CreateRole(guildID Snowflake, role *UpdateRole) (*Role, error) - UpdateRole(guildID Snowflake, roleID Snowflake, role *UpdateRole) (*Role, error) - UpdateRolePositions(guildID Snowflake, roleUpdates ...*UpdateRolePosition) ([]*Role, error) + CreateRole(guildID Snowflake, role UpdateRole) (*Role, error) + UpdateRole(guildID Snowflake, roleID Snowflake, role UpdateRole) (*Role, error) + UpdateRolePositions(guildID Snowflake, roleUpdates ...UpdateRolePosition) ([]*Role, error) DeleteRole(guildID Snowflake, roleID Snowflake) error AddReaction(channelID Snowflake, messageID Snowflake, emoji string) error @@ -56,28 +56,28 @@ type RestClient interface { GetGlobalCommands(applicationID Snowflake) ([]*Command, error) GetGlobalCommand(applicationID Snowflake, commandID Snowflake) (*Command, error) - CreateGlobalCommand(applicationID Snowflake, command *CommandCreate) (*Command, error) - SetGlobalCommands(applicationID Snowflake, commands ...*CommandCreate) ([]*Command, error) - EditGlobalCommand(applicationID Snowflake, commandID Snowflake, command *CommandUpdate) (*Command, error) + CreateGlobalCommand(applicationID Snowflake, command CommandCreate) (*Command, error) + SetGlobalCommands(applicationID Snowflake, commands ...CommandCreate) ([]*Command, error) + EditGlobalCommand(applicationID Snowflake, commandID Snowflake, command CommandUpdate) (*Command, error) DeleteGlobalCommand(applicationID Snowflake, commandID Snowflake) error GetGuildCommands(applicationID Snowflake, guildID Snowflake) ([]*Command, error) GetGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake) (*Command, error) - CreateGuildCommand(applicationID Snowflake, guildID Snowflake, command *CommandCreate) (*Command, error) - SetGuildCommands(applicationID Snowflake, guildID Snowflake, commands ...*CommandCreate) ([]*Command, error) - EditGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake, command *CommandUpdate) (*Command, error) + CreateGuildCommand(applicationID Snowflake, guildID Snowflake, command CommandCreate) (*Command, error) + SetGuildCommands(applicationID Snowflake, guildID Snowflake, commands ...CommandCreate) ([]*Command, error) + EditGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake, command CommandUpdate) (*Command, error) DeleteGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake) error GetGuildCommandsPermissions(applicationID Snowflake, guildID Snowflake) ([]*GuildCommandPermissions, error) GetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake) (*GuildCommandPermissions, error) - SetGuildCommandsPermissions(applicationID Snowflake, guildID Snowflake, commandPermissions ...*SetGuildCommandPermissions) ([]*GuildCommandPermissions, error) - SetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake, commandPermissions *SetGuildCommandPermissions) (*GuildCommandPermissions, error) + SetGuildCommandsPermissions(applicationID Snowflake, guildID Snowflake, commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, error) + SetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake, commandPermissions SetGuildCommandPermissions) (*GuildCommandPermissions, error) - SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse *InteractionResponse) error - EditInteractionResponse(applicationID Snowflake, interactionToken string, followupMessage *FollowupMessage) (*Message, error) + SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse InteractionResponse) error + EditInteractionResponse(applicationID Snowflake, interactionToken string, followupMessage FollowupMessage) (*Message, error) DeleteInteractionResponse(applicationID Snowflake, interactionToken string) error - SendFollowupMessage(applicationID Snowflake, interactionToken string, followupMessage *FollowupMessage) (*Message, error) - EditFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, followupMessage *FollowupMessage) (*Message, error) + SendFollowupMessage(applicationID Snowflake, interactionToken string, followupMessage FollowupMessage) (*Message, error) + EditFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, followupMessage FollowupMessage) (*Message, error) DeleteFollowupMessage(applicationID Snowflake, interactionToken string, followupMessageID Snowflake) error } diff --git a/api/role.go b/api/role.go index 617e6abe..b4246fbd 100644 --- a/api/role.go +++ b/api/role.go @@ -6,7 +6,7 @@ type Role struct { GuildID Snowflake ID Snowflake `json:"id"` Name string `json:"name"` - Color Color `json:"color"` + Color int `json:"color"` Hoist bool `json:"hoist"` Position int `json:"position"` Permissions Permissions `json:"permissions"` @@ -16,32 +16,32 @@ type Role struct { } // Mention parses the Role as a Mention -func (r Role) Mention() string { +func (r *Role) Mention() string { return "<@&" + r.ID.String() + ">" } // String parses the Role to a String representation -func (r Role) String() string { +func (r *Role) String() string { return r.Mention() } // Guild returns the Guild of this role from the Cache -func (r Role) Guild() *Guild { +func (r *Role) Guild() *Guild { return r.Disgo.Cache().Guild(r.GuildID) } // Update updates the Role with specific values -func (r Role) Update(roleUpdate *UpdateRole) (*Role, error) { +func (r *Role) Update(roleUpdate UpdateRole) (*Role, error) { return r.Disgo.RestClient().UpdateRole(r.GuildID, r.ID, roleUpdate) } // SetPosition sets the position of the Role -func (r Role) SetPosition(rolePositionUpdate *UpdateRolePosition) ([]*Role, error) { +func (r *Role) SetPosition(rolePositionUpdate UpdateRolePosition) ([]*Role, error) { return r.Disgo.RestClient().UpdateRolePositions(r.GuildID, rolePositionUpdate) } // Delete deletes the Role -func (r Role) Delete() error { +func (r *Role) Delete() error { return r.Disgo.RestClient().DeleteRole(r.GuildID, r.ID) } @@ -56,7 +56,7 @@ type RoleTag struct { type UpdateRole struct { Name *string `json:"name,omitempty"` Permissions *Permissions `json:"permissions,omitempty"` - Color *Color `json:"color,omitempty"` + Color *int `json:"color,omitempty"` Hoist *bool `json:"hoist,omitempty"` Mentionable *bool `json:"mentionable,omitempty"` } diff --git a/api/self_user.go b/api/self_user.go new file mode 100644 index 00000000..aa5f0416 --- /dev/null +++ b/api/self_user.go @@ -0,0 +1,12 @@ +package api + +import "errors" + +var ErrDMChannelToYourself = errors.New("can't open a dm channel to yourself") + +type SelfUser User + +// OpenDMChannel creates a DMChannel between the user and the Disgo client +func (u *SelfUser) OpenDMChannel() (*DMChannel, error) { + return nil, ErrDMChannelToYourself +} diff --git a/api/user.go b/api/user.go index 26200d64..45e7b941 100644 --- a/api/user.go +++ b/api/user.go @@ -48,20 +48,20 @@ func (u *User) AvatarURL(size int) string { } // Mention returns the user as a mention -func (u User) Mention() string { +func (u *User) Mention() string { return "<@" + u.ID.String() + ">" } // Tag returns the user's Username and Discriminator -func (u User) Tag() string { +func (u *User) Tag() string { return fmt.Sprintf("%s#%s", u.Username, u.Discriminator) } -func (u User) String() string { +func (u *User) String() string { return u.Mention() } // OpenDMChannel creates a DMChannel between the user and the Disgo client -func (u User) OpenDMChannel() (*DMChannel, error) { +func (u *User) OpenDMChannel() (*DMChannel, error) { return u.Disgo.RestClient().OpenDMChannel(u.ID) } diff --git a/api/voice_state.go b/api/voice_state.go index 8b71099d..553afbd8 100644 --- a/api/voice_state.go +++ b/api/voice_state.go @@ -24,32 +24,32 @@ type VoiceState struct { } // Muted returns if the Member is muted -func (s VoiceState) Muted() bool { +func (s *VoiceState) Muted() bool { return s.GuildMuted || s.SelfMuted } // Deafened returns if the Member is deafened -func (s VoiceState) Deafened() bool { +func (s *VoiceState) Deafened() bool { return s.GuildDeafened || s.SelfDeafened } // Member returns the Member of this VoiceState from the Cache -func (s VoiceState) Member() *Member { +func (s *VoiceState) Member() *Member { return s.Disgo.Cache().Member(s.GuildID, s.UserID) } // User returns the User of this VoiceState from the Cache -func (s VoiceState) User() *User { +func (s *VoiceState) User() *User { return s.Disgo.Cache().User(s.UserID) } // Guild returns the Guild of this VoiceState from the Cache -func (s VoiceState) Guild() *Guild { +func (s *VoiceState) Guild() *Guild { return s.Disgo.Cache().Guild(s.GuildID) } // VoiceChannel returns the VoiceChannel of this VoiceState from the Cache -func (s VoiceState) VoiceChannel() *VoiceChannel { +func (s *VoiceState) VoiceChannel() *VoiceChannel { if s.ChannelID == nil { return nil } diff --git a/example/examplebot.go b/example/examplebot.go index 69f0d0fa..9c658387 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -21,6 +21,7 @@ const red = 16711680 const orange = 16562691 const green = 65280 +var token = os.Getenv("token") var guildID = api.Snowflake(os.Getenv("guild_id")) var adminRoleID = api.Snowflake(os.Getenv("admin_role_id")) var testRoleID = api.Snowflake(os.Getenv("test_role_id")) @@ -34,7 +35,7 @@ func main() { logger.Info("starting ExampleBot...") logger.Infof("disgo %s", api.Version) - dgo, err := disgo.NewBuilder(os.Getenv("token")). + dgo, err := disgo.NewBuilder(token). SetLogger(logger). SetRawGatewayEventsEnabled(true). SetHTTPClient(client). @@ -53,12 +54,12 @@ func main() { return } - rawCmds := []*api.CommandCreate{ + rawCmds := []api.CommandCreate{ { Name: "eval", Description: "runs some go code", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ + DefaultPermission: true, + Options: []api.CommandOption{ { Type: api.CommandOptionTypeString, Name: "code", @@ -70,13 +71,13 @@ func main() { { Name: "test", Description: "test test test test test test", - DefaultPermission: ptrBool(true), + DefaultPermission: true, }, { Name: "say", Description: "says what you say", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ + DefaultPermission: true, + Options: []api.CommandOption{ { Type: api.CommandOptionTypeString, Name: "message", @@ -88,8 +89,8 @@ func main() { { Name: "addrole", Description: "This command adds a role to a member", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ + DefaultPermission: true, + Options: []api.CommandOption{ { Type: api.CommandOptionTypeUser, Name: "member", @@ -107,8 +108,8 @@ func main() { { Name: "removerole", Description: "This command removes a role from a member", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ + DefaultPermission: true, + Options: []api.CommandOption{ { Type: api.CommandOptionTypeUser, Name: "member", @@ -131,25 +132,25 @@ func main() { logger.Errorf("error while registering guild commands: %s", err) } - var cmdsPermissions []*api.SetGuildCommandPermissions + var cmdsPermissions []api.SetGuildCommandPermissions for _, cmd := range cmds { - var perms *api.CommandPermission + var perms api.CommandPermission if cmd.Name == "eval" { - perms = &api.CommandPermission{ + perms = api.CommandPermission{ ID: adminRoleID, Type: api.CommandPermissionTypeRole, Permission: true, } } else { - perms = &api.CommandPermission{ + perms = api.CommandPermission{ ID: testRoleID, Type: api.CommandPermissionTypeRole, Permission: true, } } - cmdsPermissions = append(cmdsPermissions, &api.SetGuildCommandPermissions{ + cmdsPermissions = append(cmdsPermissions, api.SetGuildCommandPermissions{ ID: cmd.ID, - Permissions: []*api.CommandPermission{perms}, + Permissions: []api.CommandPermission{perms}, }) } if _, err = dgo.RestClient().SetGuildCommandsPermissions(dgo.ApplicationID(), guildID, cmdsPermissions...); err != nil { @@ -169,17 +170,17 @@ func main() { <-s } -func guildAvailListener(event *events.GuildAvailableEvent) { +func guildAvailListener(event events.GuildAvailableEvent) { logger.Printf("guild loaded: %s", event.Guild.ID) } -func rawGatewayEventListener(event *events.RawGatewayEvent) { +func rawGatewayEventListener(event events.RawGatewayEvent) { if event.Type == api.GatewayEventInteractionCreate { println(string(event.RawPayload)) } } -func buttonClickListener(event *events.ButtonClickEvent) { +func buttonClickListener(event events.ButtonClickEvent) { switch event.CustomID() { case "test": if err := event.ReplyEdit(api.NewInteractionResponseBuilder(). @@ -207,7 +208,7 @@ func buttonClickListener(event *events.ButtonClickEvent) { } } -func commandListener(event *events.CommandEvent) { +func commandListener(event events.CommandEvent) { switch event.CommandName { case "eval": go func() { @@ -310,7 +311,7 @@ func commandListener(event *events.CommandEvent) { } } -func messageListener(event *events.GuildMessageCreateEvent) { +func messageListener(event events.GuildMessageCreateEvent) { if event.Message.Author.IsBot { return } @@ -341,7 +342,3 @@ func messageListener(event *events.GuildMessageCreateEvent) { }() } } - -func ptrBool(bool bool) *bool { - return &bool -} diff --git a/internal/cache_impl.go b/internal/cache_impl.go index 144a236e..bbf32d52 100644 --- a/internal/cache_impl.go +++ b/internal/cache_impl.go @@ -27,7 +27,7 @@ func newCacheImpl(disgo api.Disgo, memberCachePolicy api.MemberCachePolicy, mess textChannels: map[api.Snowflake]map[api.Snowflake]*api.TextChannel{}, voiceChannels: map[api.Snowflake]map[api.Snowflake]*api.VoiceChannel{}, storeChannels: map[api.Snowflake]map[api.Snowflake]*api.StoreChannel{}, - emotes: map[api.Snowflake]map[api.Snowflake]*api.Emote{}, + emotes: map[api.Snowflake]map[api.Snowflake]*api.Emoji{}, } go cache.startCleanup(10 * time.Second) return cache @@ -53,7 +53,7 @@ type CacheImpl struct { textChannels map[api.Snowflake]map[api.Snowflake]*api.TextChannel voiceChannels map[api.Snowflake]map[api.Snowflake]*api.VoiceChannel storeChannels map[api.Snowflake]map[api.Snowflake]*api.StoreChannel - emotes map[api.Snowflake]map[api.Snowflake]*api.Emote + emotes map[api.Snowflake]map[api.Snowflake]*api.Emoji } // Disgo returns the current api.Disgo instance @@ -1224,7 +1224,7 @@ func (c *CacheImpl) FindCategories(guildID api.Snowflake, check func(u *api.Cate } // Emote returns a specific emote from the cache -func (c *CacheImpl) Emote(emoteID api.Snowflake) *api.Emote { +func (c *CacheImpl) Emote(emoteID api.Snowflake) *api.Emoji { for _, guildEmotes := range c.emotes { if emote, ok := guildEmotes[emoteID]; ok { return emote @@ -1234,12 +1234,12 @@ func (c *CacheImpl) Emote(emoteID api.Snowflake) *api.Emote { } // EmotesByName returns all emotes for a guild by name -func (c *CacheImpl) EmotesByName(guildID api.Snowflake, name string, ignoreCase bool) []*api.Emote { +func (c *CacheImpl) EmotesByName(guildID api.Snowflake, name string, ignoreCase bool) []*api.Emoji { if guildEmotes, ok := c.emotes[guildID]; ok { if ignoreCase { name = strings.ToLower(name) } - emotes := make([]*api.Emote, 1) + emotes := make([]*api.Emoji, 1) for _, emote := range guildEmotes { if ignoreCase && strings.ToLower(emote.Name) == name || !ignoreCase && emote.Name == name { emotes = append(emotes, emote) @@ -1251,9 +1251,9 @@ func (c *CacheImpl) EmotesByName(guildID api.Snowflake, name string, ignoreCase } // Emotes returns all cached emotes for a guild -func (c *CacheImpl) Emotes(guildID api.Snowflake) []*api.Emote { +func (c *CacheImpl) Emotes(guildID api.Snowflake) []*api.Emoji { if guildEmotes, ok := c.emotes[guildID]; ok { - emotes := make([]*api.Emote, len(guildEmotes)) + emotes := make([]*api.Emoji, len(guildEmotes)) i := 0 for _, emote := range guildEmotes { emotes[i] = emote @@ -1265,17 +1265,17 @@ func (c *CacheImpl) Emotes(guildID api.Snowflake) []*api.Emote { } // EmoteCache returns the emote cache for a specific guild -func (c *CacheImpl) EmoteCache(guildID api.Snowflake) map[api.Snowflake]*api.Emote { +func (c *CacheImpl) EmoteCache(guildID api.Snowflake) map[api.Snowflake]*api.Emoji { return c.emotes[guildID] } // AllEmoteCache returns the full emote cache -func (c *CacheImpl) AllEmoteCache() map[api.Snowflake]map[api.Snowflake]*api.Emote { +func (c *CacheImpl) AllEmoteCache() map[api.Snowflake]map[api.Snowflake]*api.Emoji { return c.emotes } // CacheEmote adds an Emote to the api.Cache if emoji caches are used -func (c *CacheImpl) CacheEmote(emote *api.Emote) *api.Emote { +func (c *CacheImpl) CacheEmote(emote *api.Emoji) *api.Emoji { if c.cacheFlags.Missing(api.CacheFlagEmotes) { return emote } diff --git a/internal/disgo_impl.go b/internal/disgo_impl.go index cea09e4d..c65c69bb 100644 --- a/internal/disgo_impl.go +++ b/internal/disgo_impl.go @@ -64,6 +64,7 @@ type DisgoImpl struct { webhookServer api.WebhookServer cache api.Cache selfUserID api.Snowflake + selfUser *api.SelfUser largeThreshold int } @@ -173,9 +174,14 @@ func (d *DisgoImpl) ApplicationID() api.Snowflake { return d.selfUserID } -// SelfUser returns a user object for the client, if available -func (d *DisgoImpl) SelfUser() *api.User { - return d.cache.User(d.selfUserID) +// SelfUser returns a api.SelfUser for the client, if available +func (d *DisgoImpl) SelfUser() *api.SelfUser { + return d.selfUser +} + +// SelfUserID returns the current user id +func (d *DisgoImpl) SelfUserID() api.Snowflake { + return d.selfUserID } // HeartbeatLatency returns the heartbeat latency @@ -204,12 +210,12 @@ func (d *DisgoImpl) GetCommands() ([]*api.Command, error) { } // CreateCommand creates a new global api.Command -func (d *DisgoImpl) CreateCommand(command *api.CommandCreate) (*api.Command, error) { +func (d *DisgoImpl) CreateCommand(command api.CommandCreate) (*api.Command, error) { return d.RestClient().CreateGlobalCommand(d.ApplicationID(), command) } // EditCommand edits a specific global api.Command -func (d *DisgoImpl) EditCommand(commandID api.Snowflake, command *api.CommandUpdate) (*api.Command, error) { +func (d *DisgoImpl) EditCommand(commandID api.Snowflake, command api.CommandUpdate) (*api.Command, error) { return d.RestClient().EditGlobalCommand(d.ApplicationID(), commandID, command) } @@ -219,7 +225,7 @@ func (d *DisgoImpl) DeleteCommand(commandID api.Snowflake) error { } // SetCommands overrides all global api.Command(s) -func (d *DisgoImpl) SetCommands(commands ...*api.CommandCreate) ([]*api.Command, error) { +func (d *DisgoImpl) SetCommands(commands ...api.CommandCreate) ([]*api.Command, error) { return d.RestClient().SetGlobalCommands(d.ApplicationID(), commands...) } @@ -234,12 +240,12 @@ func (d *DisgoImpl) GetGuildCommands(guildID api.Snowflake, ) ([]*api.Command, e } // CreateGuildCommand creates a new api.Command for this api.Guild -func (d *DisgoImpl) CreateGuildCommand(guildID api.Snowflake, command *api.CommandCreate) (*api.Command, error) { +func (d *DisgoImpl) CreateGuildCommand(guildID api.Snowflake, command api.CommandCreate) (*api.Command, error) { return d.RestClient().CreateGuildCommand(d.ApplicationID(), guildID, command) } // EditGuildCommand edits a specific api.Guild api.Command -func (d *DisgoImpl) EditGuildCommand(guildID api.Snowflake, commandID api.Snowflake, command *api.CommandUpdate) (*api.Command, error) { +func (d *DisgoImpl) EditGuildCommand(guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (*api.Command, error) { return d.RestClient().EditGuildCommand(d.ApplicationID(), guildID, commandID, command) } @@ -249,7 +255,7 @@ func (d *DisgoImpl) DeleteGuildCommand(guildID api.Snowflake, commandID api.Snow } // SetGuildCommands overrides all api.Command(s) for this api.Guild -func (d *DisgoImpl) SetGuildCommands(guildID api.Snowflake, commands ...*api.CommandCreate) ([]*api.Command, error) { +func (d *DisgoImpl) SetGuildCommands(guildID api.Snowflake, commands ...api.CommandCreate) ([]*api.Command, error) { return d.RestClient().SetGuildCommands(d.ApplicationID(), guildID, commands...) } @@ -264,11 +270,11 @@ func (d *DisgoImpl) GetGuildCommandPermissions(guildID api.Snowflake, commandID } // SetGuildCommandsPermissions sets the api.GuildCommandPermissions for a all api.Command(s) -func (d *DisgoImpl) SetGuildCommandsPermissions(guildID api.Snowflake, commandPermissions ...*api.SetGuildCommandPermissions) ([]*api.GuildCommandPermissions, error) { +func (d *DisgoImpl) SetGuildCommandsPermissions(guildID api.Snowflake, commandPermissions ...api.SetGuildCommandPermissions) ([]*api.GuildCommandPermissions, error) { return d.RestClient().SetGuildCommandsPermissions(d.ApplicationID(), guildID, commandPermissions...) } // SetGuildCommandPermissions sets the api.GuildCommandPermissions for a specific api.Command -func (d *DisgoImpl) SetGuildCommandPermissions(guildID api.Snowflake, commandID api.Snowflake, permissions *api.SetGuildCommandPermissions) (*api.GuildCommandPermissions, error) { +func (d *DisgoImpl) SetGuildCommandPermissions(guildID api.Snowflake, commandID api.Snowflake, permissions api.SetGuildCommandPermissions) (*api.GuildCommandPermissions, error) { return d.RestClient().SetGuildCommandPermissions(d.ApplicationID(), guildID, commandID, permissions) } diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 222b960e..e2214a55 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -20,7 +20,7 @@ func (b *EntityBuilderImpl) Disgo() api.Disgo { return b.disgo } -func (b EntityBuilderImpl) createInteraction(fullInteraction *api.FullInteraction, c chan *api.InteractionResponse, updateCache api.CacheStrategy) *api.Interaction { +func (b EntityBuilderImpl) createInteraction(fullInteraction *api.FullInteraction, c chan api.InteractionResponse, updateCache api.CacheStrategy) *api.Interaction { interaction := &api.Interaction{ Disgo: b.disgo, ResponseChannel: c, @@ -43,7 +43,7 @@ func (b EntityBuilderImpl) createInteraction(fullInteraction *api.FullInteractio } // CreateButtonInteraction creates a api.ButtonInteraction from the full interaction response -func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInteraction, c chan *api.InteractionResponse, updateCache api.CacheStrategy) *api.ButtonInteraction { +func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInteraction, c chan api.InteractionResponse, updateCache api.CacheStrategy) *api.ButtonInteraction { var data *api.ButtonInteractionData _ = json.Unmarshal(fullInteraction.Data, &data) @@ -55,7 +55,7 @@ func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInt } // CreateCommandInteraction creates a api.CommandInteraction from the full interaction response -func (b *EntityBuilderImpl) CreateCommandInteraction(fullInteraction *api.FullInteraction, c chan *api.InteractionResponse, updateCache api.CacheStrategy) *api.CommandInteraction { +func (b *EntityBuilderImpl) CreateCommandInteraction(fullInteraction *api.FullInteraction, c chan api.InteractionResponse, updateCache api.CacheStrategy) *api.CommandInteraction { var data *api.CommandInteractionData _ = json.Unmarshal(fullInteraction.Data, &data) @@ -308,8 +308,8 @@ func (b *EntityBuilderImpl) CreateDMChannel(channel *api.Channel, updateCache ap return dmChannel } -// CreateEmote returns a new api.Emote entity -func (b *EntityBuilderImpl) CreateEmote(guildID api.Snowflake, emote *api.Emote, updateCache api.CacheStrategy) *api.Emote { +// CreateEmote returns a new api.Emoji entity +func (b *EntityBuilderImpl) CreateEmote(guildID api.Snowflake, emote *api.Emoji, updateCache api.CacheStrategy) *api.Emoji { emote.Disgo = b.Disgo() emote.GuildID = guildID if updateCache(b.Disgo()) { diff --git a/internal/event_manager_impl.go b/internal/event_manager_impl.go index 2265e638..78f7d00d 100644 --- a/internal/event_manager_impl.go +++ b/internal/event_manager_impl.go @@ -42,7 +42,7 @@ func (e *EventManagerImpl) Close() { } // Handle calls the correct api.EventHandler -func (e *EventManagerImpl) Handle(name api.GatewayEventType, c chan *api.InteractionResponse, sequenceNumber int, payload json.RawMessage) { +func (e *EventManagerImpl) Handle(name api.GatewayEventType, c chan api.InteractionResponse, sequenceNumber int, payload json.RawMessage) { if handler, ok := e.handlers[name]; ok { eventPayload := handler.New() if err := json.Unmarshal(payload, &eventPayload); err != nil { diff --git a/internal/handlers/interaction_create_handler.go b/internal/handlers/interaction_create_handler.go index 61c82373..d12a6071 100644 --- a/internal/handlers/interaction_create_handler.go +++ b/internal/handlers/interaction_create_handler.go @@ -27,7 +27,7 @@ func (h InteractionCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManag handleInteraction(disgo, eventManager, sequenceNumber, fullInteraction, nil) } -func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, fullInteraction *api.FullInteraction, c chan *api.InteractionResponse) { +func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, fullInteraction *api.FullInteraction, c chan api.InteractionResponse) { genericInteractionEvent := events.GenericInteractionEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), } diff --git a/internal/handlers/interaction_create_webhook_handler.go b/internal/handlers/interaction_create_webhook_handler.go index b5595c76..ddc4660c 100644 --- a/internal/handlers/interaction_create_webhook_handler.go +++ b/internal/handlers/interaction_create_webhook_handler.go @@ -18,7 +18,7 @@ func (h InteractionCreateWebhookHandler) New() interface{} { } // HandleWebhookEvent handles the specific raw gateway event -func (h InteractionCreateWebhookHandler) HandleWebhookEvent(disgo api.Disgo, eventManager api.EventManager, c chan *api.InteractionResponse, i interface{}) { +func (h InteractionCreateWebhookHandler) HandleWebhookEvent(disgo api.Disgo, eventManager api.EventManager, c chan api.InteractionResponse, i interface{}) { fullInteraction, ok := i.(*api.FullInteraction) if !ok { return @@ -26,7 +26,7 @@ func (h InteractionCreateWebhookHandler) HandleWebhookEvent(disgo api.Disgo, eve if fullInteraction.Type == api.InteractionTypePing { disgo.Logger().Debugf("received interaction ping") - c <- &api.InteractionResponse{ + c <- api.InteractionResponse{ Type: api.InteractionResponseTypePong, } return diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index e83f782a..a458015f 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -57,7 +57,7 @@ func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod } // SendMessage lets you send a api.Message to a api.MessageChannel -func (r *RestClientImpl) SendMessage(channelID api.Snowflake, message *api.MessageCreate) (msg *api.Message, err error) { +func (r *RestClientImpl) SendMessage(channelID api.Snowflake, message api.MessageCreate) (msg *api.Message, err error) { compiledRoute, err := restclient.CreateMessage.Compile(nil, channelID) if err != nil { return nil, err @@ -71,7 +71,7 @@ func (r *RestClientImpl) SendMessage(channelID api.Snowflake, message *api.Messa } // EditMessage lets you edit a api.Message -func (r *RestClientImpl) EditMessage(channelID api.Snowflake, messageID api.Snowflake, message *api.MessageUpdate) (msg *api.Message, err error) { +func (r *RestClientImpl) EditMessage(channelID api.Snowflake, messageID api.Snowflake, message api.MessageUpdate) (msg *api.Message, err error) { compiledRoute, err := restclient.UpdateMessage.Compile(nil, channelID, messageID) if err != nil { return nil, err @@ -202,7 +202,7 @@ func (r *RestClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Membe } // AddMember adds a member to the guild with the oauth2 access BotToken. requires api.PermissionCreateInstantInvite -func (r *RestClientImpl) AddMember(guildID api.Snowflake, userID api.Snowflake, addGuildMemberData *api.AddGuildMemberData) (member *api.Member, err error) { +func (r *RestClientImpl) AddMember(guildID api.Snowflake, userID api.Snowflake, addGuildMemberData api.AddGuildMemberData) (member *api.Member, err error) { compiledRoute, err := restclient.AddMember.Compile(nil, guildID, userID) if err != nil { return nil, err @@ -233,7 +233,7 @@ func (r *RestClientImpl) KickMember(guildID api.Snowflake, userID api.Snowflake, } // UpdateMember updates a member -func (r *RestClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateGuildMemberData *api.UpdateGuildMemberData) (member *api.Member, err error) { +func (r *RestClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateGuildMemberData api.UpdateGuildMemberData) (member *api.Member, err error) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { return nil, err @@ -311,7 +311,7 @@ func (r *RestClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, err } // CreateRole creates a new role for a guild. Requires api.PermissionManageRoles -func (r *RestClientImpl) CreateRole(guildID api.Snowflake, role *api.UpdateRole) (newRole *api.Role, err error) { +func (r *RestClientImpl) CreateRole(guildID api.Snowflake, role api.UpdateRole) (newRole *api.Role, err error) { compiledRoute, err := restclient.CreateRole.Compile(nil, guildID) if err != nil { return nil, err @@ -324,7 +324,7 @@ func (r *RestClientImpl) CreateRole(guildID api.Snowflake, role *api.UpdateRole) } // UpdateRole updates a role from a guild. Requires api.PermissionManageRoles -func (r *RestClientImpl) UpdateRole(guildID api.Snowflake, roleID api.Snowflake, role *api.UpdateRole) (newRole *api.Role, err error) { +func (r *RestClientImpl) UpdateRole(guildID api.Snowflake, roleID api.Snowflake, role api.UpdateRole) (newRole *api.Role, err error) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { return nil, err @@ -337,7 +337,7 @@ func (r *RestClientImpl) UpdateRole(guildID api.Snowflake, roleID api.Snowflake, } // UpdateRolePositions updates the position of a role from a guild. Requires api.PermissionManageRoles -func (r *RestClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates ...*api.UpdateRolePosition) (roles []*api.Role, err error) { +func (r *RestClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates ...api.UpdateRolePosition) (roles []*api.Role, err error) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { return nil, err @@ -420,7 +420,7 @@ func (r *RestClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID } // CreateGlobalCommand lets you create a new global command -func (r *RestClientImpl) CreateGlobalCommand(applicationID api.Snowflake, command *api.CommandCreate) (cmd *api.Command, err error) { +func (r *RestClientImpl) CreateGlobalCommand(applicationID api.Snowflake, command api.CommandCreate) (cmd *api.Command, err error) { compiledRoute, err := restclient.CreateGlobalCommand.Compile(nil, applicationID) if err != nil { return nil, err @@ -433,7 +433,7 @@ func (r *RestClientImpl) CreateGlobalCommand(applicationID api.Snowflake, comman } // SetGlobalCommands lets you override all global commands -func (r *RestClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands ...*api.CommandCreate) (cmds []*api.Command, err error) { +func (r *RestClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, err error) { compiledRoute, err := restclient.SetGlobalCommands.Compile(nil, applicationID) if err != nil { return nil, err @@ -452,7 +452,7 @@ func (r *RestClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands } // EditGlobalCommand lets you edit a specific global command -func (r *RestClientImpl) EditGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake, command *api.CommandUpdate) (cmd *api.Command, err error) { +func (r *RestClientImpl) EditGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, err error) { compiledRoute, err := restclient.UpdateGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { return nil, err @@ -493,7 +493,7 @@ func (r *RestClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID a } // CreateGuildCommand lets you create a new guild_events command -func (r *RestClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, command *api.CommandCreate) (cmd *api.Command, err error) { +func (r *RestClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, command api.CommandCreate) (cmd *api.Command, err error) { compiledRoute, err := restclient.CreateGuildCommand.Compile(nil, applicationID, guildID) if err != nil { return nil, err @@ -506,7 +506,7 @@ func (r *RestClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID } // SetGuildCommands lets you override all guild_events commands -func (r *RestClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake, commands ...*api.CommandCreate) (cmds []*api.Command, err error) { +func (r *RestClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, err error) { compiledRoute, err := restclient.SetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { return nil, err @@ -538,7 +538,7 @@ func (r *RestClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID ap } // EditGuildCommand lets you edit a specific guild_events command -func (r *RestClientImpl) EditGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, command *api.CommandUpdate) (cmd *api.Command, err error) { +func (r *RestClientImpl) EditGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, err error) { compiledRoute, err := restclient.UpdateGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { return nil, err @@ -592,7 +592,7 @@ func (r *RestClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, } // SetGuildCommandsPermissions sets the api.GuildCommandPermissions for a all api.Command(s) -func (r *RestClientImpl) SetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandsPermissions ...*api.SetGuildCommandPermissions) (cmdsPerms []*api.GuildCommandPermissions, err error) { +func (r *RestClientImpl) SetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandsPermissions ...api.SetGuildCommandPermissions) (cmdsPerms []*api.GuildCommandPermissions, err error) { compiledRoute, err := restclient.SetGuildCommandsPermissions.Compile(nil, applicationID, guildID) if err != nil { return nil, err @@ -607,7 +607,7 @@ func (r *RestClientImpl) SetGuildCommandsPermissions(applicationID api.Snowflake } // SetGuildCommandPermissions sets the api.GuildCommandPermissions for a specific api.Command -func (r *RestClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, commandPermissions *api.SetGuildCommandPermissions) (cmdPerms *api.GuildCommandPermissions, err error) { +func (r *RestClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, commandPermissions api.SetGuildCommandPermissions) (cmdPerms *api.GuildCommandPermissions, err error) { compiledRoute, err := restclient.SetGuildCommandPermissions.Compile(nil, applicationID, guildID, commandID) if err != nil { return nil, err @@ -620,7 +620,7 @@ func (r *RestClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, } // SendInteractionResponse used to send the initial response on an interaction -func (r *RestClientImpl) SendInteractionResponse(interactionID api.Snowflake, interactionToken string, interactionResponse *api.InteractionResponse) error { +func (r *RestClientImpl) SendInteractionResponse(interactionID api.Snowflake, interactionToken string, interactionResponse api.InteractionResponse) error { compiledRoute, err := restclient.CreateInteractionResponse.Compile(nil, interactionID, interactionToken) if err != nil { return err @@ -629,7 +629,7 @@ func (r *RestClientImpl) SendInteractionResponse(interactionID api.Snowflake, in } // EditInteractionResponse used to edit the initial response on an interaction -func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, interactionToken string, followupMessage *api.FollowupMessage) (message *api.Message, err error) { +func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, interactionToken string, followupMessage api.FollowupMessage) (message *api.Message, err error) { compiledRoute, err := restclient.UpdateInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { return nil, err @@ -647,7 +647,7 @@ func (r *RestClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, } // SendFollowupMessage used to send a followup message_events to an interaction -func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, followupMessage *api.FollowupMessage) (message *api.Message, err error) { +func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, followupMessage api.FollowupMessage) (message *api.Message, err error) { compiledRoute, err := restclient.CreateFollowupMessage.Compile(nil, applicationID, interactionToken) if err != nil { return nil, err @@ -656,7 +656,7 @@ func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, intera } // EditFollowupMessage used to edit a api.FollowupMessage from an api.Interaction -func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, followupMessage *api.FollowupMessage) (message *api.Message, err error) { +func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, followupMessage api.FollowupMessage) (message *api.Message, err error) { compiledRoute, err := restclient.UpdateFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { return nil, err diff --git a/internal/webhook_server_impl.go b/internal/webhook_server_impl.go index fef8da2c..edf1e827 100644 --- a/internal/webhook_server_impl.go +++ b/internal/webhook_server_impl.go @@ -99,7 +99,7 @@ func (h *webhookInteractionHandler) ServeHTTP(w http.ResponseWriter, r *http.Req w.WriteHeader(http.StatusBadRequest) return } - c := make(chan *api.InteractionResponse) + c := make(chan api.InteractionResponse) go h.webhookServer.Disgo().EventManager().Handle(api.WebhookEventInteractionCreate, c, -1, rawBody) w.Header().Set("Content-Type", "application/json") From 19493b52c063b4ce5e8cb785dce84894525813fa Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 2 Jun 2021 12:29:16 +0200 Subject: [PATCH 02/19] some emote/emoji cleanup --- api/button.go | 26 ++++++++++----------- api/cache_flags.go | 1 + api/component.go | 2 +- api/emote.go | 9 ++----- api/events/dm_message_event.go | 2 +- api/events/dm_message_reaction_events.go | 4 ++-- api/events/guild_message_reaction_events.go | 4 ++-- api/events/listener_adapter.go | 18 +++++++------- api/events/message_reaction_events.go | 4 ++-- api/guild.go | 2 +- example/examplebot.go | 4 ++-- internal/entity_builder_impl.go | 7 ++++-- internal/handlers/guild_create_handler.go | 2 +- 13 files changed, 42 insertions(+), 43 deletions(-) diff --git a/api/button.go b/api/button.go index 18fb268c..8ccf5261 100644 --- a/api/button.go +++ b/api/button.go @@ -13,41 +13,41 @@ const ( ) // NewButton creates a new Button with the provided parameters. Link Button(s) need a url and other Button(s) need a customID -func NewButton(style ButtonStyle, label *string, customID string, url string, emote *Emoji, disabled bool) Button { +func NewButton(style ButtonStyle, label *string, customID string, url string, emoji *Emoji, disabled bool) Button { return Button{ ComponentImpl: newComponentImpl(ComponentTypeButton), Style: style, CustomID: customID, URL: url, Label: label, - Emote: emote, + Emoji: emoji, Disabled: disabled, } } // NewPrimaryButton creates a new Button with ButtonStylePrimary & the provided parameters -func NewPrimaryButton(label string, customID string, emote *Emoji, disabled bool) Button { - return NewButton(ButtonStylePrimary, &label, customID, "", emote, disabled) +func NewPrimaryButton(label string, customID string, emoji *Emoji, disabled bool) Button { + return NewButton(ButtonStylePrimary, &label, customID, "", emoji, disabled) } // NewSecondaryButton creates a new Button with ButtonStyleSecondary & the provided parameters -func NewSecondaryButton(label string, customID string, emote *Emoji, disabled bool) Button { - return NewButton(ButtonStyleSecondary, &label, customID, "", emote, disabled) +func NewSecondaryButton(label string, customID string, emoji *Emoji, disabled bool) Button { + return NewButton(ButtonStyleSecondary, &label, customID, "", emoji, disabled) } // NewSuccessButton creates a new Button with ButtonStyleSuccess & the provided parameters -func NewSuccessButton(label string, customID string, emote *Emoji, disabled bool) Button { - return NewButton(ButtonStyleSuccess, &label, customID, "", emote, disabled) +func NewSuccessButton(label string, customID string, emoji *Emoji, disabled bool) Button { + return NewButton(ButtonStyleSuccess, &label, customID, "", emoji, disabled) } // NewDangerButton creates a new Button with ButtonStyleDanger & the provided parameters -func NewDangerButton(label string, customID string, emote *Emoji, disabled bool) Button { - return NewButton(ButtonStyleDanger, &label, customID, "", emote, disabled) +func NewDangerButton(label string, customID string, emoji *Emoji, disabled bool) Button { + return NewButton(ButtonStyleDanger, &label, customID, "", emoji, disabled) } // NewLinkButton creates a new link Button with ButtonStyleLink & the provided parameters -func NewLinkButton(label string, url string, emote *Emoji, disabled bool) Button { - return NewButton(ButtonStyleLink, &label, "", url, emote, disabled) +func NewLinkButton(label string, url string, emoji *Emoji, disabled bool) Button { + return NewButton(ButtonStyleLink, &label, "", url, emoji, disabled) } // Button can be attacked to all messages & be clicked by a User. If clicked it fires a events.ButtonClickEvent with the declared customID @@ -55,7 +55,7 @@ type Button struct { ComponentImpl Style ButtonStyle `json:"style,omitempty"` Label *string `json:"label,omitempty"` - Emote *Emoji `json:"emoji,omitempty"` + Emoji *Emoji `json:"emoji,omitempty"` CustomID string `json:"custom_id,omitempty"` URL string `json:"url,omitempty"` Disabled bool `json:"disabled,omitempty"` diff --git a/api/cache_flags.go b/api/cache_flags.go index dbbc9a0d..521bed28 100644 --- a/api/cache_flags.go +++ b/api/cache_flags.go @@ -12,6 +12,7 @@ const ( CacheFlagVoiceChannels CacheFlagStoreChannels CacheFlagRoles + CacheFlagRoleTags CacheFlagEmotes CacheFlagVoiceState CacheFlagCommands diff --git a/api/component.go b/api/component.go index 1340ac62..a02af2e2 100644 --- a/api/component.go +++ b/api/component.go @@ -33,7 +33,7 @@ type UnmarshalComponent struct { ComponentType ComponentType `json:"type"` Style ButtonStyle `json:"style"` Label *string `json:"label"` - Emote *Emoji `json:"emoji"` + Emoji *Emoji `json:"emoji"` CustomID string `json:"custom_id"` URL string `json:"url"` Disabled bool `json:"disabled"` diff --git a/api/emote.go b/api/emote.go index 491f5772..db1e4f0b 100644 --- a/api/emote.go +++ b/api/emote.go @@ -1,13 +1,8 @@ package api // NewEmote creates a new custom Emoji with the given parameters -func NewEmote(name string, emoteID Snowflake) *Emoji { - return &Emoji{Name: name, ID: emoteID, Animated: false} -} - -// NewAnimatedEmote creates a new animated custom Emoji with the given parameters -func NewAnimatedEmote(name string, emoteID Snowflake) *Emoji { - return &Emoji{Name: name, ID: emoteID, Animated: true} +func NewEmote(name string, emoteID Snowflake, animated bool) *Emoji { + return &Emoji{Name: name, ID: emoteID, Animated: animated} } // NewEmoji creates a new emoji with the given unicode diff --git a/api/events/dm_message_event.go b/api/events/dm_message_event.go index 8c891132..2488a62f 100644 --- a/api/events/dm_message_event.go +++ b/api/events/dm_message_event.go @@ -4,7 +4,7 @@ import ( "github.com/DisgoOrg/disgo/api" ) -// GenericDMMessageEvent is called upon receiving DMMessageCreateEvent, DMMessageUpdateEvent, DMMessageDeleteEvent, GenericDMMessageReactionEvent, DMMessageReactionAddEvent, DMMessageReactionRemoveEvent, DMMessageReactionRemoveEmoteEvent or DMMessageReactionRemoveAllEvent(requires api.GatewayIntentsDirectMessages) +// GenericDMMessageEvent is called upon receiving DMMessageCreateEvent, DMMessageUpdateEvent, DMMessageDeleteEvent, GenericDMMessageReactionEvent, DMMessageReactionAddEvent, DMMessageReactionRemoveEvent, DMMessageReactionRemoveEmojiEvent or DMMessageReactionRemoveAllEvent(requires api.GatewayIntentsDirectMessages) type GenericDMMessageEvent struct { GenericMessageEvent } diff --git a/api/events/dm_message_reaction_events.go b/api/events/dm_message_reaction_events.go index b03b677c..acb22aae 100644 --- a/api/events/dm_message_reaction_events.go +++ b/api/events/dm_message_reaction_events.go @@ -20,8 +20,8 @@ type DMMessageReactionRemoveEvent struct { GenericDMMessageReactionEvent } -// DMMessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.DMChannel(requires the api.GatewayIntentsDirectMessageReactions) -type DMMessageReactionRemoveEmoteEvent struct { +// DMMessageReactionRemoveEmojiEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.DMChannel(requires the api.GatewayIntentsDirectMessageReactions) +type DMMessageReactionRemoveEmojiEvent struct { GenericDMMessageEvent MessageReaction api.MessageReaction } diff --git a/api/events/guild_message_reaction_events.go b/api/events/guild_message_reaction_events.go index dd5b4de5..ffd70d70 100644 --- a/api/events/guild_message_reaction_events.go +++ b/api/events/guild_message_reaction_events.go @@ -20,8 +20,8 @@ type GuildMessageReactionRemoveEvent struct { GenericGuildMessageReactionEvent } -// GuildMessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.TextChannel(requires the api.GatewayIntentsGuildMessageReactions) -type GuildMessageReactionRemoveEmoteEvent struct { +// GuildMessageReactionRemoveEmojiEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.TextChannel(requires the api.GatewayIntentsGuildMessageReactions) +type GuildMessageReactionRemoveEmojiEvent struct { GenericGuildMessageEvent MessageReaction api.MessageReaction } diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index aa1ddb3a..5637cf6c 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -40,7 +40,7 @@ type ListenerAdapter struct { OnGenericDMMessageReactionEventEvent func(event GenericDMMessageReactionEvent) OnDMMessageReactionAdd func(event DMMessageReactionAddEvent) OnDMMessageReactionRemove func(event DMMessageReactionRemoveEvent) - OnDMMessageReactionRemoveEmote func(event DMMessageReactionRemoveEmoteEvent) + OnDMMessageReactionRemoveEmoji func(event DMMessageReactionRemoveEmojiEvent) OnDMMessageReactionRemoveAll func(event DMMessageReactionRemoveAllEvent) // api.StoreChannel Events @@ -106,7 +106,7 @@ type ListenerAdapter struct { OnGenericGuildMessageReactionEvent func(event GenericGuildMessageReactionEvent) OnGuildMessageReactionAdd func(event GuildMessageReactionAddEvent) OnGuildMessageReactionRemove func(event GuildMessageReactionRemoveEvent) - OnGuildMessageReactionRemoveEmote func(event GuildMessageReactionRemoveEmoteEvent) + OnGuildMessageReactionRemoveEmoji func(event GuildMessageReactionRemoveEmojiEvent) OnGuildMessageReactionRemoveAll func(event GuildMessageReactionRemoveAllEvent) // api.Guild Voice Events @@ -136,7 +136,7 @@ type ListenerAdapter struct { OnGenericReactionEvent func(event GenericReactionEvents) OnMessageReactionAdd func(event MessageReactionAddEvent) OnMessageReactionRemove func(event MessageReactionRemoveEvent) - OnMessageReactionRemoveEmote func(event MessageReactionRemoveEmoteEvent) + OnMessageReactionRemoveEmoji func(event MessageReactionRemoveEmojiEvent) OnMessageReactionRemoveAll func(event MessageReactionRemoveAllEvent) // Self Events @@ -253,8 +253,8 @@ func (l ListenerAdapter) OnEvent(event interface{}) { if listener := l.OnDMMessageReactionRemove; listener != nil { listener(e) } - case DMMessageReactionRemoveEmoteEvent: - if listener := l.OnDMMessageReactionRemoveEmote; listener != nil { + case DMMessageReactionRemoveEmojiEvent: + if listener := l.OnDMMessageReactionRemoveEmoji; listener != nil { listener(e) } case DMMessageReactionRemoveAllEvent: @@ -457,8 +457,8 @@ func (l ListenerAdapter) OnEvent(event interface{}) { if listener := l.OnGuildMessageReactionRemove; listener != nil { listener(e) } - case GuildMessageReactionRemoveEmoteEvent: - if listener := l.OnGuildMessageReactionRemoveEmote; listener != nil { + case GuildMessageReactionRemoveEmojiEvent: + if listener := l.OnGuildMessageReactionRemoveEmoji; listener != nil { listener(e) } case GuildMessageReactionRemoveAllEvent: @@ -547,8 +547,8 @@ func (l ListenerAdapter) OnEvent(event interface{}) { if listener := l.OnMessageReactionRemove; listener != nil { listener(e) } - case MessageReactionRemoveEmoteEvent: - if listener := l.OnMessageReactionRemoveEmote; listener != nil { + case MessageReactionRemoveEmojiEvent: + if listener := l.OnMessageReactionRemoveEmoji; listener != nil { listener(e) } case MessageReactionRemoveAllEvent: diff --git a/api/events/message_reaction_events.go b/api/events/message_reaction_events.go index 25567cca..58086961 100644 --- a/api/events/message_reaction_events.go +++ b/api/events/message_reaction_events.go @@ -20,8 +20,8 @@ type MessageReactionRemoveEvent struct { GenericReactionEvents } -// MessageReactionRemoveEmoteEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.Channel(requires the api.GatewayIntentsGuildMessageReactions and/or api.GatewayIntentsDirectMessageReactions) -type MessageReactionRemoveEmoteEvent struct { +// MessageReactionRemoveEmojiEvent indicates someone removed all api.MessageReaction of a specific api.Emoji from a api.Message in a api.Channel(requires the api.GatewayIntentsGuildMessageReactions and/or api.GatewayIntentsDirectMessageReactions) +type MessageReactionRemoveEmojiEvent struct { GenericMessageEvent MessageReaction api.MessageReaction } diff --git a/api/guild.go b/api/guild.go index 01aefc11..298583ca 100644 --- a/api/guild.go +++ b/api/guild.go @@ -122,7 +122,7 @@ type GuildPreview struct { type FullGuild struct { *Guild Roles []*Role `json:"roles"` - Emotes []*Emoji `json:"emojis"` + Emojis []*Emoji `json:"emojis"` Members []*Member `json:"members"` Channels []*Channel `json:"channels"` VoiceStates []*VoiceState `json:"voice_states"` diff --git a/example/examplebot.go b/example/examplebot.go index 9c658387..f0c9330a 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -187,7 +187,7 @@ func buttonClickListener(event events.ButtonClickEvent) { SetContent("test2"). SetComponents(api.NewActionRow( api.NewPrimaryButton("test2", "test2", api.NewEmoji("✔"), false), - api.NewLinkButton("KittyBot", "https://kittybot.de", api.NewEmote("kittybot", emoteID), false), + api.NewLinkButton("KittyBot", "https://kittybot.de", api.NewEmote("kittybot", emoteID, true), false), )). BuildData(), ); err != nil { @@ -199,7 +199,7 @@ func buttonClickListener(event events.ButtonClickEvent) { SetContent("test"). SetComponents(api.NewActionRow( api.NewPrimaryButton("test", "test", api.NewEmoji("❌"), false), - api.NewLinkButton("KittyBot", "https://kittybot.de", api.NewEmote("kittybot", emoteID), false), + api.NewLinkButton("KittyBot", "https://kittybot.de", api.NewEmote("kittybot", emoteID, true), false), )). BuildData(), ); err != nil { diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index e2214a55..1b0a0f2b 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -135,8 +135,8 @@ func (b *EntityBuilderImpl) createComponent(unmarshalComponent *api.UnmarshalCom URL: unmarshalComponent.URL, Disabled: unmarshalComponent.Disabled, } - if unmarshalComponent.Emote != nil { - button.Emote = b.CreateEmote("", unmarshalComponent.Emote, updateCache) + if unmarshalComponent.Emoji != nil { + button.Emoji = b.CreateEmote("", unmarshalComponent.Emoji, updateCache) } return button @@ -310,6 +310,9 @@ func (b *EntityBuilderImpl) CreateDMChannel(channel *api.Channel, updateCache ap // CreateEmote returns a new api.Emoji entity func (b *EntityBuilderImpl) CreateEmote(guildID api.Snowflake, emote *api.Emoji, updateCache api.CacheStrategy) *api.Emoji { + if emote.ID == "" {// return if emoji is no custom emote + return emote + } emote.Disgo = b.Disgo() emote.GuildID = guildID if updateCache(b.Disgo()) { diff --git a/internal/handlers/guild_create_handler.go b/internal/handlers/guild_create_handler.go index 26ffdb05..61204088 100644 --- a/internal/handlers/guild_create_handler.go +++ b/internal/handlers/guild_create_handler.go @@ -59,7 +59,7 @@ func (h GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api disgo.EntityBuilder().CreateVoiceState(guild.ID, voiceState, api.CacheStrategyYes) } - for _, emote := range fullGuild.Emotes { + for _, emote := range fullGuild.Emojis { disgo.EntityBuilder().CreateEmote(guild.ID, emote, api.CacheStrategyYes) } From 08f1c5eb7b8c1f792ce5dcee9e218cd9e63b9887 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 2 Jun 2021 12:37:11 +0200 Subject: [PATCH 03/19] added SelfMember & fixed SelfUser --- api/guild.go | 7 +++++++ api/self_member.go | 6 ++++++ api/self_user.go | 6 +++++- 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 api/self_member.go diff --git a/api/guild.go b/api/guild.go index 298583ca..ce604f9e 100644 --- a/api/guild.go +++ b/api/guild.go @@ -172,6 +172,13 @@ type Guild struct { WelcomeScreen *GuildWelcomeScreen `json:"welcome_screen"` } +// GetSelfMember returns the Member for the current logged in User for this Guild +func (g *Guild) GetSelfMember() *SelfMember { + return &SelfMember{ + Member: g.Disgo.Cache().Member(g.ID, g.Disgo.SelfUserID()), + } +} + // Disconnect sends a api.GatewayCommand to disconnect from this Guild func (g *Guild) Disconnect() error { return g.Disgo.AudioController().Disconnect(g.ID) diff --git a/api/self_member.go b/api/self_member.go new file mode 100644 index 00000000..5aa9a7b8 --- /dev/null +++ b/api/self_member.go @@ -0,0 +1,6 @@ +package api + +// SelfMember represents the current logged in Member for a specific Guild +type SelfMember struct { + *Member +} diff --git a/api/self_user.go b/api/self_user.go index aa5f0416..61d436c5 100644 --- a/api/self_user.go +++ b/api/self_user.go @@ -2,9 +2,13 @@ package api import "errors" +// ErrDMChannelToYourself occurs when opening a DMChannel to yourself var ErrDMChannelToYourself = errors.New("can't open a dm channel to yourself") -type SelfUser User +// SelfUser represents the current logged in User +type SelfUser struct { + *User +} // OpenDMChannel creates a DMChannel between the user and the Disgo client func (u *SelfUser) OpenDMChannel() (*DMChannel, error) { From 9df202392fb07b9efdfb3d669c84b52346684b49 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 2 Jun 2021 12:52:08 +0200 Subject: [PATCH 04/19] fixed emoji/emote naming --- api/{emote.go => emoji.go} | 2 +- api/entity_builder.go | 2 +- internal/entity_builder_impl.go | 18 +++++++++--------- 3 files changed, 11 insertions(+), 11 deletions(-) rename api/{emote.go => emoji.go} (95%) diff --git a/api/emote.go b/api/emoji.go similarity index 95% rename from api/emote.go rename to api/emoji.go index db1e4f0b..b9182f85 100644 --- a/api/emote.go +++ b/api/emoji.go @@ -24,7 +24,7 @@ func (e *Emoji) Guild() *Guild { return e.Disgo.Cache().Guild(e.GuildID) } -// Mention returns the string used to send the emoji +// Mention returns the string used to send the Emoji func (e *Emoji) Mention() string { start := "<:" if e.Animated { diff --git a/api/entity_builder.go b/api/entity_builder.go index 7e38cbce..b328876f 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -37,5 +37,5 @@ type EntityBuilder interface { CreateCategory(channel *Channel, updateCache CacheStrategy) *Category CreateDMChannel(channel *Channel, updateCache CacheStrategy) *DMChannel - CreateEmote(guildID Snowflake, emote *Emoji, updateCache CacheStrategy) *Emoji + CreateEmoji(guildID Snowflake, emoji *Emoji, updateCache CacheStrategy) *Emoji } diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 1b0a0f2b..74422a3b 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -136,7 +136,7 @@ func (b *EntityBuilderImpl) createComponent(unmarshalComponent *api.UnmarshalCom Disabled: unmarshalComponent.Disabled, } if unmarshalComponent.Emoji != nil { - button.Emoji = b.CreateEmote("", unmarshalComponent.Emoji, updateCache) + button.Emoji = b.CreateEmoji("", unmarshalComponent.Emoji, updateCache) } return button @@ -308,15 +308,15 @@ func (b *EntityBuilderImpl) CreateDMChannel(channel *api.Channel, updateCache ap return dmChannel } -// CreateEmote returns a new api.Emoji entity -func (b *EntityBuilderImpl) CreateEmote(guildID api.Snowflake, emote *api.Emoji, updateCache api.CacheStrategy) *api.Emoji { - if emote.ID == "" {// return if emoji is no custom emote - return emote +// CreateEmoji returns a new api.Emoji entity +func (b *EntityBuilderImpl) CreateEmoji(guildID api.Snowflake, emoji *api.Emoji, updateCache api.CacheStrategy) *api.Emoji { + if emoji.ID == "" {// return if emoji is no custom emote + return emoji } - emote.Disgo = b.Disgo() - emote.GuildID = guildID + emoji.Disgo = b.Disgo() + emoji.GuildID = guildID if updateCache(b.Disgo()) { - return b.Disgo().Cache().CacheEmote(emote) + return b.Disgo().Cache().CacheEmote(emoji) } - return emote + return emoji } From fe7e32fe72c5879f0319f2b970ce18b5679185a6 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 2 Jun 2021 13:19:52 +0200 Subject: [PATCH 05/19] fixed renaming of CreateEmote --- internal/handlers/guild_create_handler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/guild_create_handler.go b/internal/handlers/guild_create_handler.go index 61204088..a2ad428a 100644 --- a/internal/handlers/guild_create_handler.go +++ b/internal/handlers/guild_create_handler.go @@ -60,7 +60,7 @@ func (h GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api } for _, emote := range fullGuild.Emojis { - disgo.EntityBuilder().CreateEmote(guild.ID, emote, api.CacheStrategyYes) + disgo.EntityBuilder().CreateEmoji(guild.ID, emote, api.CacheStrategyYes) } // TODO: presence From 8cb9c5b49c5720b2d78b535bf49f33783ac2dfaf Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 7 Jun 2021 18:31:51 +0200 Subject: [PATCH 06/19] added message update stuff & refactored interaction response functions --- api/button_interaction.go | 24 ++ api/command_interaction.go | 133 +++++++++ api/events/interaction_events.go | 48 ++-- api/interaction.go | 261 +++++------------- api/interaction_followup.go | 132 --------- api/interaction_response.go | 205 -------------- api/message.go | 9 - api/{message_builder.go => message_create.go} | 57 ++-- api/message_update.go | 132 +++++++++ api/restclient.go | 8 +- api/webhook_message_create.go | 115 ++++++++ api/webhook_message_update.go | 145 ++++++++++ example/examplebot.go | 92 +++--- internal/restclient_impl.go | 16 +- 14 files changed, 729 insertions(+), 648 deletions(-) create mode 100644 api/button_interaction.go create mode 100644 api/command_interaction.go delete mode 100644 api/interaction_followup.go delete mode 100644 api/interaction_response.go rename api/{message_builder.go => message_create.go} (53%) create mode 100644 api/message_update.go create mode 100644 api/webhook_message_create.go create mode 100644 api/webhook_message_update.go diff --git a/api/button_interaction.go b/api/button_interaction.go new file mode 100644 index 00000000..c1899dc2 --- /dev/null +++ b/api/button_interaction.go @@ -0,0 +1,24 @@ +package api + +// ButtonInteraction is a specific Interaction when CLicked on Button(s) +type ButtonInteraction struct { + *Interaction + Message *Message `json:"message,omitempty"` + Data *ButtonInteractionData `json:"data,omitempty"` +} + +// DeferEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeDeferredUpdateMessage and cancels the loading state +func (i *ButtonInteraction) DeferEdit() error { + return i.Respond(InteractionResponseTypeDeferredUpdateMessage, nil) +} + +// Edit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.WebhookMessageCreate which edits the original api.Message +func (i *ButtonInteraction) Edit(data *WebhookMessageCreate) error { + return i.Respond(InteractionResponseTypeUpdateMessage, data) +} + +// ButtonInteractionData is the command data payload +type ButtonInteractionData struct { + CustomID string `json:"custom_id"` + ComponentType ComponentType `json:"component_type"` +} diff --git a/api/command_interaction.go b/api/command_interaction.go new file mode 100644 index 00000000..aef89689 --- /dev/null +++ b/api/command_interaction.go @@ -0,0 +1,133 @@ +package api + +// CommandInteraction is a specific Interaction when using Command(s) +type CommandInteraction struct { + *Interaction + Data *CommandInteractionData `json:"data,omitempty"` +} + +// CommandInteractionData is the command data payload +type CommandInteractionData struct { + ID Snowflake `json:"id"` + Name string `json:"name"` + Resolved *Resolved `json:"resolved,omitempty"` + Options []*OptionData `json:"options,omitempty"` +} + +// Resolved contains resolved mention data +type Resolved struct { + Users map[Snowflake]*User `json:"users,omitempty"` + Members map[Snowflake]*Member `json:"members,omitempty"` + Roles map[Snowflake]*Role `json:"roles,omitempty"` + Channels map[Snowflake]*Channel `json:"channels,omitempty"` +} + +// OptionData is used for options or subcommands in your slash commands +type OptionData struct { + Name string `json:"name"` + Type CommandOptionType `json:"type"` + Value interface{} `json:"value,omitempty"` + Options []*OptionData `json:"options,omitempty"` +} + +// Option holds info about an Option.Value +type Option struct { + Resolved *Resolved + Name string + Type CommandOptionType + Value interface{} +} + +// String returns the Option.Value as string +func (o Option) String() string { + return o.Value.(string) +} + +// Integer returns the Option.Value as int +func (o Option) Integer() int { + return o.Value.(int) +} + +// Bool returns the Option.Value as bool +func (o Option) Bool() bool { + return o.Value.(bool) +} + +// Snowflake returns the Option.Value as Snowflake +func (o Option) Snowflake() Snowflake { + return Snowflake(o.String()) +} + +// User returns the Option.Value as User +func (o Option) User() *User { + return o.Resolved.Users[o.Snowflake()] +} + +// Member returns the Option.Value as Member +func (o Option) Member() *Member { + return o.Resolved.Members[o.Snowflake()] +} + +// Role returns the Option.Value as Role +func (o Option) Role() *Role { + return o.Resolved.Roles[o.Snowflake()] +} + +// Channel returns the Option.Value as Channel +func (o Option) Channel() *Channel { + return o.Resolved.Channels[o.Snowflake()] +} + +// MessageChannel returns the Option.Value as MessageChannel +func (o Option) MessageChannel() *MessageChannel { + channel := o.Channel() + if channel == nil || (channel.Type != ChannelTypeText && channel.Type != ChannelTypeNews) { + return nil + } + return &MessageChannel{Channel: *channel} +} + +// GuildChannel returns the Option.Value as GuildChannel +func (o Option) GuildChannel() *GuildChannel { + channel := o.Channel() + if channel == nil || (channel.Type != ChannelTypeText && channel.Type != ChannelTypeNews && channel.Type != ChannelTypeCategory && channel.Type != ChannelTypeStore && channel.Type != ChannelTypeVoice) { + return nil + } + return &GuildChannel{Channel: *channel} +} + +// VoiceChannel returns the Option.Value as VoiceChannel +func (o Option) VoiceChannel() *VoiceChannel { + channel := o.Channel() + if channel == nil || channel.Type != ChannelTypeVoice { + return nil + } + return &VoiceChannel{GuildChannel: GuildChannel{Channel: *channel}} +} + +// TextChannel returns the Option.Value as TextChannel +func (o Option) TextChannel() *TextChannel { + channel := o.Channel() + if channel == nil || (channel.Type != ChannelTypeText && channel.Type != ChannelTypeNews) { + return nil + } + return &TextChannel{GuildChannel: GuildChannel{Channel: *channel}, MessageChannel: MessageChannel{Channel: *channel}} +} + +// Category returns the Option.Value as Category +func (o Option) Category() *Category { + channel := o.Channel() + if channel == nil || channel.Type != ChannelTypeCategory { + return nil + } + return &Category{GuildChannel: GuildChannel{Channel: *channel}} +} + +// StoreChannel returns the Option.Value as StoreChannel +func (o Option) StoreChannel() *StoreChannel { + channel := o.Channel() + if channel == nil || channel.Type != ChannelTypeStore { + return nil + } + return &StoreChannel{GuildChannel: GuildChannel{Channel: *channel}} +} diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index bb1c2fa9..626f770b 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -10,14 +10,24 @@ type GenericInteractionEvent struct { Interaction *api.Interaction } -// Reply replies to the api.Interaction with the provided api.InteractionResponse -func (e *GenericInteractionEvent) Reply(response api.InteractionResponse) error { - return e.Interaction.Reply(response) +// Respond replies to the api.Interaction with the provided api.InteractionResponse +func (e *GenericInteractionEvent) Respond(responseType api.InteractionResponseType, data interface{}) error { + return e.Interaction.Respond(responseType, data) +} + +// DeferReply replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource and shows a loading state +func (e *GenericInteractionEvent) DeferReply(ephemeral bool) error { + return e.Interaction.DeferReply(ephemeral) +} + +// Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.WebhookMessageCreate +func (e *GenericInteractionEvent) Reply(data *api.WebhookMessageCreate) error { + return e.Interaction.Reply(data) } // EditOriginal edits the original api.InteractionResponse -func (e *GenericInteractionEvent) EditOriginal(followupMessage api.FollowupMessage) (*api.Message, error) { - return e.Interaction.EditOriginal(followupMessage) +func (e *GenericInteractionEvent) EditOriginal(messageUpdate api.WebhookMessageUpdate) (*api.Message, error) { + return e.Interaction.EditOriginal(messageUpdate) } // DeleteOriginal deletes the original api.InteractionResponse @@ -25,17 +35,17 @@ func (e *GenericInteractionEvent) DeleteOriginal() error { return e.Interaction.DeleteOriginal() } -// SendFollowup used to send a api.FollowupMessage to an api.Interaction -func (e *GenericInteractionEvent) SendFollowup(followupMessage api.FollowupMessage) (*api.Message, error) { +// SendFollowup used to send a api.WebhookMessageCreate to an api.Interaction +func (e *GenericInteractionEvent) SendFollowup(followupMessage api.WebhookMessageCreate) (*api.Message, error) { return e.Interaction.SendFollowup(followupMessage) } -// EditFollowup used to edit a api.FollowupMessage from an api.Interaction -func (e *GenericInteractionEvent) EditFollowup(messageID api.Snowflake, followupMessage api.FollowupMessage) (*api.Message, error) { - return e.Interaction.EditFollowup(messageID, followupMessage) +// EditFollowup used to edit a api.WebhookMessageCreate from an api.Interaction +func (e *GenericInteractionEvent) EditFollowup(messageID api.Snowflake, messageUpdate api.WebhookMessageUpdate) (*api.Message, error) { + return e.Interaction.EditFollowup(messageID, messageUpdate) } -// DeleteFollowup used to delete a api.FollowupMessage from an api.Interaction +// DeleteFollowup used to delete a api.WebhookMessageCreate from an api.Interaction func (e *GenericInteractionEvent) DeleteFollowup(messageID api.Snowflake) error { return e.Interaction.DeleteFollowup(messageID) } @@ -51,16 +61,6 @@ type CommandEvent struct { Options []*api.Option } -// DeferReply replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource and shows a loading state -func (e *CommandEvent) DeferReply(ephemeral bool) error { - return e.CommandInteraction.DeferReply(ephemeral) -} - -// ReplyCreate replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.InteractionResponseData -func (e *CommandEvent) ReplyCreate(data api.InteractionResponseData) error { - return e.CommandInteraction.ReplyCreate(data) -} - // CommandPath returns the api.Command path func (e CommandEvent) CommandPath() string { path := e.CommandName @@ -115,9 +115,9 @@ func (e *ButtonClickEvent) DeferEdit() error { return e.ButtonInteraction.DeferEdit() } -// ReplyEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.InteractionResponseData which edits the original api.Message -func (e *ButtonClickEvent) ReplyEdit(data api.InteractionResponseData) error { - return e.ButtonInteraction.ReplyEdit(data) +// Edit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.WebhookMessageCreate which edits the original api.Message +func (e *ButtonClickEvent) Edit(data *api.WebhookMessageCreate) error { + return e.ButtonInteraction.Edit(data) } // CustomID returns the customID from the called api.Button diff --git a/api/interaction.go b/api/interaction.go index cabf5597..ef04beaf 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -15,6 +15,20 @@ const ( InteractionTypeComponent ) +// InteractionResponseType indicates the type of slash command response, whether it's responding immediately or deferring to edit your response later +type InteractionResponseType int + +// Constants for the InteractionResponseType(s) +const ( + InteractionResponseTypePong InteractionResponseType = iota + 1 + _ + _ + InteractionResponseTypeChannelMessageWithSource + InteractionResponseTypeDeferredChannelMessageWithSource + InteractionResponseTypeDeferredUpdateMessage + InteractionResponseTypeUpdateMessage +) + // Interaction holds the general parameters of each Interaction type Interaction struct { Disgo Disgo @@ -30,8 +44,18 @@ type Interaction struct { Version int `json:"version"` } -// Reply replies to the api.Interaction with the provided api.InteractionResponse -func (i *Interaction) Reply(response InteractionResponse) error { +// InteractionResponse is how you answer interactions. If an answer is not sent within 3 seconds of receiving it, the interaction is failed, and you will be unable to respond to it. +type InteractionResponse struct { + Type InteractionResponseType `json:"type"` + Data interface{} `json:"data,omitempty"` +} + +// Respond responds to the api.Interaction with the provided api.InteractionResponse +func (i *Interaction) Respond(responseType InteractionResponseType, data interface{}) error { + response := InteractionResponse{ + Type: responseType, + Data: data, + } if i.Replied { return errors.New("you already replied to this interaction") } @@ -45,6 +69,45 @@ func (i *Interaction) Reply(response InteractionResponse) error { return i.Disgo.RestClient().SendInteractionResponse(i.ID, i.Token, response) } +// DeferReply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource and shows a loading state +func (i *Interaction) DeferReply(ephemeral bool) error { + var data *WebhookMessageCreate + if ephemeral { + data = &WebhookMessageCreate{Flags: MessageFlagEphemeral} + } + return i.Respond(InteractionResponseTypeDeferredChannelMessageWithSource, data) +} + +// Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.WebhookMessageCreate +func (i *Interaction) Reply(data *WebhookMessageCreate) error { + return i.Respond(InteractionResponseTypeChannelMessageWithSource, data) +} + +// EditOriginal edits the original api.InteractionResponse +func (i *Interaction) EditOriginal(messageUpdate WebhookMessageUpdate) (*Message, error) { + return i.Disgo.RestClient().EditInteractionResponse(i.Disgo.ApplicationID(), i.Token, messageUpdate) +} + +// DeleteOriginal deletes the original api.InteractionResponse +func (i *Interaction) DeleteOriginal() error { + return i.Disgo.RestClient().DeleteInteractionResponse(i.Disgo.ApplicationID(), i.Token) +} + +// SendFollowup used to send a api.WebhookMessageCreate to an api.Interaction +func (i *Interaction) SendFollowup(messageCreate WebhookMessageCreate) (*Message, error) { + return i.Disgo.RestClient().SendFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageCreate) +} + +// EditFollowup used to edit a api.WebhookMessageCreate from an api.Interaction +func (i *Interaction) EditFollowup(messageID Snowflake, messageUpdate WebhookMessageUpdate) (*Message, error) { + return i.Disgo.RestClient().EditFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID, messageUpdate) +} + +// DeleteFollowup used to delete a api.WebhookMessageCreate from an api.Interaction +func (i *Interaction) DeleteFollowup(messageID Snowflake) error { + return i.Disgo.RestClient().DeleteFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID) +} + // FromWebhook returns is the Interaction was made via http func (i *Interaction) FromWebhook() bool { return i.ResponseChannel != nil @@ -90,31 +153,6 @@ func (i *Interaction) GuildChannel() *GuildChannel { return i.Disgo.Cache().GuildChannel(*i.ChannelID) } -// EditOriginal edits the original api.InteractionResponse -func (i *Interaction) EditOriginal(followupMessage FollowupMessage) (*Message, error) { - return i.Disgo.RestClient().EditInteractionResponse(i.Disgo.ApplicationID(), i.Token, followupMessage) -} - -// DeleteOriginal deletes the original api.InteractionResponse -func (i *Interaction) DeleteOriginal() error { - return i.Disgo.RestClient().DeleteInteractionResponse(i.Disgo.ApplicationID(), i.Token) -} - -// SendFollowup used to send a api.FollowupMessage to an api.Interaction -func (i *Interaction) SendFollowup(followupMessage FollowupMessage) (*Message, error) { - return i.Disgo.RestClient().SendFollowupMessage(i.Disgo.ApplicationID(), i.Token, followupMessage) -} - -// EditFollowup used to edit a api.FollowupMessage from an api.Interaction -func (i *Interaction) EditFollowup(messageID Snowflake, followupMessage FollowupMessage) (*Message, error) { - return i.Disgo.RestClient().EditFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID, followupMessage) -} - -// DeleteFollowup used to delete a api.FollowupMessage from an api.Interaction -func (i *Interaction) DeleteFollowup(messageID Snowflake) error { - return i.Disgo.RestClient().DeleteFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID) -} - // FullInteraction is used for easier unmarshalling of different Interaction(s) type FullInteraction struct { ID Snowflake `json:"id"` @@ -128,172 +166,3 @@ type FullInteraction struct { Version int `json:"version"` Data json.RawMessage `json:"data,omitempty"` } - -// CommandInteraction is a specific Interaction when using Command(s) -type CommandInteraction struct { - *Interaction - Data *CommandInteractionData `json:"data,omitempty"` -} - -// DeferReply replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource and shows a loading state -func (i *CommandInteraction) DeferReply(ephemeral bool) error { - var data InteractionResponseData - if ephemeral { - data = InteractionResponseData{Flags: MessageFlagEphemeral} - } - return i.Reply(InteractionResponse{Type: InteractionResponseTypeDeferredChannelMessageWithSource, Data: data}) -} - -// ReplyCreate replies to the api.CommandInteraction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.InteractionResponseData -func (i *CommandInteraction) ReplyCreate(data InteractionResponseData) error { - return i.Reply(InteractionResponse{Type: InteractionResponseTypeChannelMessageWithSource, Data: data}) -} - -// ButtonInteraction is a specific Interaction when CLicked on Button(s) -type ButtonInteraction struct { - *Interaction - Message *Message `json:"message,omitempty"` - Data *ButtonInteractionData `json:"data,omitempty"` -} - -// DeferEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeDeferredUpdateMessage and cancels the loading state -func (i *ButtonInteraction) DeferEdit() error { - return i.Reply(InteractionResponse{Type: InteractionResponseTypeDeferredUpdateMessage}) -} - -// ReplyEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.InteractionResponseData which edits the original api.Message -func (i *ButtonInteraction) ReplyEdit(data InteractionResponseData) error { - return i.Reply(InteractionResponse{Type: InteractionResponseTypeUpdateMessage, Data: data}) -} - -// CommandInteractionData is the command data payload -type CommandInteractionData struct { - ID Snowflake `json:"id"` - Name string `json:"name"` - Resolved *Resolved `json:"resolved,omitempty"` - Options []*OptionData `json:"options,omitempty"` -} - -// ButtonInteractionData is the command data payload -type ButtonInteractionData struct { - CustomID string `json:"custom_id"` - ComponentType ComponentType `json:"component_type"` -} - -// Resolved contains resolved mention data -type Resolved struct { - Users map[Snowflake]*User `json:"users,omitempty"` - Members map[Snowflake]*Member `json:"members,omitempty"` - Roles map[Snowflake]*Role `json:"roles,omitempty"` - Channels map[Snowflake]*Channel `json:"channels,omitempty"` -} - -// OptionData is used for options or subcommands in your slash commands -type OptionData struct { - Name string `json:"name"` - Type CommandOptionType `json:"type"` - Value interface{} `json:"value,omitempty"` - Options []*OptionData `json:"options,omitempty"` -} - -// Option holds info about an Option.Value -type Option struct { - Resolved *Resolved - Name string - Type CommandOptionType - Value interface{} -} - -// String returns the Option.Value as string -func (o Option) String() string { - return o.Value.(string) -} - -// Integer returns the Option.Value as int -func (o Option) Integer() int { - return o.Value.(int) -} - -// Bool returns the Option.Value as bool -func (o Option) Bool() bool { - return o.Value.(bool) -} - -// Snowflake returns the Option.Value as Snowflake -func (o Option) Snowflake() Snowflake { - return Snowflake(o.String()) -} - -// User returns the Option.Value as User -func (o Option) User() *User { - return o.Resolved.Users[o.Snowflake()] -} - -// Member returns the Option.Value as Member -func (o Option) Member() *Member { - return o.Resolved.Members[o.Snowflake()] -} - -// Role returns the Option.Value as Role -func (o Option) Role() *Role { - return o.Resolved.Roles[o.Snowflake()] -} - -// Channel returns the Option.Value as Channel -func (o Option) Channel() *Channel { - return o.Resolved.Channels[o.Snowflake()] -} - -// MessageChannel returns the Option.Value as MessageChannel -func (o Option) MessageChannel() *MessageChannel { - channel := o.Channel() - if channel == nil || (channel.Type != ChannelTypeText && channel.Type != ChannelTypeNews) { - return nil - } - return &MessageChannel{Channel: *channel} -} - -// GuildChannel returns the Option.Value as GuildChannel -func (o Option) GuildChannel() *GuildChannel { - channel := o.Channel() - if channel == nil || (channel.Type != ChannelTypeText && channel.Type != ChannelTypeNews && channel.Type != ChannelTypeCategory && channel.Type != ChannelTypeStore && channel.Type != ChannelTypeVoice) { - return nil - } - return &GuildChannel{Channel: *channel} -} - -// VoiceChannel returns the Option.Value as VoiceChannel -func (o Option) VoiceChannel() *VoiceChannel { - channel := o.Channel() - if channel == nil || channel.Type != ChannelTypeVoice { - return nil - } - return &VoiceChannel{GuildChannel: GuildChannel{Channel: *channel}} -} - -// TextChannel returns the Option.Value as TextChannel -func (o Option) TextChannel() *TextChannel { - channel := o.Channel() - if channel == nil || (channel.Type != ChannelTypeText && channel.Type != ChannelTypeNews) { - return nil - } - return &TextChannel{GuildChannel: GuildChannel{Channel: *channel}, MessageChannel: MessageChannel{Channel: *channel}} -} - -// Category returns the Option.Value as Category -func (o Option) Category() *Category { - channel := o.Channel() - if channel == nil || channel.Type != ChannelTypeCategory { - return nil - } - return &Category{GuildChannel: GuildChannel{Channel: *channel}} -} - -// StoreChannel returns the Option.Value as StoreChannel -func (o Option) StoreChannel() *StoreChannel { - channel := o.Channel() - if channel == nil || channel.Type != ChannelTypeStore { - return nil - } - return &StoreChannel{GuildChannel: GuildChannel{Channel: *channel}} -} diff --git a/api/interaction_followup.go b/api/interaction_followup.go deleted file mode 100644 index 7405fb4b..00000000 --- a/api/interaction_followup.go +++ /dev/null @@ -1,132 +0,0 @@ -package api - -import "fmt" - -// FollowupMessage is used to add additional messages to an Interaction after you've responded initially -type FollowupMessage struct { - TTS bool `json:"tts,omitempty"` - Content string `json:"content,omitempty"` - Embeds []*Embed `json:"embeds,omitempty"` - Components []Component `json:"components,omitempty"` - AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` - Flags MessageFlags `json:"flags,omitempty"` -} - -// FollowupMessageBuilder allows you to create an FollowupMessage with ease -type FollowupMessageBuilder struct { - FollowupMessage -} - -// NewFollowupMessageBuilder returns a new FollowupMessageBuilder -func NewFollowupMessageBuilder() *FollowupMessageBuilder { - return &FollowupMessageBuilder{ - FollowupMessage: FollowupMessage{ - AllowedMentions: &DefaultInteractionAllowedMentions, - }, - } -} - -// NewFollowupMessageBuilderByMessage returns a new FollowupMessageBuilder and takes an existing Message -func NewFollowupMessageBuilderByMessage(message *Message) *FollowupMessageBuilder { - msg := FollowupMessage{ - TTS: message.TTS, - Embeds: message.Embeds, - Components: message.Components, - AllowedMentions: &DefaultInteractionAllowedMentions, - Flags: message.Flags, - } - if message.Content != nil { - msg.Content = *message.Content - } - return &FollowupMessageBuilder{ - FollowupMessage: msg, - } -} - -// SetTTS sets if the FollowupMessage is a tts message -func (b *FollowupMessageBuilder) SetTTS(tts bool) *FollowupMessageBuilder { - b.TTS = tts - return b -} - -// SetContent sets the content of the FollowupMessage -func (b *FollowupMessageBuilder) SetContent(content string) *FollowupMessageBuilder { - b.Content = content - return b -} - -// SetContentf sets the content of the FollowupMessage with format -func (b *FollowupMessageBuilder) SetContentf(content string, a ...interface{}) *FollowupMessageBuilder { - b.Content = fmt.Sprintf(content, a...) - return b -} - -// SetEmbeds sets the embeds of the FollowupMessage -func (b *FollowupMessageBuilder) SetEmbeds(embeds ...*Embed) *FollowupMessageBuilder { - b.Embeds = embeds - return b -} - -// AddEmbeds adds multiple embeds to the FollowupMessage -func (b *FollowupMessageBuilder) AddEmbeds(embeds ...*Embed) *FollowupMessageBuilder { - b.Embeds = append(b.Embeds, embeds...) - return b -} - -// ClearEmbeds removes all of the embeds from the FollowupMessage -func (b *FollowupMessageBuilder) ClearEmbeds() *FollowupMessageBuilder { - b.Embeds = []*Embed{} - return b -} - -// RemoveEmbed removes an embed from the FollowupMessage -func (b *FollowupMessageBuilder) RemoveEmbed(index int) *FollowupMessageBuilder { - if b != nil && len(b.Embeds) > index { - b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) - } - return b -} - -// SetComponents sets the Component(s) of the FollowupMessage -func (b *FollowupMessageBuilder) SetComponents(components ...Component) *FollowupMessageBuilder { - b.Components = components - return b -} - -// AddComponents adds the Component(s) to the FollowupMessage -func (b *FollowupMessageBuilder) AddComponents(components ...Component) *FollowupMessageBuilder { - b.Components = append(b.Components, components...) - return b -} - -// SetAllowedMentions sets the allowed mentions of the FollowupMessage -func (b *FollowupMessageBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *FollowupMessageBuilder { - b.AllowedMentions = allowedMentions - return b -} - -// SetAllowedMentionsEmpty sets the allowed mentions of the FollowupMessage to nothing -func (b *FollowupMessageBuilder) SetAllowedMentionsEmpty() *FollowupMessageBuilder { - return b.SetAllowedMentions(&AllowedMentions{}) -} - -// SetFlags sets the message flags of the FollowupMessage -func (b *FollowupMessageBuilder) SetFlags(flags MessageFlags) *FollowupMessageBuilder { - b.Flags = flags - return b -} - -// SetEphemeral adds/removes MessageFlagEphemeral to the message flags -func (b *FollowupMessageBuilder) SetEphemeral(ephemeral bool) *FollowupMessageBuilder { - if ephemeral { - b.Flags = b.Flags.Add(MessageFlagEphemeral) - } else { - b.Flags = b.Flags.Remove(MessageFlagEphemeral) - } - return b -} - -// Build returns your built FollowupMessage -func (b *FollowupMessageBuilder) Build() FollowupMessage { - return b.FollowupMessage -} diff --git a/api/interaction_response.go b/api/interaction_response.go deleted file mode 100644 index bda9812a..00000000 --- a/api/interaction_response.go +++ /dev/null @@ -1,205 +0,0 @@ -package api - -import "fmt" - -// InteractionResponseType indicates the type of slash command response, whether it's responding immediately or deferring to edit your response later -type InteractionResponseType int - -// Constants for the InteractionResponseType(s) -const ( - InteractionResponseTypePong InteractionResponseType = iota + 1 - _ - _ - InteractionResponseTypeChannelMessageWithSource - InteractionResponseTypeDeferredChannelMessageWithSource - InteractionResponseTypeDeferredUpdateMessage - InteractionResponseTypeUpdateMessage -) - -// InteractionResponse is how you answer interactions. If an answer is not sent within 3 seconds of receiving it, the interaction is failed, and you will be unable to respond to it. -type InteractionResponse struct { - Type InteractionResponseType `json:"type"` - Data InteractionResponseData `json:"data,omitempty"` -} - -// The InteractionResponseData is used to specify the message_events options when creating an InteractionResponse -type InteractionResponseData struct { - TTS bool `json:"tts,omitempty"` - Content *string `json:"content,omitempty"` - Embeds []*Embed `json:"embeds,omitempty"` - Components []Component `json:"components,omitempty"` - AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` - Flags MessageFlags `json:"flags,omitempty"` -} - -// InteractionResponseBuilder allows you to create an InteractionResponse with ease -type InteractionResponseBuilder struct { - InteractionResponse -} - -// NewInteractionResponseBuilder returns a new InteractionResponseBuilder -func NewInteractionResponseBuilder() *InteractionResponseBuilder { - return &InteractionResponseBuilder{ - InteractionResponse: InteractionResponse{ - Data: InteractionResponseData{ - AllowedMentions: &DefaultInteractionAllowedMentions, - }, - }, - } -} - -// NewInteractionResponseWithTypeBuilder returns a new InteractionResponseBuilder with the given InteractionResponseType -func NewInteractionResponseWithTypeBuilder(responseType InteractionResponseType) *InteractionResponseBuilder { - return &InteractionResponseBuilder{ - InteractionResponse: InteractionResponse{ - Type: responseType, - Data: InteractionResponseData{ - AllowedMentions: &DefaultInteractionAllowedMentions, - }, - }, - } -} - -// NewInteractionResponseBuilderByMessage returns a new InteractionResponseBuilder and takes an existing Message -func NewInteractionResponseBuilderByMessage(message *Message) *InteractionResponseBuilder { - rs := InteractionResponseData{ - TTS: message.TTS, - Embeds: message.Embeds, - Components: message.Components, - AllowedMentions: &DefaultInteractionAllowedMentions, - Flags: message.Flags, - } - if message.Content != nil { - rs.Content = message.Content - } - return &InteractionResponseBuilder{ - InteractionResponse: InteractionResponse{ - Data: rs, - }, - } -} - -// SetType sets if the InteractionResponseType of this InteractionResponse -func (b *InteractionResponseBuilder) SetType(responseType InteractionResponseType) *InteractionResponseBuilder { - b.Type = responseType - return b -} - -// SetTTS sets if the InteractionResponse is a tts message -func (b *InteractionResponseBuilder) SetTTS(tts bool) *InteractionResponseBuilder { - b.Data.TTS = tts - return b -} - -// SetContent sets the content of the InteractionResponse -func (b *InteractionResponseBuilder) SetContent(content string) *InteractionResponseBuilder { - b.Data.Content = &content - return b -} - -// SetContentf sets the content of the InteractionResponse with format -func (b *InteractionResponseBuilder) SetContentf(content string, a ...interface{}) *InteractionResponseBuilder { - contentf := fmt.Sprintf(content, a...) - b.Data.Content = &contentf - return b -} - -// ClearContent sets the content of the InteractionResponse to nil -func (b *InteractionResponseBuilder) ClearContent() *InteractionResponseBuilder { - b.Data.Content = nil - return b -} - -// SetEmbeds sets the embeds of the InteractionResponse -func (b *InteractionResponseBuilder) SetEmbeds(embeds ...*Embed) *InteractionResponseBuilder { - b.Data.Embeds = embeds - return b -} - -// AddEmbeds adds multiple embeds to the InteractionResponse -func (b *InteractionResponseBuilder) AddEmbeds(embeds ...*Embed) *InteractionResponseBuilder { - b.Data.Embeds = append(b.Data.Embeds, embeds...) - return b -} - -// ClearEmbeds removes all of the embeds from the InteractionResponse -func (b *InteractionResponseBuilder) ClearEmbeds() *InteractionResponseBuilder { - if b != nil { - b.Data.Embeds = []*Embed{} - } - return b -} - -// RemoveEmbed removes an embed from the InteractionResponse -func (b *InteractionResponseBuilder) RemoveEmbed(i int) *InteractionResponseBuilder { - if b != nil && len(b.Data.Embeds) > i { - b.Data.Embeds = append(b.Data.Embeds[:i], b.Data.Embeds[i+1:]...) - } - return b -} - -// SetComponents sets the Component(s) of the InteractionResponse -func (b *InteractionResponseBuilder) SetComponents(components ...Component) *InteractionResponseBuilder { - b.Data.Components = components - return b -} - -// AddComponents adds the Component(s) to the InteractionResponse -func (b *InteractionResponseBuilder) AddComponents(components ...Component) *InteractionResponseBuilder { - b.Data.Components = append(b.Data.Components, components...) - return b -} - -// ClearComponents removes all of the Component(s) of the InteractionResponse -func (b *InteractionResponseBuilder) ClearComponents() *InteractionResponseBuilder { - if b != nil { - b.Data.Components = []Component{} - } - return b -} - -// RemoveComponent removes a Component from the InteractionResponse -func (b *InteractionResponseBuilder) RemoveComponent(i int) *InteractionResponseBuilder { - if b != nil && len(b.Data.Components) > i { - b.Data.Components = append(b.Data.Components[:i], b.Data.Components[i+1:]...) - } - return b -} - -// SetAllowedMentions sets the allowed mentions of the InteractionResponse -func (b *InteractionResponseBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *InteractionResponseBuilder { - b.Data.AllowedMentions = allowedMentions - return b -} - -// SetAllowedMentionsEmpty sets the allowed mentions of the InteractionResponse to nothing -func (b *InteractionResponseBuilder) SetAllowedMentionsEmpty() *InteractionResponseBuilder { - return b.SetAllowedMentions(&AllowedMentions{}) -} - -// SetFlags sets the message flags of the InteractionResponse -func (b *InteractionResponseBuilder) SetFlags(flags MessageFlags) *InteractionResponseBuilder { - b.Data.Flags = flags - return b -} - -// SetEphemeral adds/removes MessageFlagEphemeral to the message flags -func (b *InteractionResponseBuilder) SetEphemeral(ephemeral bool) *InteractionResponseBuilder { - if ephemeral { - b.Data.Flags = b.Data.Flags.Add(MessageFlagEphemeral) - - } else { - b.Data.Flags = b.Data.Flags.Remove(MessageFlagEphemeral) - } - return b -} - -// Build returns your built InteractionResponse -func (b *InteractionResponseBuilder) Build() InteractionResponse { - return b.InteractionResponse -} - -// BuildData returns your built InteractionResponseData -func (b *InteractionResponseBuilder) BuildData() InteractionResponseData { - return b.Data -} diff --git a/api/message.go b/api/message.go index e8dcb964..5e64318b 100644 --- a/api/message.go +++ b/api/message.go @@ -269,15 +269,6 @@ type MessageReaction struct { Emoji Emoji `json:"emoji"` } -// MessageUpdate is used to edit a Message -type MessageUpdate struct { - Content *string `json:"content,omitempty"` - Components []Component `json:"components,omitempty"` - Embed *Embed `json:"embed,omitempty"` - Flags *MessageFlags `json:"flags,omitempty"` - AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` -} - // MessageBulkDelete is used to bulk delete Message(s) type MessageBulkDelete struct { Messages []Snowflake `json:"messages"` diff --git a/api/message_builder.go b/api/message_create.go similarity index 53% rename from api/message_builder.go rename to api/message_create.go index bba0fa6c..5ae36fa7 100644 --- a/api/message_builder.go +++ b/api/message_create.go @@ -13,23 +13,22 @@ type MessageCreate struct { MessageReference *MessageReference `json:"message_reference,omitempty"` } -// MessageBuilder helper to build Message(s) easier -type MessageBuilder struct { +// MessageCreateBuilder helper to build Message(s) easier +type MessageCreateBuilder struct { MessageCreate } -// NewMessageBuilder creates a new MessageBuilder to be built later -func NewMessageBuilder() *MessageBuilder { - return &MessageBuilder{ +// NewMessageCreateBuilder creates a new MessageCreateBuilder to be built later +func NewMessageCreateBuilder() *MessageCreateBuilder { + return &MessageCreateBuilder{ MessageCreate: MessageCreate{ - Nonce: "test nonce", AllowedMentions: &DefaultMessageAllowedMentions, }, } } -// NewMessageBuilderByMessage returns a new MessageBuilder and takes an existing Message -func NewMessageBuilderByMessage(message *Message) *MessageBuilder { +// NewMessageBuilderByMessage returns a new MessageCreateBuilder and takes an existing Message +func NewMessageBuilderByMessage(message *Message) *MessageCreateBuilder { msg := MessageCreate{ TTS: message.TTS, Components: message.Components, @@ -41,59 +40,59 @@ func NewMessageBuilderByMessage(message *Message) *MessageBuilder { if len(message.Embeds) > 0 { msg.Embed = message.Embeds[0] } - return &MessageBuilder{ + return &MessageCreateBuilder{ MessageCreate: msg, } } -// NewMessageBuilderWithEmbed creates a new MessageBuilder with an Embed to be built later -func NewMessageBuilderWithEmbed(embed *Embed) *MessageBuilder { - return NewMessageBuilder().SetEmbed(embed) +// NewMessageCreateBuilderWithEmbed creates a new MessageCreateBuilder with an Embed to be built later +func NewMessageCreateBuilderWithEmbed(embed *Embed) *MessageCreateBuilder { + return NewMessageCreateBuilder().SetEmbed(embed) } -// NewMessageBuilderWithContent creates a new MessageBuilder with a content to be built later -func NewMessageBuilderWithContent(content string) *MessageBuilder { - return NewMessageBuilder().SetContent(content) +// NewMessageCreateBuilderWithContent creates a new MessageCreateBuilder with a content to be built later +func NewMessageCreateBuilderWithContent(content string) *MessageCreateBuilder { + return NewMessageCreateBuilder().SetContent(content) } // SetContent sets content of the Message -func (b *MessageBuilder) SetContent(content string) *MessageBuilder { +func (b *MessageCreateBuilder) SetContent(content string) *MessageCreateBuilder { b.Content = content return b } // SetContentf sets content of the Message -func (b *MessageBuilder) SetContentf(content string, a ...interface{}) *MessageBuilder { +func (b *MessageCreateBuilder) SetContentf(content string, a ...interface{}) *MessageCreateBuilder { b.Content = fmt.Sprintf(content, a...) return b } // SetTTS sets the text to speech of the Message -func (b *MessageBuilder) SetTTS(tts bool) *MessageBuilder { +func (b *MessageCreateBuilder) SetTTS(tts bool) *MessageCreateBuilder { b.TTS = tts return b } // SetEmbed sets the Embed of the Message -func (b *MessageBuilder) SetEmbed(embed *Embed) *MessageBuilder { +func (b *MessageCreateBuilder) SetEmbed(embed *Embed) *MessageCreateBuilder { b.Embed = embed return b } // SetComponents sets the Component(s) of the Message -func (b *MessageBuilder) SetComponents(components ...Component) *MessageBuilder { +func (b *MessageCreateBuilder) SetComponents(components ...Component) *MessageCreateBuilder { b.Components = components return b } // AddComponents adds the Component(s) to the Message -func (b *MessageBuilder) AddComponents(components ...Component) *MessageBuilder { +func (b *MessageCreateBuilder) AddComponents(components ...Component) *MessageCreateBuilder { b.Components = append(b.Components, components...) return b } // ClearComponents removes all of the Component(s) of the Message -func (b *MessageBuilder) ClearComponents() *MessageBuilder { +func (b *MessageCreateBuilder) ClearComponents() *MessageCreateBuilder { if b != nil { b.Components = []Component{} } @@ -101,7 +100,7 @@ func (b *MessageBuilder) ClearComponents() *MessageBuilder { } // RemoveComponent removes a Component from the Message -func (b *MessageBuilder) RemoveComponent(i int) *MessageBuilder { +func (b *MessageCreateBuilder) RemoveComponent(i int) *MessageCreateBuilder { if b != nil && len(b.Components) > i { b.Components = append(b.Components[:i], b.Components[i+1:]...) } @@ -109,24 +108,24 @@ func (b *MessageBuilder) RemoveComponent(i int) *MessageBuilder { } // SetAllowedMentions sets the AllowedMentions of the Message -func (b *MessageBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *MessageBuilder { +func (b *MessageCreateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *MessageCreateBuilder { b.AllowedMentions = allowedMentions return b } // ClearAllowedMentions clears the allowed mentions of the Message -func (b *MessageBuilder) ClearAllowedMentions() *MessageBuilder { +func (b *MessageCreateBuilder) ClearAllowedMentions() *MessageCreateBuilder { return b.SetAllowedMentions(&AllowedMentions{}) } // SetMessageReference allows you to specify a MessageReference to reply to -func (b *MessageBuilder) SetMessageReference(messageReference *MessageReference) *MessageBuilder { +func (b *MessageCreateBuilder) SetMessageReference(messageReference *MessageReference) *MessageCreateBuilder { b.MessageReference = messageReference return b } // SetMessageReferenceByMessageID allows you to specify a Message ID to reply to -func (b *MessageBuilder) SetMessageReferenceByMessageID(messageID Snowflake) *MessageBuilder { +func (b *MessageCreateBuilder) SetMessageReferenceByMessageID(messageID Snowflake) *MessageCreateBuilder { if b.MessageReference == nil { b.MessageReference = &MessageReference{} } @@ -134,7 +133,7 @@ func (b *MessageBuilder) SetMessageReferenceByMessageID(messageID Snowflake) *Me return b } -// Build builds the MessageBuilder to a MessageCreate struct -func (b *MessageBuilder) Build() MessageCreate { +// Build builds the MessageCreateBuilder to a MessageCreate struct +func (b *MessageCreateBuilder) Build() MessageCreate { return b.MessageCreate } diff --git a/api/message_update.go b/api/message_update.go new file mode 100644 index 00000000..35b1bcdb --- /dev/null +++ b/api/message_update.go @@ -0,0 +1,132 @@ +package api + +import ( + "encoding/json" + "fmt" +) + +type updateFlags int + +const ( + updateFlagContent = 1 << iota + updateFlagComponents + updateFlagEmbed + updateFlagFlags + updateFlagAllowedMentions +) + +// MessageUpdate is used to edit a Message +type MessageUpdate struct { + Content string `json:"content"` + Components []Component `json:"components"` + Embed *Embed `json:"embed"` + AllowedMentions *AllowedMentions `json:"allowed_mentions"` + Flags MessageFlags `json:"flags"` + updateFlags updateFlags +} + +func (u MessageUpdate) isUpdated(flag updateFlags) bool { + return (u.updateFlags & flag) == flag +} + +func (u MessageUpdate) MarshalJSON() ([]byte, error) { + data := map[string]interface{}{} + + if u.isUpdated(updateFlagContent) { + data["content"] = u.Content + } + if u.isUpdated(updateFlagComponents) { + data["components"] = u.Components + } + if u.isUpdated(updateFlagEmbed) { + data["embed"] = u.Embed + } + if u.isUpdated(updateFlagAllowedMentions) { + data["allowed_mentions"] = u.AllowedMentions + } + if u.isUpdated(updateFlagFlags) { + data["flags"] = u.Flags + } + + return json.Marshal(data) +} + +// MessageUpdateBuilder helper to build MessageUpdate easier +type MessageUpdateBuilder struct { + MessageUpdate +} + +// NewMessageUpdateBuilder creates a new MessageUpdateBuilder to be built later +func NewMessageUpdateBuilder() *MessageUpdateBuilder { + return &MessageUpdateBuilder{ + MessageUpdate: MessageUpdate{ + AllowedMentions: &DefaultMessageAllowedMentions, + }, + } +} + +// SetContent sets content of the Message +func (b *MessageUpdateBuilder) SetContent(content string) *MessageUpdateBuilder { + b.Content = content + b.updateFlags |= updateFlagContent + return b +} + +// SetContentf sets content of the Message +func (b *MessageUpdateBuilder) SetContentf(content string, a ...interface{}) *MessageUpdateBuilder { + return b.SetContent(fmt.Sprintf(content, a...)) +} + +// SetEmbed sets the Embed of the Message +func (b *MessageUpdateBuilder) SetEmbed(embed *Embed) *MessageUpdateBuilder { + b.Embed = embed + b.updateFlags |= updateFlagEmbed + return b +} + +// SetComponents sets the Component(s) of the Message +func (b *MessageUpdateBuilder) SetComponents(components ...Component) *MessageUpdateBuilder { + b.Components = components + b.updateFlags |= updateFlagComponents + return b +} + +// AddComponents adds the Component(s) to the Message +func (b *MessageUpdateBuilder) AddComponents(components ...Component) *MessageUpdateBuilder { + b.Components = append(b.Components, components...) + b.updateFlags |= updateFlagComponents + return b +} + +// ClearComponents removes all of the Component(s) of the Message +func (b *MessageUpdateBuilder) ClearComponents() *MessageUpdateBuilder { + b.Components = []Component{} + b.updateFlags |= updateFlagComponents + return b +} + +// RemoveComponent removes a Component from the Message +func (b *MessageUpdateBuilder) RemoveComponent(i int) *MessageUpdateBuilder { + if b != nil && len(b.Components) > i { + b.Components = append(b.Components[:i], b.Components[i+1:]...) + } + b.updateFlags |= updateFlagComponents + return b +} + +// SetAllowedMentions sets the AllowedMentions of the Message +func (b *MessageUpdateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *MessageUpdateBuilder { + b.AllowedMentions = allowedMentions + b.updateFlags |= updateFlagAllowedMentions + return b +} + +// ClearAllowedMentions clears the allowed mentions of the Message +func (b *MessageUpdateBuilder) ClearAllowedMentions() *MessageUpdateBuilder { + return b.SetAllowedMentions(&AllowedMentions{}) +} + +// Build builds the MessageUpdateBuilder to a MessageUpdate struct +func (b *MessageUpdateBuilder) Build() MessageUpdate { + return b.MessageUpdate +} diff --git a/api/restclient.go b/api/restclient.go index acccd158..d549aba3 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -25,7 +25,7 @@ type RestClient interface { Disgo() Disgo SendMessage(channelID Snowflake, message MessageCreate) (*Message, error) - EditMessage(channelID Snowflake, messageID Snowflake, message MessageUpdate) (*Message, error) + EditMessage(channelID Snowflake, messageID Snowflake, messageUpdate MessageUpdate) (*Message, error) DeleteMessage(channelID Snowflake, messageID Snowflake) error BulkDeleteMessages(channelID Snowflake, messageIDs ...Snowflake) error CrosspostMessage(channelID Snowflake, messageID Snowflake) (*Message, error) @@ -74,10 +74,10 @@ type RestClient interface { SetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake, commandPermissions SetGuildCommandPermissions) (*GuildCommandPermissions, error) SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse InteractionResponse) error - EditInteractionResponse(applicationID Snowflake, interactionToken string, followupMessage FollowupMessage) (*Message, error) + EditInteractionResponse(applicationID Snowflake, interactionToken string, messageUpdate WebhookMessageUpdate) (*Message, error) DeleteInteractionResponse(applicationID Snowflake, interactionToken string) error - SendFollowupMessage(applicationID Snowflake, interactionToken string, followupMessage FollowupMessage) (*Message, error) - EditFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, followupMessage FollowupMessage) (*Message, error) + SendFollowupMessage(applicationID Snowflake, interactionToken string, messageCreate WebhookMessageCreate) (*Message, error) + EditFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, messageUpdate WebhookMessageUpdate) (*Message, error) DeleteFollowupMessage(applicationID Snowflake, interactionToken string, followupMessageID Snowflake) error } diff --git a/api/webhook_message_create.go b/api/webhook_message_create.go new file mode 100644 index 00000000..712f500e --- /dev/null +++ b/api/webhook_message_create.go @@ -0,0 +1,115 @@ +package api + +import "fmt" + +// WebhookMessageCreate is used to add additional messages to an Interaction after you've responded initially +type WebhookMessageCreate struct { + TTS bool `json:"tts,omitempty"` + Content string `json:"content,omitempty"` + Embeds []*Embed `json:"embeds,omitempty"` + Components []Component `json:"components,omitempty"` + AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` + Flags MessageFlags `json:"flags,omitempty"` +} + +// WebhookMessageCreateBuilder allows you to create an WebhookMessageCreate with ease +type WebhookMessageCreateBuilder struct { + WebhookMessageCreate +} + +// NewWebhookMessageCreateBuilder returns a new WebhookMessageCreateBuilder +func NewWebhookMessageCreateBuilder() *WebhookMessageCreateBuilder { + return &WebhookMessageCreateBuilder{ + WebhookMessageCreate: WebhookMessageCreate{ + AllowedMentions: &DefaultInteractionAllowedMentions, + }, + } +} + +// SetTTS sets if the WebhookMessageCreate is a tts message +func (b *WebhookMessageCreateBuilder) SetTTS(tts bool) *WebhookMessageCreateBuilder { + b.TTS = tts + return b +} + +// SetContent sets the content of the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) SetContent(content string) *WebhookMessageCreateBuilder { + b.Content = content + return b +} + +// SetContentf sets the content of the WebhookMessageCreate with format +func (b *WebhookMessageCreateBuilder) SetContentf(content string, a ...interface{}) *WebhookMessageCreateBuilder { + b.Content = fmt.Sprintf(content, a...) + return b +} + +// SetEmbeds sets the embeds of the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) SetEmbeds(embeds ...*Embed) *WebhookMessageCreateBuilder { + b.Embeds = embeds + return b +} + +// AddEmbeds adds multiple embeds to the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) AddEmbeds(embeds ...*Embed) *WebhookMessageCreateBuilder { + b.Embeds = append(b.Embeds, embeds...) + return b +} + +// ClearEmbeds removes all of the embeds from the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) ClearEmbeds() *WebhookMessageCreateBuilder { + b.Embeds = []*Embed{} + return b +} + +// RemoveEmbed removes an embed from the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) RemoveEmbed(index int) *WebhookMessageCreateBuilder { + if b != nil && len(b.Embeds) > index { + b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) + } + return b +} + +// SetComponents sets the Component(s) of the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) SetComponents(components ...Component) *WebhookMessageCreateBuilder { + b.Components = components + return b +} + +// AddComponents adds the Component(s) to the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) AddComponents(components ...Component) *WebhookMessageCreateBuilder { + b.Components = append(b.Components, components...) + return b +} + +// SetAllowedMentions sets the allowed mentions of the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *WebhookMessageCreateBuilder { + b.AllowedMentions = allowedMentions + return b +} + +// SetAllowedMentionsEmpty sets the allowed mentions of the WebhookMessageCreate to nothing +func (b *WebhookMessageCreateBuilder) SetAllowedMentionsEmpty() *WebhookMessageCreateBuilder { + return b.SetAllowedMentions(&AllowedMentions{}) +} + +// SetFlags sets the message flags of the WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) SetFlags(flags MessageFlags) *WebhookMessageCreateBuilder { + b.Flags = flags + return b +} + +// SetEphemeral adds/removes MessageFlagEphemeral to the message flags +func (b *WebhookMessageCreateBuilder) SetEphemeral(ephemeral bool) *WebhookMessageCreateBuilder { + if ephemeral { + b.Flags = b.Flags.Add(MessageFlagEphemeral) + } else { + b.Flags = b.Flags.Remove(MessageFlagEphemeral) + } + return b +} + +// Build returns your built WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) Build() *WebhookMessageCreate { + return &b.WebhookMessageCreate +} diff --git a/api/webhook_message_update.go b/api/webhook_message_update.go new file mode 100644 index 00000000..fbbc5d98 --- /dev/null +++ b/api/webhook_message_update.go @@ -0,0 +1,145 @@ +package api + +import ( + "encoding/json" + "fmt" +) + +// WebhookMessageUpdate is used to edit a WebhookMessage +type WebhookMessageUpdate struct { + Content string `json:"content"` + Components []Component `json:"components"` + Embeds []*Embed `json:"embeds"` + AllowedMentions *AllowedMentions `json:"allowed_mentions"` + Flags MessageFlags `json:"flags"` + updateFlags updateFlags +} + +func (u WebhookMessageUpdate) isUpdated(flag updateFlags) bool { + return (u.updateFlags & flag) == flag +} + +func (u WebhookMessageUpdate) MarshalJSON() ([]byte, error) { + data := map[string]interface{}{} + + if u.isUpdated(updateFlagContent) { + data["content"] = u.Content + } + if u.isUpdated(updateFlagComponents) { + data["components"] = u.Components + } + if u.isUpdated(updateFlagEmbed) { + data["embeds"] = u.Embeds + } + if u.isUpdated(updateFlagAllowedMentions) { + data["allowed_mentions"] = u.AllowedMentions + } + if u.isUpdated(updateFlagFlags) { + data["flags"] = u.Flags + } + + return json.Marshal(data) +} + +// WebhookMessageUpdateBuilder helper to build WebhookMessageUpdate easier +type WebhookMessageUpdateBuilder struct { + WebhookMessageUpdate +} + +// NewWebhookMessageUpdateBuilder creates a new WebhookMessageUpdateBuilder to be built later +func NewWebhookMessageUpdateBuilder() *WebhookMessageUpdateBuilder { + return &WebhookMessageUpdateBuilder{ + WebhookMessageUpdate: WebhookMessageUpdate{ + AllowedMentions: &DefaultInteractionAllowedMentions, + }, + } +} + +// SetContent sets content of the Message +func (b *WebhookMessageUpdateBuilder) SetContent(content string) *WebhookMessageUpdateBuilder { + b.Content = content + b.updateFlags |= updateFlagContent + return b +} + +// SetContentf sets content of the Message +func (b *WebhookMessageUpdateBuilder) SetContentf(content string, a ...interface{}) *WebhookMessageUpdateBuilder { + return b.SetContent(fmt.Sprintf(content, a...)) +} + +// SetEmbeds sets the embeds of the WebhookMessageUpdate +func (b *WebhookMessageUpdateBuilder) SetEmbeds(embeds ...*Embed) *WebhookMessageUpdateBuilder { + b.Embeds = embeds + b.updateFlags |= updateFlagEmbed + return b +} + +// AddEmbeds adds multiple embeds to the WebhookMessageUpdate +func (b *WebhookMessageUpdateBuilder) AddEmbeds(embeds ...*Embed) *WebhookMessageUpdateBuilder { + b.Embeds = append(b.Embeds, embeds...) + b.updateFlags |= updateFlagEmbed + return b +} + +// ClearEmbeds removes all of the embeds from the WebhookMessageUpdate +func (b *WebhookMessageUpdateBuilder) ClearEmbeds() *WebhookMessageUpdateBuilder { + b.Embeds = []*Embed{} + b.updateFlags |= updateFlagEmbed + return b +} + +// RemoveEmbed removes an embed from the WebhookMessageUpdate +func (b *WebhookMessageUpdateBuilder) RemoveEmbed(index int) *WebhookMessageUpdateBuilder { + if b != nil && len(b.Embeds) > index { + b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) + } + b.updateFlags |= updateFlagEmbed + return b +} + +// SetComponents sets the Component(s) of the Message +func (b *WebhookMessageUpdateBuilder) SetComponents(components ...Component) *WebhookMessageUpdateBuilder { + b.Components = components + b.updateFlags |= updateFlagComponents + return b +} + +// AddComponents adds the Component(s) to the Message +func (b *WebhookMessageUpdateBuilder) AddComponents(components ...Component) *WebhookMessageUpdateBuilder { + b.Components = append(b.Components, components...) + b.updateFlags |= updateFlagComponents + return b +} + +// ClearComponents removes all of the Component(s) of the Message +func (b *WebhookMessageUpdateBuilder) ClearComponents() *WebhookMessageUpdateBuilder { + b.Components = []Component{} + b.updateFlags |= updateFlagComponents + return b +} + +// RemoveComponent removes a Component from the Message +func (b *WebhookMessageUpdateBuilder) RemoveComponent(i int) *WebhookMessageUpdateBuilder { + if b != nil && len(b.Components) > i { + b.Components = append(b.Components[:i], b.Components[i+1:]...) + } + b.updateFlags |= updateFlagComponents + return b +} + +// SetAllowedMentions sets the AllowedMentions of the Message +func (b *WebhookMessageUpdateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *WebhookMessageUpdateBuilder { + b.AllowedMentions = allowedMentions + b.updateFlags |= updateFlagAllowedMentions + return b +} + +// ClearAllowedMentions clears the allowed mentions of the Message +func (b *WebhookMessageUpdateBuilder) ClearAllowedMentions() *WebhookMessageUpdateBuilder { + return b.SetAllowedMentions(&AllowedMentions{}) +} + +// Build builds the WebhookMessageUpdateBuilder to a WebhookMessageUpdate struct +func (b *WebhookMessageUpdateBuilder) Build() WebhookMessageUpdate { + return b.WebhookMessageUpdate +} diff --git a/example/examplebot.go b/example/examplebot.go index f0c9330a..fb59525a 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -54,7 +54,7 @@ func main() { return } - rawCmds := []api.CommandCreate{ + /*rawCmds := []api.CommandCreate{ { Name: "eval", Description: "runs some go code", @@ -155,7 +155,7 @@ func main() { } if _, err = dgo.RestClient().SetGuildCommandsPermissions(dgo.ApplicationID(), guildID, cmdsPermissions...); err != nil { logger.Errorf("error while setting command permissions: %s", err) - } + }*/ err = dgo.Connect() if err != nil { @@ -182,29 +182,25 @@ func rawGatewayEventListener(event events.RawGatewayEvent) { func buttonClickListener(event events.ButtonClickEvent) { switch event.CustomID() { - case "test": - if err := event.ReplyEdit(api.NewInteractionResponseBuilder(). - SetContent("test2"). - SetComponents(api.NewActionRow( - api.NewPrimaryButton("test2", "test2", api.NewEmoji("✔"), false), - api.NewLinkButton("KittyBot", "https://kittybot.de", api.NewEmote("kittybot", emoteID, true), false), - )). - BuildData(), - ); err != nil { - logger.Errorf("error sending interaction response: %s", err) - } + case "test1": + _ = event.Respond(api.InteractionResponseTypeChannelMessageWithSource, + api.NewWebhookMessageCreateBuilder(). + SetContent(event.CustomID()). + Build(), + ) case "test2": - if err := event.ReplyEdit(api.NewInteractionResponseBuilder(). - SetContent("test"). - SetComponents(api.NewActionRow( - api.NewPrimaryButton("test", "test", api.NewEmoji("❌"), false), - api.NewLinkButton("KittyBot", "https://kittybot.de", api.NewEmote("kittybot", emoteID, true), false), - )). - BuildData(), - ); err != nil { - logger.Errorf("error sending interaction response: %s", err) - } + _ = event.Respond(api.InteractionResponseTypeDeferredChannelMessageWithSource, nil) + + case "test3": + _ = event.Respond(api.InteractionResponseTypeDeferredUpdateMessage, nil) + + case "test4": + _ = event.Respond(api.InteractionResponseTypeUpdateMessage, + api.NewWebhookMessageCreateBuilder(). + SetContent(event.CustomID()). + Build(), + ) } } @@ -219,7 +215,7 @@ func commandListener(event events.CommandEvent) { AddField("Time", "...", true). AddField("Code", "```go\n"+code+"\n```", false). AddField("Output", "```\n...\n```", false) - _ = event.ReplyCreate(api.NewInteractionResponseBuilder().SetEmbeds(embed.Build()).BuildData()) + _ = event.Reply(api.NewWebhookMessageCreateBuilder().SetEmbeds(embed.Build()).Build()) start := time.Now() output, err := gval.Evaluate(code, map[string]interface{}{ @@ -232,7 +228,7 @@ func commandListener(event events.CommandEvent) { embed.SetField(1, "Time", strconv.Itoa(int(elapsed.Milliseconds()))+"ms", true) if err != nil { - _, err = event.Interaction.EditOriginal(api.NewFollowupMessageBuilder(). + _, err = event.Interaction.EditOriginal(api.NewWebhookMessageUpdateBuilder(). SetEmbeds(embed. SetColor(red). SetField(0, "Status", "Failed", true). @@ -246,7 +242,7 @@ func commandListener(event events.CommandEvent) { } return } - _, err = event.Interaction.EditOriginal(api.NewFollowupMessageBuilder(). + _, err = event.Interaction.EditOriginal(api.NewWebhookMessageUpdateBuilder(). SetEmbeds(embed. SetColor(green). SetField(0, "Status", "Success", true). @@ -261,36 +257,37 @@ func commandListener(event events.CommandEvent) { }() case "say": - _ = event.Reply(api.NewInteractionResponseBuilder(). + _ = event.Reply(api.NewWebhookMessageCreateBuilder(). SetContent(event.Option("message").String()). SetAllowedMentionsEmpty(). Build(), ) case "test": - if err := event.Reply(api.NewInteractionResponseBuilder(). - SetContent("test1"). - SetEmbeds(api.NewEmbedBuilder().SetDescription("this message should have some buttons").Build()). + _ = event.Reply(api.NewWebhookMessageCreateBuilder(). + SetContent("test message"). + SetEphemeral(true). SetComponents( api.NewActionRow( - api.NewPrimaryButton("test", "test", api.NewEmoji("❌"), false), + api.NewPrimaryButton("test1", "test1", nil, false), + api.NewPrimaryButton("test2", "test2", nil, false), + api.NewPrimaryButton("test3", "test3", nil, false), + api.NewPrimaryButton("test4", "test4", nil, false), ), ). Build(), - ); err != nil { - logger.Errorf("error sending interaction response: %s", err) - } + ) case "addrole": user := event.Option("member").User() role := event.Option("role").Role() err := event.Disgo().RestClient().AddMemberRole(*event.Interaction.GuildID, user.ID, role.ID) if err == nil { - _ = event.Reply(api.NewInteractionResponseBuilder().AddEmbeds( + _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(green).SetDescriptionf("Added %s to %s", role, user).Build(), ).Build()) } else { - _ = event.Reply(api.NewInteractionResponseBuilder().AddEmbeds( + _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(red).SetDescriptionf("Failed to add %s to %s", role, user).Build(), ).Build()) } @@ -300,11 +297,11 @@ func commandListener(event events.CommandEvent) { role := event.Option("role").Role() err := event.Disgo().RestClient().RemoveMemberRole(*event.Interaction.GuildID, user.ID, role.ID) if err == nil { - _ = event.Reply(api.NewInteractionResponseBuilder().AddEmbeds( + _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(65280).SetDescriptionf("Removed %s from %s", role, user).Build(), ).Build()) } else { - _ = event.Reply(api.NewInteractionResponseBuilder().AddEmbeds( + _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(16711680).SetDescriptionf("Failed to remove %s from %s", role, user).Build(), ).Build()) } @@ -321,10 +318,23 @@ func messageListener(event events.GuildMessageCreateEvent) { switch *event.Message.Content { case "ping": - _, _ = event.Message.Reply(api.NewMessageBuilder().SetContent("pong").SetAllowedMentions(&api.AllowedMentions{RepliedUser: false}).Build()) + _, _ = event.Message.Reply(api.NewMessageCreateBuilder().SetContent("pong").SetAllowedMentions(&api.AllowedMentions{RepliedUser: false}).Build()) case "pong": - _, _ = event.Message.Reply(api.NewMessageBuilder().SetContent("ping").SetAllowedMentions(&api.AllowedMentions{RepliedUser: false}).Build()) + _, _ = event.Message.Reply(api.NewMessageCreateBuilder().SetContent("ping").SetAllowedMentions(&api.AllowedMentions{RepliedUser: false}).Build()) + + case "test": + go func() { + message, _ := event.MessageChannel().SendMessage(api.NewMessageCreateBuilder().SetContent("test").Build()) + + time.Sleep(time.Second * 2) + + message, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbed(api.NewEmbedBuilder().SetDescription("edit").Build()).Build()) + + time.Sleep(time.Second * 2) + + _, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("").SetEmbed(api.NewEmbedBuilder().SetDescription("edit2").Build()).Build()) + }() case "dm": go func() { @@ -333,7 +343,7 @@ func messageListener(event events.GuildMessageCreateEvent) { _ = event.Message.AddReaction("❌") return } - _, err = channel.SendMessage(api.NewMessageBuilder().SetContent("helo").Build()) + _, err = channel.SendMessage(api.NewMessageCreateBuilder().SetContent("helo").Build()) if err == nil { _ = event.Message.AddReaction("✅") } else { diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index a458015f..e2a4470b 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -629,12 +629,12 @@ func (r *RestClientImpl) SendInteractionResponse(interactionID api.Snowflake, in } // EditInteractionResponse used to edit the initial response on an interaction -func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, interactionToken string, followupMessage api.FollowupMessage) (message *api.Message, err error) { +func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, interactionToken string, messageUpdate api.WebhookMessageUpdate) (message *api.Message, err error) { compiledRoute, err := restclient.UpdateInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { return nil, err } - return message, r.Do(compiledRoute, followupMessage, &message) + return message, r.Do(compiledRoute, messageUpdate, &message) } // DeleteInteractionResponse used to delete the initial response on an interaction @@ -647,24 +647,24 @@ func (r *RestClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, } // SendFollowupMessage used to send a followup message_events to an interaction -func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, followupMessage api.FollowupMessage) (message *api.Message, err error) { +func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, messageCreate api.WebhookMessageCreate) (message *api.Message, err error) { compiledRoute, err := restclient.CreateFollowupMessage.Compile(nil, applicationID, interactionToken) if err != nil { return nil, err } - return message, r.Do(compiledRoute, followupMessage, &message) + return message, r.Do(compiledRoute, messageCreate, &message) } -// EditFollowupMessage used to edit a api.FollowupMessage from an api.Interaction -func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, followupMessage api.FollowupMessage) (message *api.Message, err error) { +// EditFollowupMessage used to edit a api.WebhookMessageCreate from an api.Interaction +func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, messageUpdate api.WebhookMessageUpdate) (message *api.Message, err error) { compiledRoute, err := restclient.UpdateFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { return nil, err } - return message, r.Do(compiledRoute, followupMessage, &message) + return message, r.Do(compiledRoute, messageUpdate, &message) } -// DeleteFollowupMessage used to delete a api.FollowupMessage from an api.Interaction +// DeleteFollowupMessage used to delete a api.WebhookMessageCreate from an api.Interaction func (r *RestClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake) error { compiledRoute, err := restclient.DeleteFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { From f5388ed618adf30b80cffe84f054156ba6700c8f Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 7 Jun 2021 18:33:44 +0200 Subject: [PATCH 07/19] added docs --- api/message_update.go | 1 + api/webhook_message_update.go | 1 + 2 files changed, 2 insertions(+) diff --git a/api/message_update.go b/api/message_update.go index 35b1bcdb..d2a33725 100644 --- a/api/message_update.go +++ b/api/message_update.go @@ -29,6 +29,7 @@ func (u MessageUpdate) isUpdated(flag updateFlags) bool { return (u.updateFlags & flag) == flag } +// MarshalJSON marshals the MessageUpdate into json func (u MessageUpdate) MarshalJSON() ([]byte, error) { data := map[string]interface{}{} diff --git a/api/webhook_message_update.go b/api/webhook_message_update.go index fbbc5d98..9f38bb4d 100644 --- a/api/webhook_message_update.go +++ b/api/webhook_message_update.go @@ -19,6 +19,7 @@ func (u WebhookMessageUpdate) isUpdated(flag updateFlags) bool { return (u.updateFlags & flag) == flag } +// MarshalJSON marshals the WebhookMessageUpdate into json func (u WebhookMessageUpdate) MarshalJSON() ([]byte, error) { data := map[string]interface{}{} From 781f2acb684c530b35b8ffd751cb14bde2c25a0e Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 7 Jun 2021 18:51:29 +0200 Subject: [PATCH 08/19] fixed inconsistencies --- api/command_option.go | 4 +-- api/command_permission.go | 6 ++-- api/component.go | 16 ++++----- api/embed_builder.go | 4 +-- api/events/interaction_events.go | 2 +- api/gateway_commands.go | 4 +-- api/interaction.go | 2 +- api/message.go | 58 ++++++++++++++++---------------- api/message_create.go | 22 +++++------- api/message_update.go | 11 ++++-- api/role.go | 2 +- api/webhook_message_create.go | 12 +++---- api/webhook_message_update.go | 8 ++--- internal/entity_builder_impl.go | 4 +-- 14 files changed, 79 insertions(+), 76 deletions(-) diff --git a/api/command_option.go b/api/command_option.go index 3b521459..1a7d3d6e 100644 --- a/api/command_option.go +++ b/api/command_option.go @@ -72,8 +72,8 @@ type CommandOption struct { Name string `json:"name"` Description string `json:"description"` Required bool `json:"required,omitempty"` - Choices []OptionChoice `json:"choices,omitempty"` - Options []CommandOption `json:"options,omitempty"` + Choices []OptionChoice `json:"choices,omitempty"` + Options []CommandOption `json:"options,omitempty"` } // AddChoice adds a new choice to the the CommandOption diff --git a/api/command_permission.go b/api/command_permission.go index e7170a2f..2b93abc2 100644 --- a/api/command_permission.go +++ b/api/command_permission.go @@ -3,9 +3,9 @@ package api // GuildCommandPermissions holds all permissions for a Command type GuildCommandPermissions struct { Disgo Disgo - ID Snowflake `json:"id"` - ApplicationID Snowflake `json:"application_id"` - GuildID Snowflake `json:"guild_id"` + ID Snowflake `json:"id"` + ApplicationID Snowflake `json:"application_id"` + GuildID Snowflake `json:"guild_id"` Permissions []CommandPermission `json:"permissions"` } diff --git a/api/component.go b/api/component.go index a02af2e2..9d87d3f6 100644 --- a/api/component.go +++ b/api/component.go @@ -30,12 +30,12 @@ func (t ComponentImpl) Type() ComponentType { // UnmarshalComponent is used for easier unmarshalling of different Component(s) type UnmarshalComponent struct { - ComponentType ComponentType `json:"type"` - Style ButtonStyle `json:"style"` - Label *string `json:"label"` - Emoji *Emoji `json:"emoji"` - CustomID string `json:"custom_id"` - URL string `json:"url"` - Disabled bool `json:"disabled"` - Components []*UnmarshalComponent `json:"components"` + ComponentType ComponentType `json:"type"` + Style ButtonStyle `json:"style"` + Label *string `json:"label"` + Emoji *Emoji `json:"emoji"` + CustomID string `json:"custom_id"` + URL string `json:"url"` + Disabled bool `json:"disabled"` + Components []UnmarshalComponent `json:"components"` } diff --git a/api/embed_builder.go b/api/embed_builder.go index c2e445d5..bc4732f9 100644 --- a/api/embed_builder.go +++ b/api/embed_builder.go @@ -186,6 +186,6 @@ func (b *EmbedBuilder) RemoveField(i int) *EmbedBuilder { } // Build returns your built Embed -func (b *EmbedBuilder) Build() *Embed { - return &b.Embed +func (b *EmbedBuilder) Build() Embed { + return b.Embed } diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index 626f770b..3747e5d4 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -21,7 +21,7 @@ func (e *GenericInteractionEvent) DeferReply(ephemeral bool) error { } // Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.WebhookMessageCreate -func (e *GenericInteractionEvent) Reply(data *api.WebhookMessageCreate) error { +func (e *GenericInteractionEvent) Reply(data api.WebhookMessageCreate) error { return e.Interaction.Reply(data) } diff --git a/api/gateway_commands.go b/api/gateway_commands.go index fc6c5434..6aae033f 100644 --- a/api/gateway_commands.go +++ b/api/gateway_commands.go @@ -1,8 +1,8 @@ package api // NewGatewayCommand returns a new GatewayCommand struct with the given payload -func NewGatewayCommand(op GatewayOp, d interface{}) *GatewayCommand { - return &GatewayCommand{ +func NewGatewayCommand(op GatewayOp, d interface{}) GatewayCommand { + return GatewayCommand{ GatewayPacket: GatewayPacket{ Op: op, S: nil, diff --git a/api/interaction.go b/api/interaction.go index ef04beaf..2052adf5 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -79,7 +79,7 @@ func (i *Interaction) DeferReply(ephemeral bool) error { } // Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.WebhookMessageCreate -func (i *Interaction) Reply(data *WebhookMessageCreate) error { +func (i *Interaction) Reply(data WebhookMessageCreate) error { return i.Respond(InteractionResponseTypeChannelMessageWithSource, data) } diff --git a/api/message.go b/api/message.go index 5e64318b..3884b4b5 100644 --- a/api/message.go +++ b/api/message.go @@ -160,40 +160,40 @@ type MessageSticker struct { // Message is a struct for messages sent in discord text-based channels type Message struct { Disgo Disgo - ID Snowflake `json:"id"` - GuildID *Snowflake `json:"guild_id"` - Reactions []*MessageReaction `json:"reactions"` - Attachments []*MessageAttachment `json:"attachments"` - TTS bool `json:"tts"` - Embeds []*Embed `json:"embeds,omitempty"` - Components []Component `json:"components,omitempty"` - CreatedAt time.Time `json:"timestamp"` - Mentions []interface{} `json:"mentions"` - MentionEveryone bool `json:"mention_everyone"` - MentionRoles []*Role `json:"mention_roles"` - MentionChannels []*Channel `json:"mention_channels"` - Pinned bool `json:"pinned"` - EditedTimestamp *time.Time `json:"edited_timestamp"` - Author *User `json:"author"` - Member *Member `json:"member"` - Content *string `json:"content,omitempty"` - ChannelID Snowflake `json:"channel_id"` - Type MessageType `json:"type"` - Flags MessageFlags `json:"flags"` - MessageReference *MessageReference `json:"message_reference,omitempty"` - Interaction *MessageInteraction `json:"message_interaction,omitempty"` - WebhookID *Snowflake `json:"webhook_id,omitempty"` - Activity *MessageActivity `json:"activity,omitempty"` - Application *MessageApplication `json:"application,omitempty"` - Stickers []*MessageSticker `json:"stickers,omitempty"` - ReferencedMessage *Message `json:"referenced_message,omitempty"` - LastUpdated *time.Time `json:"last_updated,omitempty"` + ID Snowflake `json:"id"` + GuildID *Snowflake `json:"guild_id"` + Reactions []MessageReaction `json:"reactions"` + Attachments []MessageAttachment `json:"attachments"` + TTS bool `json:"tts"` + Embeds []Embed `json:"embeds,omitempty"` + Components []Component `json:"components,omitempty"` + CreatedAt time.Time `json:"timestamp"` + Mentions []interface{} `json:"mentions"` + MentionEveryone bool `json:"mention_everyone"` + MentionRoles []*Role `json:"mention_roles"` + MentionChannels []*Channel `json:"mention_channels"` + Pinned bool `json:"pinned"` + EditedTimestamp *time.Time `json:"edited_timestamp"` + Author *User `json:"author"` + Member *Member `json:"member"` + Content *string `json:"content,omitempty"` + ChannelID Snowflake `json:"channel_id"` + Type MessageType `json:"type"` + Flags MessageFlags `json:"flags"` + MessageReference *MessageReference `json:"message_reference,omitempty"` + Interaction *MessageInteraction `json:"message_interaction,omitempty"` + WebhookID *Snowflake `json:"webhook_id,omitempty"` + Activity *MessageActivity `json:"activity,omitempty"` + Application *MessageApplication `json:"application,omitempty"` + Stickers []*MessageSticker `json:"stickers,omitempty"` + ReferencedMessage *Message `json:"referenced_message,omitempty"` + LastUpdated *time.Time `json:"last_updated,omitempty"` } // FullMessage is used for easier unmarshalling of Component(s) in Message(s) type FullMessage struct { *Message - UnmarshalComponents []*UnmarshalComponent `json:"components,omitempty"` + UnmarshalComponents []UnmarshalComponent `json:"components,omitempty"` } // MessageReference is a reference to another message diff --git a/api/message_create.go b/api/message_create.go index 5ae36fa7..e829d8d3 100644 --- a/api/message_create.go +++ b/api/message_create.go @@ -38,23 +38,13 @@ func NewMessageBuilderByMessage(message *Message) *MessageCreateBuilder { msg.Content = *message.Content } if len(message.Embeds) > 0 { - msg.Embed = message.Embeds[0] + msg.Embed = &message.Embeds[0] } return &MessageCreateBuilder{ MessageCreate: msg, } } -// NewMessageCreateBuilderWithEmbed creates a new MessageCreateBuilder with an Embed to be built later -func NewMessageCreateBuilderWithEmbed(embed *Embed) *MessageCreateBuilder { - return NewMessageCreateBuilder().SetEmbed(embed) -} - -// NewMessageCreateBuilderWithContent creates a new MessageCreateBuilder with a content to be built later -func NewMessageCreateBuilderWithContent(content string) *MessageCreateBuilder { - return NewMessageCreateBuilder().SetContent(content) -} - // SetContent sets content of the Message func (b *MessageCreateBuilder) SetContent(content string) *MessageCreateBuilder { b.Content = content @@ -74,8 +64,14 @@ func (b *MessageCreateBuilder) SetTTS(tts bool) *MessageCreateBuilder { } // SetEmbed sets the Embed of the Message -func (b *MessageCreateBuilder) SetEmbed(embed *Embed) *MessageCreateBuilder { - b.Embed = embed +func (b *MessageCreateBuilder) SetEmbed(embed Embed) *MessageCreateBuilder { + b.Embed = &embed + return b +} + +// ClearEmbed clears the Embed of the Message +func (b *MessageCreateBuilder) ClearEmbed() *MessageCreateBuilder { + b.Embed = nil return b } diff --git a/api/message_update.go b/api/message_update.go index d2a33725..e6919ff4 100644 --- a/api/message_update.go +++ b/api/message_update.go @@ -79,8 +79,15 @@ func (b *MessageUpdateBuilder) SetContentf(content string, a ...interface{}) *Me } // SetEmbed sets the Embed of the Message -func (b *MessageUpdateBuilder) SetEmbed(embed *Embed) *MessageUpdateBuilder { - b.Embed = embed +func (b *MessageUpdateBuilder) SetEmbed(embed Embed) *MessageUpdateBuilder { + b.Embed = &embed + b.updateFlags |= updateFlagEmbed + return b +} + +// ClearEmbed clears the Embed of the Message +func (b *MessageUpdateBuilder) ClearEmbed() *MessageUpdateBuilder { + b.Embed = nil b.updateFlags |= updateFlagEmbed return b } diff --git a/api/role.go b/api/role.go index b4246fbd..79cad9af 100644 --- a/api/role.go +++ b/api/role.go @@ -56,7 +56,7 @@ type RoleTag struct { type UpdateRole struct { Name *string `json:"name,omitempty"` Permissions *Permissions `json:"permissions,omitempty"` - Color *int `json:"color,omitempty"` + Color *int `json:"color,omitempty"` Hoist *bool `json:"hoist,omitempty"` Mentionable *bool `json:"mentionable,omitempty"` } diff --git a/api/webhook_message_create.go b/api/webhook_message_create.go index 712f500e..fea38ef5 100644 --- a/api/webhook_message_create.go +++ b/api/webhook_message_create.go @@ -6,7 +6,7 @@ import "fmt" type WebhookMessageCreate struct { TTS bool `json:"tts,omitempty"` Content string `json:"content,omitempty"` - Embeds []*Embed `json:"embeds,omitempty"` + Embeds []Embed `json:"embeds,omitempty"` Components []Component `json:"components,omitempty"` AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` Flags MessageFlags `json:"flags,omitempty"` @@ -45,20 +45,20 @@ func (b *WebhookMessageCreateBuilder) SetContentf(content string, a ...interface } // SetEmbeds sets the embeds of the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) SetEmbeds(embeds ...*Embed) *WebhookMessageCreateBuilder { +func (b *WebhookMessageCreateBuilder) SetEmbeds(embeds ...Embed) *WebhookMessageCreateBuilder { b.Embeds = embeds return b } // AddEmbeds adds multiple embeds to the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) AddEmbeds(embeds ...*Embed) *WebhookMessageCreateBuilder { +func (b *WebhookMessageCreateBuilder) AddEmbeds(embeds ...Embed) *WebhookMessageCreateBuilder { b.Embeds = append(b.Embeds, embeds...) return b } // ClearEmbeds removes all of the embeds from the WebhookMessageCreate func (b *WebhookMessageCreateBuilder) ClearEmbeds() *WebhookMessageCreateBuilder { - b.Embeds = []*Embed{} + b.Embeds = []Embed{} return b } @@ -110,6 +110,6 @@ func (b *WebhookMessageCreateBuilder) SetEphemeral(ephemeral bool) *WebhookMessa } // Build returns your built WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) Build() *WebhookMessageCreate { - return &b.WebhookMessageCreate +func (b *WebhookMessageCreateBuilder) Build() WebhookMessageCreate { + return b.WebhookMessageCreate } diff --git a/api/webhook_message_update.go b/api/webhook_message_update.go index 9f38bb4d..4b18644a 100644 --- a/api/webhook_message_update.go +++ b/api/webhook_message_update.go @@ -9,7 +9,7 @@ import ( type WebhookMessageUpdate struct { Content string `json:"content"` Components []Component `json:"components"` - Embeds []*Embed `json:"embeds"` + Embeds []Embed `json:"embeds"` AllowedMentions *AllowedMentions `json:"allowed_mentions"` Flags MessageFlags `json:"flags"` updateFlags updateFlags @@ -69,14 +69,14 @@ func (b *WebhookMessageUpdateBuilder) SetContentf(content string, a ...interface } // SetEmbeds sets the embeds of the WebhookMessageUpdate -func (b *WebhookMessageUpdateBuilder) SetEmbeds(embeds ...*Embed) *WebhookMessageUpdateBuilder { +func (b *WebhookMessageUpdateBuilder) SetEmbeds(embeds ...Embed) *WebhookMessageUpdateBuilder { b.Embeds = embeds b.updateFlags |= updateFlagEmbed return b } // AddEmbeds adds multiple embeds to the WebhookMessageUpdate -func (b *WebhookMessageUpdateBuilder) AddEmbeds(embeds ...*Embed) *WebhookMessageUpdateBuilder { +func (b *WebhookMessageUpdateBuilder) AddEmbeds(embeds ...Embed) *WebhookMessageUpdateBuilder { b.Embeds = append(b.Embeds, embeds...) b.updateFlags |= updateFlagEmbed return b @@ -84,7 +84,7 @@ func (b *WebhookMessageUpdateBuilder) AddEmbeds(embeds ...*Embed) *WebhookMessag // ClearEmbeds removes all of the embeds from the WebhookMessageUpdate func (b *WebhookMessageUpdateBuilder) ClearEmbeds() *WebhookMessageUpdateBuilder { - b.Embeds = []*Embed{} + b.Embeds = []Embed{} b.updateFlags |= updateFlagEmbed return b } diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 74422a3b..0473af65 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -110,7 +110,7 @@ func (b *EntityBuilderImpl) CreateUser(user *api.User, updateCache api.CacheStra return user } -func (b *EntityBuilderImpl) createComponent(unmarshalComponent *api.UnmarshalComponent, updateCache api.CacheStrategy) api.Component { +func (b *EntityBuilderImpl) createComponent(unmarshalComponent api.UnmarshalComponent, updateCache api.CacheStrategy) api.Component { switch unmarshalComponent.ComponentType { case api.ComponentTypeActionRow: components := make([]api.Component, len(unmarshalComponent.Components)) @@ -310,7 +310,7 @@ func (b *EntityBuilderImpl) CreateDMChannel(channel *api.Channel, updateCache ap // CreateEmoji returns a new api.Emoji entity func (b *EntityBuilderImpl) CreateEmoji(guildID api.Snowflake, emoji *api.Emoji, updateCache api.CacheStrategy) *api.Emoji { - if emoji.ID == "" {// return if emoji is no custom emote + if emoji.ID == "" { // return if emoji is no custom emote return emoji } emoji.Disgo = b.Disgo() From c3e2c77abed9612822848549ef597fb4c2b6ed73 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 7 Jun 2021 18:54:21 +0200 Subject: [PATCH 09/19] added missing helper --- api/command_option.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/api/command_option.go b/api/command_option.go index 1a7d3d6e..33f4ca43 100644 --- a/api/command_option.go +++ b/api/command_option.go @@ -61,6 +61,11 @@ func NewChannelOption(name string, description string, options ...CommandOption) return NewCommandOption(CommandOptionTypeChannel, name, description, options...) } +// NewRoleOption creates a new CommandOption with CommandOptionTypeRole +func NewRoleOption(name string, description string, options ...CommandOption) CommandOption { + return NewCommandOption(CommandOptionTypeRole, name, description, options...) +} + // NewMentionableOption creates a new CommandOption with CommandOptionTypeUser or CommandOptionTypeRole func NewMentionableOption(name string, description string, options ...CommandOption) CommandOption { return NewCommandOption(CommandOptionTypeMentionable, name, description, options...) From 363f8bf5eb557b2b479347550d4cb6b1a8ab0d1a Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 7 Jun 2021 19:00:48 +0200 Subject: [PATCH 10/19] moved flag consts over bit helpers --- api/gateway_intents.go | 76 ++++++++++---------- api/message.go | 26 +++---- api/permissions.go | 156 ++++++++++++++++++++--------------------- 3 files changed, 129 insertions(+), 129 deletions(-) diff --git a/api/gateway_intents.go b/api/gateway_intents.go index fa3eced1..bcd054da 100644 --- a/api/gateway_intents.go +++ b/api/gateway_intents.go @@ -3,6 +3,44 @@ package api // GatewayIntents is an extension of the Bit structure used when identifying with discord type GatewayIntents int64 +// Constants for the different bit offsets of GatewayIntents +const ( + GatewayIntentsGuilds GatewayIntents = 1 << iota + GatewayIntentsGuildMembers + GatewayIntentsGuildBans + GatewayIntentsGuildEmojis + GatewayIntentsGuildIntegrations + GatewayIntentsGuildWebhooks + GatewayIntentsGuildInvites + GatewayIntentsGuildVoiceStates + GatewayIntentsGuildPresences + GatewayIntentsGuildMessages + GatewayIntentsGuildMessageReactions + GatewayIntentsGuildMessageTyping + GatewayIntentsDirectMessages + GatewayIntentsDirectMessageReactions + GatewayIntentsDirectMessageTyping + + GatewayIntentsNonPrivileged = GatewayIntentsGuilds | + GatewayIntentsGuildBans | + GatewayIntentsGuildEmojis | + GatewayIntentsGuildIntegrations | + GatewayIntentsGuildWebhooks | + GatewayIntentsGuildInvites | + GatewayIntentsGuildVoiceStates | + GatewayIntentsGuildMessages | + GatewayIntentsGuildMessageReactions | + GatewayIntentsGuildMessageTyping | + GatewayIntentsDirectMessages | + GatewayIntentsDirectMessageReactions | + GatewayIntentsDirectMessageTyping + GatewayIntentsPrivileged = GatewayIntentsGuildMembers | + GatewayIntentsGuildPresences + GatewayIntentsAll = GatewayIntentsNonPrivileged | + GatewayIntentsPrivileged + GatewayIntentsNone GatewayIntents = 0 +) + // Add allows you to add multiple bits together, producing a new bit func (p GatewayIntents) Add(bits ...GatewayIntents) GatewayIntents { total := GatewayIntents(0) @@ -52,41 +90,3 @@ func (p GatewayIntents) MissingAny(bits ...GatewayIntents) bool { func (p GatewayIntents) Missing(bit GatewayIntents) bool { return !p.Has(bit) } - -// Constants for the different bit offsets of GatewayIntents -const ( - GatewayIntentsGuilds GatewayIntents = 1 << iota - GatewayIntentsGuildMembers - GatewayIntentsGuildBans - GatewayIntentsGuildEmojis - GatewayIntentsGuildIntegrations - GatewayIntentsGuildWebhooks - GatewayIntentsGuildInvites - GatewayIntentsGuildVoiceStates - GatewayIntentsGuildPresences - GatewayIntentsGuildMessages - GatewayIntentsGuildMessageReactions - GatewayIntentsGuildMessageTyping - GatewayIntentsDirectMessages - GatewayIntentsDirectMessageReactions - GatewayIntentsDirectMessageTyping - - GatewayIntentsNonPrivileged = GatewayIntentsGuilds | - GatewayIntentsGuildBans | - GatewayIntentsGuildEmojis | - GatewayIntentsGuildIntegrations | - GatewayIntentsGuildWebhooks | - GatewayIntentsGuildInvites | - GatewayIntentsGuildVoiceStates | - GatewayIntentsGuildMessages | - GatewayIntentsGuildMessageReactions | - GatewayIntentsGuildMessageTyping | - GatewayIntentsDirectMessages | - GatewayIntentsDirectMessageReactions | - GatewayIntentsDirectMessageTyping - GatewayIntentsPrivileged = GatewayIntentsGuildMembers | - GatewayIntentsGuildPresences - GatewayIntentsAll = GatewayIntentsNonPrivileged | - GatewayIntentsPrivileged - GatewayIntentsNone GatewayIntents = 0 -) diff --git a/api/message.go b/api/message.go index 3884b4b5..19f3155f 100644 --- a/api/message.go +++ b/api/message.go @@ -36,6 +36,19 @@ const ( // The MessageFlags of a Message type MessageFlags int64 +// Constants for MessageFlags +const ( + MessageFlagCrossposted MessageFlags = 1 << iota + MessageFlagIsCrosspost + MessageFlagSuppressEmbeds + MessageFlagSourceMessageDeleted + MessageFlagUrgent + _ + MessageFlagEphemeral + MessageFlagLoading // Message is an interaction of type 5, awaiting further response + MessageFlagNone MessageFlags = 0 +) + // Add allows you to add multiple bits together, producing a new bit func (f MessageFlags) Add(bits ...MessageFlags) MessageFlags { total := MessageFlags(0) @@ -86,19 +99,6 @@ func (f MessageFlags) Missing(bit MessageFlags) bool { return !f.Has(bit) } -// Constants for MessageFlags -const ( - MessageFlagCrossposted MessageFlags = 1 << iota - MessageFlagIsCrosspost - MessageFlagSuppressEmbeds - MessageFlagSourceMessageDeleted - MessageFlagUrgent - _ - MessageFlagEphemeral - MessageFlagLoading // Message is an interaction of type 5, awaiting further response - MessageFlagNone MessageFlags = 0 -) - //MessageAttachment is used for files sent in a Message type MessageAttachment struct { ID Snowflake `json:"id,omitempty"` diff --git a/api/permissions.go b/api/permissions.go index d305d0d7..88590da4 100644 --- a/api/permissions.go +++ b/api/permissions.go @@ -25,84 +25,6 @@ type PermissionOverwrite struct { // Permissions extends the Bit structure, and is used within roles and channels type Permissions int64 -// MarshalJSON marshals permissions into a string -func (p Permissions) MarshalJSON() ([]byte, error) { - strPermissions := strconv.FormatInt(int64(p), 10) - - jsonValue, err := json.Marshal(strPermissions) - if err != nil { - return nil, err - } - - return jsonValue, nil -} - -// UnmarshalJSON unmarshalls permissions into an int64 -func (p *Permissions) UnmarshalJSON(b []byte) error { - var strPermissions string - err := json.Unmarshal(b, &strPermissions) - if err != nil { - return err - } - - intPermissions, err := strconv.Atoi(strPermissions) - if err != nil { - return err - } - *p = Permissions(intPermissions) - return nil -} - -// Add allows you to add multiple bits together, producing a new bit -func (p Permissions) Add(bits ...Permissions) Permissions { - total := Permissions(0) - for _, bit := range bits { - total |= bit - } - p |= total - return p -} - -// Remove allows you to subtract multiple bits from the first, producing a new bit -func (p Permissions) Remove(bits ...Permissions) Permissions { - total := Permissions(0) - for _, bit := range bits { - total |= bit - } - p &^= total - return p -} - -// HasAll will ensure that the bit includes all of the bits entered -func (p Permissions) HasAll(bits ...Permissions) bool { - for _, bit := range bits { - if !p.Has(bit) { - return false - } - } - return true -} - -// Has will check whether the Bit contains another bit -func (p Permissions) Has(bit Permissions) bool { - return (p & bit) == bit -} - -// MissingAny will check whether the bit is missing any one of the bits -func (p Permissions) MissingAny(bits ...Permissions) bool { - for _, bit := range bits { - if !p.Has(bit) { - return true - } - } - return false -} - -// Missing will do the inverse of Bit.Has -func (p Permissions) Missing(bit Permissions) bool { - return !p.Has(bit) -} - // Constants for the different bit offsets of text channel permissions const ( PermissionSendMessages Permissions = 1 << (iota + 11) @@ -181,3 +103,81 @@ const ( PermissionsNone Permissions = 0 ) + +// MarshalJSON marshals permissions into a string +func (p Permissions) MarshalJSON() ([]byte, error) { + strPermissions := strconv.FormatInt(int64(p), 10) + + jsonValue, err := json.Marshal(strPermissions) + if err != nil { + return nil, err + } + + return jsonValue, nil +} + +// UnmarshalJSON unmarshalls permissions into an int64 +func (p *Permissions) UnmarshalJSON(b []byte) error { + var strPermissions string + err := json.Unmarshal(b, &strPermissions) + if err != nil { + return err + } + + intPermissions, err := strconv.Atoi(strPermissions) + if err != nil { + return err + } + *p = Permissions(intPermissions) + return nil +} + +// Add allows you to add multiple bits together, producing a new bit +func (p Permissions) Add(bits ...Permissions) Permissions { + total := Permissions(0) + for _, bit := range bits { + total |= bit + } + p |= total + return p +} + +// Remove allows you to subtract multiple bits from the first, producing a new bit +func (p Permissions) Remove(bits ...Permissions) Permissions { + total := Permissions(0) + for _, bit := range bits { + total |= bit + } + p &^= total + return p +} + +// HasAll will ensure that the bit includes all of the bits entered +func (p Permissions) HasAll(bits ...Permissions) bool { + for _, bit := range bits { + if !p.Has(bit) { + return false + } + } + return true +} + +// Has will check whether the Bit contains another bit +func (p Permissions) Has(bit Permissions) bool { + return (p & bit) == bit +} + +// MissingAny will check whether the bit is missing any one of the bits +func (p Permissions) MissingAny(bits ...Permissions) bool { + for _, bit := range bits { + if !p.Has(bit) { + return true + } + } + return false +} + +// Missing will do the inverse of Bit.Has +func (p Permissions) Missing(bit Permissions) bool { + return !p.Has(bit) +} From 2925d54e3703ebcb449ef19b830adb171143436e Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 9 Jun 2021 21:27:20 +0200 Subject: [PATCH 11/19] implemented multiple emebds in normal messages & some docs cleanup --- api/button_interaction.go | 6 +- api/events/interaction_events.go | 26 +++--- api/interaction.go | 24 ++--- api/message_create.go | 61 +++++++++---- api/message_update.go | 43 ++++++--- api/restclient.go | 6 +- api/webhook_message_create.go | 115 ------------------------ api/webhook_message_update.go | 146 ------------------------------- example/examplebot.go | 28 +++--- example/go.sum | 1 + internal/restclient_impl.go | 64 +++++++------- 11 files changed, 155 insertions(+), 365 deletions(-) delete mode 100644 api/webhook_message_create.go delete mode 100644 api/webhook_message_update.go diff --git a/api/button_interaction.go b/api/button_interaction.go index c1899dc2..4bd14e40 100644 --- a/api/button_interaction.go +++ b/api/button_interaction.go @@ -12,9 +12,9 @@ func (i *ButtonInteraction) DeferEdit() error { return i.Respond(InteractionResponseTypeDeferredUpdateMessage, nil) } -// Edit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.WebhookMessageCreate which edits the original api.Message -func (i *ButtonInteraction) Edit(data *WebhookMessageCreate) error { - return i.Respond(InteractionResponseTypeUpdateMessage, data) +// Edit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.MessageCreate which edits the original api.Message +func (i *ButtonInteraction) Edit(messageCreate MessageCreate) error { + return i.Respond(InteractionResponseTypeUpdateMessage, messageCreate) } // ButtonInteractionData is the command data payload diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index 3747e5d4..463b1b28 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -20,13 +20,13 @@ func (e *GenericInteractionEvent) DeferReply(ephemeral bool) error { return e.Interaction.DeferReply(ephemeral) } -// Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.WebhookMessageCreate -func (e *GenericInteractionEvent) Reply(data api.WebhookMessageCreate) error { - return e.Interaction.Reply(data) +// Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.MessageCreate +func (e *GenericInteractionEvent) Reply(messageCreate api.MessageCreate) error { + return e.Interaction.Reply(messageCreate) } // EditOriginal edits the original api.InteractionResponse -func (e *GenericInteractionEvent) EditOriginal(messageUpdate api.WebhookMessageUpdate) (*api.Message, error) { +func (e *GenericInteractionEvent) EditOriginal(messageUpdate api.MessageUpdate) (*api.Message, error) { return e.Interaction.EditOriginal(messageUpdate) } @@ -35,17 +35,17 @@ func (e *GenericInteractionEvent) DeleteOriginal() error { return e.Interaction.DeleteOriginal() } -// SendFollowup used to send a api.WebhookMessageCreate to an api.Interaction -func (e *GenericInteractionEvent) SendFollowup(followupMessage api.WebhookMessageCreate) (*api.Message, error) { - return e.Interaction.SendFollowup(followupMessage) +// SendFollowup used to send a followup api.MessageCreate to an api.Interaction +func (e *GenericInteractionEvent) SendFollowup(messageCreate api.MessageCreate) (*api.Message, error) { + return e.Interaction.SendFollowup(messageCreate) } -// EditFollowup used to edit a api.WebhookMessageCreate from an api.Interaction -func (e *GenericInteractionEvent) EditFollowup(messageID api.Snowflake, messageUpdate api.WebhookMessageUpdate) (*api.Message, error) { +// EditFollowup used to edit a followup api.Message from an api.Interaction +func (e *GenericInteractionEvent) EditFollowup(messageID api.Snowflake, messageUpdate api.MessageUpdate) (*api.Message, error) { return e.Interaction.EditFollowup(messageID, messageUpdate) } -// DeleteFollowup used to delete a api.WebhookMessageCreate from an api.Interaction +// DeleteFollowup used to delete a followup api.Message from an api.Interaction func (e *GenericInteractionEvent) DeleteFollowup(messageID api.Snowflake) error { return e.Interaction.DeleteFollowup(messageID) } @@ -115,9 +115,9 @@ func (e *ButtonClickEvent) DeferEdit() error { return e.ButtonInteraction.DeferEdit() } -// Edit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.WebhookMessageCreate which edits the original api.Message -func (e *ButtonClickEvent) Edit(data *api.WebhookMessageCreate) error { - return e.ButtonInteraction.Edit(data) +// Edit replies to the api.ButtonInteraction with api.InteractionResponseTypeUpdateMessage & api.MessageCreate which edits the original api.Message +func (e *ButtonClickEvent) Edit(messageCreate api.MessageCreate) error { + return e.ButtonInteraction.Edit(messageCreate) } // CustomID returns the customID from the called api.Button diff --git a/api/interaction.go b/api/interaction.go index 2052adf5..7f0efe1a 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -71,20 +71,20 @@ func (i *Interaction) Respond(responseType InteractionResponseType, data interfa // DeferReply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource and shows a loading state func (i *Interaction) DeferReply(ephemeral bool) error { - var data *WebhookMessageCreate + var messageCreate *MessageCreate if ephemeral { - data = &WebhookMessageCreate{Flags: MessageFlagEphemeral} + messageCreate = &MessageCreate{Flags: MessageFlagEphemeral} } - return i.Respond(InteractionResponseTypeDeferredChannelMessageWithSource, data) + return i.Respond(InteractionResponseTypeDeferredChannelMessageWithSource, messageCreate) } -// Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.WebhookMessageCreate -func (i *Interaction) Reply(data WebhookMessageCreate) error { - return i.Respond(InteractionResponseTypeChannelMessageWithSource, data) +// Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.MessageCreate +func (i *Interaction) Reply(messageCreate MessageCreate) error { + return i.Respond(InteractionResponseTypeChannelMessageWithSource, messageCreate) } // EditOriginal edits the original api.InteractionResponse -func (i *Interaction) EditOriginal(messageUpdate WebhookMessageUpdate) (*Message, error) { +func (i *Interaction) EditOriginal(messageUpdate MessageUpdate) (*Message, error) { return i.Disgo.RestClient().EditInteractionResponse(i.Disgo.ApplicationID(), i.Token, messageUpdate) } @@ -93,17 +93,17 @@ func (i *Interaction) DeleteOriginal() error { return i.Disgo.RestClient().DeleteInteractionResponse(i.Disgo.ApplicationID(), i.Token) } -// SendFollowup used to send a api.WebhookMessageCreate to an api.Interaction -func (i *Interaction) SendFollowup(messageCreate WebhookMessageCreate) (*Message, error) { +// SendFollowup used to send a api.MessageCreate to an api.Interaction +func (i *Interaction) SendFollowup(messageCreate MessageCreate) (*Message, error) { return i.Disgo.RestClient().SendFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageCreate) } -// EditFollowup used to edit a api.WebhookMessageCreate from an api.Interaction -func (i *Interaction) EditFollowup(messageID Snowflake, messageUpdate WebhookMessageUpdate) (*Message, error) { +// EditFollowup used to edit a api.Message from an api.Interaction +func (i *Interaction) EditFollowup(messageID Snowflake, messageUpdate MessageUpdate) (*Message, error) { return i.Disgo.RestClient().EditFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID, messageUpdate) } -// DeleteFollowup used to delete a api.WebhookMessageCreate from an api.Interaction +// DeleteFollowup used to delete a api.Message from an api.Interaction func (i *Interaction) DeleteFollowup(messageID Snowflake) error { return i.Disgo.RestClient().DeleteFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID) } diff --git a/api/message_create.go b/api/message_create.go index e829d8d3..43636c70 100644 --- a/api/message_create.go +++ b/api/message_create.go @@ -6,11 +6,12 @@ import "fmt" type MessageCreate struct { Nonce string `json:"nonce,omitempty"` Content string `json:"content,omitempty"` - Components []Component `json:"components,omitempty"` TTS bool `json:"tts,omitempty"` - Embed *Embed `json:"embed,omitempty"` + Embeds []Embed `json:"embeds,omitempty"` + Components []Component `json:"components,omitempty"` AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` MessageReference *MessageReference `json:"message_reference,omitempty"` + Flags MessageFlags `json:"flags,omitempty"` } // MessageCreateBuilder helper to build Message(s) easier @@ -32,14 +33,12 @@ func NewMessageBuilderByMessage(message *Message) *MessageCreateBuilder { msg := MessageCreate{ TTS: message.TTS, Components: message.Components, + Embeds: message.Embeds, AllowedMentions: &DefaultInteractionAllowedMentions, } if message.Content != nil { msg.Content = *message.Content } - if len(message.Embeds) > 0 { - msg.Embed = &message.Embeds[0] - } return &MessageCreateBuilder{ MessageCreate: msg, } @@ -63,15 +62,29 @@ func (b *MessageCreateBuilder) SetTTS(tts bool) *MessageCreateBuilder { return b } -// SetEmbed sets the Embed of the Message -func (b *MessageCreateBuilder) SetEmbed(embed Embed) *MessageCreateBuilder { - b.Embed = &embed +// SetEmbeds sets the embeds of the Message +func (b *MessageCreateBuilder) SetEmbeds(embeds ...Embed) *MessageCreateBuilder { + b.Embeds = embeds + return b +} + +// AddEmbeds adds multiple embeds to the Message +func (b *MessageCreateBuilder) AddEmbeds(embeds ...Embed) *MessageCreateBuilder { + b.Embeds = append(b.Embeds, embeds...) + return b +} + +// ClearEmbeds removes all of the embeds from the Message +func (b *MessageCreateBuilder) ClearEmbeds() *MessageCreateBuilder { + b.Embeds = []Embed{} return b } -// ClearEmbed clears the Embed of the Message -func (b *MessageCreateBuilder) ClearEmbed() *MessageCreateBuilder { - b.Embed = nil +// RemoveEmbed removes an embed from the Message +func (b *MessageCreateBuilder) RemoveEmbed(index int) *MessageCreateBuilder { + if b != nil && len(b.Embeds) > index { + b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) + } return b } @@ -89,9 +102,7 @@ func (b *MessageCreateBuilder) AddComponents(components ...Component) *MessageCr // ClearComponents removes all of the Component(s) of the Message func (b *MessageCreateBuilder) ClearComponents() *MessageCreateBuilder { - if b != nil { - b.Components = []Component{} - } + b.Components = []Component{} return b } @@ -111,7 +122,7 @@ func (b *MessageCreateBuilder) SetAllowedMentions(allowedMentions *AllowedMentio // ClearAllowedMentions clears the allowed mentions of the Message func (b *MessageCreateBuilder) ClearAllowedMentions() *MessageCreateBuilder { - return b.SetAllowedMentions(&AllowedMentions{}) + return b.SetAllowedMentions(nil) } // SetMessageReference allows you to specify a MessageReference to reply to @@ -120,8 +131,8 @@ func (b *MessageCreateBuilder) SetMessageReference(messageReference *MessageRefe return b } -// SetMessageReferenceByMessageID allows you to specify a Message ID to reply to -func (b *MessageCreateBuilder) SetMessageReferenceByMessageID(messageID Snowflake) *MessageCreateBuilder { +// SetMessageReferenceByID allows you to specify a Message ID to reply to +func (b *MessageCreateBuilder) SetMessageReferenceByID(messageID Snowflake) *MessageCreateBuilder { if b.MessageReference == nil { b.MessageReference = &MessageReference{} } @@ -129,6 +140,22 @@ func (b *MessageCreateBuilder) SetMessageReferenceByMessageID(messageID Snowflak return b } +// SetFlags sets the message flags of the Message +func (b *MessageCreateBuilder) SetFlags(flags MessageFlags) *MessageCreateBuilder { + b.Flags = flags + return b +} + +// SetEphemeral adds/removes MessageFlagEphemeral to the Message flags +func (b *MessageCreateBuilder) SetEphemeral(ephemeral bool) *MessageCreateBuilder { + if ephemeral { + b.Flags = b.Flags.Add(MessageFlagEphemeral) + } else { + b.Flags = b.Flags.Remove(MessageFlagEphemeral) + } + return b +} + // Build builds the MessageCreateBuilder to a MessageCreate struct func (b *MessageCreateBuilder) Build() MessageCreate { return b.MessageCreate diff --git a/api/message_update.go b/api/message_update.go index e6919ff4..8e184a33 100644 --- a/api/message_update.go +++ b/api/message_update.go @@ -18,8 +18,8 @@ const ( // MessageUpdate is used to edit a Message type MessageUpdate struct { Content string `json:"content"` + Embeds []Embed `json:"embeds"` Components []Component `json:"components"` - Embed *Embed `json:"embed"` AllowedMentions *AllowedMentions `json:"allowed_mentions"` Flags MessageFlags `json:"flags"` updateFlags updateFlags @@ -36,12 +36,12 @@ func (u MessageUpdate) MarshalJSON() ([]byte, error) { if u.isUpdated(updateFlagContent) { data["content"] = u.Content } + if u.isUpdated(updateFlagEmbed) { + data["embeds"] = u.Embeds + } if u.isUpdated(updateFlagComponents) { data["components"] = u.Components } - if u.isUpdated(updateFlagEmbed) { - data["embed"] = u.Embed - } if u.isUpdated(updateFlagAllowedMentions) { data["allowed_mentions"] = u.AllowedMentions } @@ -78,16 +78,32 @@ func (b *MessageUpdateBuilder) SetContentf(content string, a ...interface{}) *Me return b.SetContent(fmt.Sprintf(content, a...)) } -// SetEmbed sets the Embed of the Message -func (b *MessageUpdateBuilder) SetEmbed(embed Embed) *MessageUpdateBuilder { - b.Embed = &embed +// SetEmbeds sets the embeds of the Message +func (b *MessageUpdateBuilder) SetEmbeds(embeds ...Embed) *MessageUpdateBuilder { + b.Embeds = embeds b.updateFlags |= updateFlagEmbed return b } -// ClearEmbed clears the Embed of the Message -func (b *MessageUpdateBuilder) ClearEmbed() *MessageUpdateBuilder { - b.Embed = nil +// AddEmbeds adds multiple embeds to the Message +func (b *MessageUpdateBuilder) AddEmbeds(embeds ...Embed) *MessageUpdateBuilder { + b.Embeds = append(b.Embeds, embeds...) + b.updateFlags |= updateFlagEmbed + return b +} + +// ClearEmbeds removes all of the embeds from the Message +func (b *MessageUpdateBuilder) ClearEmbeds() *MessageUpdateBuilder { + b.Embeds = []Embed{} + b.updateFlags |= updateFlagEmbed + return b +} + +// RemoveEmbed removes an embed from the Message +func (b *MessageUpdateBuilder) RemoveEmbed(index int) *MessageUpdateBuilder { + if b != nil && len(b.Embeds) > index { + b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) + } b.updateFlags |= updateFlagEmbed return b } @@ -134,6 +150,13 @@ func (b *MessageUpdateBuilder) ClearAllowedMentions() *MessageUpdateBuilder { return b.SetAllowedMentions(&AllowedMentions{}) } +// SetFlags sets the MessageFlags of the Message +func (b *MessageUpdateBuilder) SetFlags(flags MessageFlags) *MessageUpdateBuilder { + b.Flags = flags + return b +} + + // Build builds the MessageUpdateBuilder to a MessageUpdate struct func (b *MessageUpdateBuilder) Build() MessageUpdate { return b.MessageUpdate diff --git a/api/restclient.go b/api/restclient.go index d549aba3..2484b0eb 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -74,10 +74,10 @@ type RestClient interface { SetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake, commandPermissions SetGuildCommandPermissions) (*GuildCommandPermissions, error) SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse InteractionResponse) error - EditInteractionResponse(applicationID Snowflake, interactionToken string, messageUpdate WebhookMessageUpdate) (*Message, error) + EditInteractionResponse(applicationID Snowflake, interactionToken string, messageUpdate MessageUpdate) (*Message, error) DeleteInteractionResponse(applicationID Snowflake, interactionToken string) error - SendFollowupMessage(applicationID Snowflake, interactionToken string, messageCreate WebhookMessageCreate) (*Message, error) - EditFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, messageUpdate WebhookMessageUpdate) (*Message, error) + SendFollowupMessage(applicationID Snowflake, interactionToken string, messageCreate MessageCreate) (*Message, error) + EditFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, messageUpdate MessageUpdate) (*Message, error) DeleteFollowupMessage(applicationID Snowflake, interactionToken string, followupMessageID Snowflake) error } diff --git a/api/webhook_message_create.go b/api/webhook_message_create.go deleted file mode 100644 index fea38ef5..00000000 --- a/api/webhook_message_create.go +++ /dev/null @@ -1,115 +0,0 @@ -package api - -import "fmt" - -// WebhookMessageCreate is used to add additional messages to an Interaction after you've responded initially -type WebhookMessageCreate struct { - TTS bool `json:"tts,omitempty"` - Content string `json:"content,omitempty"` - Embeds []Embed `json:"embeds,omitempty"` - Components []Component `json:"components,omitempty"` - AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` - Flags MessageFlags `json:"flags,omitempty"` -} - -// WebhookMessageCreateBuilder allows you to create an WebhookMessageCreate with ease -type WebhookMessageCreateBuilder struct { - WebhookMessageCreate -} - -// NewWebhookMessageCreateBuilder returns a new WebhookMessageCreateBuilder -func NewWebhookMessageCreateBuilder() *WebhookMessageCreateBuilder { - return &WebhookMessageCreateBuilder{ - WebhookMessageCreate: WebhookMessageCreate{ - AllowedMentions: &DefaultInteractionAllowedMentions, - }, - } -} - -// SetTTS sets if the WebhookMessageCreate is a tts message -func (b *WebhookMessageCreateBuilder) SetTTS(tts bool) *WebhookMessageCreateBuilder { - b.TTS = tts - return b -} - -// SetContent sets the content of the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) SetContent(content string) *WebhookMessageCreateBuilder { - b.Content = content - return b -} - -// SetContentf sets the content of the WebhookMessageCreate with format -func (b *WebhookMessageCreateBuilder) SetContentf(content string, a ...interface{}) *WebhookMessageCreateBuilder { - b.Content = fmt.Sprintf(content, a...) - return b -} - -// SetEmbeds sets the embeds of the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) SetEmbeds(embeds ...Embed) *WebhookMessageCreateBuilder { - b.Embeds = embeds - return b -} - -// AddEmbeds adds multiple embeds to the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) AddEmbeds(embeds ...Embed) *WebhookMessageCreateBuilder { - b.Embeds = append(b.Embeds, embeds...) - return b -} - -// ClearEmbeds removes all of the embeds from the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) ClearEmbeds() *WebhookMessageCreateBuilder { - b.Embeds = []Embed{} - return b -} - -// RemoveEmbed removes an embed from the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) RemoveEmbed(index int) *WebhookMessageCreateBuilder { - if b != nil && len(b.Embeds) > index { - b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) - } - return b -} - -// SetComponents sets the Component(s) of the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) SetComponents(components ...Component) *WebhookMessageCreateBuilder { - b.Components = components - return b -} - -// AddComponents adds the Component(s) to the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) AddComponents(components ...Component) *WebhookMessageCreateBuilder { - b.Components = append(b.Components, components...) - return b -} - -// SetAllowedMentions sets the allowed mentions of the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *WebhookMessageCreateBuilder { - b.AllowedMentions = allowedMentions - return b -} - -// SetAllowedMentionsEmpty sets the allowed mentions of the WebhookMessageCreate to nothing -func (b *WebhookMessageCreateBuilder) SetAllowedMentionsEmpty() *WebhookMessageCreateBuilder { - return b.SetAllowedMentions(&AllowedMentions{}) -} - -// SetFlags sets the message flags of the WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) SetFlags(flags MessageFlags) *WebhookMessageCreateBuilder { - b.Flags = flags - return b -} - -// SetEphemeral adds/removes MessageFlagEphemeral to the message flags -func (b *WebhookMessageCreateBuilder) SetEphemeral(ephemeral bool) *WebhookMessageCreateBuilder { - if ephemeral { - b.Flags = b.Flags.Add(MessageFlagEphemeral) - } else { - b.Flags = b.Flags.Remove(MessageFlagEphemeral) - } - return b -} - -// Build returns your built WebhookMessageCreate -func (b *WebhookMessageCreateBuilder) Build() WebhookMessageCreate { - return b.WebhookMessageCreate -} diff --git a/api/webhook_message_update.go b/api/webhook_message_update.go deleted file mode 100644 index 4b18644a..00000000 --- a/api/webhook_message_update.go +++ /dev/null @@ -1,146 +0,0 @@ -package api - -import ( - "encoding/json" - "fmt" -) - -// WebhookMessageUpdate is used to edit a WebhookMessage -type WebhookMessageUpdate struct { - Content string `json:"content"` - Components []Component `json:"components"` - Embeds []Embed `json:"embeds"` - AllowedMentions *AllowedMentions `json:"allowed_mentions"` - Flags MessageFlags `json:"flags"` - updateFlags updateFlags -} - -func (u WebhookMessageUpdate) isUpdated(flag updateFlags) bool { - return (u.updateFlags & flag) == flag -} - -// MarshalJSON marshals the WebhookMessageUpdate into json -func (u WebhookMessageUpdate) MarshalJSON() ([]byte, error) { - data := map[string]interface{}{} - - if u.isUpdated(updateFlagContent) { - data["content"] = u.Content - } - if u.isUpdated(updateFlagComponents) { - data["components"] = u.Components - } - if u.isUpdated(updateFlagEmbed) { - data["embeds"] = u.Embeds - } - if u.isUpdated(updateFlagAllowedMentions) { - data["allowed_mentions"] = u.AllowedMentions - } - if u.isUpdated(updateFlagFlags) { - data["flags"] = u.Flags - } - - return json.Marshal(data) -} - -// WebhookMessageUpdateBuilder helper to build WebhookMessageUpdate easier -type WebhookMessageUpdateBuilder struct { - WebhookMessageUpdate -} - -// NewWebhookMessageUpdateBuilder creates a new WebhookMessageUpdateBuilder to be built later -func NewWebhookMessageUpdateBuilder() *WebhookMessageUpdateBuilder { - return &WebhookMessageUpdateBuilder{ - WebhookMessageUpdate: WebhookMessageUpdate{ - AllowedMentions: &DefaultInteractionAllowedMentions, - }, - } -} - -// SetContent sets content of the Message -func (b *WebhookMessageUpdateBuilder) SetContent(content string) *WebhookMessageUpdateBuilder { - b.Content = content - b.updateFlags |= updateFlagContent - return b -} - -// SetContentf sets content of the Message -func (b *WebhookMessageUpdateBuilder) SetContentf(content string, a ...interface{}) *WebhookMessageUpdateBuilder { - return b.SetContent(fmt.Sprintf(content, a...)) -} - -// SetEmbeds sets the embeds of the WebhookMessageUpdate -func (b *WebhookMessageUpdateBuilder) SetEmbeds(embeds ...Embed) *WebhookMessageUpdateBuilder { - b.Embeds = embeds - b.updateFlags |= updateFlagEmbed - return b -} - -// AddEmbeds adds multiple embeds to the WebhookMessageUpdate -func (b *WebhookMessageUpdateBuilder) AddEmbeds(embeds ...Embed) *WebhookMessageUpdateBuilder { - b.Embeds = append(b.Embeds, embeds...) - b.updateFlags |= updateFlagEmbed - return b -} - -// ClearEmbeds removes all of the embeds from the WebhookMessageUpdate -func (b *WebhookMessageUpdateBuilder) ClearEmbeds() *WebhookMessageUpdateBuilder { - b.Embeds = []Embed{} - b.updateFlags |= updateFlagEmbed - return b -} - -// RemoveEmbed removes an embed from the WebhookMessageUpdate -func (b *WebhookMessageUpdateBuilder) RemoveEmbed(index int) *WebhookMessageUpdateBuilder { - if b != nil && len(b.Embeds) > index { - b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) - } - b.updateFlags |= updateFlagEmbed - return b -} - -// SetComponents sets the Component(s) of the Message -func (b *WebhookMessageUpdateBuilder) SetComponents(components ...Component) *WebhookMessageUpdateBuilder { - b.Components = components - b.updateFlags |= updateFlagComponents - return b -} - -// AddComponents adds the Component(s) to the Message -func (b *WebhookMessageUpdateBuilder) AddComponents(components ...Component) *WebhookMessageUpdateBuilder { - b.Components = append(b.Components, components...) - b.updateFlags |= updateFlagComponents - return b -} - -// ClearComponents removes all of the Component(s) of the Message -func (b *WebhookMessageUpdateBuilder) ClearComponents() *WebhookMessageUpdateBuilder { - b.Components = []Component{} - b.updateFlags |= updateFlagComponents - return b -} - -// RemoveComponent removes a Component from the Message -func (b *WebhookMessageUpdateBuilder) RemoveComponent(i int) *WebhookMessageUpdateBuilder { - if b != nil && len(b.Components) > i { - b.Components = append(b.Components[:i], b.Components[i+1:]...) - } - b.updateFlags |= updateFlagComponents - return b -} - -// SetAllowedMentions sets the AllowedMentions of the Message -func (b *WebhookMessageUpdateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *WebhookMessageUpdateBuilder { - b.AllowedMentions = allowedMentions - b.updateFlags |= updateFlagAllowedMentions - return b -} - -// ClearAllowedMentions clears the allowed mentions of the Message -func (b *WebhookMessageUpdateBuilder) ClearAllowedMentions() *WebhookMessageUpdateBuilder { - return b.SetAllowedMentions(&AllowedMentions{}) -} - -// Build builds the WebhookMessageUpdateBuilder to a WebhookMessageUpdate struct -func (b *WebhookMessageUpdateBuilder) Build() WebhookMessageUpdate { - return b.WebhookMessageUpdate -} diff --git a/example/examplebot.go b/example/examplebot.go index fb59525a..5420c2c4 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -184,7 +184,7 @@ func buttonClickListener(event events.ButtonClickEvent) { switch event.CustomID() { case "test1": _ = event.Respond(api.InteractionResponseTypeChannelMessageWithSource, - api.NewWebhookMessageCreateBuilder(). + api.NewMessageCreateBuilder(). SetContent(event.CustomID()). Build(), ) @@ -197,7 +197,7 @@ func buttonClickListener(event events.ButtonClickEvent) { case "test4": _ = event.Respond(api.InteractionResponseTypeUpdateMessage, - api.NewWebhookMessageCreateBuilder(). + api.NewMessageCreateBuilder(). SetContent(event.CustomID()). Build(), ) @@ -215,7 +215,7 @@ func commandListener(event events.CommandEvent) { AddField("Time", "...", true). AddField("Code", "```go\n"+code+"\n```", false). AddField("Output", "```\n...\n```", false) - _ = event.Reply(api.NewWebhookMessageCreateBuilder().SetEmbeds(embed.Build()).Build()) + _ = event.Reply(api.NewMessageCreateBuilder().SetEmbeds(embed.Build()).Build()) start := time.Now() output, err := gval.Evaluate(code, map[string]interface{}{ @@ -228,7 +228,7 @@ func commandListener(event events.CommandEvent) { embed.SetField(1, "Time", strconv.Itoa(int(elapsed.Milliseconds()))+"ms", true) if err != nil { - _, err = event.Interaction.EditOriginal(api.NewWebhookMessageUpdateBuilder(). + _, err = event.Interaction.EditOriginal(api.NewMessageUpdateBuilder(). SetEmbeds(embed. SetColor(red). SetField(0, "Status", "Failed", true). @@ -242,7 +242,7 @@ func commandListener(event events.CommandEvent) { } return } - _, err = event.Interaction.EditOriginal(api.NewWebhookMessageUpdateBuilder(). + _, err = event.Interaction.EditOriginal(api.NewMessageUpdateBuilder(). SetEmbeds(embed. SetColor(green). SetField(0, "Status", "Success", true). @@ -257,14 +257,14 @@ func commandListener(event events.CommandEvent) { }() case "say": - _ = event.Reply(api.NewWebhookMessageCreateBuilder(). + _ = event.Reply(api.NewMessageCreateBuilder(). SetContent(event.Option("message").String()). - SetAllowedMentionsEmpty(). + ClearAllowedMentions(). Build(), ) case "test": - _ = event.Reply(api.NewWebhookMessageCreateBuilder(). + _ = event.Reply(api.NewMessageCreateBuilder(). SetContent("test message"). SetEphemeral(true). SetComponents( @@ -283,11 +283,11 @@ func commandListener(event events.CommandEvent) { role := event.Option("role").Role() err := event.Disgo().RestClient().AddMemberRole(*event.Interaction.GuildID, user.ID, role.ID) if err == nil { - _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( + _ = event.Reply(api.NewMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(green).SetDescriptionf("Added %s to %s", role, user).Build(), ).Build()) } else { - _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( + _ = event.Reply(api.NewMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(red).SetDescriptionf("Failed to add %s to %s", role, user).Build(), ).Build()) } @@ -297,11 +297,11 @@ func commandListener(event events.CommandEvent) { role := event.Option("role").Role() err := event.Disgo().RestClient().RemoveMemberRole(*event.Interaction.GuildID, user.ID, role.ID) if err == nil { - _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( + _ = event.Reply(api.NewMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(65280).SetDescriptionf("Removed %s from %s", role, user).Build(), ).Build()) } else { - _ = event.Reply(api.NewWebhookMessageCreateBuilder().AddEmbeds( + _ = event.Reply(api.NewMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(16711680).SetDescriptionf("Failed to remove %s from %s", role, user).Build(), ).Build()) } @@ -329,11 +329,11 @@ func messageListener(event events.GuildMessageCreateEvent) { time.Sleep(time.Second * 2) - message, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbed(api.NewEmbedBuilder().SetDescription("edit").Build()).Build()) + message, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbeds(api.NewEmbedBuilder().SetDescription("edit").Build()).Build()) time.Sleep(time.Second * 2) - _, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("").SetEmbed(api.NewEmbedBuilder().SetDescription("edit2").Build()).Build()) + _, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("").SetEmbeds(api.NewEmbedBuilder().SetDescription("edit2").Build()).Build()) }() case "dm": diff --git a/example/go.sum b/example/go.sum index 7e9bfcca..eb77c93b 100644 --- a/example/go.sum +++ b/example/go.sum @@ -23,6 +23,7 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index e2a4470b..c5c6f837 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -214,7 +214,7 @@ func (r *RestClientImpl) AddMember(guildID api.Snowflake, userID api.Snowflake, return } -// KickMember kicks a member from the guild. requires api.PermissionKickMembers +// KickMember kicks a api.Member from the api.Guild. requires api.PermissionKickMembers func (r *RestClientImpl) KickMember(guildID api.Snowflake, userID api.Snowflake, reason *string) (err error) { var compiledRoute *restclient.CompiledAPIRoute var params map[string]interface{} @@ -232,7 +232,7 @@ func (r *RestClientImpl) KickMember(guildID api.Snowflake, userID api.Snowflake, return } -// UpdateMember updates a member +// UpdateMember updates a api.Member func (r *RestClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateGuildMemberData api.UpdateGuildMemberData) (member *api.Member, err error) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { @@ -245,7 +245,7 @@ func (r *RestClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflak return } -// MoveMember moves/kicks the member to/from a voice channel +// MoveMember moves/kicks the api.Member to/from a api.VoiceChannel func (r *RestClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, channelID *api.Snowflake) (member *api.Member, err error) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { @@ -258,7 +258,7 @@ func (r *RestClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, return } -// AddMemberRole adds a role to a member +// AddMemberRole adds a api.Rol to a api.Member func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (err error) { compiledRoute, err := restclient.AddMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { @@ -274,7 +274,7 @@ func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowfla return } -// RemoveMemberRole removes a role from a member +// RemoveMemberRole removes a api.Role(s) from a api.Member func (r *RestClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (err error) { compiledRoute, err := restclient.RemoveMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { @@ -295,7 +295,7 @@ func (r *RestClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snow return } -// GetRoles fetches all roles from a guild +// GetRoles fetches all api.Role(s) from a api.Guild func (r *RestClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, err error) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { @@ -364,7 +364,7 @@ func (r *RestClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) return } -// AddReaction lets you add a reaction to a message_events +// AddReaction lets you add a reaction to a api.Message func (r *RestClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) error { compiledRoute, err := restclient.AddReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { @@ -373,7 +373,7 @@ func (r *RestClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snow return r.Do(compiledRoute, nil, nil) } -// RemoveOwnReaction lets you remove your own reaction from a message_events +// RemoveOwnReaction lets you remove your own reaction from a api.Message func (r *RestClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) error { compiledRoute, err := restclient.RemoveOwnReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { @@ -382,7 +382,7 @@ func (r *RestClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID ap return r.Do(compiledRoute, nil, nil) } -// RemoveUserReaction lets you remove a specific reaction from a user from a message_events +// RemoveUserReaction lets you remove a specific reaction from a api.User from a api.Message func (r *RestClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string, userID api.Snowflake) error { compiledRoute, err := restclient.RemoveUserReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji), userID) if err != nil { @@ -391,7 +391,7 @@ func (r *RestClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID a return r.Do(compiledRoute, nil, nil) } -// GetGlobalCommands gets you all global commands +// GetGlobalCommands gets you all global api.Command(s) func (r *RestClientImpl) GetGlobalCommands(applicationID api.Snowflake) (commands []*api.Command, err error) { compiledRoute, err := restclient.GetGlobalCommands.Compile(nil, applicationID) if err != nil { @@ -406,7 +406,7 @@ func (r *RestClientImpl) GetGlobalCommands(applicationID api.Snowflake) (command return } -// GetGlobalCommand gets you a specific global global command +// GetGlobalCommand gets you a specific global global api.Command func (r *RestClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, err error) { compiledRoute, err := restclient.GetGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { @@ -419,7 +419,7 @@ func (r *RestClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID return } -// CreateGlobalCommand lets you create a new global command +// CreateGlobalCommand lets you create a new global api.Command func (r *RestClientImpl) CreateGlobalCommand(applicationID api.Snowflake, command api.CommandCreate) (cmd *api.Command, err error) { compiledRoute, err := restclient.CreateGlobalCommand.Compile(nil, applicationID) if err != nil { @@ -432,7 +432,7 @@ func (r *RestClientImpl) CreateGlobalCommand(applicationID api.Snowflake, comman return } -// SetGlobalCommands lets you override all global commands +// SetGlobalCommands lets you override all global api.Command func (r *RestClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, err error) { compiledRoute, err := restclient.SetGlobalCommands.Compile(nil, applicationID) if err != nil { @@ -451,7 +451,7 @@ func (r *RestClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands return } -// EditGlobalCommand lets you edit a specific global command +// EditGlobalCommand lets you edit a specific global api.Command func (r *RestClientImpl) EditGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, err error) { compiledRoute, err := restclient.UpdateGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { @@ -464,7 +464,7 @@ func (r *RestClientImpl) EditGlobalCommand(applicationID api.Snowflake, commandI return } -// DeleteGlobalCommand lets you delete a specific global command +// DeleteGlobalCommand lets you delete a specific global api.Command func (r *RestClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (err error) { compiledRoute, err := restclient.DeleteGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { @@ -477,7 +477,7 @@ func (r *RestClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, comman return } -// GetGuildCommands gets you all guild_events commands +// GetGuildCommands gets you all api.Command(s) from a api.Guild func (r *RestClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake) (commands []*api.Command, err error) { compiledRoute, err := restclient.GetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { @@ -492,7 +492,7 @@ func (r *RestClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID a return } -// CreateGuildCommand lets you create a new guild_events command +// CreateGuildCommand lets you create a new api.Command in a api.Guild func (r *RestClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, command api.CommandCreate) (cmd *api.Command, err error) { compiledRoute, err := restclient.CreateGuildCommand.Compile(nil, applicationID, guildID) if err != nil { @@ -505,7 +505,7 @@ func (r *RestClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID return } -// SetGuildCommands lets you override all guild_events commands +// SetGuildCommands lets you override all api.Command(s) in a api.Guild func (r *RestClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, err error) { compiledRoute, err := restclient.SetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { @@ -524,7 +524,7 @@ func (r *RestClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID a return } -// GetGuildCommand gets you a specific guild_events command +// GetGuildCommand gets you a specific api.Command in a api.Guild func (r *RestClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, err error) { compiledRoute, err := restclient.GetGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { @@ -537,7 +537,7 @@ func (r *RestClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID ap return } -// EditGuildCommand lets you edit a specific guild_events command +// EditGuildCommand lets you edit a specific api.Command in a api.Guild func (r *RestClientImpl) EditGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, err error) { compiledRoute, err := restclient.UpdateGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { @@ -550,7 +550,7 @@ func (r *RestClientImpl) EditGuildCommand(applicationID api.Snowflake, guildID a return } -// DeleteGuildCommand lets you delete a specific guild_events command +// DeleteGuildCommand lets you delete a specific api.Command in a api.Guild func (r *RestClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (err error) { compiledRoute, err := restclient.DeleteGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { @@ -563,7 +563,7 @@ func (r *RestClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID return } -// GetGuildCommandsPermissions returns the api.CommandPermission for a all api.Command(s) in a guild +// GetGuildCommandsPermissions returns the api.CommandPermission for a all api.Command(s) in a api.Guild func (r *RestClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake) (cmdsPerms []*api.GuildCommandPermissions, err error) { compiledRoute, err := restclient.GetGuildCommandPermissions.Compile(nil, applicationID, guildID) if err != nil { @@ -578,7 +578,7 @@ func (r *RestClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake return } -// GetGuildCommandPermissions returns the api.CommandPermission for a specific api.Command in a guild +// GetGuildCommandPermissions returns the api.CommandPermission for a specific api.Command in a api.Guild func (r *RestClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmdPerms *api.GuildCommandPermissions, err error) { compiledRoute, err := restclient.GetGuildCommandPermission.Compile(nil, applicationID, guildID, commandID) if err != nil { @@ -619,7 +619,7 @@ func (r *RestClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, return } -// SendInteractionResponse used to send the initial response on an interaction +// SendInteractionResponse used to send the initial response on an api.Interaction func (r *RestClientImpl) SendInteractionResponse(interactionID api.Snowflake, interactionToken string, interactionResponse api.InteractionResponse) error { compiledRoute, err := restclient.CreateInteractionResponse.Compile(nil, interactionID, interactionToken) if err != nil { @@ -628,8 +628,8 @@ func (r *RestClientImpl) SendInteractionResponse(interactionID api.Snowflake, in return r.Do(compiledRoute, interactionResponse, nil) } -// EditInteractionResponse used to edit the initial response on an interaction -func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, interactionToken string, messageUpdate api.WebhookMessageUpdate) (message *api.Message, err error) { +// EditInteractionResponse used to edit the initial response on an api.Interaction +func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, interactionToken string, messageUpdate api.MessageUpdate) (message *api.Message, err error) { compiledRoute, err := restclient.UpdateInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { return nil, err @@ -637,7 +637,7 @@ func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, in return message, r.Do(compiledRoute, messageUpdate, &message) } -// DeleteInteractionResponse used to delete the initial response on an interaction +// DeleteInteractionResponse used to delete the initial response on an api.Interaction func (r *RestClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, interactionToken string) error { compiledRoute, err := restclient.DeleteInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { @@ -646,8 +646,8 @@ func (r *RestClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, return r.Do(compiledRoute, nil, nil) } -// SendFollowupMessage used to send a followup message_events to an interaction -func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, messageCreate api.WebhookMessageCreate) (message *api.Message, err error) { +// SendFollowupMessage used to send a followup api.Message to an api.Interaction +func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, messageCreate api.MessageCreate) (message *api.Message, err error) { compiledRoute, err := restclient.CreateFollowupMessage.Compile(nil, applicationID, interactionToken) if err != nil { return nil, err @@ -655,8 +655,8 @@ func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, intera return message, r.Do(compiledRoute, messageCreate, &message) } -// EditFollowupMessage used to edit a api.WebhookMessageCreate from an api.Interaction -func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, messageUpdate api.WebhookMessageUpdate) (message *api.Message, err error) { +// EditFollowupMessage used to edit a followup api.Message from an api.Interaction +func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, err error) { compiledRoute, err := restclient.UpdateFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { return nil, err @@ -664,7 +664,7 @@ func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, intera return message, r.Do(compiledRoute, messageUpdate, &message) } -// DeleteFollowupMessage used to delete a api.WebhookMessageCreate from an api.Interaction +// DeleteFollowupMessage used to delete a followup api.Message from an api.Interaction func (r *RestClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake) error { compiledRoute, err := restclient.DeleteFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { From 3d6a673e89e526ef34b97d4a366609cc9b0998bc Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Thu, 10 Jun 2021 09:24:11 +0200 Subject: [PATCH 12/19] implement example with multiple embeds & go.sum update --- example/examplebot.go | 3 ++- example/go.sum | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/example/examplebot.go b/example/examplebot.go index 5420c2c4..0bc42428 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -329,7 +329,8 @@ func messageListener(event events.GuildMessageCreateEvent) { time.Sleep(time.Second * 2) - message, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbeds(api.NewEmbedBuilder().SetDescription("edit").Build()).Build()) + embed := api.NewEmbedBuilder().SetDescription("edit").Build() + message, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbeds(embed, embed).Build()) time.Sleep(time.Second * 2) diff --git a/example/go.sum b/example/go.sum index eb77c93b..7e9bfcca 100644 --- a/example/go.sum +++ b/example/go.sum @@ -23,7 +23,6 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From ff3e786f7f030b21159ead73e61e283696a90e83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?To=CF=80Senpai?= <15636011+TopiSenpai@users.noreply.github.com> Date: Thu, 10 Jun 2021 09:53:57 +0200 Subject: [PATCH 13/19] Update internal/restclient_impl.go Co-authored-by: Eve <46286597+EveCodes31@users.noreply.github.com> --- internal/restclient_impl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index c5c6f837..db51c321 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -258,7 +258,7 @@ func (r *RestClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, return } -// AddMemberRole adds a api.Rol to a api.Member +// AddMemberRole adds a api.Role to a api.Member func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (err error) { compiledRoute, err := restclient.AddMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { From ff02571e60bc2b4ef12cbcfd4ba4b5e443da7c6c Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 11 Jun 2021 02:55:26 +0200 Subject: [PATCH 14/19] wip file upload support --- api/message_create.go | 40 ++++++++++++++++++++++++++++- example/examplebot.go | 12 +++++++-- example/go.mod | 5 +++- example/go.sum | 3 +-- example/gopher.png | Bin 0 -> 5948 bytes go.mod | 4 +++ internal/restclient_impl.go | 49 +++++++++++++++++++++++++----------- 7 files changed, 93 insertions(+), 20 deletions(-) create mode 100644 example/gopher.png diff --git a/api/message_create.go b/api/message_create.go index 43636c70..585002ea 100644 --- a/api/message_create.go +++ b/api/message_create.go @@ -1,6 +1,11 @@ package api -import "fmt" +import ( + "fmt" + "io" + + "github.com/DisgoOrg/restclient" +) // MessageCreate is the struct to create a new Message with type MessageCreate struct { @@ -9,6 +14,7 @@ type MessageCreate struct { TTS bool `json:"tts,omitempty"` Embeds []Embed `json:"embeds,omitempty"` Components []Component `json:"components,omitempty"` + Files []restclient.File `json:"-"` AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` MessageReference *MessageReference `json:"message_reference,omitempty"` Flags MessageFlags `json:"flags,omitempty"` @@ -114,6 +120,38 @@ func (b *MessageCreateBuilder) RemoveComponent(i int) *MessageCreateBuilder { return b } +func (b *MessageCreateBuilder) SetFiles(files ...restclient.File) *MessageCreateBuilder { + b.Files = files + return b +} + +func (b *MessageCreateBuilder) AddFiles(files ...restclient.File) *MessageCreateBuilder { + b.Files = append(b.Files, files...) + return b +} + +func (b *MessageCreateBuilder) AddFile(name string, reader io.Reader, contentType string, flags ...restclient.FileFlags) *MessageCreateBuilder { + b.Files = append(b.Files, restclient.File{ + Name: name, + Reader: reader, + ContentType: contentType, + Flags: restclient.FileFlagNone.Add(flags...), + }) + return b +} + +func (b *MessageCreateBuilder) ClearFiles() *MessageCreateBuilder { + b.Files = []restclient.File{} + return b +} + +func (b *MessageCreateBuilder) RemoveFiles(i int) *MessageCreateBuilder { + if b != nil && len(b.Files) > i { + b.Files = append(b.Files[:i], b.Files[i+1:]...) + } + return b +} + // SetAllowedMentions sets the AllowedMentions of the Message func (b *MessageCreateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *MessageCreateBuilder { b.AllowedMentions = allowedMentions diff --git a/example/examplebot.go b/example/examplebot.go index 0bc42428..a86a82e7 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -325,8 +325,16 @@ func messageListener(event events.GuildMessageCreateEvent) { case "test": go func() { - message, _ := event.MessageChannel().SendMessage(api.NewMessageCreateBuilder().SetContent("test").Build()) - + reader, err := os.Open("example/gopher.png") + if err != nil { + logger.Errorf("error while opening file: %s", err) + return + } + message, err := event.MessageChannel().SendMessage(api.NewMessageCreateBuilder().SetContent("test").AddFile("gopher.png", reader, "image/png").Build()) + if err != nil { + logger.Errorf("error while sending file: %s", err) + return + } time.Sleep(time.Second * 2) embed := api.NewEmbedBuilder().SetDescription("edit").Build() diff --git a/example/go.mod b/example/go.mod index b1eb9510..f758f52d 100644 --- a/example/go.mod +++ b/example/go.mod @@ -2,7 +2,10 @@ module github.com/DisgoOrg/disgo/example go 1.16 -replace github.com/DisgoOrg/disgo => ../ +replace ( + github.com/DisgoOrg/disgo => ../ + github.com/DisgoOrg/restclient => ../../restclient +) require ( github.com/DisgoOrg/disgo v0.3.2 diff --git a/example/go.sum b/example/go.sum index 7e9bfcca..45dce8a0 100644 --- a/example/go.sum +++ b/example/go.sum @@ -1,7 +1,5 @@ github.com/DisgoOrg/log v1.0.3 h1:IjmZQQu/kuBIui22EdXmxzQGYwcPCJEkXa0Fe6W9fJk= github.com/DisgoOrg/log v1.0.3/go.mod h1:KFGKhBQr37d6rxZ7p2bmc8BEmDH8DZbtgdlJDSCsE7I= -github.com/DisgoOrg/restclient v1.1.4 h1:mjl6bRfq8Lj2n0zpMV4hcozVF1AQioG1huiJSs5ZSjY= -github.com/DisgoOrg/restclient v1.1.4/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= github.com/PaesslerAG/gval v1.1.1 h1:4d7pprU9876+m3rc08X33UjGip8oV1kkm8Gh5GBuTss= github.com/PaesslerAG/gval v1.1.1/go.mod h1:Fa8gfkCmUsELXgayr8sfL/sw+VzCVoa03dcOcR/if2w= github.com/PaesslerAG/jsonpath v0.1.0 h1:gADYeifvlqK3R3i2cR5B4DGgxLXIPb3TRTH1mGi0jPI= @@ -23,6 +21,7 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/example/gopher.png b/example/gopher.png new file mode 100644 index 0000000000000000000000000000000000000000..08ea25ee2ca97d2c74392296acd71d1597087bd4 GIT binary patch literal 5948 zcmV-C7sKd@P) z3ve6PbwDq6v5Uore~<)8@MDRxNJ+M(`lr~EEqf9>QBvELIuk2SW2JH2PTh{|wwZoB z9VgR?8_y);XvRr8<4oNoO&w3HSZZ23vK-r$C0mJQi;^XZswjz~_yGle01%(W?qboo z4_pug7a%|Yy9)|uW{1T7@D_XDd-vXV-+cfTDpaUYp+bcU6)IGyP@zJFYXy_u1y~8V zSM@yUUe&Wl?byi0fxROa2fnX;sdB@tcL8#NwOCygO>x=I;lrUJ?Mjq@qG*ogI2UKL zcXBp+m)beXF@fhjvK-^JF5^;^MGLU;j!(Z+>ulbZ?VNZ2>*tz33ziAXmdm+)@4t1A zZ*t<@(w8bf4BY}aYU(yRs_QngoYl3|xvutAyM-w4nZ7#q8!gI)-)D1Fuf_jsU2dpx zwE<0=0Zdflgt!c`m;`>$DEK@hP~X^cKf_v_-m&3VwJ2Y%7`g@MT6^O+yVlBb=ieIyc_F=$wnk-y`L%2tbi}WA8K2;O>Ikc78Rv zPvFB#_GFts{m`Xc?w`$MQ%pV7`qPh@8J4s}M}Gbzm>RwSpWE{-pv+7zU#UA~B>+fF z5+UrH0*12z!&xC7$F4XIw%P`eB@y^w0L%#hg<<AAj%mTpXI@DD&#)FSvlck?um1uQ z7tWG>SY9l5MF}h-m-~JPA|EFGZcVd$(XrVnkLq=5{j?g2$)<*4>ZN`kS5*V8JvV@f zN@)JAYi|I1ofBe`kWpzh8f7H_#}E80S+mrRW#X0x|0JjTV{OeO0IfYYE@*M~ed{lw zd37&z-E>=W-}-yLK>kL8ftu&~IO~ZnH$~|jb?gjU`Er1$$p5HqLXWsd5(yAcC=g)j+)<6AGP6g4BvJwEb zrhMW;Kk55X0MHynvv9f8w{{TQK9x-OTy@LVjQ61#2E<61bQ22G-tmJ*bOjqy2~-AI z(Ck9<3$<-DtI)hk2Q_ch{_ER1$>X3#zFZWGVj;`Brx@iS;2nqazk3%3kG%szG~$Vb zf`ccHyqQ^YbfBzS05#@KF{I7|Oz+Tq~_SyzwGSb0-D=x<+G$mt_6cmN1 zA?!s%wgB18z)V=@1i@%XLKH+HO3YL2su0hWi~l}w;)Aa)d9eo2dKVxabmdmpId89N zXxf6NS95nSxVqPY#pcL*9ophX1P6t1?njO@$T!v`@S~|KPbFW(aR~Q4J?89b%sit4S zs4W1POh8j+kmEAZQ>q%8fweopH+}^e3+JqDXu8Wk?L8{TVqrasSGeX>Bx)KO?@S#5 zTq#f#P0T`6FwtF%rmVAlH93Z@06sHqHfQhON{DVspv7u)Z@Tlo_mt0%Kf24g^^RK? z{19ZoC&l^ltIKl6`(f=uo1NuybNb{09|}Sv2e8$Z-_P{Acd_39P0Y9~lOPdP425tI zP954$x`b#XJi^XLniBUm3f8LiM$N*w|t~^v?)R3`oq%|I(<@vFIGeH*mgNYZ7FQ2nJASR0F7|OeRr9e{wz&_7vuj=0VsaqXw zZLLe5k3S}cdu79I7r|i$xGV_io*s_1yFyc`1}8cy*PD=mMu_0Ax9a3IUkS?2={< z_Q$N*M6S;Uc1QV^O}P%Y7ES;=C10BYpvKk7Dfs$R|D<|s%{@YLIb-(KBYOvd5 z@D*zaPEN05@OIRRutUOONiY;K?Tf#k_rG0 z>sHr0H@CUnYd7?+f!dnHfX%tVOGE%t>2S9~eQhGZ!qwy?KQ8`tH8qy9h(z13&r&I| zna3tPy*tA44PLsuU|;ujo#3$B$p7ijfUN+wG>vSGD1);S1(b<`I87HUh=ov60l+bR z9M!{Sf6wDzN$&sd5B_bD0PNcNhw#~Z6Mhh-X6=4>2RyoKM=6U4_qSzl`tilv?TZ~d zYBm3f$G%KzKBznc$8o^2GHi5+uHXv#P!WJ@9K#F;zr63) zaPYT>$^XHSE(2o)^MfD%M^XnUmuE1H01S_ek*%CbR|?Ak-2?#b_fB_<>ahqPg)z@n z&C8T8R?Y>|rxEtJfe2R^_01PYd6h&J8aTv`*b5U_lLDCYbO=&qLK z%){Awp^E_g?Gt}mbVrcZVEOWK1o1pigurO%)&v%B{9mKE{nAze4JmXNaQ5CpiP*MTFgb0|wZ{WlS zyWf8A*h@Gbu+(rc%)QJ&KwZ1W)&YI<(P)%xh4RxunG6UmH72l9(Zm&u`TKBY?8Qq% zp3`T~6Z5GM)M_Nw{As~NqHS`SCy3$NN=mm}!0*HFO$3hSj&dC-cRW!}zp(u1rDCH= z7l6qdapNPQmwtWd@NNtS%_SsE4g4{&PfiDeLn)fdd3rcT=0YCH97Ith8@4`l9)g3{ zC@mF6Fk?AsCJsiK$6`1gAXl&^c~SyvF%oz=GlcOv9%MKe6%;l7LamMhMAC6z5;+RKQ-#d>R4Wt!ZCS17K4-1B0xQcgJ(ZqOzFO| zg^6KTu}DWT!Lq{DONpieFns>ZbDk>~fAZ}2Tra!bZWnq4^8uSrg^-l^ADeRQ&oRUc z)3Ka9xG#Cm6JPr>bg$}wr=ETm>RLPCmIoeDy)T-J*mVp=1n`VXaH}(Wl#qgABId$} zlW~}e8fi9W0!;-V91INLcJ}`+@F6~bMNpXll8U0tB_@T;CeySbRq-&iSWOG|sX=D+ z&@_YviYRCz(Jz;_3KSDD7p9{CULJs3eg>P8pquT3nKDu{cw&y9T+_L!(LVSJj7<39 z)wfQm9`9Y%0{{5uUw{kH0fVN_toKR{7%kL9R032}6G^AD|JlDzCYaPZc|_Uj0BYE* zEP2stbhIX{4i2JF4}J)M9i$A8Pf_z3zeO3HOY_I-EGA%=&^1$As!$9ktr|5K%L)^K z&ejI_%+^g=&uN1RXp2w4ho&208r0LgrJ9J?bf@Yb_qQ!=DWsmyu;`XHmg1MniV}cW zOomW+epMEZV}UMUJRmjc1TOx7Ey7>`Es&)hIcSoa83riY*gvtcOP41xd7%KXjJY5I zSYWaVi7p}6Ify38WH^&gjTI#TqA0=D$@!d1m@9x)$sCGEj#yq#Ppi~soPvh=02LII zl#oN8kBK6%Wy#mQTufG!0H9qSjS9)nf*@t|4$67{=y)H~5;lC^;|p<_v?_Xz46GOd zxYGSaaKt0fEsm0DX1FQ5@Ud^v`4-Av@JLvAd=SpR`dwJNx*e`x-45Q)&q35)9$CT_ zbP<5+I_GAq-O**YP+(yhaM-P2x2iYQ#fH>m%2cpf792STa$o{F+%9l7)RG9NShgZGw#(x?!TB9<)fZj+%KflryaP`0~HB^S=3=m-`?T zj=;z|LnHys2~7pS>2g2hsHxxBT*uYc)mUN6?Hi!F+73;P^&m-8!1%*3Rnwc(y(lv8 z-VBl`&LxIIMcoV@x*j4S20Y^_%2~<_FVrlHrF>sHwY61Xw_73LJpmF^1>xFm)$>q! z#FR9cA#7%Bm@I-JiGpwB;<>#+|8!qL1Ds40OB#3B%>PX zKaor+FNvaW=-jDq7OkK;Vi+aR>8vF+DB?K`QMLxWbvNa3)tuMPH~}_ghhYT3!m?mt z0j$x{yso1R6kJh`7;bv_`rdBnb+NE!cpo(QGY{ip6NM0Nz|@R?(Rt{;MYGCg62KbuCO17GIRr5X zHG|@(1}QsZ0!zpPW>LTFAGx5Z0N}z&xVZDh@mbHnm09@DeQ(0CTH7! zW*XcRhm)HgDEWP3c|z^x*ejn z7KpJ6^CHIO#M1J3^XkTCvQ!0!G50qAZt-dIgz|7>a(5(MlUEA6x z!x0{QQ(kCuH9~V^{etswiZwQ;$~GV__OO*&07#ZF^c~D~1*zc6x3zS`>C%od`J-hT%iotL%8_SQOr}!;ZixWEc26|kpm@rpfq$>0)tT*h9*UL z>*y)cC8+U<&v9|(NJQ)~s%Z~}m}eL0{WQ0UUJ`Jnba z?e~1C;QQ7$wSE@2?OS`{hVF#Y>ksm-$$;=qDMH2#Cji$vP4y1AzM~PkJDbTU>D2V% zV3uN{yA@DjAh=m7cv(D@Zl$#H-YQ4elg4|O$msI9HZ z7|dF1DgvMf@?xiwnWmt_RZDUs;f!Od2#aCog6>u=nmVb=#qNCOg=ODMOC_)n(pL?` zg(A2(4^RKu{4%+-vq6$u@JGM=04A2#Up| zAog)FNg}aRxO^I)W9qhalHpr&EMx4x-jGGEvxG4#ITeLy#G^%dbQb{c*zl`p;&{i0 zUxhi7==b|xTKd8)NTNVi;?i?DHZ}0&W4Tgi6zk23>H^XslSX9O5Z!@N7NfDE1pwWx zh}8fBfMqdSiv%lO02ETaZZypRZPxCwaUttiOf+QehigRuQloAXK6dRMJ1)oa3Mtnb z-NynH7}nyX&1MJY4y4TtSRB=`=JsvSz4@M^eorFA+XO6U%`2NnJ}g`cHl8sB%qNFl zgOUC|hy-TvnvoMn-`tAUkSIhaOHwcu4ATPOLn{v+lSE<;iYZNZu}Hj(c)}cuo0gSe zdg1*RH|@EapwV!UJm*}wq*A(kGhrA3&>DeH2v;Ff$5E-%A|$<(7%s@2vpKrZ31YQZ zbu*lmBvRlU)g?>0MwW1gc*e*Z;#`svCS3YP5S(A%uf)>dPZ|So4)ZFugEj3n0re9{WT-9J-8uWjW?Tp}=FDql%bL3}*vW5{-n#BmoUFNm(1G zXo%5P5cn{Nkr0G@QxNvgNYO}mgpZJC)1}W($B->RI;aq$Vwk#b-L~z}d-wLt7wNzj z?gBXJAe=cnNV0@s=1}bOPrdmXIbO;+e#^y>EkHWc-tmK2YhZ5f98R6WqzbA1X(6kP zEEhV)gPorM&SD{{=`E&tJt7kD!^Pw8!OZAz;u)@v{U$W)Uz`p_XUakVFtv>GKehxY z0AmBE05=6a1b~%hp?T^!nZngrvoN_uz&j4_zwvtVGe-Gfpoiv#T!OL?05z`faKf6- zMzC3}K$~g!AjPiMiY5mQ?ll&OMnwn&!(g{^K+_8yN|TYfcxD*F%a|HXCKQfW24 zs}Rc83cweP+tk#|kSNn6pBg4o&~lVb8MXBJ{FgC{hqB)&BYhPrRH#s)LWK$yDpaUY ep+bcUsr)~6EESRHaz5_>0000 ../restclient +) + require ( github.com/DisgoOrg/log v1.0.3 github.com/DisgoOrg/restclient v1.1.4 diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index db51c321..87d29ca2 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -46,26 +46,37 @@ func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod // TODO reimplement api.ErrorResponse unmarshalling /* - var errorRs api.ErrorResponse - if err = json.Unmarshal(rawRsBody, &errorRs); err != nil { - r.Disgo().Logger().Errorf("error unmarshalling error response. code: %d, error: %s", rs.StatusCode, err) - return err - } - return fmt.Errorf("request to %s failed. statuscode: %d, errorcode: %d, message_events: %s", rq.URL, rs.StatusCode, errorRs.Code, errorRs.Message) + var errorRs api.ErrorResponse + if err = json.Unmarshal(rawRsBody, &errorRs); err != nil { + r.Disgo().Logger().Errorf("error unmarshalling error response. code: %d, error: %s", rs.StatusCode, err) + return err + } + return fmt.Errorf("request to %s failed. statuscode: %d, errorcode: %d, message_events: %s", rq.URL, rs.StatusCode, errorRs.Code, errorRs.Message) */ return } // SendMessage lets you send a api.Message to a api.MessageChannel -func (r *RestClientImpl) SendMessage(channelID api.Snowflake, message api.MessageCreate) (msg *api.Message, err error) { +func (r *RestClientImpl) SendMessage(channelID api.Snowflake, messageCreate api.MessageCreate) (message *api.Message, err error) { compiledRoute, err := restclient.CreateMessage.Compile(nil, channelID) if err != nil { return nil, err } - var fullMsg *api.FullMessage - err = r.Do(compiledRoute, message, &fullMsg) + + var body interface{} + if len(messageCreate.Files) > 0 { + body, err = restclient.PayloadWithFiles(messageCreate, messageCreate.Files...) + if err != nil { + return + } + } else { + body = messageCreate + } + + var fullMessage *api.FullMessage + err = r.Do(compiledRoute, body, &fullMessage) if err == nil { - msg = r.Disgo().EntityBuilder().CreateMessage(fullMsg, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } @@ -76,10 +87,10 @@ func (r *RestClientImpl) EditMessage(channelID api.Snowflake, messageID api.Snow if err != nil { return nil, err } - var fullMsg *api.FullMessage - err = r.Do(compiledRoute, message, &fullMsg) + var fullMessage *api.FullMessage + err = r.Do(compiledRoute, message, &fullMessage) if err == nil { - msg = r.Disgo().EntityBuilder().CreateMessage(fullMsg, api.CacheStrategyNoWs) + msg = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } @@ -652,7 +663,16 @@ func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, intera if err != nil { return nil, err } - return message, r.Do(compiledRoute, messageCreate, &message) + var body interface{} + if len(messageCreate.Files) > 0 { + body, err = restclient.PayloadWithFiles(messageCreate, messageCreate.Files...) + if err != nil { + return + } + } else { + body = messageCreate + } + return message, r.Do(compiledRoute, body, &message) } // EditFollowupMessage used to edit a followup api.Message from an api.Interaction @@ -676,3 +696,4 @@ func (r *RestClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, inte func normalizeEmoji(emoji string) string { return strings.Replace(emoji, "#", "%23", -1) } + From 4e1d084ce3b77a6f86e8348857a2673254737ba8 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 11 Jun 2021 18:56:54 +0200 Subject: [PATCH 15/19] file uplaod refactor --- api/interaction.go | 23 ++++++- api/message.go | 6 +- api/message_create.go | 16 +++-- api/message_update.go | 120 ++++++++++++++++++++++++++++-------- example/examplebot.go | 12 ++-- example/go.mod | 1 - go.mod | 5 +- internal/restclient_impl.go | 80 ++++++++++++++++-------- 8 files changed, 190 insertions(+), 73 deletions(-) diff --git a/api/interaction.go b/api/interaction.go index 7f0efe1a..6d6cff7b 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -3,6 +3,8 @@ package api import ( "encoding/json" "errors" + + "github.com/DisgoOrg/restclient" ) // InteractionType is the type of Interaction @@ -50,6 +52,23 @@ type InteractionResponse struct { Data interface{} `json:"data,omitempty"` } +func (r InteractionResponse) ToBody() (interface{}, error) { + if r.Data == nil { + return r, nil + } + switch v := r.Data.(type) { + case MessageCreate: + if len(v.Files) > 0 { + return restclient.PayloadWithFiles(r, v.Files...) + } + case MessageUpdate: + if len(v.Files) > 0 { + return restclient.PayloadWithFiles(r, v.Files...) + } + } + return r, nil +} + // Respond responds to the api.Interaction with the provided api.InteractionResponse func (i *Interaction) Respond(responseType InteractionResponseType, data interface{}) error { response := InteractionResponse{ @@ -71,9 +90,9 @@ func (i *Interaction) Respond(responseType InteractionResponseType, data interfa // DeferReply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource and shows a loading state func (i *Interaction) DeferReply(ephemeral bool) error { - var messageCreate *MessageCreate + var messageCreate interface{} if ephemeral { - messageCreate = &MessageCreate{Flags: MessageFlagEphemeral} + messageCreate = MessageCreate{Flags: MessageFlagEphemeral} } return i.Respond(InteractionResponseTypeDeferredChannelMessageWithSource, messageCreate) } diff --git a/api/message.go b/api/message.go index 19f3155f..e1b6bc14 100644 --- a/api/message.go +++ b/api/message.go @@ -99,8 +99,8 @@ func (f MessageFlags) Missing(bit MessageFlags) bool { return !f.Has(bit) } -//MessageAttachment is used for files sent in a Message -type MessageAttachment struct { +//Attachment is used for files sent in a Message +type Attachment struct { ID Snowflake `json:"id,omitempty"` Filename string `json:"filename"` Size int `json:"size"` @@ -163,7 +163,7 @@ type Message struct { ID Snowflake `json:"id"` GuildID *Snowflake `json:"guild_id"` Reactions []MessageReaction `json:"reactions"` - Attachments []MessageAttachment `json:"attachments"` + Attachments []Attachment `json:"attachments"` TTS bool `json:"tts"` Embeds []Embed `json:"embeds,omitempty"` Components []Component `json:"components,omitempty"` diff --git a/api/message_create.go b/api/message_create.go index 585002ea..f80e3c70 100644 --- a/api/message_create.go +++ b/api/message_create.go @@ -20,6 +20,13 @@ type MessageCreate struct { Flags MessageFlags `json:"flags,omitempty"` } +func (m MessageCreate) ToBody() (interface{}, error) { + if len(m.Files) > 0 { + return restclient.PayloadWithFiles(m, m.Files...) + } + return m, nil +} + // MessageCreateBuilder helper to build Message(s) easier type MessageCreateBuilder struct { MessageCreate @@ -130,12 +137,11 @@ func (b *MessageCreateBuilder) AddFiles(files ...restclient.File) *MessageCreate return b } -func (b *MessageCreateBuilder) AddFile(name string, reader io.Reader, contentType string, flags ...restclient.FileFlags) *MessageCreateBuilder { +func (b *MessageCreateBuilder) AddFile(name string, reader io.Reader, flags ...restclient.FileFlags) *MessageCreateBuilder { b.Files = append(b.Files, restclient.File{ - Name: name, - Reader: reader, - ContentType: contentType, - Flags: restclient.FileFlagNone.Add(flags...), + Name: name, + Reader: reader, + Flags: restclient.FileFlagNone.Add(flags...), }) return b } diff --git a/api/message_update.go b/api/message_update.go index 8e184a33..7d97cb2f 100644 --- a/api/message_update.go +++ b/api/message_update.go @@ -3,6 +3,9 @@ package api import ( "encoding/json" "fmt" + "io" + + "github.com/DisgoOrg/restclient" ) type updateFlags int @@ -10,43 +13,57 @@ type updateFlags int const ( updateFlagContent = 1 << iota updateFlagComponents - updateFlagEmbed - updateFlagFlags + updateFlagEmbeds + updateFlagFiles + updateFlagRetainAttachment updateFlagAllowedMentions + updateFlagFlags ) // MessageUpdate is used to edit a Message type MessageUpdate struct { - Content string `json:"content"` - Embeds []Embed `json:"embeds"` - Components []Component `json:"components"` - AllowedMentions *AllowedMentions `json:"allowed_mentions"` - Flags MessageFlags `json:"flags"` + Content string `json:"content"` + Embeds []Embed `json:"embeds"` + Components []Component `json:"components"` + Attachments []Attachment `json:"attachments"` + Files []restclient.File `json:"-"` + AllowedMentions *AllowedMentions `json:"allowed_mentions"` + Flags MessageFlags `json:"flags"` updateFlags updateFlags } -func (u MessageUpdate) isUpdated(flag updateFlags) bool { - return (u.updateFlags & flag) == flag +func (m MessageUpdate) ToBody() (interface{}, error) { + if len(m.Files) > 0 && m.isUpdated(updateFlagFiles) { + return restclient.PayloadWithFiles(m, m.Files...) + } + return m, nil +} + +func (m MessageUpdate) isUpdated(flag updateFlags) bool { + return (m.updateFlags & flag) == flag } // MarshalJSON marshals the MessageUpdate into json -func (u MessageUpdate) MarshalJSON() ([]byte, error) { +func (m MessageUpdate) MarshalJSON() ([]byte, error) { data := map[string]interface{}{} - if u.isUpdated(updateFlagContent) { - data["content"] = u.Content + if m.isUpdated(updateFlagContent) { + data["content"] = m.Content } - if u.isUpdated(updateFlagEmbed) { - data["embeds"] = u.Embeds + if m.isUpdated(updateFlagEmbeds) { + data["embeds"] = m.Embeds } - if u.isUpdated(updateFlagComponents) { - data["components"] = u.Components + if m.isUpdated(updateFlagComponents) { + data["components"] = m.Components } - if u.isUpdated(updateFlagAllowedMentions) { - data["allowed_mentions"] = u.AllowedMentions + if m.isUpdated(updateFlagRetainAttachment) { + data["attachments"] = m.Attachments } - if u.isUpdated(updateFlagFlags) { - data["flags"] = u.Flags + if m.isUpdated(updateFlagAllowedMentions) { + data["allowed_mentions"] = m.AllowedMentions + } + if m.isUpdated(updateFlagFlags) { + data["flags"] = m.Flags } return json.Marshal(data) @@ -81,21 +98,21 @@ func (b *MessageUpdateBuilder) SetContentf(content string, a ...interface{}) *Me // SetEmbeds sets the embeds of the Message func (b *MessageUpdateBuilder) SetEmbeds(embeds ...Embed) *MessageUpdateBuilder { b.Embeds = embeds - b.updateFlags |= updateFlagEmbed + b.updateFlags |= updateFlagEmbeds return b } // AddEmbeds adds multiple embeds to the Message func (b *MessageUpdateBuilder) AddEmbeds(embeds ...Embed) *MessageUpdateBuilder { b.Embeds = append(b.Embeds, embeds...) - b.updateFlags |= updateFlagEmbed + b.updateFlags |= updateFlagEmbeds return b } // ClearEmbeds removes all of the embeds from the Message func (b *MessageUpdateBuilder) ClearEmbeds() *MessageUpdateBuilder { b.Embeds = []Embed{} - b.updateFlags |= updateFlagEmbed + b.updateFlags |= updateFlagEmbeds return b } @@ -104,7 +121,7 @@ func (b *MessageUpdateBuilder) RemoveEmbed(index int) *MessageUpdateBuilder { if b != nil && len(b.Embeds) > index { b.Embeds = append(b.Embeds[:index], b.Embeds[index+1:]...) } - b.updateFlags |= updateFlagEmbed + b.updateFlags |= updateFlagEmbeds return b } @@ -131,13 +148,65 @@ func (b *MessageUpdateBuilder) ClearComponents() *MessageUpdateBuilder { // RemoveComponent removes a Component from the Message func (b *MessageUpdateBuilder) RemoveComponent(i int) *MessageUpdateBuilder { - if b != nil && len(b.Components) > i { + if len(b.Components) > i { b.Components = append(b.Components[:i], b.Components[i+1:]...) } b.updateFlags |= updateFlagComponents return b } +func (b *MessageUpdateBuilder) SetFiles(files ...restclient.File) *MessageUpdateBuilder { + b.Files = files + b.updateFlags |= updateFlagFiles + return b +} + +func (b *MessageUpdateBuilder) AddFiles(files ...restclient.File) *MessageUpdateBuilder { + b.Files = append(b.Files, files...) + b.updateFlags |= updateFlagFiles + return b +} + +func (b *MessageUpdateBuilder) AddFile(name string, reader io.Reader, flags ...restclient.FileFlags) *MessageUpdateBuilder { + b.Files = append(b.Files, restclient.File{ + Name: name, + Reader: reader, + Flags: restclient.FileFlagNone.Add(flags...), + }) + b.updateFlags |= updateFlagFiles + return b +} + +func (b *MessageUpdateBuilder) ClearFiles() *MessageUpdateBuilder { + b.Files = []restclient.File{} + b.updateFlags |= updateFlagFiles + return b +} + +func (b *MessageUpdateBuilder) RemoveFiles(i int) *MessageUpdateBuilder { + if len(b.Files) > i { + b.Files = append(b.Files[:i], b.Files[i+1:]...) + } + b.updateFlags |= updateFlagFiles + return b +} + +func (b *MessageUpdateBuilder) RetainAttachments(attachments ...Attachment) *MessageUpdateBuilder { + b.Attachments = append(b.Attachments, attachments...) + b.updateFlags |= updateFlagRetainAttachment + return b +} + +func (b *MessageUpdateBuilder) RetainAttachmentsByID(attachmentIDs ...Snowflake) *MessageUpdateBuilder { + for _, attachmentID := range attachmentIDs { + b.Attachments = append(b.Attachments, Attachment{ + ID: attachmentID, + }) + } + b.updateFlags |= updateFlagRetainAttachment + return b +} + // SetAllowedMentions sets the AllowedMentions of the Message func (b *MessageUpdateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *MessageUpdateBuilder { b.AllowedMentions = allowedMentions @@ -156,7 +225,6 @@ func (b *MessageUpdateBuilder) SetFlags(flags MessageFlags) *MessageUpdateBuilde return b } - // Build builds the MessageUpdateBuilder to a MessageUpdate struct func (b *MessageUpdateBuilder) Build() MessageUpdate { return b.MessageUpdate diff --git a/example/examplebot.go b/example/examplebot.go index a86a82e7..e121adda 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -164,7 +164,7 @@ func main() { defer dgo.Close() - logger.Infof("TestBot is now running. Press CTRL-C to exit.") + logger.Infof("ExampleBot is now running. Press CTRL-C to exit.") s := make(chan os.Signal, 1) signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill) <-s @@ -264,9 +264,10 @@ func commandListener(event events.CommandEvent) { ) case "test": + reader, _ := os.Open("gopher.png") _ = event.Reply(api.NewMessageCreateBuilder(). SetContent("test message"). - SetEphemeral(true). + AddFile("gopher.png", reader). SetComponents( api.NewActionRow( api.NewPrimaryButton("test1", "test1", nil, false), @@ -325,12 +326,7 @@ func messageListener(event events.GuildMessageCreateEvent) { case "test": go func() { - reader, err := os.Open("example/gopher.png") - if err != nil { - logger.Errorf("error while opening file: %s", err) - return - } - message, err := event.MessageChannel().SendMessage(api.NewMessageCreateBuilder().SetContent("test").AddFile("gopher.png", reader, "image/png").Build()) + message, err := event.MessageChannel().SendMessage(api.NewMessageCreateBuilder().SetContent("test").Build()) if err != nil { logger.Errorf("error while sending file: %s", err) return diff --git a/example/go.mod b/example/go.mod index f758f52d..e3505594 100644 --- a/example/go.mod +++ b/example/go.mod @@ -4,7 +4,6 @@ go 1.16 replace ( github.com/DisgoOrg/disgo => ../ - github.com/DisgoOrg/restclient => ../../restclient ) require ( diff --git a/go.mod b/go.mod index d8da2717..b048d913 100644 --- a/go.mod +++ b/go.mod @@ -2,13 +2,10 @@ module github.com/DisgoOrg/disgo go 1.16 -replace ( - github.com/DisgoOrg/restclient => ../restclient -) require ( github.com/DisgoOrg/log v1.0.3 - github.com/DisgoOrg/restclient v1.1.4 + github.com/DisgoOrg/restclient v1.1.5 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/stretchr/testify v1.7.0 diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 87d29ca2..f4befccc 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -63,14 +63,9 @@ func (r *RestClientImpl) SendMessage(channelID api.Snowflake, messageCreate api. return nil, err } - var body interface{} - if len(messageCreate.Files) > 0 { - body, err = restclient.PayloadWithFiles(messageCreate, messageCreate.Files...) - if err != nil { - return - } - } else { - body = messageCreate + body, err := messageCreate.ToBody() + if err != nil { + return nil, err } var fullMessage *api.FullMessage @@ -82,15 +77,21 @@ func (r *RestClientImpl) SendMessage(channelID api.Snowflake, messageCreate api. } // EditMessage lets you edit a api.Message -func (r *RestClientImpl) EditMessage(channelID api.Snowflake, messageID api.Snowflake, message api.MessageUpdate) (msg *api.Message, err error) { +func (r *RestClientImpl) EditMessage(channelID api.Snowflake, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, err error) { compiledRoute, err := restclient.UpdateMessage.Compile(nil, channelID, messageID) if err != nil { return nil, err } + + body, err := messageUpdate.ToBody() + if err != nil { + return nil, err + } + var fullMessage *api.FullMessage - err = r.Do(compiledRoute, message, &fullMessage) + err = r.Do(compiledRoute, body, &fullMessage) if err == nil { - msg = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } @@ -636,7 +637,13 @@ func (r *RestClientImpl) SendInteractionResponse(interactionID api.Snowflake, in if err != nil { return err } - return r.Do(compiledRoute, interactionResponse, nil) + + body, err := interactionResponse.ToBody() + if err != nil { + return err + } + + return r.Do(compiledRoute, body, nil) } // EditInteractionResponse used to edit the initial response on an api.Interaction @@ -645,7 +652,18 @@ func (r *RestClientImpl) EditInteractionResponse(applicationID api.Snowflake, in if err != nil { return nil, err } - return message, r.Do(compiledRoute, messageUpdate, &message) + + body, err := messageUpdate.ToBody() + if err != nil { + return nil, err + } + + var fullMessage *api.FullMessage + err = r.Do(compiledRoute, body, &fullMessage) + if err == nil { + message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + } + return } // DeleteInteractionResponse used to delete the initial response on an api.Interaction @@ -663,16 +681,19 @@ func (r *RestClientImpl) SendFollowupMessage(applicationID api.Snowflake, intera if err != nil { return nil, err } - var body interface{} - if len(messageCreate.Files) > 0 { - body, err = restclient.PayloadWithFiles(messageCreate, messageCreate.Files...) - if err != nil { - return - } - } else { - body = messageCreate + + body, err := messageCreate.ToBody() + if err != nil { + return nil, err } - return message, r.Do(compiledRoute, body, &message) + + var fullMessage *api.FullMessage + err = r.Do(compiledRoute, body, &fullMessage) + if err == nil { + message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + } + + return } // EditFollowupMessage used to edit a followup api.Message from an api.Interaction @@ -681,7 +702,19 @@ func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, intera if err != nil { return nil, err } - return message, r.Do(compiledRoute, messageUpdate, &message) + + body, err := messageUpdate.ToBody() + if err != nil { + return nil, err + } + + var fullMessage *api.FullMessage + err = r.Do(compiledRoute, body, &fullMessage) + if err == nil { + message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + } + + return } // DeleteFollowupMessage used to delete a followup api.Message from an api.Interaction @@ -696,4 +729,3 @@ func (r *RestClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, inte func normalizeEmoji(emoji string) string { return strings.Replace(emoji, "#", "%23", -1) } - From d085caeb2d4d4527f022f4aee735b2b4f9803a47 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 12 Jun 2021 01:38:32 +0200 Subject: [PATCH 16/19] updated restclient --- example/go.mod | 4 +--- example/go.sum | 2 ++ go.mod | 1 - go.sum | 4 ++-- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/example/go.mod b/example/go.mod index e3505594..b1eb9510 100644 --- a/example/go.mod +++ b/example/go.mod @@ -2,9 +2,7 @@ module github.com/DisgoOrg/disgo/example go 1.16 -replace ( - github.com/DisgoOrg/disgo => ../ -) +replace github.com/DisgoOrg/disgo => ../ require ( github.com/DisgoOrg/disgo v0.3.2 diff --git a/example/go.sum b/example/go.sum index 45dce8a0..da0ba1cf 100644 --- a/example/go.sum +++ b/example/go.sum @@ -1,5 +1,7 @@ github.com/DisgoOrg/log v1.0.3 h1:IjmZQQu/kuBIui22EdXmxzQGYwcPCJEkXa0Fe6W9fJk= github.com/DisgoOrg/log v1.0.3/go.mod h1:KFGKhBQr37d6rxZ7p2bmc8BEmDH8DZbtgdlJDSCsE7I= +github.com/DisgoOrg/restclient v1.1.5 h1:qjYNUeFo2NcqaMS+lLxyQIwED1gomn5TIub88wrA2mI= +github.com/DisgoOrg/restclient v1.1.5/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= github.com/PaesslerAG/gval v1.1.1 h1:4d7pprU9876+m3rc08X33UjGip8oV1kkm8Gh5GBuTss= github.com/PaesslerAG/gval v1.1.1/go.mod h1:Fa8gfkCmUsELXgayr8sfL/sw+VzCVoa03dcOcR/if2w= github.com/PaesslerAG/jsonpath v0.1.0 h1:gADYeifvlqK3R3i2cR5B4DGgxLXIPb3TRTH1mGi0jPI= diff --git a/go.mod b/go.mod index b048d913..fbb451bd 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,6 @@ module github.com/DisgoOrg/disgo go 1.16 - require ( github.com/DisgoOrg/log v1.0.3 github.com/DisgoOrg/restclient v1.1.5 diff --git a/go.sum b/go.sum index 6bb9bf7b..7ede71b2 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/DisgoOrg/log v1.0.3 h1:IjmZQQu/kuBIui22EdXmxzQGYwcPCJEkXa0Fe6W9fJk= github.com/DisgoOrg/log v1.0.3/go.mod h1:KFGKhBQr37d6rxZ7p2bmc8BEmDH8DZbtgdlJDSCsE7I= -github.com/DisgoOrg/restclient v1.1.4 h1:mjl6bRfq8Lj2n0zpMV4hcozVF1AQioG1huiJSs5ZSjY= -github.com/DisgoOrg/restclient v1.1.4/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= +github.com/DisgoOrg/restclient v1.1.5 h1:qjYNUeFo2NcqaMS+lLxyQIwED1gomn5TIub88wrA2mI= +github.com/DisgoOrg/restclient v1.1.5/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= From a676751d0995ba2d737a5ce9646fd197f2d7f352 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 12 Jun 2021 02:18:46 +0200 Subject: [PATCH 17/19] added missing docs --- api/interaction.go | 1 + api/message_create.go | 6 ++++++ api/message_update.go | 8 ++++++++ 3 files changed, 15 insertions(+) diff --git a/api/interaction.go b/api/interaction.go index 6d6cff7b..5cb360b0 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -52,6 +52,7 @@ type InteractionResponse struct { Data interface{} `json:"data,omitempty"` } +// ToBody returns the InteractionResponse ready for body func (r InteractionResponse) ToBody() (interface{}, error) { if r.Data == nil { return r, nil diff --git a/api/message_create.go b/api/message_create.go index f80e3c70..34425283 100644 --- a/api/message_create.go +++ b/api/message_create.go @@ -20,6 +20,7 @@ type MessageCreate struct { Flags MessageFlags `json:"flags,omitempty"` } +// ToBody returns the MessageCreate ready for body func (m MessageCreate) ToBody() (interface{}, error) { if len(m.Files) > 0 { return restclient.PayloadWithFiles(m, m.Files...) @@ -127,16 +128,19 @@ func (b *MessageCreateBuilder) RemoveComponent(i int) *MessageCreateBuilder { return b } +// SetFiles sets the files for this WebhookMessageCreate func (b *MessageCreateBuilder) SetFiles(files ...restclient.File) *MessageCreateBuilder { b.Files = files return b } +// AddFiles adds the files to the WebhookMessageCreate func (b *MessageCreateBuilder) AddFiles(files ...restclient.File) *MessageCreateBuilder { b.Files = append(b.Files, files...) return b } +// AddFile adds a file to the WebhookMessageCreate func (b *MessageCreateBuilder) AddFile(name string, reader io.Reader, flags ...restclient.FileFlags) *MessageCreateBuilder { b.Files = append(b.Files, restclient.File{ Name: name, @@ -146,11 +150,13 @@ func (b *MessageCreateBuilder) AddFile(name string, reader io.Reader, flags ...r return b } +// ClearFiles removes all files of this WebhookMessageCreate func (b *MessageCreateBuilder) ClearFiles() *MessageCreateBuilder { b.Files = []restclient.File{} return b } +// RemoveFiles removes the file at this index func (b *MessageCreateBuilder) RemoveFiles(i int) *MessageCreateBuilder { if b != nil && len(b.Files) > i { b.Files = append(b.Files[:i], b.Files[i+1:]...) diff --git a/api/message_update.go b/api/message_update.go index 7d97cb2f..58ce9ada 100644 --- a/api/message_update.go +++ b/api/message_update.go @@ -32,6 +32,7 @@ type MessageUpdate struct { updateFlags updateFlags } +// ToBody returns the MessageUpdate ready for body func (m MessageUpdate) ToBody() (interface{}, error) { if len(m.Files) > 0 && m.isUpdated(updateFlagFiles) { return restclient.PayloadWithFiles(m, m.Files...) @@ -155,18 +156,21 @@ func (b *MessageUpdateBuilder) RemoveComponent(i int) *MessageUpdateBuilder { return b } +// SetFiles sets the files for this Message func (b *MessageUpdateBuilder) SetFiles(files ...restclient.File) *MessageUpdateBuilder { b.Files = files b.updateFlags |= updateFlagFiles return b } +// AddFiles adds the files to the Message func (b *MessageUpdateBuilder) AddFiles(files ...restclient.File) *MessageUpdateBuilder { b.Files = append(b.Files, files...) b.updateFlags |= updateFlagFiles return b } +// AddFile adds a file to the Message func (b *MessageUpdateBuilder) AddFile(name string, reader io.Reader, flags ...restclient.FileFlags) *MessageUpdateBuilder { b.Files = append(b.Files, restclient.File{ Name: name, @@ -177,12 +181,14 @@ func (b *MessageUpdateBuilder) AddFile(name string, reader io.Reader, flags ...r return b } +// ClearFiles removes all files of this Message func (b *MessageUpdateBuilder) ClearFiles() *MessageUpdateBuilder { b.Files = []restclient.File{} b.updateFlags |= updateFlagFiles return b } +// RemoveFiles removes the file at this index func (b *MessageUpdateBuilder) RemoveFiles(i int) *MessageUpdateBuilder { if len(b.Files) > i { b.Files = append(b.Files[:i], b.Files[i+1:]...) @@ -191,12 +197,14 @@ func (b *MessageUpdateBuilder) RemoveFiles(i int) *MessageUpdateBuilder { return b } +// RetainAttachments removes all Attachment(s) from this Message except the ones provided func (b *MessageUpdateBuilder) RetainAttachments(attachments ...Attachment) *MessageUpdateBuilder { b.Attachments = append(b.Attachments, attachments...) b.updateFlags |= updateFlagRetainAttachment return b } +// RetainAttachmentsByID removes all Attachment(s) from this Message except the ones provided func (b *MessageUpdateBuilder) RetainAttachmentsByID(attachmentIDs ...Snowflake) *MessageUpdateBuilder { for _, attachmentID := range attachmentIDs { b.Attachments = append(b.Attachments, Attachment{ From 39451571616ef7d81e6d9aa8ffd21740bdd83cce Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 12 Jun 2021 02:20:04 +0200 Subject: [PATCH 18/19] fixed method name --- internal/restclient_impl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index f4befccc..aedd8f37 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -31,7 +31,7 @@ func (r *RestClientImpl) Disgo() api.Disgo { // Close cleans up the http managers connections func (r *RestClientImpl) Close() { - r.HttpClient().CloseIdleConnections() + r.HTTPClient().CloseIdleConnections() } // DoWithHeaders executes a rest request with custom headers From 249f061c3a78952a26899e58a487c3b71bbf404d Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sun, 13 Jun 2021 03:59:27 +0200 Subject: [PATCH 19/19] added generic guild channel event & added webhooks update event --- api/disgo_builder.go | 2 +- api/events/category_events.go | 2 +- api/events/channel_events.go | 6 +- api/events/guild_channel_events.go | 31 +++++++++++ api/events/guild_events.go | 3 +- api/events/listener_adapter.go | 24 ++++++++ api/events/store_channel_events.go | 2 +- api/events/text_channel_events.go | 7 ++- api/events/voice_channel_events.go | 2 +- example/examplebot.go | 2 +- internal/disgo_builder_impl.go | 4 +- internal/handlers/all_handlers.go | 2 + internal/handlers/channel_create_handler.go | 35 +++++++++--- internal/handlers/channel_delete_handler.go | 35 +++++++++--- internal/handlers/channel_update_handler.go | 36 +++++++++--- internal/handlers/guild_create_handler.go | 1 + .../handlers/guild_role_create_handler.go | 4 -- .../handlers/voice_state_update_handler.go | 2 +- internal/handlers/webhooks_update_handler.go | 55 +++++++++++++++++++ internal/util.go | 1 + 20 files changed, 213 insertions(+), 43 deletions(-) create mode 100644 api/events/guild_channel_events.go diff --git a/api/disgo_builder.go b/api/disgo_builder.go index a9b0620b..4076a3f8 100644 --- a/api/disgo_builder.go +++ b/api/disgo_builder.go @@ -11,7 +11,7 @@ type DisgoBuilder interface { SetLogger(level log.Logger) DisgoBuilder SetToken(token string) DisgoBuilder SetHTTPClient(httpClient *http.Client) DisgoBuilder - SetGatewayIntents(GatewayIntents GatewayIntents) DisgoBuilder + SetGatewayIntents(GatewayIntents ...GatewayIntents) DisgoBuilder SetRawGatewayEventsEnabled(enabled bool) DisgoBuilder SetVoiceDispatchInterceptor(voiceDispatchInterceptor VoiceDispatchInterceptor) DisgoBuilder SetEntityBuilder(entityBuilder EntityBuilder) DisgoBuilder diff --git a/api/events/category_events.go b/api/events/category_events.go index 722cb544..90e17e07 100644 --- a/api/events/category_events.go +++ b/api/events/category_events.go @@ -6,7 +6,7 @@ import ( // GenericCategoryEvent is called upon receiving CategoryCreateEvent, CategoryUpdateEvent or CategoryDeleteEvent type GenericCategoryEvent struct { - GenericChannelEvent + GenericGuildChannelEvent Category *api.Category } diff --git a/api/events/channel_events.go b/api/events/channel_events.go index 949a1523..6e2f0d85 100644 --- a/api/events/channel_events.go +++ b/api/events/channel_events.go @@ -8,9 +8,5 @@ import ( type GenericChannelEvent struct { GenericEvent ChannelID api.Snowflake -} - -// Channel returns the api.Channel from the api.Cache if cached -func (e GenericChannelEvent) Channel() *api.Channel { - return e.Disgo().Cache().Channel(e.ChannelID) + Channel *api.Channel } diff --git a/api/events/guild_channel_events.go b/api/events/guild_channel_events.go new file mode 100644 index 00000000..5d430147 --- /dev/null +++ b/api/events/guild_channel_events.go @@ -0,0 +1,31 @@ +package events + +import "github.com/DisgoOrg/disgo/api" + +// GenericGuildChannelEvent is called upon receiving GuildChannelCreateEvent, GuildChannelUpdateEvent or GuildChannelDeleteEvent +type GenericGuildChannelEvent struct { + GenericChannelEvent + GuildID api.Snowflake + GuildChannel *api.GuildChannel +} + +// Guild returns the cached api.Guild the event happened in +func (e GenericGuildChannelEvent) Guild() *api.Guild { + return e.Disgo().Cache().Guild(e.GuildID) +} + +// GuildChannelCreateEvent indicates that a new api.GuildChannel got created in a api.Guild +type GuildChannelCreateEvent struct { + GenericGuildChannelEvent +} + +// GuildChannelUpdateEvent indicates that a api.GuildChannel got updated in a api.Guild +type GuildChannelUpdateEvent struct { + GenericGuildChannelEvent + OldGuildChannel *api.GuildChannel +} + +// GuildChannelDeleteEvent indicates that a api.GuildChannel got deleted in a api.Guild +type GuildChannelDeleteEvent struct { + GenericGuildChannelEvent +} diff --git a/api/events/guild_events.go b/api/events/guild_events.go index aa214bae..d5257a40 100644 --- a/api/events/guild_events.go +++ b/api/events/guild_events.go @@ -7,7 +7,8 @@ import ( // GenericGuildEvent is called upon receiving GuildUpdateEvent, GuildAvailableEvent, GuildUnavailableEvent, GuildJoinEvent, GuildLeaveEvent, GuildReadyEvent, GuildBanEvent, GuildUnbanEvent type GenericGuildEvent struct { GenericEvent - Guild *api.Guild + GuildID api.Snowflake + Guild *api.Guild } // GuildUpdateEvent is called upon receiving api.Guild updates diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index 5637cf6c..85e9aa17 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -24,6 +24,12 @@ type ListenerAdapter struct { // api.Channel Events OnGenericChannelEvent func(event GenericChannelEvent) + // api.GuildChannel Events + OnGenericGuildChannelEvent func(event GenericGuildChannelEvent) + OnGuildChannelCreate func(event GuildChannelCreateEvent) + OnGuildChannelUpdate func(event GuildChannelUpdateEvent) + OnGuildChannelDelete func(event GuildChannelDeleteEvent) + // api.Category Events OnGenericCategoryEvent func(event GenericCategoryEvent) OnCategoryCreate func(event CategoryCreateEvent) @@ -204,6 +210,24 @@ func (l ListenerAdapter) OnEvent(event interface{}) { listener(e) } + // api.GuildChannel Events + case GenericGuildChannelEvent: + if listener := l.OnGenericGuildChannelEvent; listener != nil { + listener(e) + } + case GuildChannelCreateEvent: + if listener := l.OnGuildChannelCreate; listener != nil { + listener(e) + } + case GuildChannelUpdateEvent: + if listener := l.OnGuildChannelUpdate; listener != nil { + listener(e) + } + case GuildChannelDeleteEvent: + if listener := l.OnGuildChannelDelete; listener != nil { + listener(e) + } + // api.Category Events case GenericCategoryEvent: if listener := l.OnGenericCategoryEvent; listener != nil { diff --git a/api/events/store_channel_events.go b/api/events/store_channel_events.go index fffc1b5d..28dbdae3 100644 --- a/api/events/store_channel_events.go +++ b/api/events/store_channel_events.go @@ -6,7 +6,7 @@ import ( // GenericStoreChannelEvent is called upon receiving StoreChannelCreateEvent, StoreChannelUpdateEvent or StoreChannelDeleteEvent type GenericStoreChannelEvent struct { - GenericChannelEvent + GenericGuildChannelEvent StoreChannel *api.StoreChannel } diff --git a/api/events/text_channel_events.go b/api/events/text_channel_events.go index 7ddc08f0..2de076fa 100644 --- a/api/events/text_channel_events.go +++ b/api/events/text_channel_events.go @@ -6,7 +6,7 @@ import ( // GenericTextChannelEvent is called upon receiving TextChannelCreateEvent, TextChannelUpdateEvent or TextChannelDeleteEvent type GenericTextChannelEvent struct { - GenericChannelEvent + GenericGuildChannelEvent TextChannel *api.TextChannel } @@ -25,3 +25,8 @@ type TextChannelUpdateEvent struct { type TextChannelDeleteEvent struct { GenericTextChannelEvent } + +// WebhooksUpdateEvent indicates that a api.Webhook updated in this api.TextChannel +type WebhooksUpdateEvent struct { + GenericTextChannelEvent +} diff --git a/api/events/voice_channel_events.go b/api/events/voice_channel_events.go index d2de4cb2..3cd965db 100644 --- a/api/events/voice_channel_events.go +++ b/api/events/voice_channel_events.go @@ -6,7 +6,7 @@ import ( // GenericVoiceChannelEvent is called upon receiving VoiceChannelCreateEvent, VoiceChannelUpdateEvent or VoiceChannelDeleteEvent type GenericVoiceChannelEvent struct { - GenericChannelEvent + GenericGuildChannelEvent VoiceChannel *api.VoiceChannel } diff --git a/example/examplebot.go b/example/examplebot.go index e121adda..19556de6 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -39,7 +39,7 @@ func main() { SetLogger(logger). SetRawGatewayEventsEnabled(true). SetHTTPClient(client). - SetGatewayIntents(api.GatewayIntentsGuilds | api.GatewayIntentsGuildMessages | api.GatewayIntentsGuildMembers). + SetGatewayIntents(api.GatewayIntentsGuilds, api.GatewayIntentsGuildMessages, api.GatewayIntentsGuildMembers, api.GatewayIntentsGuildWebhooks). SetMemberCachePolicy(api.MemberCachePolicyAll). AddEventListeners(&events.ListenerAdapter{ OnRawGateway: rawGatewayEventListener, diff --git a/internal/disgo_builder_impl.go b/internal/disgo_builder_impl.go index 853d54ab..848ff53e 100644 --- a/internal/disgo_builder_impl.go +++ b/internal/disgo_builder_impl.go @@ -60,8 +60,8 @@ func (b *DisgoBuilderImpl) SetHTTPClient(httpClient *http.Client) api.DisgoBuild } // SetGatewayIntents sets the api.GatewayIntents to connect to discord -func (b *DisgoBuilderImpl) SetGatewayIntents(gatewayIntents api.GatewayIntents) api.DisgoBuilder { - b.gatewayIntents = gatewayIntents +func (b *DisgoBuilderImpl) SetGatewayIntents(gatewayIntents ...api.GatewayIntents) api.DisgoBuilder { + b.gatewayIntents = api.GatewayIntentsNone.Add(gatewayIntents...) return b } diff --git a/internal/handlers/all_handlers.go b/internal/handlers/all_handlers.go index 1bbc90b8..9d527781 100644 --- a/internal/handlers/all_handlers.go +++ b/internal/handlers/all_handlers.go @@ -27,6 +27,8 @@ func GetAllHandlers() []api.EventHandler { GuildRoleDeleteHandler{}, GuildRoleUpdateHandler{}, + WebhooksUpdateHandler{}, + InteractionCreateHandler{}, InteractionCreateWebhookHandler{}, diff --git a/internal/handlers/channel_create_handler.go b/internal/handlers/channel_create_handler.go index 23ef93e1..556d0f84 100644 --- a/internal/handlers/channel_create_handler.go +++ b/internal/handlers/channel_create_handler.go @@ -25,12 +25,31 @@ func (h ChannelCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a return } + channel.Disgo = disgo + genericChannelEvent := events.GenericChannelEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), ChannelID: channel.ID, + Channel: channel, } eventManager.Dispatch(genericChannelEvent) + var genericGuildChannelEvent events.GenericGuildChannelEvent + if channel.GuildID != nil { + genericGuildChannelEvent = events.GenericGuildChannelEvent{ + GuildID: *channel.GuildID, + GenericChannelEvent: genericChannelEvent, + GuildChannel: &api.GuildChannel{ + Channel: *channel, + }, + } + eventManager.Dispatch(genericGuildChannelEvent) + + eventManager.Dispatch(events.GuildChannelCreateEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + }) + } + switch channel.Type { case api.ChannelTypeDM: dmChannel := disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyYes) @@ -52,8 +71,8 @@ func (h ChannelCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a textChannel := disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes) genericTextChannelEvent := events.GenericTextChannelEvent{ - GenericChannelEvent: genericChannelEvent, - TextChannel: textChannel, + GenericGuildChannelEvent: genericGuildChannelEvent, + TextChannel: textChannel, } eventManager.Dispatch(genericTextChannelEvent) @@ -65,8 +84,8 @@ func (h ChannelCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a storeChannel := disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes) genericStoreChannelEvent := events.GenericStoreChannelEvent{ - GenericChannelEvent: genericChannelEvent, - StoreChannel: storeChannel, + GenericGuildChannelEvent: genericGuildChannelEvent, + StoreChannel: storeChannel, } eventManager.Dispatch(genericStoreChannelEvent) @@ -78,8 +97,8 @@ func (h ChannelCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a category := disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes) genericCategoryEvent := events.GenericCategoryEvent{ - GenericChannelEvent: genericChannelEvent, - Category: category, + GenericGuildChannelEvent: genericGuildChannelEvent, + Category: category, } eventManager.Dispatch(genericCategoryEvent) @@ -91,8 +110,8 @@ func (h ChannelCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a voiceChannel := disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes) genericVoiceChannelEvent := events.GenericVoiceChannelEvent{ - GenericChannelEvent: genericChannelEvent, - VoiceChannel: voiceChannel, + GenericGuildChannelEvent: genericGuildChannelEvent, + VoiceChannel: voiceChannel, } eventManager.Dispatch(genericVoiceChannelEvent) diff --git a/internal/handlers/channel_delete_handler.go b/internal/handlers/channel_delete_handler.go index 5a06361d..e4124d27 100644 --- a/internal/handlers/channel_delete_handler.go +++ b/internal/handlers/channel_delete_handler.go @@ -25,12 +25,31 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a return } + channel.Disgo = disgo + genericChannelEvent := events.GenericChannelEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), ChannelID: channel.ID, + Channel: channel, } eventManager.Dispatch(genericChannelEvent) + var genericGuildChannelEvent events.GenericGuildChannelEvent + if channel.GuildID != nil { + genericGuildChannelEvent = events.GenericGuildChannelEvent{ + GenericChannelEvent: genericChannelEvent, + GuildID: *channel.GuildID, + GuildChannel: &api.GuildChannel{ + Channel: *channel, + }, + } + eventManager.Dispatch(genericGuildChannelEvent) + + eventManager.Dispatch(events.GuildChannelDeleteEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + }) + } + switch channel.Type { case api.ChannelTypeDM: disgo.Cache().UncacheDMChannel(channel.ID) @@ -52,8 +71,8 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a disgo.Cache().UncacheTextChannel(*channel.GuildID, channel.ID) genericTextChannelEvent := events.GenericTextChannelEvent{ - GenericChannelEvent: genericChannelEvent, - TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyNo), + GenericGuildChannelEvent: genericGuildChannelEvent, + TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyNo), } eventManager.Dispatch(genericTextChannelEvent) @@ -65,8 +84,8 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a disgo.Cache().UncacheStoreChannel(*channel.GuildID, channel.ID) genericStoreChannelEvent := events.GenericStoreChannelEvent{ - GenericChannelEvent: genericChannelEvent, - StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyNo), + GenericGuildChannelEvent: genericGuildChannelEvent, + StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyNo), } eventManager.Dispatch(genericStoreChannelEvent) @@ -78,8 +97,8 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a disgo.Cache().UncacheCategory(*channel.GuildID, channel.ID) genericCategoryEvent := events.GenericCategoryEvent{ - GenericChannelEvent: genericChannelEvent, - Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyNo), + GenericGuildChannelEvent: genericGuildChannelEvent, + Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyNo), } eventManager.Dispatch(genericCategoryEvent) @@ -91,8 +110,8 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a disgo.Cache().UncacheVoiceChannel(*channel.GuildID, channel.ID) genericVoiceChannelEvent := events.GenericVoiceChannelEvent{ - GenericChannelEvent: genericChannelEvent, - VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyNo), + GenericGuildChannelEvent: genericGuildChannelEvent, + VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyNo), } eventManager.Dispatch(genericVoiceChannelEvent) diff --git a/internal/handlers/channel_update_handler.go b/internal/handlers/channel_update_handler.go index 2320b53c..2aaa7441 100644 --- a/internal/handlers/channel_update_handler.go +++ b/internal/handlers/channel_update_handler.go @@ -25,12 +25,32 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a return } + channel.Disgo = disgo + genericChannelEvent := events.GenericChannelEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), ChannelID: channel.ID, + Channel: channel, } eventManager.Dispatch(genericChannelEvent) + var genericGuildChannelEvent events.GenericGuildChannelEvent + if channel.GuildID != nil { + genericGuildChannelEvent = events.GenericGuildChannelEvent{ + GenericChannelEvent: genericChannelEvent, + GuildID: *channel.GuildID, + GuildChannel: &api.GuildChannel{ + Channel: *channel, + }, + } + eventManager.Dispatch(genericGuildChannelEvent) + + eventManager.Dispatch(events.GuildChannelUpdateEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + OldGuildChannel: disgo.Cache().GuildChannel(channel.ID), + }) + } + switch channel.Type { case api.ChannelTypeDM: oldDMChannel := disgo.Cache().DMChannel(channel.ID) @@ -59,8 +79,8 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a } genericTextChannelEvent := events.GenericTextChannelEvent{ - GenericChannelEvent: genericChannelEvent, - TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes), + GenericGuildChannelEvent: genericGuildChannelEvent, + TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes), } eventManager.Dispatch(genericTextChannelEvent) @@ -76,8 +96,8 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a } genericStoreChannelEvent := events.GenericStoreChannelEvent{ - GenericChannelEvent: genericChannelEvent, - StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes), + GenericGuildChannelEvent: genericGuildChannelEvent, + StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes), } eventManager.Dispatch(genericStoreChannelEvent) @@ -93,8 +113,8 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a } genericCategoryEvent := events.GenericCategoryEvent{ - GenericChannelEvent: genericChannelEvent, - Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes), + GenericGuildChannelEvent: genericGuildChannelEvent, + Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes), } eventManager.Dispatch(genericCategoryEvent) @@ -110,8 +130,8 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a } genericVoiceChannelEvent := events.GenericVoiceChannelEvent{ - GenericChannelEvent: genericChannelEvent, - VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes), + GenericGuildChannelEvent: genericGuildChannelEvent, + VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes), } eventManager.Dispatch(genericVoiceChannelEvent) diff --git a/internal/handlers/guild_create_handler.go b/internal/handlers/guild_create_handler.go index a2ad428a..917fa4cc 100644 --- a/internal/handlers/guild_create_handler.go +++ b/internal/handlers/guild_create_handler.go @@ -72,6 +72,7 @@ func (h GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api genericGuildEvent := events.GenericGuildEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), + GuildID: guild.ID, Guild: guild, } eventManager.Dispatch(genericGuildEvent) diff --git a/internal/handlers/guild_role_create_handler.go b/internal/handlers/guild_role_create_handler.go index bfa10b7a..1116ba68 100644 --- a/internal/handlers/guild_role_create_handler.go +++ b/internal/handlers/guild_role_create_handler.go @@ -31,10 +31,6 @@ func (h GuildRoleCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager } guild := disgo.Cache().Guild(roleCreateData.GuildID) - if guild == nil { - // todo: replay event later. maybe guild is not cached yet but in a few seconds - return - } role := disgo.EntityBuilder().CreateRole(roleCreateData.GuildID, roleCreateData.Role, api.CacheStrategyYes) diff --git a/internal/handlers/voice_state_update_handler.go b/internal/handlers/voice_state_update_handler.go index ac4b6b47..0eae20ea 100644 --- a/internal/handlers/voice_state_update_handler.go +++ b/internal/handlers/voice_state_update_handler.go @@ -5,7 +5,7 @@ import ( "github.com/DisgoOrg/disgo/api/events" ) -// VoiceStateUpdateHandler handles api.VoiceStateUpdateGatewayEvent +// VoiceStateUpdateHandler handles api.GatewayEventVoiceStateUpdate type VoiceStateUpdateHandler struct{} // Event returns the raw gateway event Event diff --git a/internal/handlers/webhooks_update_handler.go b/internal/handlers/webhooks_update_handler.go index 5ac8282f..3c81cb1c 100644 --- a/internal/handlers/webhooks_update_handler.go +++ b/internal/handlers/webhooks_update_handler.go @@ -1 +1,56 @@ package handlers + +import ( + "github.com/DisgoOrg/disgo/api" + "github.com/DisgoOrg/disgo/api/events" +) + +type webhooksUpdateData struct { + GuildID api.Snowflake `json:"guild_id"` + ChannelID api.Snowflake `json:"channel_id"` +} + +// WebhooksUpdateHandler handles api.GatewayEventWebhooksUpdate +type WebhooksUpdateHandler struct{} + +// Event returns the raw api.GatewayEventType +func (h WebhooksUpdateHandler) Event() api.GatewayEventType { + return api.GatewayEventWebhooksUpdate +} + +// New constructs a new payload receiver for the raw gateway event +func (h WebhooksUpdateHandler) New() interface{} { + return &webhooksUpdateData{} +} + +// HandleGatewayEvent handles the specific raw gateway event +func (h WebhooksUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { + webhooksUpdateData, ok := i.(*webhooksUpdateData) + if !ok { + return + } + + genericChannelEvent := events.GenericChannelEvent{ + GenericEvent: events.NewEvent(disgo, sequenceNumber), + ChannelID: webhooksUpdateData.ChannelID, + Channel: disgo.Cache().Channel(webhooksUpdateData.ChannelID), + } + eventManager.Dispatch(genericChannelEvent) + + genericGuildChannelEvent := events.GenericGuildChannelEvent{ + GenericChannelEvent: genericChannelEvent, + GuildID: webhooksUpdateData.GuildID, + GuildChannel: disgo.Cache().GuildChannel(webhooksUpdateData.ChannelID), + } + eventManager.Dispatch(genericGuildChannelEvent) + + genericTextChannelEvent := events.GenericTextChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + TextChannel: disgo.Cache().TextChannel(webhooksUpdateData.ChannelID), + } + eventManager.Dispatch(genericTextChannelEvent) + + eventManager.Dispatch(events.WebhooksUpdateEvent{ + GenericTextChannelEvent: genericTextChannelEvent, + }) +} diff --git a/internal/util.go b/internal/util.go index 92be3dbb..df890a80 100644 --- a/internal/util.go +++ b/internal/util.go @@ -21,3 +21,4 @@ func IDFromToken(token string) (*api.Snowflake, error) { strID := api.Snowflake(byteID) return &strID, nil } +