From 60082fdfc1dcdaa6336f67d45e17e9baa1505abb Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sun, 30 May 2021 21:33:39 +0200 Subject: [PATCH 01/64] added dropdowns --- api/component.go | 1 + api/dropdown.go | 32 ++++++++++++++++++++++++++++++++ example/examplebot.go | 10 ++++++---- 3 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 api/dropdown.go diff --git a/api/component.go b/api/component.go index bddaa23c..b478cf4a 100644 --- a/api/component.go +++ b/api/component.go @@ -7,6 +7,7 @@ type ComponentType int const ( ComponentTypeActionRow = iota + 1 ComponentTypeButton + ComponentTypeDropdown ) // Component is a general interface each Component needs to implement diff --git a/api/dropdown.go b/api/dropdown.go new file mode 100644 index 00000000..57bcb851 --- /dev/null +++ b/api/dropdown.go @@ -0,0 +1,32 @@ +package api + +func NewDropdown(placeholder string, minValues int, maxValues int, options ...*DropdownOption) *Dropdown { + return &Dropdown{ + ComponentImpl: newComponentImpl(ComponentTypeDropdown), + Placeholder: placeholder, + MinValues: minValues, + MaxValues: maxValues, + Options: options, + } +} + +// Dropdown ... +type Dropdown struct { + ComponentImpl + Placeholder string `json:"placeholder"` + MinValues int `json:"min_values,omitempty"` + MaxValues int `json:"max_values,omitempty"` + Options []*DropdownOption `json:"options"` +} + +func NewDropdownOption(label string, value string) *DropdownOption { + return &DropdownOption{ + Label: label, + Value: value, + } +} + +type DropdownOption struct { + Label string `json:"label"` + Value string `json:"value"` +} diff --git a/example/examplebot.go b/example/examplebot.go index 3cf4dacc..ea7c7d45 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -51,7 +51,7 @@ func main() { logger.Fatalf("error while building disgo instance: %s", err) return } - +/* rawCmds := []*api.CommandCreate{ { Name: "eval", @@ -153,7 +153,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 { @@ -268,11 +268,13 @@ func commandListener(event *events.CommandEvent) { case "test": if err := event.Reply(api.NewInteractionResponseBuilder(). SetContent("test1"). + SetEphemeral(true). SetEmbeds(api.NewEmbedBuilder().SetDescription("this message should have some buttons").Build()). SetComponents( - api.NewActionRow( + /*api.NewActionRow( api.NewPrimaryButton("test", "test", api.NewEmoji("❌"), false), - ), + ),*/ + api.NewDropdown("test", 0, 0, api.NewDropdownOption("test1", "1"), api.NewDropdownOption("test2", "2"), api.NewDropdownOption("test3", "3")), ). Build(), ); err != nil { From ab58ae3b41e43259753fc768356d7afb6da88c26 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sun, 30 May 2021 22:57:33 +0200 Subject: [PATCH 02/64] added other dropdown logic --- api/component.go | 28 ++- api/dropdown.go | 4 +- api/entity_builder.go | 4 +- api/events/interaction_events.go | 48 ++-- api/events/listener_adapter.go | 12 +- api/gateway.go | 6 +- api/interaction.go | 64 ++++-- api/restclient.go | 8 +- example/examplebot.go | 211 ++++++++++-------- internal/entity_builder_impl.go | 60 ++++- .../handlers/interaction_create_handler.go | 27 ++- internal/restclient_impl.go | 12 +- 12 files changed, 311 insertions(+), 173 deletions(-) diff --git a/api/component.go b/api/component.go index b478cf4a..5d3ff6a0 100644 --- a/api/component.go +++ b/api/component.go @@ -31,12 +31,24 @@ 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"` - Emote *Emote `json:"emoji"` - CustomID string `json:"custom_id"` - URL string `json:"url"` - Disabled bool `json:"disabled"` - Components []*UnmarshalComponent `json:"components"` + ComponentType ComponentType `json:"type"` + + // Button && Dropdown + CustomID string `json:"custom_id"` + + // Button + Style ButtonStyle `json:"style"` + Label *string `json:"label"` + Emote *Emote `json:"emoji"` + URL string `json:"url"` + Disabled bool `json:"disabled"` + + // ActionRow + Components []*UnmarshalComponent `json:"components"` + + // Dropdown + Placeholder string `json:"placeholder"` + MinValues int `json:"min_values,omitempty"` + MaxValues int `json:"max_values,omitempty"` + Options []*DropdownOption `json:"options"` } diff --git a/api/dropdown.go b/api/dropdown.go index 57bcb851..a062f050 100644 --- a/api/dropdown.go +++ b/api/dropdown.go @@ -1,8 +1,9 @@ package api -func NewDropdown(placeholder string, minValues int, maxValues int, options ...*DropdownOption) *Dropdown { +func NewDropdown(customID string, placeholder string, minValues int, maxValues int, options ...*DropdownOption) *Dropdown { return &Dropdown{ ComponentImpl: newComponentImpl(ComponentTypeDropdown), + CustomID: customID, Placeholder: placeholder, MinValues: minValues, MaxValues: maxValues, @@ -13,6 +14,7 @@ func NewDropdown(placeholder string, minValues int, maxValues int, options ...*D // Dropdown ... type Dropdown struct { ComponentImpl + CustomID string `json:"custom_id"` Placeholder string `json:"placeholder"` MinValues int `json:"min_values,omitempty"` MaxValues int `json:"max_values,omitempty"` diff --git a/api/entity_builder.go b/api/entity_builder.go index 41c179a2..cb9498cf 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -15,8 +15,10 @@ var ( type EntityBuilder interface { Disgo() Disgo - CreateButtonInteraction(fullInteraction *FullInteraction, c chan *InteractionResponse, updateCache CacheStrategy) *ButtonInteraction CreateCommandInteraction(fullInteraction *FullInteraction, c chan *InteractionResponse, updateCache CacheStrategy) *CommandInteraction + CreateComponentInteraction(fullInteraction *FullInteraction, c chan *InteractionResponse, updateCache CacheStrategy) *ComponentInteraction + CreateButtonInteraction(fullInteraction *FullInteraction, cInteraction *ComponentInteraction) *ButtonInteraction + CreateDropdownInteraction(fullInteraction *FullInteraction, cInteraction *ComponentInteraction) *DropdownInteraction CreateGlobalCommand(command *Command, updateCache CacheStrategy) *Command diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index 1e18049f..615e629a 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -104,33 +104,49 @@ func (e CommandEvent) OptionsT(optionType api.CommandOptionType) []*api.Option { return options } -// ButtonClickEvent indicates that a api.Button was clicked -type ButtonClickEvent struct { +type GenericComponentEvent struct { GenericInteractionEvent - ButtonInteraction *api.ButtonInteraction + ComponentInteraction *api.ComponentInteraction } // DeferEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeDeferredUpdateMessage and cancels the loading state -func (e *ButtonClickEvent) DeferEdit() error { - return e.ButtonInteraction.DeferEdit() +func (e *GenericComponentEvent) DeferEdit() error { + return e.ComponentInteraction.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) +func (e *GenericComponentEvent) ReplyEdit(data *api.InteractionResponseData) error { + return e.ComponentInteraction.ReplyEdit(data) +} + +// CustomID returns the customID from the called api.Component +func (e *GenericComponentEvent) CustomID() string { + return e.ComponentInteraction.Data.CustomID +} + +// ComponentType returns the api.ComponentType from the called api.Component +func (e *GenericComponentEvent) ComponentType() string { + return e.ComponentInteraction.Data.CustomID +} + +// Message returns the api.Message the api.Component is called from +func (e *GenericComponentEvent) Message() *api.Message { + return e.ComponentInteraction.Message } -// CustomID returns the customID from the called api.Button -func (e *ButtonClickEvent) CustomID() string { - return e.ButtonInteraction.Data.CustomID +// ButtonClickEvent indicates that a api.Button was clicked +type ButtonClickEvent struct { + GenericComponentEvent + ButtonInteraction *api.ButtonInteraction } -// ComponentType returns the api.ComponentType from the called api.Button -func (e *ButtonClickEvent) ComponentType() string { - return e.ButtonInteraction.Data.CustomID +// DropdownSubmitEvent indicates that a api.Dropdown was submitted +type DropdownSubmitEvent struct { + GenericComponentEvent + DropdownInteraction *api.DropdownInteraction } -// Message returns the api.Message the api.Button is called from -func (e *ButtonClickEvent) Message() *api.Message { - return e.ButtonInteraction.Message +// Values returns the submitted values from the api.Dropdown +func (e *DropdownSubmitEvent) Values() []string { + return e.DropdownInteraction.Data.Values } diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index 75ded836..6b8b355e 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -123,8 +123,10 @@ type ListenerAdapter struct { // api.Interaction Events OnGenericInteractionEvent func(event *GenericInteractionEvent) - OnCommand func(event *CommandEvent) + OnCommand func(event *CommandEvent) + OnGenericComponentEvent func(event *GenericComponentEvent) OnButtonClick func(event *ButtonClickEvent) + OnDropdownSubmit func(event *DropdownSubmitEvent) // api.Message Events OnGenericMessageEvent func(event *GenericMessageEvent) @@ -511,10 +513,18 @@ func (l ListenerAdapter) OnEvent(event interface{}) { if listener := l.OnCommand; listener != nil { listener(&e) } + case GenericComponentEvent: + if listener := l.OnGenericComponentEvent; listener != nil { + listener(&e) + } case ButtonClickEvent: if listener := l.OnButtonClick; listener != nil { listener(&e) } + case DropdownSubmitEvent: + if listener := l.OnDropdownSubmit; listener != nil { + listener(&e) + } // api.Message Events case GenericMessageEvent: diff --git a/api/gateway.go b/api/gateway.go index e0835ee7..e617ca80 100644 --- a/api/gateway.go +++ b/api/gateway.go @@ -62,9 +62,9 @@ const ( GatewayEventResumed GatewayEventType = "RESUMED" GatewayEventReconnect GatewayEventType = "RECONNECT" GatewayEventInvalidSession GatewayEventType = "INVALID_SESSION" - GatewayEventCommandCreate GatewayEventType = "APPLICATION_COMMAND_CREATE" - GatewayEventCommandUpdate GatewayEventType = "APPLICATION_COMMAND_UPDATE" - GatewayEventCommandDelete GatewayEventType = "APPLICATION_COMMAND_DELETE" + GatewayEventCommandCreate GatewayEventType = "APPLICATION_COMMAND_CREATE" + GatewayEventCommandUpdate GatewayEventType = "APPLICATION_COMMAND_UPDATE" + GatewayEventCommandDelete GatewayEventType = "APPLICATION_COMMAND_DELETE" GatewayEventChannelCreate GatewayEventType = "CHANNEL_CREATE" GatewayEventChannelUpdate GatewayEventType = "CHANNEL_UPDATE" GatewayEventChannelDelete GatewayEventType = "CHANNEL_DELETE" diff --git a/api/interaction.go b/api/interaction.go index ca5b4222..2168fc68 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -117,16 +117,19 @@ func (i *Interaction) DeleteFollowup(messageID Snowflake) error { // FullInteraction is used for easier unmarshalling of different Interaction(s) type FullInteraction struct { - ID Snowflake `json:"id"` - Type InteractionType `json:"type"` - GuildID *Snowflake `json:"guild_id,omitempty"` - ChannelID *Snowflake `json:"channel_id,omitempty"` - FullMessage *FullMessage `json:"message,omitempty"` - Member *Member `json:"member,omitempty"` - User *User `json:"User,omitempty"` - Token string `json:"token"` - Version int `json:"version"` - Data json.RawMessage `json:"data,omitempty"` + // CommandInteraction & ComponentInteraction + ID Snowflake `json:"id"` + Type InteractionType `json:"type"` + GuildID *Snowflake `json:"guild_id,omitempty"` + ChannelID *Snowflake `json:"channel_id,omitempty"` + Member *Member `json:"member,omitempty"` + User *User `json:"User,omitempty"` + Token string `json:"token"` + Version int `json:"version"` + Data json.RawMessage `json:"data,omitempty"` + + // ComponentInteraction + FullMessage *FullMessage `json:"message,omitempty"` } // CommandInteraction is a specific Interaction when using Command(s) @@ -149,24 +152,36 @@ 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 { +// ComponentInteraction is a specific Interaction when using Component(s) +type ComponentInteraction struct { *Interaction - Message *Message `json:"message,omitempty"` - Data *ButtonInteractionData `json:"data,omitempty"` + Message *Message `json:"message,omitempty"` + Data *ComponentInteractionData `json:"data,omitempty"` } // DeferEdit replies to the api.ButtonInteraction with api.InteractionResponseTypeDeferredUpdateMessage and cancels the loading state -func (i *ButtonInteraction) DeferEdit() error { +func (i *ComponentInteraction) 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 { +func (i *ComponentInteraction) ReplyEdit(data *InteractionResponseData) error { return i.Reply(&InteractionResponse{Type: InteractionResponseTypeUpdateMessage, Data: data}) } -// CommandInteractionData is the command data payload +// ButtonInteraction is a specific Interaction when CLicked on Button(s) +type ButtonInteraction struct { + *ComponentInteraction + Data *ButtonInteractionData `json:"data,omitempty"` +} + +// DropdownInteraction is a specific Interaction when CLicked on Dropdown(s) +type DropdownInteraction struct { + *ComponentInteraction + Data *DropdownInteractionData `json:"data,omitempty"` +} + +// CommandInteractionData is the Command data payload type CommandInteractionData struct { ID Snowflake `json:"id"` Name string `json:"name"` @@ -174,12 +189,23 @@ type CommandInteractionData struct { Options []*OptionData `json:"options,omitempty"` } -// ButtonInteractionData is the command data payload -type ButtonInteractionData struct { +// ComponentInteractionData is the Component data payload +type ComponentInteractionData struct { CustomID string `json:"custom_id"` ComponentType ComponentType `json:"component_type"` } +// ButtonInteractionData is the Button data payload +type ButtonInteractionData struct { + *ComponentInteractionData +} + +// DropdownInteractionData is the Dropdown data payload +type DropdownInteractionData struct { + *ComponentInteractionData + Values []string `json:"values"` +} + // Resolved contains resolved mention data type Resolved struct { Users map[Snowflake]*User `json:"users,omitempty"` diff --git a/api/restclient.go b/api/restclient.go index 19cbdff5..d7f1e758 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -8,10 +8,10 @@ import ( // Errors when connecting to discord var ( - ErrBadGateway = errors.New("bad gateway could not reach discord") - ErrUnauthorized = errors.New("not authorized for this endpoint") - ErrBadRequest = errors.New("bad request please check your request") - ErrRatelimited = errors.New("too many requests") + ErrBadGateway = errors.New("bad gateway could not reach discord") + ErrUnauthorized = errors.New("not authorized for this endpoint") + ErrBadRequest = errors.New("bad request please check your request") + ErrRatelimited = errors.New("too many requests") ErrTooMuchCommands = errors.New("you can provide a max of 100 application commands") ) diff --git a/example/examplebot.go b/example/examplebot.go index ea7c7d45..072e478f 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -43,117 +43,118 @@ func main() { OnRawGateway: rawGatewayEventListener, OnGuildAvailable: guildAvailListener, OnGuildMessageCreate: messageListener, - OnCommand: commandListener, + OnCommand: commandListener, OnButtonClick: buttonClickListener, + OnDropdownSubmit: dropdownSubmitListener, }). Build() if err != nil { logger.Fatalf("error while building disgo instance: %s", err) return } -/* - rawCmds := []*api.CommandCreate{ - { - Name: "eval", - Description: "runs some go code", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ - { - Type: api.CommandOptionTypeString, - Name: "code", - Description: "the code to eval", - Required: true, + /* + rawCmds := []*api.CommandCreate{ + { + Name: "eval", + Description: "runs some go code", + DefaultPermission: ptrBool(true), + Options: []*api.CommandOption{ + { + Type: api.CommandOptionTypeString, + Name: "code", + Description: "the code to eval", + Required: true, + }, }, }, - }, - { - Name: "test", - Description: "test test test test test test", - DefaultPermission: ptrBool(true), - }, - { - Name: "say", - Description: "says what you say", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ - { - Type: api.CommandOptionTypeString, - Name: "message", - Description: "What to say", - Required: true, - }, + { + Name: "test", + Description: "test test test test test test", + DefaultPermission: ptrBool(true), }, - }, - { - Name: "addrole", - Description: "This command adds a role to a member", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ - { - Type: api.CommandOptionTypeUser, - Name: "member", - Description: "The member to add a role to", - Required: true, - }, - { - Type: api.CommandOptionTypeRole, - Name: "role", - Description: "The role to add to a member", - Required: true, + { + Name: "say", + Description: "says what you say", + DefaultPermission: ptrBool(true), + Options: []*api.CommandOption{ + { + Type: api.CommandOptionTypeString, + Name: "message", + Description: "What to say", + Required: true, + }, }, }, - }, - { - Name: "removerole", - Description: "This command removes a role from a member", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ - { - Type: api.CommandOptionTypeUser, - Name: "member", - Description: "The member to removes a role from", - Required: true, + { + Name: "addrole", + Description: "This command adds a role to a member", + DefaultPermission: ptrBool(true), + Options: []*api.CommandOption{ + { + Type: api.CommandOptionTypeUser, + Name: "member", + Description: "The member to add a role to", + Required: true, + }, + { + Type: api.CommandOptionTypeRole, + Name: "role", + Description: "The role to add to a member", + Required: true, + }, }, - { - Type: api.CommandOptionTypeRole, - Name: "role", - Description: "The role to removes from a member", - Required: true, + }, + { + Name: "removerole", + Description: "This command removes a role from a member", + DefaultPermission: ptrBool(true), + Options: []*api.CommandOption{ + { + Type: api.CommandOptionTypeUser, + Name: "member", + Description: "The member to removes a role from", + Required: true, + }, + { + Type: api.CommandOptionTypeRole, + Name: "role", + Description: "The role to removes from a member", + Required: true, + }, }, }, - }, - } + } - // using the api.RestClient directly to avoid the guild needing to be cached - cmds, err := dgo.RestClient().SetGuildCommands(dgo.ApplicationID(), guildID, rawCmds...) - if err != nil { - logger.Errorf("error while registering guild commands: %s", err) - } + // using the api.RestClient directly to avoid the guild needing to be cached + cmds, err := dgo.RestClient().SetGuildCommands(dgo.ApplicationID(), guildID, rawCmds...) + if err != nil { + logger.Errorf("error while registering guild commands: %s", err) + } - var cmdsPermissions []*api.SetGuildCommandPermissions - for _, cmd := range cmds { - var perms *api.CommandPermission - if cmd.Name == "eval" { - perms = &api.CommandPermission{ - ID: adminRoleID, - Type: api.CommandPermissionTypeRole, - Permission: true, - } - } else { - perms = &api.CommandPermission{ - ID: testRoleID, - Type: api.CommandPermissionTypeRole, - Permission: true, + var cmdsPermissions []*api.SetGuildCommandPermissions + for _, cmd := range cmds { + var perms *api.CommandPermission + if cmd.Name == "eval" { + perms = &api.CommandPermission{ + ID: adminRoleID, + Type: api.CommandPermissionTypeRole, + Permission: true, + } + } else { + perms = &api.CommandPermission{ + ID: testRoleID, + Type: api.CommandPermissionTypeRole, + Permission: true, + } } + cmdsPermissions = append(cmdsPermissions, &api.SetGuildCommandPermissions{ + ID: cmd.ID, + Permissions: []*api.CommandPermission{perms}, + }) } - cmdsPermissions = append(cmdsPermissions, &api.SetGuildCommandPermissions{ - ID: cmd.ID, - Permissions: []*api.CommandPermission{perms}, - }) - } - if _, err = dgo.RestClient().SetGuildCommandsPermissions(dgo.ApplicationID(), guildID, cmdsPermissions...); err != nil { - logger.Errorf("error while setting command permissions: %s", err) - }*/ + 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 { @@ -206,6 +207,20 @@ func buttonClickListener(event *events.ButtonClickEvent) { } } +func dropdownSubmitListener(event *events.DropdownSubmitEvent) { + switch event.CustomID() { + case "test3": + if err := event.DeferEdit(); err != nil { + logger.Errorf("error sending interaction response: %s", err) + } + _, _ = event.SendFollowup(api.NewFollowupMessageBuilder(). + SetEphemeral(true). + SetContentf("selected options: %s", event.Values()). + Build(), + ) + } +} + func commandListener(event *events.CommandEvent) { switch event.CommandName { case "eval": @@ -266,17 +281,19 @@ func commandListener(event *events.CommandEvent) { ) case "test": - if err := event.Reply(api.NewInteractionResponseBuilder(). + if err := event.ReplyCreate(api.NewInteractionResponseBuilder(). SetContent("test1"). SetEphemeral(true). SetEmbeds(api.NewEmbedBuilder().SetDescription("this message should have some buttons").Build()). SetComponents( - /*api.NewActionRow( + api.NewActionRow( api.NewPrimaryButton("test", "test", api.NewEmoji("❌"), false), - ),*/ - api.NewDropdown("test", 0, 0, api.NewDropdownOption("test1", "1"), api.NewDropdownOption("test2", "2"), api.NewDropdownOption("test3", "3")), + ), + api.NewActionRow( + api.NewDropdown("test3", "test", 1, 1, api.NewDropdownOption("test1", "1"), api.NewDropdownOption("test2", "2"), api.NewDropdownOption("test3", "3")), + ), ). - Build(), + BuildData(), ); err != nil { logger.Errorf("error sending interaction response: %s", err) } diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 222b960e..89edbdae 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -42,18 +42,6 @@ func (b EntityBuilderImpl) createInteraction(fullInteraction *api.FullInteractio return interaction } -// 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 { - var data *api.ButtonInteractionData - _ = json.Unmarshal(fullInteraction.Data, &data) - - return &api.ButtonInteraction{ - Interaction: b.createInteraction(fullInteraction, c, updateCache), - Message: b.CreateMessage(fullInteraction.FullMessage, updateCache), - Data: data, - } -} - // 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 { var data *api.CommandInteractionData @@ -92,6 +80,42 @@ func (b *EntityBuilderImpl) CreateCommandInteraction(fullInteraction *api.FullIn } } +func (b *EntityBuilderImpl) CreateComponentInteraction(fullInteraction *api.FullInteraction, c chan *api.InteractionResponse, updateCache api.CacheStrategy) *api.ComponentInteraction { + var data *api.ComponentInteractionData + _ = json.Unmarshal(fullInteraction.Data, &data) + + return &api.ComponentInteraction{ + Interaction: b.createInteraction(fullInteraction, c, updateCache), + Message: b.CreateMessage(fullInteraction.FullMessage, updateCache), + Data: &api.ComponentInteractionData{ + ComponentType: data.ComponentType, + CustomID: data.CustomID, + }, + } +} + +// CreateButtonInteraction creates a api.ButtonInteraction from the full interaction response +func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInteraction, cInteraction *api.ComponentInteraction) *api.ButtonInteraction { + var data *api.ButtonInteractionData + _ = json.Unmarshal(fullInteraction.Data, &data) + + return &api.ButtonInteraction{ + ComponentInteraction: cInteraction, + Data: data, + } +} + +// CreateDropdownInteraction creates a api.DropdownInteraction from the full interaction response +func (b *EntityBuilderImpl) CreateDropdownInteraction(fullInteraction *api.FullInteraction, cInteraction *api.ComponentInteraction) *api.DropdownInteraction { + var data *api.DropdownInteractionData + _ = json.Unmarshal(fullInteraction.Data, &data) + + return &api.DropdownInteraction{ + ComponentInteraction: cInteraction, + Data: data, + } +} + // CreateGlobalCommand returns a new api.Command entity func (b *EntityBuilderImpl) CreateGlobalCommand(command *api.Command, updateCache api.CacheStrategy) *api.Command { command.Disgo = b.Disgo() @@ -139,6 +163,18 @@ func (b *EntityBuilderImpl) createComponent(unmarshalComponent *api.UnmarshalCom button.Emote = b.CreateEmote("", unmarshalComponent.Emote, updateCache) } return button + case api.ComponentTypeDropdown: + dropdown := &api.Dropdown{ + ComponentImpl: api.ComponentImpl{ + ComponentType: api.ComponentTypeButton, + }, + CustomID: unmarshalComponent.CustomID, + Placeholder: unmarshalComponent.Placeholder, + MinValues: unmarshalComponent.MinValues, + MaxValues: unmarshalComponent.MaxValues, + Options: unmarshalComponent.Options, + } + return dropdown default: b.Disgo().Logger().Errorf("unexpected component type %d received", unmarshalComponent.ComponentType) diff --git a/internal/handlers/interaction_create_handler.go b/internal/handlers/interaction_create_handler.go index 61c82373..0b3d306d 100644 --- a/internal/handlers/interaction_create_handler.go +++ b/internal/handlers/interaction_create_handler.go @@ -74,15 +74,32 @@ func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceN SubCommandGroupName: subCommandGroupName, Options: newOptions, }) + case api.InteractionTypeComponent: - interaction := disgo.EntityBuilder().CreateButtonInteraction(fullInteraction, c, api.CacheStrategyYes) + componentInteraction := disgo.EntityBuilder().CreateComponentInteraction(fullInteraction, c, api.CacheStrategyYes) - genericInteractionEvent.Interaction = interaction.Interaction + genericInteractionEvent.Interaction = componentInteraction.Interaction eventManager.Dispatch(genericInteractionEvent) - eventManager.Dispatch(events.ButtonClickEvent{ + genericComponentEvent := events.GenericComponentEvent{ GenericInteractionEvent: genericInteractionEvent, - ButtonInteraction: interaction, - }) + ComponentInteraction: componentInteraction, + } + eventManager.Dispatch(genericComponentEvent) + + switch componentInteraction.Data.ComponentType { + case api.ComponentTypeButton: + eventManager.Dispatch(events.ButtonClickEvent{ + GenericComponentEvent: genericComponentEvent, + ButtonInteraction: disgo.EntityBuilder().CreateButtonInteraction(fullInteraction, componentInteraction), + }) + + case api.ComponentTypeDropdown: + eventManager.Dispatch(events.DropdownSubmitEvent{ + GenericComponentEvent: genericComponentEvent, + DropdownInteraction: disgo.EntityBuilder().CreateDropdownInteraction(fullInteraction, componentInteraction), + }) + } + } } diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 17ada390..4d8935cc 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -46,12 +46,12 @@ 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 } From e017cb80caf6d33efebcd54da435bfa919ec101e Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sun, 30 May 2021 23:06:58 +0200 Subject: [PATCH 03/64] added missing docs --- api/dropdown.go | 5 ++++- api/events/interaction_events.go | 1 + internal/entity_builder_impl.go | 3 ++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/api/dropdown.go b/api/dropdown.go index a062f050..afdea633 100644 --- a/api/dropdown.go +++ b/api/dropdown.go @@ -1,5 +1,6 @@ package api +// NewDropdown builds a new Dropdown from the provided values func NewDropdown(customID string, placeholder string, minValues int, maxValues int, options ...*DropdownOption) *Dropdown { return &Dropdown{ ComponentImpl: newComponentImpl(ComponentTypeDropdown), @@ -11,7 +12,7 @@ func NewDropdown(customID string, placeholder string, minValues int, maxValues i } } -// Dropdown ... +// Dropdown is a Component which lets the User select from various options type Dropdown struct { ComponentImpl CustomID string `json:"custom_id"` @@ -21,6 +22,7 @@ type Dropdown struct { Options []*DropdownOption `json:"options"` } +// NewDropdownOption builds a new DropdownOption func NewDropdownOption(label string, value string) *DropdownOption { return &DropdownOption{ Label: label, @@ -28,6 +30,7 @@ func NewDropdownOption(label string, value string) *DropdownOption { } } +// DropdownOption represents an option in a Dropdown type DropdownOption struct { Label string `json:"label"` Value string `json:"value"` diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index 615e629a..d56bd842 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -104,6 +104,7 @@ func (e CommandEvent) OptionsT(optionType api.CommandOptionType) []*api.Option { return options } +// GenericComponentEvent generic api.ComponentInteraction event type GenericComponentEvent struct { GenericInteractionEvent ComponentInteraction *api.ComponentInteraction diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 89edbdae..208754e1 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -80,6 +80,7 @@ func (b *EntityBuilderImpl) CreateCommandInteraction(fullInteraction *api.FullIn } } +// CreateComponentInteraction creates a api.ComponentInteraction from the api.FullInteraction response func (b *EntityBuilderImpl) CreateComponentInteraction(fullInteraction *api.FullInteraction, c chan *api.InteractionResponse, updateCache api.CacheStrategy) *api.ComponentInteraction { var data *api.ComponentInteractionData _ = json.Unmarshal(fullInteraction.Data, &data) @@ -94,7 +95,7 @@ func (b *EntityBuilderImpl) CreateComponentInteraction(fullInteraction *api.Full } } -// CreateButtonInteraction creates a api.ButtonInteraction from the full interaction response +// CreateButtonInteraction creates a api.ButtonInteraction from the api.FullInteraction response func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInteraction, cInteraction *api.ComponentInteraction) *api.ButtonInteraction { var data *api.ButtonInteractionData _ = json.Unmarshal(fullInteraction.Data, &data) From adbe93b19c1c4663a6d0425b8552ebadd59428fe Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 7 Jun 2021 23:29:47 +0200 Subject: [PATCH 04/64] added missing option fields --- api/dropdown.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/api/dropdown.go b/api/dropdown.go index 07e379da..e4dc28a1 100644 --- a/api/dropdown.go +++ b/api/dropdown.go @@ -1,8 +1,8 @@ package api // NewDropdown builds a new Dropdown from the provided values -func NewDropdown(customID string, placeholder string, minValues int, maxValues int, options ...DropdownOption) *Dropdown { - return &Dropdown{ +func NewDropdown(customID string, placeholder string, minValues int, maxValues int, options ...DropdownOption) Dropdown { + return Dropdown{ ComponentImpl: newComponentImpl(ComponentTypeDropdown), CustomID: customID, Placeholder: placeholder, @@ -32,6 +32,9 @@ func NewDropdownOption(label string, value string) DropdownOption { // DropdownOption represents an option in a Dropdown type DropdownOption struct { - Label string `json:"label"` - Value string `json:"value"` + Label string `json:"label"` + Value string `json:"value"` + Description string `json:"description,omitempty"` + Default bool `json:"default"` + Emoji *Emoji `json:"emoji"` } From 74b4a8c2957b8ceecf365162cfd1d784f48e5e03 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 7 Jun 2021 23:44:59 +0200 Subject: [PATCH 05/64] uncomment command create --- example/examplebot.go | 44 ++++++++++++++++--------------------------- 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/example/examplebot.go b/example/examplebot.go index deba2b48..98a286e9 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -55,7 +55,7 @@ func main() { return } - /*rawCmds := []api.CommandCreate{ + rawCmds := []api.CommandCreate{ { Name: "eval", Description: "runs some go code", @@ -117,33 +117,21 @@ func main() { Description: "The member to removes a role from", Required: true, }, - }, - { - Name: "removerole", - Description: "This command removes a role from a member", - DefaultPermission: ptrBool(true), - Options: []*api.CommandOption{ - { - Type: api.CommandOptionTypeUser, - Name: "member", - Description: "The member to removes a role from", - Required: true, - }, - { - Type: api.CommandOptionTypeRole, - Name: "role", - Description: "The role to removes from a member", - Required: true, - }, + { + Type: api.CommandOptionTypeRole, + Name: "role", + Description: "The role to removes from a member", + Required: true, }, }, - } + }, + } - // using the api.RestClient directly to avoid the guild needing to be cached - cmds, err := dgo.RestClient().SetGuildCommands(dgo.ApplicationID(), guildID, rawCmds...) - if err != nil { - logger.Errorf("error while registering guild commands: %s", err) - } + // using the api.RestClient directly to avoid the guild needing to be cached + cmds, err := dgo.RestClient().SetGuildCommands(dgo.ApplicationID(), guildID, rawCmds...) + if err != nil { + logger.Errorf("error while registering guild commands: %s", err) + } var cmdsPermissions []api.SetGuildCommandPermissions for _, cmd := range cmds { @@ -160,9 +148,9 @@ func main() { 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}, }) } cmdsPermissions = append(cmdsPermissions, api.SetGuildCommandPermissions{ @@ -172,7 +160,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 { From c1cafb9e45512405a0933c14c92d9f2146a38b14 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Thu, 10 Jun 2021 13:54:32 +0200 Subject: [PATCH 06/64] implemented getters for component types on events etc --- api/button_interaction.go | 5 +++ api/component_interaction.go | 4 ++ api/dropdown_interaction.go | 5 +++ api/message.go | 78 ++++++++++++++++++++++++++++++++++++ 4 files changed, 92 insertions(+) diff --git a/api/button_interaction.go b/api/button_interaction.go index 042205df..3c69cf03 100644 --- a/api/button_interaction.go +++ b/api/button_interaction.go @@ -10,3 +10,8 @@ type ButtonInteraction struct { type ButtonInteractionData struct { *ComponentInteractionData } + +// Button returns the Button which issued this ButtonInteraction. nil for ephemeral Message(s) +func (i *ButtonInteraction) Button() *Button { + return i.Message.ButtonByID(i.Data.CustomID) +} diff --git a/api/component_interaction.go b/api/component_interaction.go index 7482cea3..7ce52cfb 100644 --- a/api/component_interaction.go +++ b/api/component_interaction.go @@ -22,4 +22,8 @@ func (i *ComponentInteraction) DeferEdit() error { func (i *ComponentInteraction) Edit(messageUpdate MessageUpdate) error { return i.Respond(InteractionResponseTypeUpdateMessage, messageUpdate) } + +// Component returns the Component which issued this ComponentInteraction. nil for ephemeral Message(s) +func (i *ComponentInteraction) Component() Component { + return i.Message.ComponentByID(i.Data.CustomID) } diff --git a/api/dropdown_interaction.go b/api/dropdown_interaction.go index c5b88312..d899ee39 100644 --- a/api/dropdown_interaction.go +++ b/api/dropdown_interaction.go @@ -12,3 +12,8 @@ type DropdownInteractionData struct { Values []string `json:"values"` } +// Dropdown returns the Dropdown which issued this DropdownInteraction. nil for ephemeral Message(s) +func (i *DropdownInteraction) Dropdown() *Dropdown { + return i.Message.DropdownByID(i.Data.CustomID) +} + diff --git a/api/message.go b/api/message.go index 19f3155f..35ecd2c6 100644 --- a/api/message.go +++ b/api/message.go @@ -262,6 +262,84 @@ func (m *Message) Reply(message MessageCreate) (*Message, error) { return m.Disgo.RestClient().SendMessage(m.ChannelID, message) } +// ComponentByID returns the first Button or Dropdown with the specific customID +func (m *Message) ComponentByID(customID string) Component { + for _, actionRow := range m.ActionRows() { + for _, component := range actionRow.Components { + switch c := component.(type) { + case Button: + if c.CustomID == customID { + return c + } + case Dropdown: + if c.CustomID == customID { + return c + } + default: + continue + } + } + } + return nil +} + +// ActionRows returns all ActionRow(s) from this Message +func (m *Message) ActionRows() []ActionRow { + var actionRows []ActionRow + for _, component := range m.Components { + if actionRow, ok := component.(ActionRow); ok { + actionRows = append(actionRows, actionRow) + } + } + return actionRows +} + +// Buttons returns all Button(s) from this Message +func (m *Message) Buttons() []Button { + var buttons []Button + for _, actionRow := range m.ActionRows() { + for _, component := range actionRow.Components { + if button, ok := component.(Button); ok { + buttons = append(buttons, button) + } + } + } + return buttons +} + +// ButtonByID returns a Button with the specific customID from this Message +func (m *Message) ButtonByID(customID string) *Button { + for _, button := range m.Buttons() { + if button.CustomID == customID { + return &button + } + } + return nil +} + +// Dropdowns returns all Dropdown(s) from this Message +func (m *Message) Dropdowns() []Dropdown { + var dropdowns []Dropdown + for _, actionRow := range m.ActionRows() { + for _, component := range actionRow.Components { + if dropdown, ok := component.(Dropdown); ok { + dropdowns = append(dropdowns, dropdown) + } + } + } + return dropdowns +} + +// DropdownByID returns a Dropdown with the specific customID from this Message +func (m *Message) DropdownByID(customID string) *Dropdown { + for _, dropdown := range m.Dropdowns() { + if dropdown.CustomID == customID { + return &dropdown + } + } + return nil +} + // MessageReaction contains information about the reactions of a message_events type MessageReaction struct { Count int `json:"count"` From 4a37c8744fb9cb860b876c45adb4944b82a8bd38 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 11 Jun 2021 02:55:26 +0200 Subject: [PATCH 07/64] 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 | 37 +++++++++++++++++++++++++-------- 7 files changed, 87 insertions(+), 14 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 f8a7ebc6..57c28209 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -349,8 +349,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 c5fbff06..87d29ca2 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -57,15 +57,26 @@ 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, 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 36fceeace3476844df580454a18e630643d9e63f Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 11 Jun 2021 18:56:54 +0200 Subject: [PATCH 08/64] file uplaod refactor --- api/interaction.go | 23 ++++++- api/message.go | 6 +- api/message_create.go | 16 +++-- api/message_update.go | 120 ++++++++++++++++++++++++++++-------- example/examplebot.go | 14 ++--- example/go.mod | 1 - go.mod | 5 +- internal/restclient_impl.go | 80 ++++++++++++++++-------- 8 files changed, 191 insertions(+), 74 deletions(-) diff --git a/api/interaction.go b/api/interaction.go index 2fae4ebe..38299d00 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 35ecd2c6..f1a33dc2 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 57c28209..5fa64548 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -169,7 +169,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 @@ -283,9 +283,10 @@ func commandListener(event events.CommandEvent) { ) case "test": - if err := event.Reply(api.NewMessageCreateBuilder(). + 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), @@ -349,12 +350,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 29bb4fa4a6ae60db488fe19a5e55b676f246f456 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 12 Jun 2021 01:38:32 +0200 Subject: [PATCH 09/64] 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 c64544502dae5a512ae5d9c391fcb999f7f966a3 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 12 Jun 2021 02:18:46 +0200 Subject: [PATCH 10/64] 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 38299d00..24417b2a 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 85ed0c20e4b4fee4560d472918911ca629b9a86a Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 12 Jun 2021 02:20:04 +0200 Subject: [PATCH 11/64] 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 70a1a6017189b371d64d32aa75744e5ba39d200f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?To=CF=80Senpai?= <15636011+TopiSenpai@users.noreply.github.com> Date: Tue, 8 Jun 2021 17:28:39 +0200 Subject: [PATCH 12/64] add missing target-branch --- .github/dependabot.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 3cc9868f..cd204104 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,3 +11,4 @@ updates: schedule: interval: daily open-pull-requests-limit: 10 + target-branch: development From b51bf776b0d6ff6995196494874d1e541418ab85 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 12 Jun 2021 15:15:53 +0200 Subject: [PATCH 13/64] fixed example --- example/examplebot.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/examplebot.go b/example/examplebot.go index 5fa64548..67611688 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -284,7 +284,7 @@ func commandListener(event events.CommandEvent) { case "test": reader, _ := os.Open("gopher.png") - _ = event.Reply(api.NewMessageCreateBuilder(). + if err := event.Reply(api.NewMessageCreateBuilder(). SetContent("test message"). AddFile("gopher.png", reader). SetComponents( From ac3b93f14b493f91ec17bd0b99f339d1f5409b8c Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 14 Jun 2021 18:17:19 +0200 Subject: [PATCH 14/64] added more methods for restroutes --- api/guild.go | 75 +++++++++++++++++++++++++++++++++++-- api/member.go | 38 +++++++++++-------- api/restclient.go | 14 +++++-- api/role.go | 19 +++++++--- internal/restclient_impl.go | 34 ++++++++++++++--- 5 files changed, 146 insertions(+), 34 deletions(-) diff --git a/api/guild.go b/api/guild.go index ce604f9e..bd24104b 100644 --- a/api/guild.go +++ b/api/guild.go @@ -184,14 +184,44 @@ func (g *Guild) Disconnect() error { return g.Disgo.AudioController().Disconnect(g.ID) } +// Update updates the current Guild +func (g *Guild) Update(updateGuild UpdateGuild) (*Guild, error) { + return g.Disgo.RestClient().UpdateGuild(g.ID, updateGuild) +} + +// Delete deletes the current Guild +func (g *Guild) Delete() error { + return g.Disgo.RestClient().DeleteGuild(g.ID) +} + // CreateRole allows you to create a new Role -func (g *Guild) CreateRole(role UpdateRole) (*Role, error) { - return g.Disgo.RestClient().CreateRole(g.ID, role) +func (g *Guild) CreateRole(createRole CreateRole) (*Role, error) { + return g.Disgo.RestClient().CreateRole(g.ID, createRole) +} + +// UpdateRole allows you to update a Role +func (g *Guild) UpdateRole(roleID Snowflake, role UpdateRole) (*Role, error) { + return g.Disgo.RestClient().UpdateRole(g.ID, roleID, role) +} + +// DeleteRole allows you to delete a Role +func (g *Guild) DeleteRole(roleID Snowflake) error { + return g.Disgo.RestClient().DeleteRole(g.ID, roleID) } // AddMember adds a member to the Guild with the oauth2 access token -func (g *Guild) AddMember(userID Snowflake, addGuildMemberData AddGuildMemberData) (*Member, error) { - return g.Disgo.RestClient().AddMember(g.ID, userID, addGuildMemberData) +func (g *Guild) AddMember(userID Snowflake, addMember AddMember) (*Member, error) { + return g.Disgo.RestClient().AddMember(g.ID, userID, addMember) +} + +// UpdateMember updates an existing member of the Guild +func (g *Guild) UpdateMember(userID Snowflake, updateMember UpdateMember) (*Member, error) { + return g.Disgo.RestClient().UpdateMember(g.ID, userID, updateMember) +} + +// KickMember kicks an existing member from the Guild +func (g *Guild) KickMember(userID Snowflake, reason *string) error { + return g.Disgo.RestClient().KickMember(g.ID, userID, reason) } // IconURL returns the Icon of a Guild @@ -261,3 +291,40 @@ func (g *Guild) SetCommandsPermissions(commandPermissions ...SetGuildCommandPerm func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, error) { return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } + +type CreateGuild struct { + Name string `json:"name"` + Region string `json:"region,omitempty"` + Icon string `json:"icon,omitempty"` + VerificationLevel VerificationLevel `json:"verification_level,omitempty"` + DefaultMessageNotificationLevel MessageNotifications `json:"default_message_notification_level"` + ExplicitContentFilterLevel ExplicitContentFilterLevel `json:"explicit_content_filter_level"` + Roles []CreateRole `json:"roles,omitempty"` + Channels []interface{} `json:"channels,omitempty"` + AFKChannelID Snowflake `json:"afk_channel_id,omitempty"` + AFKTimeout int `json:"afk_timeout,omitempty"` + SystemChannelID Snowflake `json:"system_channel_id,omitempty"` + SystemChannelFlags SystemChannelFlag `json:"system_channel_flags,omitempty"` +} + +type UpdateGuild struct { + Name string `json:"name"` + Region *string `json:"region"` + VerificationLevel *VerificationLevel `json:"verification_level"` + DefaultMessageNotificationLevel *MessageNotifications `json:"default_message_notification_level"` + ExplicitContentFilterLevel *ExplicitContentFilterLevel `json:"explicit_content_filter_level"` + AFKChannelID *Snowflake `json:"afk_channel_id"` + AFKTimeout int `json:"afk_timeout"` + Icon *string `json:"icon"` + OwnerID Snowflake `json:"owner_id"` + Splash interface{} `json:"splash"` + DiscoverySplash interface{} `json:"discovery_splash"` + Banner interface{} `json:"banner"` + SystemChannelID *Snowflake `json:"system_channel_id"` + SystemChannelFlags *SystemChannelFlag `json:"system_channel_flags"` + RulesChannelID *Snowflake `json:"rules_channel_id"` + PublicUpdatesChannelID *Snowflake `json:"public_updates_channel_id"` + PreferredLocale *string `json:"preferred_locale"` + Features []GuildFeature `json:"features"` + Description *string `json:"description"` +} diff --git a/api/member.go b/api/member.go index 5c0e5e93..716d32e8 100644 --- a/api/member.go +++ b/api/member.go @@ -18,12 +18,12 @@ type Member struct { } // VoiceState returns the VoiceState for this Member from the Cache(requires CacheFlagVoiceState and GatewayIntentsGuildVoiceStates) -func (m Member) VoiceState() *VoiceState { +func (m *Member) VoiceState() *VoiceState { return m.Disgo.Cache().VoiceState(m.GuildID, m.User.ID) } // EffectiveName returns either the nickname or username depending on if the user has a nickname -func (m Member) EffectiveName() string { +func (m *Member) EffectiveName() string { if m.Nick != nil { return *m.Nick } @@ -31,37 +31,42 @@ func (m Member) EffectiveName() string { } // Guild returns the members guild from the cache -func (m Member) Guild() *Guild { +func (m *Member) Guild() *Guild { return m.Disgo.Cache().Guild(m.GuildID) } // IsOwner returns whether the member is the owner of the guild_events that it belongs to -func (m Member) IsOwner() bool { +func (m *Member) IsOwner() bool { return m.Guild().OwnerID == m.User.ID } -// Update updates the member -func (m Member) Update(updateGuildMemberData UpdateGuildMemberData) (*Member, error) { - return m.Disgo.RestClient().UpdateMember(m.GuildID, m.User.ID, updateGuildMemberData) +// Update updates the Member +func (m *Member) Update(updateGuildMember UpdateMember) (*Member, error) { + return m.Disgo.RestClient().UpdateMember(m.GuildID, m.User.ID, updateGuildMember) +} + +// Kick kicks the Member from the Guild +func (m *Member) Kick(reason *string) error { + return m.Disgo.RestClient().KickMember(m.GuildID, m.User.ID, reason) } // Move moves/kicks the member to/from a voice channel -func (m Member) Move(channelID *Snowflake) (*Member, error) { +func (m *Member) Move(channelID *Snowflake) (*Member, error) { return m.Disgo.RestClient().MoveMember(m.GuildID, m.User.ID, channelID) } // AddRole adds a specific role the member -func (m Member) AddRole(roleID Snowflake) error { +func (m *Member) AddRole(roleID Snowflake) error { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } // RemoveRole removes a specific role the member -func (m Member) RemoveRole(roleID Snowflake) error { +func (m *Member) RemoveRole(roleID Snowflake) error { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } -// AddGuildMemberData is used to add a member via the oauth2 access token to a guild -type AddGuildMemberData struct { +// AddMember is used to add a member via the oauth2 access token to a guild +type AddMember struct { AccessToken string `json:"access_token"` Nick *string `json:"nick,omitempty"` Roles []Snowflake `json:"roles,omitempty"` @@ -69,16 +74,17 @@ type AddGuildMemberData struct { Deaf *bool `json:"deaf,omitempty"` } -// UpdateGuildMemberData is used to modify -type UpdateGuildMemberData struct { +// UpdateMember is used to modify +type UpdateMember struct { + *MoveMember Nick *string `json:"nick,omitempty"` Roles []Snowflake `json:"roles,omitempty"` Mute *bool `json:"mute,omitempty"` Deaf *bool `json:"deaf,omitempty"` } -// MoveGuildMemberData is used to move a member -type MoveGuildMemberData struct { +// MoveMember is used to move a member +type MoveMember struct { ChannelID *Snowflake `json:"channel_id"` } diff --git a/api/restclient.go b/api/restclient.go index 2484b0eb..68e19303 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -37,16 +37,22 @@ 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, addMember AddMember) (*Member, error) KickMember(guildID Snowflake, userID Snowflake, reason *string) error - UpdateMember(guildID Snowflake, userID Snowflake, updateGuildMemberData UpdateGuildMemberData) (*Member, error) + UpdateMember(guildID Snowflake, userID Snowflake, updateMember UpdateMember) (*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 + GetGuild(guildID Snowflake, withCounts bool) (*Guild, error) + GetGuildPreview(guildID Snowflake) (*GuildPreview, error) + CreateGuild(guildID Snowflake, createGuild CreateGuild) (*Guild, error) + UpdateGuild(guildID Snowflake, updateGuild UpdateGuild) (*Guild, error) + DeleteGuild(guildID Snowflake) error + GetRoles(guildID Snowflake) ([]*Role, error) - CreateRole(guildID Snowflake, role UpdateRole) (*Role, error) - UpdateRole(guildID Snowflake, roleID Snowflake, role UpdateRole) (*Role, error) + CreateRole(guildID Snowflake, createRole CreateRole) (*Role, error) + UpdateRole(guildID Snowflake, roleID Snowflake, updateRole UpdateRole) (*Role, error) UpdateRolePositions(guildID Snowflake, roleUpdates ...UpdateRolePosition) ([]*Role, error) DeleteRole(guildID Snowflake, roleID Snowflake) error diff --git a/api/role.go b/api/role.go index 79cad9af..0f591786 100644 --- a/api/role.go +++ b/api/role.go @@ -52,13 +52,22 @@ type RoleTag struct { PremiumSubscriber bool `json:"premium_subscriber"` } +// CreateRole is the payload to create a Role +type CreateRole struct { + Name string `json:"name,omitempty"` + Permissions Permissions `json:"permissions,omitempty"` + Color int `json:"color,omitempty"` + Hoist bool `json:"hoist,omitempty"` + Mentionable bool `json:"mentionable,omitempty"` +} + // UpdateRole is the payload to update a Role type UpdateRole struct { - Name *string `json:"name,omitempty"` - Permissions *Permissions `json:"permissions,omitempty"` - Color *int `json:"color,omitempty"` - Hoist *bool `json:"hoist,omitempty"` - Mentionable *bool `json:"mentionable,omitempty"` + Name *string `json:"name"` + Permissions *Permissions `json:"permissions"` + Color *int `json:"color"` + Hoist *bool `json:"hoist"` + Mentionable *bool `json:"mentionable"` } // UpdateRolePosition is the payload to update a Role(s) position diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index aedd8f37..276a0a2b 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -24,6 +24,30 @@ type RestClientImpl struct { disgo api.Disgo } +func (r *RestClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (*api.Guild, error) { + panic("implement me") +} + +func (r *RestClientImpl) GetGuildPreview(guildID api.Snowflake) (*api.GuildPreview, error) { + panic("implement me") +} + +func (r *RestClientImpl) CreateGuild(guildID api.Snowflake, createGuild api.CreateGuild) (*api.Guild, error) { + panic("implement me") +} + +func (r *RestClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (*api.Guild, error) { + panic("implement me") +} + +func (r *RestClientImpl) DeleteGuild(guildID api.Snowflake) error { + panic("implement me") +} + +func (r *RestClientImpl) CreateRole(guildID api.Snowflake, createRole api.CreateRole) (*api.Role, error) { + panic("implement me") +} + // Disgo returns the api.Disgo instance func (r *RestClientImpl) Disgo() api.Disgo { return r.disgo @@ -214,12 +238,12 @@ 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, addMember api.AddMember) (member *api.Member, err error) { compiledRoute, err := restclient.AddMember.Compile(nil, guildID, userID) if err != nil { return nil, err } - err = r.Do(compiledRoute, addGuildMemberData, &member) + err = r.Do(compiledRoute, addMember, &member) if err == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } @@ -245,12 +269,12 @@ func (r *RestClientImpl) KickMember(guildID api.Snowflake, userID api.Snowflake, } // UpdateMember updates a api.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, updateMember api.UpdateMember) (member *api.Member, err error) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { return nil, err } - err = r.Do(compiledRoute, updateGuildMemberData, &member) + err = r.Do(compiledRoute, updateMember, &member) if err == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } @@ -263,7 +287,7 @@ func (r *RestClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, if err != nil { return nil, err } - err = r.Do(compiledRoute, api.MoveGuildMemberData{ChannelID: channelID}, &member) + err = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) if err == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } From ef0def05d97842399d10899ab51d7ca02762c77e Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 15 Jun 2021 15:33:25 +0200 Subject: [PATCH 15/64] new rest routes & cleanup --- api/channels.go | 28 +- api/command.go | 4 +- api/disgo.go | 74 +-- api/entity_builder.go | 2 +- api/event_manager.go | 41 ++ api/gateway.go | 31 +- api/guild.go | 69 ++- api/interaction.go | 26 +- api/member.go | 28 +- api/message.go | 22 +- api/restclient.go | 132 ++--- api/role.go | 8 +- api/self_user.go | 21 +- api/user.go | 8 +- example/examplebot.go | 4 +- go.mod | 4 + internal/audio_controller_impl.go | 16 +- internal/disgo_builder_impl.go | 3 +- internal/disgo_impl.go | 51 +- internal/entity_builder_impl.go | 41 +- internal/gateway_impl.go | 91 ++-- internal/handlers/guild_create_handler.go | 39 +- internal/handlers/guild_delete_handler.go | 8 +- internal/handlers/guild_update_handler.go | 8 +- internal/restclient_impl.go | 622 +++++++++++++--------- internal/util.go | 1 - 26 files changed, 806 insertions(+), 576 deletions(-) create mode 100644 api/event_manager.go diff --git a/api/channels.go b/api/channels.go index 29e473ce..53048c89 100644 --- a/api/channels.go +++ b/api/channels.go @@ -1,6 +1,10 @@ package api -import "errors" +import ( + "errors" + + "github.com/DisgoOrg/restclient" +) // ChannelType for interacting with discord's channels type ChannelType int @@ -45,30 +49,29 @@ type MessageChannel struct { } // SendMessage sends a Message to a TextChannel -func (c MessageChannel) SendMessage(message MessageCreate) (*Message, error) { - // Todo: attachments - return c.Disgo.RestClient().SendMessage(c.ID, message) +func (c MessageChannel) SendMessage(message MessageCreate) (*Message, restclient.RestError) { + return c.Disgo.RestClient().CreateMessage(c.ID, message) } // EditMessage edits a Message in this TextChannel -func (c MessageChannel) EditMessage(messageID Snowflake, message MessageUpdate) (*Message, error) { - return c.Disgo.RestClient().EditMessage(c.ID, messageID, message) +func (c MessageChannel) EditMessage(messageID Snowflake, message MessageUpdate) (*Message, restclient.RestError) { + return c.Disgo.RestClient().UpdateMessage(c.ID, messageID, message) } // DeleteMessage allows you to edit an existing Message sent by you -func (c MessageChannel) DeleteMessage(messageID Snowflake) error { +func (c MessageChannel) DeleteMessage(messageID Snowflake) restclient.RestError { return c.Disgo.RestClient().DeleteMessage(c.ID, messageID) } // BulkDeleteMessages allows you bulk delete Message(s) -func (c MessageChannel) BulkDeleteMessages(messageIDs ...Snowflake) error { +func (c MessageChannel) BulkDeleteMessages(messageIDs ...Snowflake) restclient.RestError { return c.Disgo.RestClient().BulkDeleteMessages(c.ID, messageIDs...) } // CrosspostMessage crossposts an existing Message -func (c MessageChannel) CrosspostMessage(messageID Snowflake) (*Message, error) { +func (c MessageChannel) CrosspostMessage(messageID Snowflake) (*Message, restclient.RestError) { if c.Type != ChannelTypeNews { - return nil, errors.New("channel type is not NEWS") + return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) } return c.Disgo.RestClient().CrosspostMessage(c.ID, messageID) } @@ -78,6 +81,11 @@ type DMChannel struct { MessageChannel } +// CreateDMChannel is the payload used to create a DMChannel +type CreateDMChannel struct { + RecipientID Snowflake `json:"recipient_id"` +} + // GuildChannel is a generic type for all server channels type GuildChannel struct { Channel diff --git a/api/command.go b/api/command.go index 4c013c0b..4ae3b0ae 100644 --- a/api/command.go +++ b/api/command.go @@ -68,10 +68,10 @@ func (c *Command) Update(command CommandUpdate) error { var rC *Command var err error if c.GuildID == nil { - rC, err = c.Disgo.RestClient().EditGlobalCommand(c.Disgo.ApplicationID(), c.ID, command) + rC, err = c.Disgo.RestClient().UpdateGlobalCommand(c.Disgo.ApplicationID(), c.ID, command) } else { - rC, err = c.Disgo.RestClient().EditGuildCommand(c.Disgo.ApplicationID(), *c.GuildID, c.ID, command) + rC, err = c.Disgo.RestClient().UpdateGuildCommand(c.Disgo.ApplicationID(), *c.GuildID, c.ID, command) } if err != nil { return err diff --git a/api/disgo.go b/api/disgo.go index 6967d900..70c15e78 100644 --- a/api/disgo.go +++ b/api/disgo.go @@ -1,12 +1,12 @@ package api import ( - "encoding/json" "runtime" "strings" "time" "github.com/DisgoOrg/log" + "github.com/DisgoOrg/restclient" ) // Disgo is the main discord interface @@ -23,8 +23,8 @@ type Disgo interface { GatewayIntents() GatewayIntents RawGatewayEventsEnabled() bool ApplicationID() Snowflake + ClientID() Snowflake SelfUser() *SelfUser - SelfUserID() Snowflake EntityBuilder() EntityBuilder EventManager() EventManager VoiceDispatchInterceptor() VoiceDispatchInterceptor @@ -34,62 +34,24 @@ type Disgo interface { LargeThreshold() int HasGateway() bool - GetCommand(commandID Snowflake) (*Command, error) - GetCommands() ([]*Command, error) - CreateCommand(command CommandCreate) (*Command, error) - EditCommand(commandID Snowflake, command CommandUpdate) (*Command, error) - DeleteCommand(commandID Snowflake) error - SetCommands(commands ...CommandCreate) ([]*Command, error) + GetCommand(commandID Snowflake) (*Command, restclient.RestError) + GetCommands() ([]*Command, restclient.RestError) + CreateCommand(command CommandCreate) (*Command, restclient.RestError) + EditCommand(commandID Snowflake, command CommandUpdate) (*Command, restclient.RestError) + DeleteCommand(commandID Snowflake) restclient.RestError + SetCommands(commands ...CommandCreate) ([]*Command, restclient.RestError) - 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) - DeleteGuildCommand(guildID Snowflake, commandID Snowflake) error - SetGuildCommands(guildID Snowflake, commands ...CommandCreate) ([]*Command, error) + GetGuildCommand(guildID Snowflake, commandID Snowflake) (*Command, restclient.RestError) + GetGuildCommands(guildID Snowflake) ([]*Command, restclient.RestError) + CreateGuildCommand(guildID Snowflake, commandCreate CommandCreate) (*Command, restclient.RestError) + EditGuildCommand(guildID Snowflake, commandID Snowflake, commandUpdate CommandUpdate) (*Command, restclient.RestError) + DeleteGuildCommand(guildID Snowflake, commandID Snowflake) restclient.RestError + SetGuildCommands(guildID Snowflake, commandCreates ...CommandCreate) ([]*Command, restclient.RestError) - 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) -} - -// EventHandler provides info about the EventHandler -type EventHandler interface { - Event() GatewayEventType - New() interface{} -} - -// GatewayEventHandler is used to handle raw gateway events -type GatewayEventHandler interface { - EventHandler - HandleGatewayEvent(disgo Disgo, eventManager EventManager, sequenceNumber int, payload interface{}) -} - -// WebhookEventHandler is used to handle raw webhook events -type WebhookEventHandler interface { - EventHandler - HandleWebhookEvent(disgo Disgo, eventManager EventManager, replyChannel chan InteractionResponse, payload interface{}) -} - -// EventListener is used to create new EventListener to listen to events -type EventListener interface { - OnEvent(event interface{}) -} - -// Event the basic interface each event implement -type Event interface { - Disgo() Disgo - SequenceNumber() int -} - -// EventManager lets you listen for specific events triggered by raw gateway events -type EventManager interface { - Disgo() Disgo - Close() - AddEventListeners(eventListeners ...EventListener) - Handle(eventType GatewayEventType, replyChannel chan InteractionResponse, sequenceNumber int, payload json.RawMessage) - Dispatch(event Event) + GetGuildCommandsPermissions(guildID Snowflake) ([]*GuildCommandPermissions, restclient.RestError) + GetGuildCommandPermissions(guildID Snowflake, commandID Snowflake) (*GuildCommandPermissions, restclient.RestError) + SetGuildCommandsPermissions(guildID Snowflake, commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, restclient.RestError) + SetGuildCommandPermissions(guildID Snowflake, commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, restclient.RestError) } // GetOS returns the simplified version of the operating system for sending to Discord in the IdentifyCommandDataProperties.OS payload diff --git a/api/entity_builder.go b/api/entity_builder.go index b328876f..fa51a164 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -24,7 +24,7 @@ type EntityBuilder interface { CreateMessage(message *FullMessage, updateCache CacheStrategy) *Message - CreateGuild(guild *Guild, updateCache CacheStrategy) *Guild + CreateGuild(fullGuild *FullGuild, updateCache CacheStrategy) *Guild CreateMember(guildID Snowflake, member *Member, updateCache CacheStrategy) *Member CreateGuildCommand(guildID Snowflake, command *Command, updateCache CacheStrategy) *Command CreateGuildCommandPermissions(guildCommandPermissions *GuildCommandPermissions, updateCache CacheStrategy) *GuildCommandPermissions diff --git a/api/event_manager.go b/api/event_manager.go new file mode 100644 index 00000000..d22e28a8 --- /dev/null +++ b/api/event_manager.go @@ -0,0 +1,41 @@ +package api + +import "encoding/json" + +// EventManager lets you listen for specific events triggered by raw gateway events +type EventManager interface { + Disgo() Disgo + Close() + AddEventListeners(eventListeners ...EventListener) + Handle(eventType GatewayEventType, replyChannel chan InteractionResponse, sequenceNumber int, payload json.RawMessage) + Dispatch(event Event) +} + +// EventListener is used to create new EventListener to listen to events +type EventListener interface { + OnEvent(event interface{}) +} + +// Event the basic interface each event implement +type Event interface { + Disgo() Disgo + SequenceNumber() int +} + +// EventHandler provides info about the EventHandler +type EventHandler interface { + Event() GatewayEventType + New() interface{} +} + +// GatewayEventHandler is used to handle raw gateway events +type GatewayEventHandler interface { + EventHandler + HandleGatewayEvent(disgo Disgo, eventManager EventManager, sequenceNumber int, payload interface{}) +} + +// WebhookEventHandler is used to handle raw webhook events +type WebhookEventHandler interface { + EventHandler + HandleWebhookEvent(disgo Disgo, eventManager EventManager, replyChannel chan InteractionResponse, payload interface{}) +} diff --git a/api/gateway.go b/api/gateway.go index e617ca80..e91ae78b 100644 --- a/api/gateway.go +++ b/api/gateway.go @@ -9,18 +9,28 @@ import ( // GatewayStatus is the state that the client is currently in type GatewayStatus int +// IsConnected returns weather you can send payloads to the Gateway +func (s GatewayStatus) IsConnected() bool { + switch s { + case GatewayStatusWaitingForGuilds, GatewayStatusReady: + return true + default: + return false + } +} + // Indicates how far along the client is to connecting const ( - Ready GatewayStatus = iota - Unconnected - Connecting - Reconnecting - WaitingForHello - WaitingForReady - Disconnected - WaitingForGuilds - Identifying - Resuming + GatewayStatusUnconnected GatewayStatus = iota + GatewayStatusConnecting + GatewayStatusReconnecting + GatewayStatusIdentifying + GatewayStatusWaitingForHello + GatewayStatusWaitingForReady + GatewayStatusWaitingForGuilds + GatewayStatusReady + GatewayStatusDisconnected + GatewayStatusResuming ) // Gateway is what is used to connect to discord @@ -28,6 +38,7 @@ type Gateway interface { Disgo() Disgo Open() error Status() GatewayStatus + Send(command GatewayCommand) error Close() Conn() *websocket.Conn Latency() time.Duration diff --git a/api/guild.go b/api/guild.go index bd24104b..2f44206f 100644 --- a/api/guild.go +++ b/api/guild.go @@ -105,7 +105,6 @@ type GuildWelcomeChannel struct { // GuildPreview is used for previewing public Guild(s) before joining them type GuildPreview struct { - Disgo Disgo ID Snowflake `json:"id"` Name string `json:"name"` Icon *string `json:"icon"` @@ -172,56 +171,64 @@ 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) } // Update updates the current Guild -func (g *Guild) Update(updateGuild UpdateGuild) (*Guild, error) { +func (g *Guild) Update(updateGuild UpdateGuild) (*Guild, restclient.RestError) { return g.Disgo.RestClient().UpdateGuild(g.ID, updateGuild) } // Delete deletes the current Guild -func (g *Guild) Delete() error { +func (g *Guild) Delete() restclient.RestError { return g.Disgo.RestClient().DeleteGuild(g.ID) } // CreateRole allows you to create a new Role -func (g *Guild) CreateRole(createRole CreateRole) (*Role, error) { +func (g *Guild) CreateRole(createRole CreateRole) (*Role, restclient.RestError) { return g.Disgo.RestClient().CreateRole(g.ID, createRole) } // UpdateRole allows you to update a Role -func (g *Guild) UpdateRole(roleID Snowflake, role UpdateRole) (*Role, error) { +func (g *Guild) UpdateRole(roleID Snowflake, role UpdateRole) (*Role, restclient.RestError) { return g.Disgo.RestClient().UpdateRole(g.ID, roleID, role) } // DeleteRole allows you to delete a Role -func (g *Guild) DeleteRole(roleID Snowflake) error { +func (g *Guild) DeleteRole(roleID Snowflake) restclient.RestError { return g.Disgo.RestClient().DeleteRole(g.ID, roleID) } +// GetSelfMember returns the SelfMember for this Guild +func (g *Guild) GetSelfMember() *SelfMember { + return &SelfMember{Member: g.GetMember(g.Disgo.ClientID())} +} + +// Leave leaves the Guild +func (g *Guild) Leave() restclient.RestError { + return g.Disgo.RestClient().LeaveGuild(g.ID) +} + +// GetMember returns the Member for the current logged in User for this Guild +func (g *Guild) GetMember(userID Snowflake) *Member { + return g.Disgo.Cache().Member(g.ID, userID) +} + // AddMember adds a member to the Guild with the oauth2 access token -func (g *Guild) AddMember(userID Snowflake, addMember AddMember) (*Member, error) { +func (g *Guild) AddMember(userID Snowflake, addMember AddMember) (*Member, restclient.RestError) { return g.Disgo.RestClient().AddMember(g.ID, userID, addMember) } // UpdateMember updates an existing member of the Guild -func (g *Guild) UpdateMember(userID Snowflake, updateMember UpdateMember) (*Member, error) { +func (g *Guild) UpdateMember(userID Snowflake, updateMember UpdateMember) (*Member, restclient.RestError) { return g.Disgo.RestClient().UpdateMember(g.ID, userID, updateMember) } // KickMember kicks an existing member from the Guild -func (g *Guild) KickMember(userID Snowflake, reason *string) error { - return g.Disgo.RestClient().KickMember(g.ID, userID, reason) +func (g *Guild) KickMember(userID Snowflake, reason string) restclient.RestError { + return g.Disgo.RestClient().RemoveMember(g.ID, userID, reason) } // IconURL returns the Icon of a Guild @@ -243,42 +250,42 @@ func (g *Guild) IconURL(size int) *string { } // GetCommand fetches a specific Guild Command -func (g *Guild) GetCommand(commandID Snowflake) (*Command, error) { +func (g *Guild) GetCommand(commandID Snowflake) (*Command, restclient.RestError) { return g.Disgo.GetGuildCommand(g.ID, commandID) } // GetCommands fetches all Guild Command(s) -func (g *Guild) GetCommands() ([]*Command, error) { +func (g *Guild) GetCommands() ([]*Command, restclient.RestError) { return g.Disgo.GetGuildCommands(g.ID) } // CreateCommand creates a new Command for this Guild -func (g *Guild) CreateCommand(command CommandCreate) (*Command, error) { +func (g *Guild) CreateCommand(command CommandCreate) (*Command, restclient.RestError) { 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, restclient.RestError) { return g.Disgo.EditGuildCommand(g.ID, commandID, command) } // DeleteCommand creates a new Command for this Guild -func (g *Guild) DeleteCommand(commandID Snowflake) error { +func (g *Guild) DeleteCommand(commandID Snowflake) restclient.RestError { return g.Disgo.DeleteGuildCommand(g.ID, commandID) } // SetCommands overrides all Command(s) for this Guild -func (g *Guild) SetCommands(commands ...CommandCreate) ([]*Command, error) { +func (g *Guild) SetCommands(commands ...CommandCreate) ([]*Command, restclient.RestError) { return g.Disgo.SetGuildCommands(g.ID, commands...) } // GetCommandsPermissions returns the GuildCommandPermissions for a all Command(s) in a Guild -func (g *Guild) GetCommandsPermissions() ([]*GuildCommandPermissions, error) { +func (g *Guild) GetCommandsPermissions() ([]*GuildCommandPermissions, restclient.RestError) { return g.Disgo.GetGuildCommandsPermissions(g.ID) } // GetCommandPermissions returns the GuildCommandPermissions for a specific Command in a Guild -func (g *Guild) GetCommandPermissions(commandID Snowflake) (*GuildCommandPermissions, error) { +func (g *Guild) GetCommandPermissions(commandID Snowflake) (*GuildCommandPermissions, restclient.RestError) { return g.Disgo.GetGuildCommandPermissions(g.ID, commandID) } @@ -292,6 +299,17 @@ func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildC return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } +// PartialGuild is returned on the restclient.GetGuilds route +type PartialGuild struct { + ID Snowflake `json:"id"` + Name string `json:"name"` + Icon string `json:"icon"` + Owner bool `json:"owner"` + Permissions Permissions `json:"permissions"` + Features []GuildFeature `json:"features"` +} + +// CreateGuild is the payload used to create a Guild type CreateGuild struct { Name string `json:"name"` Region string `json:"region,omitempty"` @@ -307,6 +325,7 @@ type CreateGuild struct { SystemChannelFlags SystemChannelFlag `json:"system_channel_flags,omitempty"` } +// UpdateGuild is the payload used to update a Guild type UpdateGuild struct { Name string `json:"name"` Region *string `json:"region"` diff --git a/api/interaction.go b/api/interaction.go index 5cb360b0..037eda67 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -59,11 +59,11 @@ func (r InteractionResponse) ToBody() (interface{}, error) { } switch v := r.Data.(type) { case MessageCreate: - if len(v.Files) > 0 { + if len(v.Files) > 0 { return restclient.PayloadWithFiles(r, v.Files...) } case MessageUpdate: - if len(v.Files) > 0 { + if len(v.Files) > 0 { return restclient.PayloadWithFiles(r, v.Files...) } } @@ -71,13 +71,13 @@ func (r InteractionResponse) ToBody() (interface{}, error) { } // Respond responds to the api.Interaction with the provided api.InteractionResponse -func (i *Interaction) Respond(responseType InteractionResponseType, data interface{}) error { +func (i *Interaction) Respond(responseType InteractionResponseType, data interface{}) restclient.RestError { response := InteractionResponse{ Type: responseType, Data: data, } if i.Replied { - return errors.New("you already replied to this interaction") + return restclient.NewRestError(nil, errors.New("you already replied to this interaction")) } i.Replied = true @@ -90,7 +90,7 @@ 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 { +func (i *Interaction) DeferReply(ephemeral bool) restclient.RestError { var messageCreate interface{} if ephemeral { messageCreate = MessageCreate{Flags: MessageFlagEphemeral} @@ -99,32 +99,32 @@ func (i *Interaction) DeferReply(ephemeral bool) error { } // Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.MessageCreate -func (i *Interaction) Reply(messageCreate MessageCreate) error { +func (i *Interaction) Reply(messageCreate MessageCreate) restclient.RestError { return i.Respond(InteractionResponseTypeChannelMessageWithSource, messageCreate) } // EditOriginal edits the original api.InteractionResponse -func (i *Interaction) EditOriginal(messageUpdate MessageUpdate) (*Message, error) { - return i.Disgo.RestClient().EditInteractionResponse(i.Disgo.ApplicationID(), i.Token, messageUpdate) +func (i *Interaction) EditOriginal(messageUpdate MessageUpdate) (*Message, restclient.RestError) { + return i.Disgo.RestClient().UpdateInteractionResponse(i.Disgo.ApplicationID(), i.Token, messageUpdate) } // DeleteOriginal deletes the original api.InteractionResponse -func (i *Interaction) DeleteOriginal() error { +func (i *Interaction) DeleteOriginal() restclient.RestError { return i.Disgo.RestClient().DeleteInteractionResponse(i.Disgo.ApplicationID(), i.Token) } // SendFollowup used to send a api.MessageCreate to an api.Interaction -func (i *Interaction) SendFollowup(messageCreate MessageCreate) (*Message, error) { +func (i *Interaction) SendFollowup(messageCreate MessageCreate) (*Message, restclient.RestError) { return i.Disgo.RestClient().SendFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageCreate) } // 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) +func (i *Interaction) EditFollowup(messageID Snowflake, messageUpdate MessageUpdate) (*Message, restclient.RestError) { + return i.Disgo.RestClient().UpdateFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID, messageUpdate) } // DeleteFollowup used to delete a api.Message from an api.Interaction -func (i *Interaction) DeleteFollowup(messageID Snowflake) error { +func (i *Interaction) DeleteFollowup(messageID Snowflake) restclient.RestError { return i.Disgo.RestClient().DeleteFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID) } diff --git a/api/member.go b/api/member.go index 716d32e8..38551da4 100644 --- a/api/member.go +++ b/api/member.go @@ -1,6 +1,10 @@ package api -import "time" +import ( + "time" + + "github.com/DisgoOrg/restclient" +) // Member is a discord GuildMember type Member struct { @@ -41,37 +45,37 @@ func (m *Member) IsOwner() bool { } // Update updates the Member -func (m *Member) Update(updateGuildMember UpdateMember) (*Member, error) { +func (m *Member) Update(updateGuildMember UpdateMember) (*Member, restclient.RestError) { return m.Disgo.RestClient().UpdateMember(m.GuildID, m.User.ID, updateGuildMember) } // Kick kicks the Member from the Guild -func (m *Member) Kick(reason *string) error { - return m.Disgo.RestClient().KickMember(m.GuildID, m.User.ID, reason) +func (m *Member) Kick(reason string) restclient.RestError { + return m.Disgo.RestClient().RemoveMember(m.GuildID, m.User.ID, reason) } // Move moves/kicks the member to/from a voice channel -func (m *Member) Move(channelID *Snowflake) (*Member, error) { +func (m *Member) Move(channelID *Snowflake) (*Member, restclient.RestError) { return m.Disgo.RestClient().MoveMember(m.GuildID, m.User.ID, channelID) } // AddRole adds a specific role the member -func (m *Member) AddRole(roleID Snowflake) error { +func (m *Member) AddRole(roleID Snowflake) restclient.RestError { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } // RemoveRole removes a specific role the member -func (m *Member) RemoveRole(roleID Snowflake) error { +func (m *Member) RemoveRole(roleID Snowflake) restclient.RestError { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } // AddMember is used to add a member via the oauth2 access token to a guild type AddMember struct { AccessToken string `json:"access_token"` - Nick *string `json:"nick,omitempty"` + Nick string `json:"nick,omitempty"` Roles []Snowflake `json:"roles,omitempty"` - Mute *bool `json:"mute,omitempty"` - Deaf *bool `json:"deaf,omitempty"` + Mute bool `json:"mute,omitempty"` + Deaf bool `json:"deaf,omitempty"` } // UpdateMember is used to modify @@ -85,10 +89,10 @@ type UpdateMember struct { // MoveMember is used to move a member type MoveMember struct { - ChannelID *Snowflake `json:"channel_id"` + ChannelID *Snowflake `json:"channel_id,omitempty"` } // UpdateSelfNick is used to update your own nick type UpdateSelfNick struct { - Nick *string `json:"nick"` + Nick string `json:"nick"` } diff --git a/api/message.go b/api/message.go index e1b6bc14..498cec60 100644 --- a/api/message.go +++ b/api/message.go @@ -3,6 +3,8 @@ package api import ( "errors" "time" + + "github.com/DisgoOrg/restclient" ) // The MessageType indicates the Message type @@ -226,40 +228,40 @@ func (m *Message) Channel() *MessageChannel { } // AddReactionByEmote allows you to add an Emoji to a message_events via reaction -func (m *Message) AddReactionByEmote(emote Emoji) error { +func (m *Message) AddReactionByEmote(emote Emoji) restclient.RestError { return m.AddReaction(emote.Reaction()) } // AddReaction allows you to add a reaction to a message_events from a string, for example a custom emoji ID, or a native emoji -func (m *Message) AddReaction(emoji string) error { +func (m *Message) AddReaction(emoji string) restclient.RestError { return m.Disgo.RestClient().AddReaction(m.ChannelID, m.ID, emoji) } -// Edit allows you to edit an existing Message sent by you -func (m *Message) Edit(message MessageUpdate) (*Message, error) { - return m.Disgo.RestClient().EditMessage(m.ChannelID, m.ID, message) +// Update allows you to edit an existing Message sent by you +func (m *Message) Update(message MessageUpdate) (*Message, restclient.RestError) { + return m.Disgo.RestClient().UpdateMessage(m.ChannelID, m.ID, message) } // Delete allows you to edit an existing Message sent by you -func (m *Message) Delete() error { +func (m *Message) Delete() restclient.RestError { return m.Disgo.RestClient().DeleteMessage(m.ChannelID, m.ID) } // Crosspost crossposts an existing message -func (m *Message) Crosspost() (*Message, error) { +func (m *Message) Crosspost() (*Message, restclient.RestError) { channel := m.Channel() if channel != nil && channel.Type != ChannelTypeNews { - return nil, errors.New("channel type is not NEWS") + return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) } return m.Disgo.RestClient().CrosspostMessage(m.ChannelID, m.ID) } // Reply allows you to reply to an existing Message -func (m *Message) Reply(message MessageCreate) (*Message, error) { +func (m *Message) Reply(message MessageCreate) (*Message, restclient.RestError) { message.MessageReference = &MessageReference{ MessageID: &m.ID, } - return m.Disgo.RestClient().SendMessage(m.ChannelID, message) + return m.Disgo.RestClient().CreateMessage(m.ChannelID, message) } // MessageReaction contains information about the reactions of a message_events diff --git a/api/restclient.go b/api/restclient.go index 68e19303..8a21efaa 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -18,72 +18,78 @@ type ErrorResponse struct { Message string } -// RestClient is a manager for all of disgo's HTTP requests +// RestClient is a manager for all of Disgo's HTTP requests type RestClient interface { restclient.RestClient Close() Disgo() Disgo - SendMessage(channelID Snowflake, message MessageCreate) (*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) - - OpenDMChannel(userID Snowflake) (*DMChannel, error) - - UpdateSelfNick(guildID Snowflake, nick *string) (*string, error) - - GetUser(userID Snowflake) (*User, error) - GetMember(guildID Snowflake, userID Snowflake) (*Member, error) - GetMembers(guildID Snowflake) ([]*Member, error) - AddMember(guildID Snowflake, userID Snowflake, addMember AddMember) (*Member, error) - KickMember(guildID Snowflake, userID Snowflake, reason *string) error - UpdateMember(guildID Snowflake, userID Snowflake, updateMember UpdateMember) (*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 - - GetGuild(guildID Snowflake, withCounts bool) (*Guild, error) - GetGuildPreview(guildID Snowflake) (*GuildPreview, error) - CreateGuild(guildID Snowflake, createGuild CreateGuild) (*Guild, error) - UpdateGuild(guildID Snowflake, updateGuild UpdateGuild) (*Guild, error) - DeleteGuild(guildID Snowflake) error - - GetRoles(guildID Snowflake) ([]*Role, error) - CreateRole(guildID Snowflake, createRole CreateRole) (*Role, error) - UpdateRole(guildID Snowflake, roleID Snowflake, updateRole UpdateRole) (*Role, error) - UpdateRolePositions(guildID Snowflake, roleUpdates ...UpdateRolePosition) ([]*Role, error) - DeleteRole(guildID Snowflake, roleID Snowflake) error - - AddReaction(channelID Snowflake, messageID Snowflake, emoji string) error - RemoveOwnReaction(channelID Snowflake, messageID Snowflake, emoji string) error - RemoveUserReaction(channelID Snowflake, messageID Snowflake, emoji string, userID Snowflake) error - - 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) - 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) - 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) - - SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse InteractionResponse) error - EditInteractionResponse(applicationID Snowflake, interactionToken string, messageUpdate MessageUpdate) (*Message, error) - DeleteInteractionResponse(applicationID Snowflake, interactionToken string) 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 + GetUser(userID Snowflake) (*User, restclient.RestError) + GetSelfUser() (*SelfUser, restclient.RestError) + UpdateSelfUser(updateSelfUser UpdateSelfUser) (*SelfUser, restclient.RestError) + GetGuilds(before int, after int, limit int) ([]*PartialGuild, restclient.RestError) + LeaveGuild(guildID Snowflake) restclient.RestError + GetDMChannels() ([]*DMChannel, restclient.RestError) + CreateDMChannel(userID Snowflake) (*DMChannel, restclient.RestError) + + GetMessage(channelID Snowflake, messageID Snowflake) (*Message, restclient.RestError) + CreateMessage(channelID Snowflake, message MessageCreate) (*Message, restclient.RestError) + UpdateMessage(channelID Snowflake, messageID Snowflake, messageUpdate MessageUpdate) (*Message, restclient.RestError) + DeleteMessage(channelID Snowflake, messageID Snowflake) restclient.RestError + BulkDeleteMessages(channelID Snowflake, messageIDs ...Snowflake) restclient.RestError + CrosspostMessage(channelID Snowflake, messageID Snowflake) (*Message, restclient.RestError) + + GetGuild(guildID Snowflake, withCounts bool) (*Guild, restclient.RestError) + GetGuildPreview(guildID Snowflake) (*GuildPreview, restclient.RestError) + CreateGuild(createGuild CreateGuild) (*Guild, restclient.RestError) + UpdateGuild(guildID Snowflake, updateGuild UpdateGuild) (*Guild, restclient.RestError) + DeleteGuild(guildID Snowflake) restclient.RestError + + GetMember(guildID Snowflake, userID Snowflake) (*Member, restclient.RestError) + GetMembers(guildID Snowflake) ([]*Member, restclient.RestError) + SearchMembers(guildID Snowflake, query string, limit int) ([]*Member, restclient.RestError) + AddMember(guildID Snowflake, userID Snowflake, addMember AddMember) (*Member, restclient.RestError) + RemoveMember(guildID Snowflake, userID Snowflake, reason string) restclient.RestError + UpdateMember(guildID Snowflake, userID Snowflake, updateMember UpdateMember) (*Member, restclient.RestError) + UpdateSelfNick(guildID Snowflake, nick string) (*string, restclient.RestError) + MoveMember(guildID Snowflake, userID Snowflake, channelID *Snowflake) (*Member, restclient.RestError) + AddMemberRole(guildID Snowflake, userID Snowflake, roleID Snowflake) restclient.RestError + RemoveMemberRole(guildID Snowflake, userID Snowflake, roleID Snowflake) restclient.RestError + + GetRoles(guildID Snowflake) ([]*Role, restclient.RestError) + CreateRole(guildID Snowflake, createRole CreateRole) (*Role, restclient.RestError) + UpdateRole(guildID Snowflake, roleID Snowflake, updateRole UpdateRole) (*Role, restclient.RestError) + UpdateRolePositions(guildID Snowflake, roleUpdates ...UpdateRolePosition) ([]*Role, restclient.RestError) + DeleteRole(guildID Snowflake, roleID Snowflake) restclient.RestError + + AddReaction(channelID Snowflake, messageID Snowflake, emoji string) restclient.RestError + RemoveOwnReaction(channelID Snowflake, messageID Snowflake, emoji string) restclient.RestError + RemoveUserReaction(channelID Snowflake, messageID Snowflake, emoji string, userID Snowflake) restclient.RestError + + GetGlobalCommands(applicationID Snowflake) ([]*Command, restclient.RestError) + GetGlobalCommand(applicationID Snowflake, commandID Snowflake) (*Command, restclient.RestError) + CreateGlobalCommand(applicationID Snowflake, command CommandCreate) (*Command, restclient.RestError) + SetGlobalCommands(applicationID Snowflake, commands ...CommandCreate) ([]*Command, restclient.RestError) + UpdateGlobalCommand(applicationID Snowflake, commandID Snowflake, command CommandUpdate) (*Command, restclient.RestError) + DeleteGlobalCommand(applicationID Snowflake, commandID Snowflake) restclient.RestError + + GetGuildCommands(applicationID Snowflake, guildID Snowflake) ([]*Command, restclient.RestError) + GetGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake) (*Command, restclient.RestError) + CreateGuildCommand(applicationID Snowflake, guildID Snowflake, command CommandCreate) (*Command, restclient.RestError) + SetGuildCommands(applicationID Snowflake, guildID Snowflake, commands ...CommandCreate) ([]*Command, restclient.RestError) + UpdateGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake, command CommandUpdate) (*Command, restclient.RestError) + DeleteGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake) restclient.RestError + + GetGuildCommandsPermissions(applicationID Snowflake, guildID Snowflake) ([]*GuildCommandPermissions, restclient.RestError) + GetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake) (*GuildCommandPermissions, restclient.RestError) + SetGuildCommandsPermissions(applicationID Snowflake, guildID Snowflake, commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, restclient.RestError) + SetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake, commandPermissions SetGuildCommandPermissions) (*GuildCommandPermissions, restclient.RestError) + + SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse InteractionResponse) restclient.RestError + UpdateInteractionResponse(applicationID Snowflake, interactionToken string, messageUpdate MessageUpdate) (*Message, restclient.RestError) + DeleteInteractionResponse(applicationID Snowflake, interactionToken string) restclient.RestError + + SendFollowupMessage(applicationID Snowflake, interactionToken string, messageCreate MessageCreate) (*Message, restclient.RestError) + UpdateFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, messageUpdate MessageUpdate) (*Message, restclient.RestError) + DeleteFollowupMessage(applicationID Snowflake, interactionToken string, followupMessageID Snowflake) restclient.RestError } diff --git a/api/role.go b/api/role.go index 0f591786..a62741e8 100644 --- a/api/role.go +++ b/api/role.go @@ -1,5 +1,7 @@ package api +import "github.com/DisgoOrg/restclient" + // Role is a Guild Role object type Role struct { Disgo Disgo @@ -31,17 +33,17 @@ func (r *Role) Guild() *Guild { } // Update updates the Role with specific values -func (r *Role) Update(roleUpdate UpdateRole) (*Role, error) { +func (r *Role) Update(roleUpdate UpdateRole) (*Role, restclient.RestError) { 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, restclient.RestError) { return r.Disgo.RestClient().UpdateRolePositions(r.GuildID, rolePositionUpdate) } // Delete deletes the Role -func (r *Role) Delete() error { +func (r *Role) Delete() restclient.RestError { return r.Disgo.RestClient().DeleteRole(r.GuildID, r.ID) } diff --git a/api/self_user.go b/api/self_user.go index 61d436c5..a39d5fe3 100644 --- a/api/self_user.go +++ b/api/self_user.go @@ -1,16 +1,31 @@ package api -import "errors" +import ( + "errors" + + "github.com/DisgoOrg/restclient" +) // ErrDMChannelToYourself occurs when opening a DMChannel to yourself -var ErrDMChannelToYourself = errors.New("can't open a dm channel to yourself") +var ErrDMChannelToYourself = restclient.NewRestError(nil, errors.New("can't open a dm channel to yourself")) // SelfUser represents the current logged in User type SelfUser struct { *User } +// Update updates the SelfUser with the given payload +func (u *SelfUser) Update(updateSelfUser UpdateSelfUser) (*SelfUser, restclient.RestError) { + return u.Disgo.RestClient().UpdateSelfUser(updateSelfUser) +} + // OpenDMChannel creates a DMChannel between the user and the Disgo client -func (u *SelfUser) OpenDMChannel() (*DMChannel, error) { +func (u *SelfUser) OpenDMChannel() (*DMChannel, restclient.RestError) { return nil, ErrDMChannelToYourself } + +// UpdateSelfUser is the payload used to update the SelfUser +type UpdateSelfUser struct { + Username string `json:"username"` + Avatar interface{} +} diff --git a/api/user.go b/api/user.go index 45e7b941..78c9bc9c 100644 --- a/api/user.go +++ b/api/user.go @@ -29,8 +29,8 @@ type User struct { // AvatarURL returns the Avatar URL of the User func (u *User) AvatarURL(size int) string { if u.Avatar == nil { - discrim, _ := strconv.Atoi(u.Discriminator) - route, err := restclient.DefaultUserAvatar.Compile(nil, restclient.PNG, size, discrim%5) + discriminator, _ := strconv.Atoi(u.Discriminator) + route, err := restclient.DefaultUserAvatar.Compile(nil, restclient.PNG, size, discriminator%5) if err != nil { return "" } @@ -62,6 +62,6 @@ func (u *User) String() string { } // OpenDMChannel creates a DMChannel between the user and the Disgo client -func (u *User) OpenDMChannel() (*DMChannel, error) { - return u.Disgo.RestClient().OpenDMChannel(u.ID) +func (u *User) OpenDMChannel() (*DMChannel, restclient.RestError) { + return u.Disgo.RestClient().CreateDMChannel(u.ID) } diff --git a/example/examplebot.go b/example/examplebot.go index ddaada0d..f59f79cc 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -334,11 +334,11 @@ func messageListener(event events.GuildMessageCreateEvent) { time.Sleep(time.Second * 2) embed := api.NewEmbedBuilder().SetDescription("edit").Build() - message, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbeds(embed, embed).Build()) + message, _ = message.Update(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbeds(embed, embed).Build()) time.Sleep(time.Second * 2) - _, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("").SetEmbeds(api.NewEmbedBuilder().SetDescription("edit2").Build()).Build()) + _, _ = message.Update(api.NewMessageUpdateBuilder().SetContent("").SetEmbeds(api.NewEmbedBuilder().SetDescription("edit2").Build()).Build()) }() case "dm": diff --git a/go.mod b/go.mod index fbb451bd..42971df3 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +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.5 diff --git a/internal/audio_controller_impl.go b/internal/audio_controller_impl.go index 6b201ff5..ef1337df 100644 --- a/internal/audio_controller_impl.go +++ b/internal/audio_controller_impl.go @@ -2,7 +2,6 @@ package internal import ( "github.com/DisgoOrg/disgo/api" - "github.com/gorilla/websocket" ) func newAudioControllerImpl(disgo api.Disgo) api.AudioController { @@ -21,11 +20,11 @@ func (c *AudioControllerImpl) Disgo() api.Disgo { // Connect sends a api.GatewayCommand to connect to a api.VoiceChannel func (c *AudioControllerImpl) Connect(guildID api.Snowflake, channelID api.Snowflake) error { - conn, err := c.getConn() + gateway, err := c.getGateway() if err != nil { return err } - return conn.WriteJSON(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ + return gateway.Send(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ GuildID: guildID, ChannelID: &channelID, })) @@ -33,24 +32,23 @@ func (c *AudioControllerImpl) Connect(guildID api.Snowflake, channelID api.Snowf // Disconnect sends a api.GatewayCommand to disconnect from a api.VoiceChannel func (c *AudioControllerImpl) Disconnect(guildID api.Snowflake) error { - conn, err := c.getConn() + gateway, err := c.getGateway() if err != nil { return err } - return conn.WriteJSON(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ + return gateway.Send(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ GuildID: guildID, ChannelID: nil, })) } -func (c *AudioControllerImpl) getConn() (*websocket.Conn, error) { +func (c *AudioControllerImpl) getGateway() (api.Gateway, error) { gateway := c.Disgo().Gateway() if gateway == nil { return nil, api.ErrNoGateway } - conn := gateway.Conn() - if conn == nil { + if !gateway.Status().IsConnected() { return nil, api.ErrNoGatewayConn } - return conn, nil + return gateway, nil } diff --git a/internal/disgo_builder_impl.go b/internal/disgo_builder_impl.go index a608679c..e6273bc2 100644 --- a/internal/disgo_builder_impl.go +++ b/internal/disgo_builder_impl.go @@ -183,7 +183,8 @@ func (b *DisgoBuilderImpl) Build() (api.Disgo, error) { return nil, err } - disgo.selfUserID = *id + disgo.applicationID = *id + disgo.clientID = *id if b.gateway == nil { b.gateway = newGatewayImpl(disgo) diff --git a/internal/disgo_impl.go b/internal/disgo_impl.go index c65c69bb..35b958db 100644 --- a/internal/disgo_impl.go +++ b/internal/disgo_impl.go @@ -4,6 +4,7 @@ import ( "time" "github.com/DisgoOrg/log" + "github.com/DisgoOrg/restclient" "github.com/DisgoOrg/disgo/api" ) @@ -30,7 +31,8 @@ func New(token string, options api.Options) (api.Disgo, error) { return nil, err } - disgo.selfUserID = *id + disgo.applicationID = *id + disgo.clientID = *id disgo.restClient = newRestClientImpl(disgo, options.HTTPClient) @@ -63,7 +65,8 @@ type DisgoImpl struct { audioController api.AudioController webhookServer api.WebhookServer cache api.Cache - selfUserID api.Snowflake + applicationID api.Snowflake + clientID api.Snowflake selfUser *api.SelfUser largeThreshold int } @@ -171,7 +174,7 @@ func (d *DisgoImpl) RawGatewayEventsEnabled() bool { // ApplicationID returns the current application id func (d *DisgoImpl) ApplicationID() api.Snowflake { - return d.selfUserID + return d.applicationID } // SelfUser returns a api.SelfUser for the client, if available @@ -179,9 +182,9 @@ func (d *DisgoImpl) SelfUser() *api.SelfUser { return d.selfUser } -// SelfUserID returns the current user id -func (d *DisgoImpl) SelfUserID() api.Snowflake { - return d.selfUserID +// ClientID returns the current user id +func (d *DisgoImpl) ClientID() api.Snowflake { + return d.clientID } // HeartbeatLatency returns the heartbeat latency @@ -200,81 +203,81 @@ func (d *DisgoImpl) HasGateway() bool { } // GetCommand fetches a specific global api.Command -func (d *DisgoImpl) GetCommand(commandID api.Snowflake) (*api.Command, error) { +func (d *DisgoImpl) GetCommand(commandID api.Snowflake) (*api.Command, restclient.RestError) { return d.RestClient().GetGlobalCommand(d.ApplicationID(), commandID) } // GetCommands fetches all global api.Command(s) -func (d *DisgoImpl) GetCommands() ([]*api.Command, error) { +func (d *DisgoImpl) GetCommands() ([]*api.Command, restclient.RestError) { return d.RestClient().GetGlobalCommands(d.ApplicationID()) } // 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, restclient.RestError) { 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) { - return d.RestClient().EditGlobalCommand(d.ApplicationID(), commandID, command) +func (d *DisgoImpl) EditCommand(commandID api.Snowflake, command api.CommandUpdate) (*api.Command, restclient.RestError) { + return d.RestClient().UpdateGlobalCommand(d.ApplicationID(), commandID, command) } // DeleteCommand creates a new global api.Command -func (d *DisgoImpl) DeleteCommand(commandID api.Snowflake) error { +func (d *DisgoImpl) DeleteCommand(commandID api.Snowflake) restclient.RestError { return d.RestClient().DeleteGlobalCommand(d.ApplicationID(), commandID) } // 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, restclient.RestError) { return d.RestClient().SetGlobalCommands(d.ApplicationID(), commands...) } // GetGuildCommand fetches a specific api.Guild api.Command -func (d *DisgoImpl) GetGuildCommand(guildID api.Snowflake, commandID api.Snowflake) (*api.Command, error) { +func (d *DisgoImpl) GetGuildCommand(guildID api.Snowflake, commandID api.Snowflake) (*api.Command, restclient.RestError) { return d.RestClient().GetGuildCommand(d.ApplicationID(), guildID, commandID) } // GetGuildCommands fetches all api.Guild api.Command(s) -func (d *DisgoImpl) GetGuildCommands(guildID api.Snowflake, ) ([]*api.Command, error) { +func (d *DisgoImpl) GetGuildCommands(guildID api.Snowflake) ([]*api.Command, restclient.RestError) { return d.RestClient().GetGuildCommands(d.ApplicationID(), guildID) } // 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, restclient.RestError) { 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) { - return d.RestClient().EditGuildCommand(d.ApplicationID(), guildID, commandID, command) +func (d *DisgoImpl) EditGuildCommand(guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (*api.Command, restclient.RestError) { + return d.RestClient().UpdateGuildCommand(d.ApplicationID(), guildID, commandID, command) } // DeleteGuildCommand creates a new api.Command for this api.Guild -func (d *DisgoImpl) DeleteGuildCommand(guildID api.Snowflake, commandID api.Snowflake) error { +func (d *DisgoImpl) DeleteGuildCommand(guildID api.Snowflake, commandID api.Snowflake) restclient.RestError { return d.RestClient().DeleteGuildCommand(d.ApplicationID(), guildID, commandID) } // 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, restclient.RestError) { return d.RestClient().SetGuildCommands(d.ApplicationID(), guildID, commands...) } // GetGuildCommandsPermissions returns the api.GuildCommandPermissions for a all api.Command(s) in a api.Guild -func (d *DisgoImpl) GetGuildCommandsPermissions(guildID api.Snowflake) ([]*api.GuildCommandPermissions, error) { +func (d *DisgoImpl) GetGuildCommandsPermissions(guildID api.Snowflake) ([]*api.GuildCommandPermissions, restclient.RestError) { return d.RestClient().GetGuildCommandsPermissions(d.ApplicationID(), guildID) } // GetGuildCommandPermissions returns the api.GuildCommandPermissions for a specific api.Command in a api.Guild -func (d *DisgoImpl) GetGuildCommandPermissions(guildID api.Snowflake, commandID api.Snowflake) (*api.GuildCommandPermissions, error) { +func (d *DisgoImpl) GetGuildCommandPermissions(guildID api.Snowflake, commandID api.Snowflake) (*api.GuildCommandPermissions, restclient.RestError) { return d.RestClient().GetGuildCommandPermissions(d.ApplicationID(), guildID, 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, restclient.RestError) { 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, restclient.RestError) { return d.RestClient().SetGuildCommandPermissions(d.ApplicationID(), guildID, commandID, permissions) } diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 0473af65..c7a5ba9e 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -173,8 +173,47 @@ func (b *EntityBuilderImpl) CreateMessage(fullMessage *api.FullMessage, updateCa } // CreateGuild returns a new api.Guild entity -func (b *EntityBuilderImpl) CreateGuild(guild *api.Guild, updateCache api.CacheStrategy) *api.Guild { +func (b *EntityBuilderImpl) CreateGuild(fullGuild *api.FullGuild, updateCache api.CacheStrategy) *api.Guild { + guild := fullGuild.Guild guild.Disgo = b.Disgo() + + for _, channel := range fullGuild.Channels { + channel.GuildID = &guild.ID + switch channel.Type { + case api.ChannelTypeText, api.ChannelTypeNews: + b.Disgo().EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes) + case api.ChannelTypeVoice: + b.Disgo().EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes) + case api.ChannelTypeCategory: + b.Disgo().EntityBuilder().CreateCategory(channel, api.CacheStrategyYes) + case api.ChannelTypeStore: + b.Disgo().EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes) + } + } + + for _, role := range fullGuild.Roles { + b.Disgo().EntityBuilder().CreateRole(guild.ID, role, api.CacheStrategyYes) + } + + for _, member := range fullGuild.Members { + b.Disgo().EntityBuilder().CreateMember(guild.ID, member, api.CacheStrategyYes) + } + + for _, voiceState := range fullGuild.VoiceStates { + b.Disgo().EntityBuilder().CreateVoiceState(guild.ID, voiceState, api.CacheStrategyYes) + } + + for _, emote := range fullGuild.Emojis { + b.Disgo().EntityBuilder().CreateEmoji(guild.ID, emote, api.CacheStrategyYes) + } + + // TODO: presence + /*for i := range fullGuild.Presences { + presence := fullGuild.Presences[i] + presence.Disgo = disgo + b.Disgo().Cache().CachePresence(presence) + }*/ + if updateCache(b.Disgo()) { return b.Disgo().Cache().CacheGuild(guild) } diff --git a/internal/gateway_impl.go b/internal/gateway_impl.go index 8ba97913..d516079c 100644 --- a/internal/gateway_impl.go +++ b/internal/gateway_impl.go @@ -1,12 +1,12 @@ package internal import ( - "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" + "net/http" "runtime/debug" "time" @@ -20,7 +20,7 @@ import ( func newGatewayImpl(disgo api.Disgo) api.Gateway { return &GatewayImpl{ disgo: disgo, - status: api.Unconnected, + status: api.GatewayStatusUnconnected, } } @@ -47,14 +47,14 @@ func (g *GatewayImpl) reconnect(delay time.Duration) { go func() { time.Sleep(delay) - if g.Status() == api.Connecting || g.Status() == api.Reconnecting { + if g.Status() == api.GatewayStatusConnecting || g.Status() == api.GatewayStatusReconnecting { g.Disgo().Logger().Error("tried to reconnect gateway while connecting/reconnecting") return } g.Disgo().Logger().Info("reconnecting gateway...") if err := g.Open(); err != nil { g.Disgo().Logger().Errorf("failed to reconnect gateway: %s", err) - g.status = api.Disconnected + g.status = api.GatewayStatusDisconnected g.reconnect(delay * 2) } }() @@ -63,9 +63,9 @@ func (g *GatewayImpl) reconnect(delay time.Duration) { // Open initializes the client and connection to discord func (g *GatewayImpl) Open() error { if g.lastSequenceReceived == nil || g.sessionID == nil { - g.status = api.Connecting + g.status = api.GatewayStatusConnecting } else { - g.status = api.Reconnecting + g.status = api.GatewayStatusReconnecting } g.Disgo().Logger().Info("starting ws...") @@ -84,41 +84,44 @@ func (g *GatewayImpl) Open() error { } gatewayURL := *g.url + "?v=" + restclient.APIVersion + "&encoding=json" - wsConn, rs, err := websocket.DefaultDialer.Dial(gatewayURL, nil) + var rs *http.Response + var err error + g.conn, rs, err = websocket.DefaultDialer.Dial(gatewayURL, nil) if err != nil { g.Close() - var body string + var body []byte if rs != nil && rs.Body != nil { - rawBody, err := ioutil.ReadAll(rs.Body) + body, err = ioutil.ReadAll(rs.Body) if err != nil { g.Disgo().Logger().Errorf("error while reading response body: %s", err) g.url = nil return err } - body = string(rawBody) } else { - body = "null" + body = []byte("null") } - g.Disgo().Logger().Errorf("error connecting to gateway. url: %s, error: %s, body: %s", gatewayURL, err.Error(), body) + g.Disgo().Logger().Errorf("error connecting to gateway. url: %s, error: %s, body: %s", gatewayURL, err, string(body)) return err } - wsConn.SetCloseHandler(func(code int, error string) error { + + g.conn.SetCloseHandler(func(code int, error string) error { g.Disgo().Logger().Infof("connection to websocket closed with code: %d, error: %s", code, error) return nil }) - g.conn = wsConn - g.status = api.WaitingForHello + g.status = api.GatewayStatusWaitingForHello - mt, data, err := g.conn.ReadMessage() + mt, reader, err := g.conn.NextReader() if err != nil { return err } - event, err := g.parseGatewayEvent(mt, data) + + event, err := g.parseGatewayEvent(mt, reader) if err != nil { return err } + if event.Op != api.OpHello { return fmt.Errorf("expected op: hello type: 10, received: %d", mt) } @@ -133,9 +136,9 @@ func (g *GatewayImpl) Open() error { g.heartbeatInterval = eventData.HeartbeatInterval * time.Millisecond if g.lastSequenceReceived == nil || g.sessionID == nil { - g.status = api.Identifying - g.Disgo().Logger().Infof("sending Identifying command...") - if err = wsConn.WriteJSON( + g.status = api.GatewayStatusIdentifying + g.Disgo().Logger().Infof("sending GatewayStatusIdentifying command...") + if err = g.Send( api.NewGatewayCommand(api.OpIdentify, api.IdentifyCommand{ Token: g.Disgo().Token(), Properties: api.IdentifyCommandDataProperties{ @@ -150,17 +153,17 @@ func (g *GatewayImpl) Open() error { ); err != nil { return err } - g.status = api.WaitingForReady + g.status = api.GatewayStatusWaitingForReady } else { - g.status = api.Resuming + g.status = api.GatewayStatusResuming cmd := api.NewGatewayCommand(api.OpResume, api.ResumeCommand{ Token: g.Disgo().Token(), SessionID: *g.sessionID, Seq: *g.lastSequenceReceived, }) - g.Disgo().Logger().Infof("sending Resuming command...") + g.Disgo().Logger().Infof("sending GatewayStatusResuming command...") - if err = wsConn.WriteJSON(cmd); err != nil { + if err = g.Send(cmd); err != nil { return err } } @@ -178,6 +181,11 @@ func (g *GatewayImpl) Status() api.GatewayStatus { return g.status } +// Send sends a payload to the Gateway +func (g *GatewayImpl) Send(command api.GatewayCommand) error { + return g.conn.WriteJSON(command) +} + // Latency returns the api.Gateway latency func (g *GatewayImpl) Latency() time.Duration { return g.lastHeartbeatReceived.Sub(g.lastHeartbeatSent) @@ -248,7 +256,7 @@ func (g *GatewayImpl) sendHeartbeat() { OldPing: g.Latency(), } - if err := g.conn.WriteJSON(api.NewGatewayCommand(api.OpHeartbeat, g.lastSequenceReceived)); err != nil { + if err := g.Send(api.NewGatewayCommand(api.OpHeartbeat, g.lastSequenceReceived)); err != nil { g.Disgo().Logger().Errorf("failed to send heartbeat with error: %s", err) g.closeWithCode(websocket.CloseServiceRestart) g.reconnect(1 * time.Second) @@ -269,6 +277,7 @@ func (g *GatewayImpl) listen() { } g.Disgo().Logger().Info("shut down listen goroutine") }() + for { select { case <-g.quit: @@ -278,7 +287,7 @@ func (g *GatewayImpl) listen() { if g.conn == nil { return } - mt, data, err := g.conn.ReadMessage() + mt, reader, err := g.conn.NextReader() if err != nil { g.Disgo().Logger().Errorf("error while reading from ws. error: %s", err) g.closeWithCode(websocket.CloseServiceRestart) @@ -286,7 +295,7 @@ func (g *GatewayImpl) listen() { return } - event, err := g.parseGatewayEvent(mt, data) + event, err := g.parseGatewayEvent(mt, reader) if err != nil { g.Disgo().Logger().Errorf("error while unpacking gateway event. error: %s", err) } @@ -299,7 +308,7 @@ func (g *GatewayImpl) listen() { g.lastSequenceReceived = event.S } if event.T == nil { - g.Disgo().Logger().Errorf("received event without T. playload: %s", string(data)) + g.Disgo().Logger().Errorf("received event without T. payload: %+v", event) continue } @@ -307,12 +316,12 @@ func (g *GatewayImpl) listen() { if *event.T == api.GatewayEventReady { var readyEvent api.ReadyGatewayEvent - if err := g.parseEventToStruct(event, &readyEvent); err != nil { + if err = g.parseEventToStruct(event, &readyEvent); err != nil { g.Disgo().Logger().Errorf("Error parsing ready event: %s", err) continue } g.sessionID = &readyEvent.SessionID - + g.status = api.GatewayStatusWaitingForGuilds g.Disgo().Logger().Info("ready event received") } @@ -343,12 +352,12 @@ func (g *GatewayImpl) listen() { g.reconnect(1 * time.Second) case api.OpInvalidSession: - var resumable bool - if err = g.parseEventToStruct(event, &resumable); err != nil { + var canResume bool + if err = g.parseEventToStruct(event, &canResume); err != nil { g.Disgo().Logger().Errorf("Error parsing invalid session data: %s", err) } - g.Disgo().Logger().Debugf("received: OpInvalidSession, resumable: %b", resumable) - if resumable { + g.Disgo().Logger().Debugf("received: OpInvalidSession, canResume: %b", canResume) + if canResume { g.closeWithCode(websocket.CloseServiceRestart) } else { g.Close() @@ -370,27 +379,25 @@ func (g *GatewayImpl) listen() { func (g *GatewayImpl) parseEventToStruct(event *api.RawGatewayEvent, v interface{}) error { if err := json.Unmarshal(event.D, v); err != nil { - g.Disgo().Logger().Errorf("error while unmarshaling event. error: %s", err) + g.Disgo().Logger().Errorf("error while unmarshalling event. error: %s", err) return err } return nil } -func (g *GatewayImpl) parseGatewayEvent(mt int, data []byte) (*api.RawGatewayEvent, error) { - - var reader io.Reader = bytes.NewBuffer(data) - +func (g *GatewayImpl) parseGatewayEvent(mt int, reader io.Reader) (*api.RawGatewayEvent, error) { if mt == websocket.BinaryMessage { return nil, errors.New("we don't handle compressed yet") } + if mt != websocket.TextMessage { - return nil, fmt.Errorf("recieved unexpected message_events type: %d", mt) + return nil, fmt.Errorf("recieved unexpected message type: %d", mt) } - var event api.RawGatewayEvent decoder := json.NewDecoder(reader) + var event api.RawGatewayEvent if err := decoder.Decode(&event); err != nil { - g.Disgo().Logger().Errorf("error decoding websocket message_events, %s", err) + g.Disgo().Logger().Errorf("error decoding websocket message, %s", err) return nil, err } return &event, nil diff --git a/internal/handlers/guild_create_handler.go b/internal/handlers/guild_create_handler.go index 917fa4cc..0902df42 100644 --- a/internal/handlers/guild_create_handler.go +++ b/internal/handlers/guild_create_handler.go @@ -31,44 +31,7 @@ func (h GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api oldGuild = &*oldGuild wasUnavailable = oldGuild.Unavailable } - guild := disgo.EntityBuilder().CreateGuild(fullGuild.Guild, api.CacheStrategyYes) - - for _, channel := range fullGuild.Channels { - channel.GuildID = &guild.ID - switch channel.Type { - case api.ChannelTypeText, api.ChannelTypeNews: - disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes) - case api.ChannelTypeVoice: - disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes) - case api.ChannelTypeCategory: - disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes) - case api.ChannelTypeStore: - disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes) - } - } - - for _, role := range fullGuild.Roles { - disgo.EntityBuilder().CreateRole(guild.ID, role, api.CacheStrategyYes) - } - - for _, member := range fullGuild.Members { - disgo.EntityBuilder().CreateMember(guild.ID, member, api.CacheStrategyYes) - } - - for _, voiceState := range fullGuild.VoiceStates { - disgo.EntityBuilder().CreateVoiceState(guild.ID, voiceState, api.CacheStrategyYes) - } - - for _, emote := range fullGuild.Emojis { - disgo.EntityBuilder().CreateEmoji(guild.ID, emote, api.CacheStrategyYes) - } - - // TODO: presence - /*for i := range fullGuild.Presences { - presence := fullGuild.Presences[i] - presence.Disgo = disgo - disgo.Cache().CachePresence(presence) - }*/ + guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyYes) genericGuildEvent := events.GenericGuildEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), diff --git a/internal/handlers/guild_delete_handler.go b/internal/handlers/guild_delete_handler.go index 1c4add1e..f33061ad 100644 --- a/internal/handlers/guild_delete_handler.go +++ b/internal/handlers/guild_delete_handler.go @@ -15,17 +15,17 @@ func (h GuildDeleteHandler) Event() api.GatewayEventType { // New constructs a new payload receiver for the raw gateway event func (h GuildDeleteHandler) New() interface{} { - return &api.Guild{} + return &api.FullGuild{} } // HandleGatewayEvent handles the specific raw gateway event func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { - guild, ok := i.(*api.Guild) + fullGuild, ok := i.(*api.FullGuild) if !ok { return } - guild = disgo.EntityBuilder().CreateGuild(guild, api.CacheStrategyNo) + guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNo) genericGuildEvent := events.GenericGuildEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), @@ -34,7 +34,7 @@ func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api eventManager.Dispatch(genericGuildEvent) if guild.Unavailable { - // set guild to unavail for now + // set guild to unavailable for now disgo.Cache().Guild(guild.ID).Unavailable = true eventManager.Dispatch(events.GuildUnavailableEvent{ diff --git a/internal/handlers/guild_update_handler.go b/internal/handlers/guild_update_handler.go index 0179d101..836b0a9b 100644 --- a/internal/handlers/guild_update_handler.go +++ b/internal/handlers/guild_update_handler.go @@ -15,21 +15,21 @@ func (h GuildUpdateHandler) Event() api.GatewayEventType { // New constructs a new payload receiver for the raw gateway event func (h GuildUpdateHandler) New() interface{} { - return &api.Guild{} + return &api.FullGuild{} } // HandleGatewayEvent handles the specific raw gateway event func (h GuildUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { - guild, ok := i.(*api.Guild) + fullGuild, ok := i.(*api.FullGuild) if !ok { return } - oldGuild := disgo.Cache().Guild(guild.ID) + oldGuild := disgo.Cache().Guild(fullGuild.ID) if oldGuild != nil { oldGuild = &*oldGuild } - guild = disgo.EntityBuilder().CreateGuild(guild, api.CacheStrategyYes) + guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyYes) genericGuildEvent := events.GenericGuildEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 276a0a2b..b50ca27b 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -12,56 +12,33 @@ func newRestClientImpl(disgo api.Disgo, httpClient *http.Client) api.RestClient if httpClient == nil { httpClient = http.DefaultClient } - return &RestClientImpl{ + return &restClientImpl{ RestClient: restclient.NewRestClient(httpClient, disgo.Logger(), api.UserAgent, http.Header{"Authorization": []string{"Bot " + disgo.Token()}}), disgo: disgo, } } -// RestClientImpl is the rest client implementation used for HTTP requests to discord -type RestClientImpl struct { +// restClientImpl is the rest client implementation used for HTTP requests to discord +type restClientImpl struct { restclient.RestClient disgo api.Disgo } -func (r *RestClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (*api.Guild, error) { - panic("implement me") -} - -func (r *RestClientImpl) GetGuildPreview(guildID api.Snowflake) (*api.GuildPreview, error) { - panic("implement me") -} - -func (r *RestClientImpl) CreateGuild(guildID api.Snowflake, createGuild api.CreateGuild) (*api.Guild, error) { - panic("implement me") -} - -func (r *RestClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (*api.Guild, error) { - panic("implement me") -} - -func (r *RestClientImpl) DeleteGuild(guildID api.Snowflake) error { - panic("implement me") -} - -func (r *RestClientImpl) CreateRole(guildID api.Snowflake, createRole api.CreateRole) (*api.Role, error) { - panic("implement me") -} - // Disgo returns the api.Disgo instance -func (r *RestClientImpl) Disgo() api.Disgo { +func (r *restClientImpl) Disgo() api.Disgo { return r.disgo } // Close cleans up the http managers connections -func (r *RestClientImpl) Close() { +func (r *restClientImpl) Close() { r.HTTPClient().CloseIdleConnections() } // DoWithHeaders executes a rest request with custom headers -func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBody interface{}, rsBody interface{}, customHeader http.Header) (err restclient.RestError) { - err = r.RestClient.DoWithHeaders(route, rqBody, rsBody, customHeader) - // TODO reimplement events.HTTPRequestEvent +func (r *restClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBody interface{}, rsBody interface{}, customHeader http.Header) (rErr restclient.RestError) { + err := r.RestClient.DoWithHeaders(route, rqBody, rsBody, customHeader) + rErr = restclient.NewRestError(nil, err) + // TODO reimplement events.HTTPRequestEvent /*r.Disgo().EventManager().Dispatch(events.HTTPRequestEvent{ GenericEvent: events.NewEvent(r.Disgo(), 0), Request: rq, @@ -72,7 +49,7 @@ func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod /* 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) + r.Disgo().Logger().Errorf("restclient.RestError unmarshalling restclient.RestError response. code: %d, restclient.RestError: %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) @@ -80,67 +57,179 @@ func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod return } -// SendMessage lets you send a api.Message to a api.MessageChannel -func (r *RestClientImpl) SendMessage(channelID api.Snowflake, messageCreate api.MessageCreate) (message *api.Message, err error) { +// GetUser fetches the specific user +func (r *restClientImpl) GetUser(userID api.Snowflake) (user *api.User, rErr restclient.RestError) { + compiledRoute, err := restclient.GetUser.Compile(nil, userID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + rErr = r.Do(compiledRoute, nil, &user) + if rErr == nil { + user = r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs) + } + return +} + +func (r *restClientImpl) GetSelfUser() (selfUser *api.SelfUser, rErr restclient.RestError) { + compiledRoute, err := restclient.GetSelfUser.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + var user *api.User + rErr = r.Do(compiledRoute, nil, &user) + if rErr == nil { + selfUser = &api.SelfUser{User: r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs)} + } + return +} + +func (r *restClientImpl) UpdateSelfUser(updateSelfUser api.UpdateSelfUser) (selfUser *api.SelfUser, rErr restclient.RestError) { + compiledRoute, err := restclient.GetSelfUser.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + var user *api.User + rErr = r.Do(compiledRoute, updateSelfUser, &user) + if rErr == nil { + selfUser = &api.SelfUser{User: r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs)} + } + return +} + +func (r *restClientImpl) GetGuilds(before int, after int, limit int) (guilds []*api.PartialGuild, rErr restclient.RestError) { + queryParams := restclient.QueryValues{} + if before > 0 { + queryParams["before"] = before + } + if after > 0 { + queryParams["after"] = after + } + if limit > 0 { + queryParams["limit"] = limit + } + compiledRoute, err := restclient.GetGuilds.Compile(queryParams) + if err != nil { + return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + } + + rErr = r.Do(compiledRoute, nil, &guilds) + return +} + +func (r *restClientImpl) LeaveGuild(guildID api.Snowflake) restclient.RestError { + compiledRoute, err := restclient.LeaveGuild.Compile(nil, guildID) + if err != nil { + return restclient.NewRestError(nil, err) + } + return r.Do(compiledRoute, nil, nil) +} + +func (r *restClientImpl) GetDMChannels() (dmChannels []*api.DMChannel, rErr restclient.RestError) { + compiledRoute, err := restclient.GetDMChannels.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + + var channels []*api.Channel + rErr = r.Do(compiledRoute, nil, &channels) + if rErr == nil { + dmChannels = make([]*api.DMChannel, len(channels)) + for i, channel := range channels { + dmChannels[i] = r.Disgo().EntityBuilder().CreateDMChannel(channel, api.CacheStrategyNoWs) + } + } + return +} + +// CreateDMChannel opens a new api.DMChannel to a api.User +func (r *restClientImpl) CreateDMChannel(userID api.Snowflake) (channel *api.DMChannel, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateDMChannel.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + + rErr = r.Do(compiledRoute, api.CreateDMChannel{RecipientID: userID}, &channel) + if rErr == nil { + channel = r.Disgo().EntityBuilder().CreateDMChannel(&channel.MessageChannel.Channel, api.CacheStrategyNoWs) + } + return +} + +func (r *restClientImpl) GetMessage(channelID api.Snowflake, messageID api.Snowflake) (message *api.Message, rErr restclient.RestError) { + compiledRoute, err := restclient.GetMessage.Compile(nil, channelID, messageID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + + var fullMessage *api.FullMessage + rErr = r.Do(compiledRoute, nil, &fullMessage) + if rErr == nil { + message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + } + return +} + +// CreateMessage lets you send a api.Message to a api.MessageChannel +func (r *restClientImpl) CreateMessage(channelID api.Snowflake, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateMessage.Compile(nil, channelID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } -// EditMessage lets you edit a api.Message -func (r *RestClientImpl) EditMessage(channelID api.Snowflake, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, err error) { +// UpdateMessage lets you edit a api.Message +func (r *restClientImpl) UpdateMessage(channelID api.Snowflake, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } // DeleteMessage lets you delete a api.Message -func (r *RestClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Snowflake) (err error) { +func (r *restClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteMessage.Compile(nil, channelID, messageID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheMessage(channelID, messageID) } return } // BulkDeleteMessages lets you bulk delete api.Message(s) -func (r *RestClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs ...api.Snowflake) (err error) { +func (r *restClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs ...api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.BulkDeleteMessage.Compile(nil, channelID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, api.MessageBulkDelete{Messages: messageIDs}, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, api.MessageBulkDelete{Messages: messageIDs}, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { // TODO: check here if no err means all messages deleted for _, messageID := range messageIDs { r.Disgo().Cache().UncacheMessage(channelID, messageID) @@ -150,86 +239,103 @@ func (r *RestClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs } // CrosspostMessage lets you crosspost a api.Message in a channel with type api.ChannelTypeNews -func (r *RestClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (msg *api.Message, err error) { +func (r *restClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (msg *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CrosspostMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMsg *api.FullMessage - err = r.Do(compiledRoute, nil, &fullMsg) - if err == nil { + rErr = r.Do(compiledRoute, nil, &fullMsg) + if rErr == nil { msg = r.Disgo().EntityBuilder().CreateMessage(fullMsg, api.CacheStrategyNoWs) } return } -// OpenDMChannel opens a new dm channel a user -func (r *RestClientImpl) OpenDMChannel(userID api.Snowflake) (channel *api.DMChannel, err error) { - compiledRoute, err := restclient.CreateDMChannel.Compile(nil) +func (r *restClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (guild *api.Guild, rErr restclient.RestError) { + var queryParams = restclient.QueryValues{ + "with_counts": withCounts, + } + compiledRoute, err := restclient.GetGuild.Compile(queryParams, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) } - body := struct { - RecipientID api.Snowflake `json:"recipient_id"` - }{ - RecipientID: userID, + + var fullGuild *api.FullGuild + rErr = r.Do(compiledRoute, nil, &fullGuild) + if rErr == nil { + guild = r.Disgo().EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNoWs) } - err = r.Do(compiledRoute, body, &channel) - if err == nil { - channel = r.Disgo().EntityBuilder().CreateDMChannel(&channel.MessageChannel.Channel, api.CacheStrategyNoWs) + return +} + +func (r *restClientImpl) GetGuildPreview(guildID api.Snowflake) (guildPreview *api.GuildPreview, rErr restclient.RestError) { + compiledRoute, err := restclient.GetGuildPreview.Compile(nil, guildID) + if err != nil { + return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) } + + rErr = r.Do(compiledRoute, nil, &guildPreview) return } -// UpdateSelfNick updates the bots nickname in a guild -func (r *RestClientImpl) UpdateSelfNick(guildID api.Snowflake, nick *string) (newNick *string, err error) { - compiledRoute, err := restclient.UpdateSelfNick.Compile(nil, guildID) +func (r *restClientImpl) CreateGuild(createGuild api.CreateGuild) (guild *api.Guild, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateGuild.Compile(nil) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - var updateNick *api.UpdateSelfNick - err = r.Do(compiledRoute, &api.UpdateSelfNick{Nick: nick}, &updateNick) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { - r.Disgo().Cache().Member(guildID, r.Disgo().ApplicationID()).Nick = updateNick.Nick - newNick = updateNick.Nick + + var fullGuild *api.FullGuild + rErr = r.Do(compiledRoute, createGuild, &fullGuild) + if rErr == nil { + guild = r.Disgo().EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNoWs) } return } -// GetUser fetches the specific user -func (r *RestClientImpl) GetUser(userID api.Snowflake) (user *api.User, err error) { - compiledRoute, err := restclient.GetUser.Compile(nil, userID) +func (r *restClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (guild *api.Guild, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateGuild.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &user) - if err == nil { - user = r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs) + + var fullGuild *api.FullGuild + rErr = r.Do(compiledRoute, updateGuild, &fullGuild) + if rErr == nil { + guild = r.Disgo().EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNoWs) } return } +func (r *restClientImpl) DeleteGuild(guildID api.Snowflake) restclient.RestError { + compiledRoute, err := restclient.DeleteGuild.Compile(nil, guildID) + if err != nil { + return restclient.NewRestError(nil, err) + } + return r.Do(compiledRoute, nil, nil) +} + // GetMember fetches the specific member -func (r *RestClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) (member *api.Member, err error) { +func (r *restClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &member) - if err == nil { + rErr = r.Do(compiledRoute, nil, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } // GetMembers fetches all members for a guild -func (r *RestClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Member, err error) { +func (r *restClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMembers.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &members) - if err == nil { + rErr = r.Do(compiledRoute, nil, &members) + if rErr == nil { for _, member := range members { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } @@ -237,71 +343,111 @@ func (r *RestClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Membe return } +func (r *restClientImpl) SearchMembers(guildID api.Snowflake, query string, limit int) (members []*api.Member, rErr restclient.RestError) { + queryParams := restclient.QueryValues{} + if query != "" { + queryParams["query"] = query + } + if limit > 0 { + queryParams["limit"] = limit + } + compiledRoute, err := restclient.GetMembers.Compile(queryParams, guildID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + rErr = r.Do(compiledRoute, nil, &members) + if rErr == nil { + members = make([]*api.Member, len(members)) + for i, member := range members { + members[i] = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) + } + } + return +} + // 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, addMember api.AddMember) (member *api.Member, err error) { +func (r *restClientImpl) AddMember(guildID api.Snowflake, userID api.Snowflake, addMember api.AddMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.AddMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, addMember, &member) - if err == nil { + rErr = r.Do(compiledRoute, addMember, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } -// 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{} - if reason != nil { - params = map[string]interface{}{"reason": *reason} +// RemoveMember kicks a api.Member from the api.Guild. requires api.PermissionKickMembers +func (r *restClientImpl) RemoveMember(guildID api.Snowflake, userID api.Snowflake, reason string) (rErr restclient.RestError) { + var params restclient.QueryValues + if reason != "" { + params = restclient.QueryValues{"reason": reason} } - compiledRoute, err = restclient.RemoveMember.Compile(params, guildID, userID) + compiledRoute, err := restclient.RemoveMember.Compile(params, guildID, userID) if err != nil { - return + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheMember(guildID, userID) } return } // UpdateMember updates a api.Member -func (r *RestClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateMember api.UpdateMember) (member *api.Member, err error) { +func (r *restClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateMember api.UpdateMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, updateMember, &member) - if err == nil { + rErr = r.Do(compiledRoute, updateMember, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } +// UpdateSelfNick updates the bots nickname in a guild +func (r *restClientImpl) UpdateSelfNick(guildID api.Snowflake, nick string) (newNick *string, rErr restclient.RestError) { + compiledRoute, err := restclient.UpdateSelfNick.Compile(nil, guildID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + var updateNick *api.UpdateSelfNick + rErr = r.Do(compiledRoute, &api.UpdateSelfNick{Nick: nick}, &updateNick) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { + var nick *string + if updateNick.Nick == "" { + nick = nil + } + r.Disgo().Cache().Member(guildID, r.Disgo().ClientID()).Nick = nick + newNick = nick + } + return +} + // 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) { +func (r *restClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, channelID *api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) - if err == nil { + rErr = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } // AddMemberRole adds a api.Role to a api.Member -func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (err error) { +func (r *restClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.AddMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { member := r.Disgo().Cache().Member(guildID, userID) if member != nil { member.Roles = append(member.Roles, roleID) @@ -311,13 +457,13 @@ func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowfla } // 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) { +func (r *restClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.RemoveMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { member := r.Disgo().Cache().Member(guildID, userID) if member != nil { for i, id := range member.Roles { @@ -332,13 +478,13 @@ func (r *RestClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snow } // GetRoles fetches all api.Role(s) from a api.Guild -func (r *RestClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, err error) { +func (r *restClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &roles) - if err == nil { + rErr = r.Do(compiledRoute, nil, &roles) + if rErr == nil { for _, role := range roles { role = r.Disgo().EntityBuilder().CreateRole(guildID, role, api.CacheStrategyNoWs) } @@ -347,39 +493,39 @@ 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, createRole api.CreateRole) (newRole *api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.CreateRole.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, role, &newRole) - if err == nil { + rErr = r.Do(compiledRoute, createRole, &newRole) + if rErr == nil { newRole = r.Disgo().EntityBuilder().CreateRole(guildID, newRole, api.CacheStrategyNoWs) } return } // 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, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, role, &newRole) - if err == nil { + rErr = r.Do(compiledRoute, role, &newRole) + if rErr == nil { newRole = r.Disgo().EntityBuilder().CreateRole(guildID, newRole, api.CacheStrategyNoWs) } return } // 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, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, roleUpdates, &roles) - if err == nil { + rErr = r.Do(compiledRoute, roleUpdates, &roles) + if rErr == nil { for _, role := range roles { role = r.Disgo().EntityBuilder().CreateRole(guildID, role, api.CacheStrategyNoWs) } @@ -388,53 +534,53 @@ func (r *RestClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates } // DeleteRole deletes a role from a guild. Requires api.PermissionManageRoles -func (r *RestClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) (err error) { +func (r *restClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.disgo.Cache().UncacheRole(guildID, roleID) } return } // AddReaction lets you add a reaction to a api.Message -func (r *RestClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) error { +func (r *restClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.AddReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // RemoveOwnReaction lets you remove your own reaction from a api.Message -func (r *RestClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) error { +func (r *restClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.RemoveOwnReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // 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 { +func (r *restClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string, userID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.RemoveUserReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji), userID) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // GetGlobalCommands gets you all global api.Command(s) -func (r *RestClientImpl) GetGlobalCommands(applicationID api.Snowflake) (commands []*api.Command, err error) { +func (r *restClientImpl) GetGlobalCommands(applicationID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &commands) - if err == nil { + rErr = r.Do(compiledRoute, nil, &commands) + if rErr == nil { for _, cmd := range commands { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } @@ -443,43 +589,43 @@ func (r *RestClientImpl) GetGlobalCommands(applicationID api.Snowflake) (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) { +func (r *restClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } return } // CreateGlobalCommand lets you create a new global api.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, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGlobalCommand.Compile(nil, applicationID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } return } // SetGlobalCommands lets you override all global api.Command -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, rErr restclient.RestError) { compiledRoute, err := restclient.SetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands return } - err = r.Do(compiledRoute, commands, &cmds) - if err == nil { + rErr = r.Do(compiledRoute, commands, &cmds) + if rErr == nil { for _, cmd := range cmds { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } @@ -487,40 +633,40 @@ func (r *RestClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands return } -// 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) { +// UpdateGlobalCommand lets you edit a specific global api.Command +func (r *restClientImpl) UpdateGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } return } // DeleteGlobalCommand lets you delete a specific global api.Command -func (r *RestClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (err error) { +func (r *restClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheCommand(commandID) } return } // 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) { +func (r *restClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &commands) - if err == nil { + rErr = r.Do(compiledRoute, nil, &commands) + if rErr == nil { for _, cmd := range commands { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } @@ -529,30 +675,30 @@ func (r *RestClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID a } // 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) { +func (r *restClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, command api.CommandCreate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuildCommand.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } return } // 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) { +func (r *restClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands return } - err = r.Do(compiledRoute, commands, &cmds) - if err == nil { + rErr = r.Do(compiledRoute, commands, &cmds) + if rErr == nil { for _, cmd := range cmds { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } @@ -561,52 +707,52 @@ func (r *RestClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID a } // 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) { +func (r *restClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } return } -// 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) { +// UpdateGuildCommand lets you edit a specific api.Command in a api.Guild +func (r *restClientImpl) UpdateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } return } // 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) { +func (r *restClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheCommand(commandID) } return } // 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) { +func (r *restClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake) (cmdsPerms []*api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmdsPerms) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmdsPerms) + if rErr == nil { for _, cmdPerms := range cmdsPerms { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } @@ -615,26 +761,26 @@ func (r *RestClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake } // 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) { +func (r *restClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmdPerms *api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermission.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmdPerms) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmdPerms) + if rErr == nil { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } return } // 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, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandsPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, api.SetGuildCommandsPermissions(commandsPermissions), &cmdsPerms) - if err == nil { + rErr = r.Do(compiledRoute, api.SetGuildCommandsPermissions(commandsPermissions), &cmdsPerms) + if rErr == nil { for _, cmdPerms := range cmdsPerms { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } @@ -643,98 +789,98 @@ 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, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandPermissions.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, commandPermissions, &cmdPerms) - if err == nil { + rErr = r.Do(compiledRoute, commandPermissions, &cmdPerms) + if rErr == nil { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } return } // SendInteractionResponse used to send the initial response on an api.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) restclient.RestError { compiledRoute, err := restclient.CreateInteractionResponse.Compile(nil, interactionID, interactionToken) if err != nil { - return err + return restclient.NewRestError(nil, err) } body, err := interactionResponse.ToBody() if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, body, nil) } -// 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) { +// UpdateInteractionResponse used to edit the initial response on an api.Interaction +func (r *restClientImpl) UpdateInteractionResponse(applicationID api.Snowflake, interactionToken string, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } // DeleteInteractionResponse used to delete the initial response on an api.Interaction -func (r *RestClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, interactionToken string) error { +func (r *restClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, interactionToken string) restclient.RestError { compiledRoute, err := restclient.DeleteInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // 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) { +func (r *restClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateFollowupMessage.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } -// 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) { +// UpdateFollowupMessage used to edit a followup api.Message from an api.Interaction +func (r *restClientImpl) UpdateFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } @@ -742,10 +888,10 @@ func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, intera } // 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 { +func (r *restClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.DeleteFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } diff --git a/internal/util.go b/internal/util.go index df890a80..92be3dbb 100644 --- a/internal/util.go +++ b/internal/util.go @@ -21,4 +21,3 @@ func IDFromToken(token string) (*api.Snowflake, error) { strID := api.Snowflake(byteID) return &strID, nil } - From 2e4df4ee7db321ed95a8e700a8a41d4d0adbf6bb Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 16 Jun 2021 00:42:26 +0200 Subject: [PATCH 16/64] bump restclient --- go.mod | 6 +----- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 42971df3..fb5141cf 100644 --- a/go.mod +++ b/go.mod @@ -2,13 +2,9 @@ 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.5 + github.com/DisgoOrg/restclient v1.2.0 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/stretchr/testify v1.7.0 diff --git a/go.sum b/go.sum index 7ede71b2..c1098959 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.5 h1:qjYNUeFo2NcqaMS+lLxyQIwED1gomn5TIub88wrA2mI= -github.com/DisgoOrg/restclient v1.1.5/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= +github.com/DisgoOrg/restclient v1.2.0 h1:M2GXPf5Ja+Ynt7DBTLv+TQ4iMVLQX17FRHXQ0gqAExw= +github.com/DisgoOrg/restclient v1.2.0/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 63269edf9f5b6ec1d6048a05b252499fdffa1755 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 16 Jun 2021 00:46:15 +0200 Subject: [PATCH 17/64] fixed compile errors caused by restcleint dump --- api/channels.go | 2 +- api/interaction.go | 2 +- api/message.go | 2 +- api/self_user.go | 2 +- example/go.sum | 2 + internal/restclient_impl.go | 130 ++++++++++++++++++------------------ 6 files changed, 71 insertions(+), 69 deletions(-) diff --git a/api/channels.go b/api/channels.go index 53048c89..2a92ee9b 100644 --- a/api/channels.go +++ b/api/channels.go @@ -71,7 +71,7 @@ func (c MessageChannel) BulkDeleteMessages(messageIDs ...Snowflake) restclient.R // CrosspostMessage crossposts an existing Message func (c MessageChannel) CrosspostMessage(messageID Snowflake) (*Message, restclient.RestError) { if c.Type != ChannelTypeNews { - return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) + return nil, restclient.NewError(nil, errors.New("channel type is not NEWS")) } return c.Disgo.RestClient().CrosspostMessage(c.ID, messageID) } diff --git a/api/interaction.go b/api/interaction.go index 037eda67..89722e62 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -77,7 +77,7 @@ func (i *Interaction) Respond(responseType InteractionResponseType, data interfa Data: data, } if i.Replied { - return restclient.NewRestError(nil, errors.New("you already replied to this interaction")) + return restclient.NewError(nil, errors.New("you already replied to this interaction")) } i.Replied = true diff --git a/api/message.go b/api/message.go index 498cec60..0294294e 100644 --- a/api/message.go +++ b/api/message.go @@ -251,7 +251,7 @@ func (m *Message) Delete() restclient.RestError { func (m *Message) Crosspost() (*Message, restclient.RestError) { channel := m.Channel() if channel != nil && channel.Type != ChannelTypeNews { - return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) + return nil, restclient.NewError(nil, errors.New("channel type is not NEWS")) } return m.Disgo.RestClient().CrosspostMessage(m.ChannelID, m.ID) } diff --git a/api/self_user.go b/api/self_user.go index a39d5fe3..69a3185a 100644 --- a/api/self_user.go +++ b/api/self_user.go @@ -7,7 +7,7 @@ import ( ) // ErrDMChannelToYourself occurs when opening a DMChannel to yourself -var ErrDMChannelToYourself = restclient.NewRestError(nil, errors.New("can't open a dm channel to yourself")) +var ErrDMChannelToYourself = restclient.NewError(nil, errors.New("can't open a dm channel to yourself")) // SelfUser represents the current logged in User type SelfUser struct { diff --git a/example/go.sum b/example/go.sum index da0ba1cf..e9fca82e 100644 --- a/example/go.sum +++ b/example/go.sum @@ -2,6 +2,8 @@ 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/DisgoOrg/restclient v1.2.0 h1:M2GXPf5Ja+Ynt7DBTLv+TQ4iMVLQX17FRHXQ0gqAExw= +github.com/DisgoOrg/restclient v1.2.0/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/internal/restclient_impl.go b/internal/restclient_impl.go index b50ca27b..259bcf09 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -37,7 +37,7 @@ func (r *restClientImpl) Close() { // DoWithHeaders executes a rest request with custom headers func (r *restClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBody interface{}, rsBody interface{}, customHeader http.Header) (rErr restclient.RestError) { err := r.RestClient.DoWithHeaders(route, rqBody, rsBody, customHeader) - rErr = restclient.NewRestError(nil, err) + rErr = restclient.NewError(nil, err) // TODO reimplement events.HTTPRequestEvent /*r.Disgo().EventManager().Dispatch(events.HTTPRequestEvent{ GenericEvent: events.NewEvent(r.Disgo(), 0), @@ -61,7 +61,7 @@ func (r *restClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod func (r *restClientImpl) GetUser(userID api.Snowflake) (user *api.User, rErr restclient.RestError) { compiledRoute, err := restclient.GetUser.Compile(nil, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &user) if rErr == nil { @@ -73,7 +73,7 @@ func (r *restClientImpl) GetUser(userID api.Snowflake) (user *api.User, rErr res func (r *restClientImpl) GetSelfUser() (selfUser *api.SelfUser, rErr restclient.RestError) { compiledRoute, err := restclient.GetSelfUser.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var user *api.User rErr = r.Do(compiledRoute, nil, &user) @@ -86,7 +86,7 @@ func (r *restClientImpl) GetSelfUser() (selfUser *api.SelfUser, rErr restclient. func (r *restClientImpl) UpdateSelfUser(updateSelfUser api.UpdateSelfUser) (selfUser *api.SelfUser, rErr restclient.RestError) { compiledRoute, err := restclient.GetSelfUser.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var user *api.User rErr = r.Do(compiledRoute, updateSelfUser, &user) @@ -109,7 +109,7 @@ func (r *restClientImpl) GetGuilds(before int, after int, limit int) (guilds []* } compiledRoute, err := restclient.GetGuilds.Compile(queryParams) if err != nil { - return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + return nil, restclient.NewError(nil, restclient.NewError(nil, err)) } rErr = r.Do(compiledRoute, nil, &guilds) @@ -119,7 +119,7 @@ func (r *restClientImpl) GetGuilds(before int, after int, limit int) (guilds []* func (r *restClientImpl) LeaveGuild(guildID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.LeaveGuild.Compile(nil, guildID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -127,7 +127,7 @@ func (r *restClientImpl) LeaveGuild(guildID api.Snowflake) restclient.RestError func (r *restClientImpl) GetDMChannels() (dmChannels []*api.DMChannel, rErr restclient.RestError) { compiledRoute, err := restclient.GetDMChannels.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var channels []*api.Channel @@ -145,7 +145,7 @@ func (r *restClientImpl) GetDMChannels() (dmChannels []*api.DMChannel, rErr rest func (r *restClientImpl) CreateDMChannel(userID api.Snowflake) (channel *api.DMChannel, rErr restclient.RestError) { compiledRoute, err := restclient.CreateDMChannel.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.CreateDMChannel{RecipientID: userID}, &channel) @@ -158,7 +158,7 @@ func (r *restClientImpl) CreateDMChannel(userID api.Snowflake) (channel *api.DMC func (r *restClientImpl) GetMessage(channelID api.Snowflake, messageID api.Snowflake) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.GetMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -173,12 +173,12 @@ func (r *restClientImpl) GetMessage(channelID api.Snowflake, messageID api.Snowf func (r *restClientImpl) CreateMessage(channelID api.Snowflake, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateMessage.Compile(nil, channelID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -193,12 +193,12 @@ func (r *restClientImpl) CreateMessage(channelID api.Snowflake, messageCreate ap func (r *restClientImpl) UpdateMessage(channelID api.Snowflake, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -213,7 +213,7 @@ func (r *restClientImpl) UpdateMessage(channelID api.Snowflake, messageID api.Sn func (r *restClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteMessage.Compile(nil, channelID, messageID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -226,7 +226,7 @@ func (r *restClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Sn func (r *restClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs ...api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.BulkDeleteMessage.Compile(nil, channelID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.MessageBulkDelete{Messages: messageIDs}, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -242,7 +242,7 @@ func (r *restClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs func (r *restClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (msg *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CrosspostMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMsg *api.FullMessage rErr = r.Do(compiledRoute, nil, &fullMsg) @@ -258,7 +258,7 @@ func (r *restClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (guild } compiledRoute, err := restclient.GetGuild.Compile(queryParams, guildID) if err != nil { - return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + return nil, restclient.NewError(nil, restclient.NewError(nil, err)) } var fullGuild *api.FullGuild @@ -272,7 +272,7 @@ func (r *restClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (guild func (r *restClientImpl) GetGuildPreview(guildID api.Snowflake) (guildPreview *api.GuildPreview, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildPreview.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + return nil, restclient.NewError(nil, restclient.NewError(nil, err)) } rErr = r.Do(compiledRoute, nil, &guildPreview) @@ -282,7 +282,7 @@ func (r *restClientImpl) GetGuildPreview(guildID api.Snowflake) (guildPreview *a func (r *restClientImpl) CreateGuild(createGuild api.CreateGuild) (guild *api.Guild, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuild.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullGuild *api.FullGuild @@ -296,7 +296,7 @@ func (r *restClientImpl) CreateGuild(createGuild api.CreateGuild) (guild *api.Gu func (r *restClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (guild *api.Guild, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuild.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullGuild *api.FullGuild @@ -310,7 +310,7 @@ func (r *restClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.Upda func (r *restClientImpl) DeleteGuild(guildID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.DeleteGuild.Compile(nil, guildID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -319,7 +319,7 @@ func (r *restClientImpl) DeleteGuild(guildID api.Snowflake) restclient.RestError func (r *restClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &member) if rErr == nil { @@ -332,7 +332,7 @@ func (r *restClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) func (r *restClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMembers.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &members) if rErr == nil { @@ -353,7 +353,7 @@ func (r *restClientImpl) SearchMembers(guildID api.Snowflake, query string, limi } compiledRoute, err := restclient.GetMembers.Compile(queryParams, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &members) if rErr == nil { @@ -369,7 +369,7 @@ func (r *restClientImpl) SearchMembers(guildID api.Snowflake, query string, limi func (r *restClientImpl) AddMember(guildID api.Snowflake, userID api.Snowflake, addMember api.AddMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.AddMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, addMember, &member) if rErr == nil { @@ -386,7 +386,7 @@ func (r *restClientImpl) RemoveMember(guildID api.Snowflake, userID api.Snowflak } compiledRoute, err := restclient.RemoveMember.Compile(params, guildID, userID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -399,7 +399,7 @@ func (r *restClientImpl) RemoveMember(guildID api.Snowflake, userID api.Snowflak func (r *restClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateMember api.UpdateMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, updateMember, &member) if rErr == nil { @@ -412,7 +412,7 @@ func (r *restClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflak func (r *restClientImpl) UpdateSelfNick(guildID api.Snowflake, nick string) (newNick *string, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateSelfNick.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var updateNick *api.UpdateSelfNick rErr = r.Do(compiledRoute, &api.UpdateSelfNick{Nick: nick}, &updateNick) @@ -431,7 +431,7 @@ func (r *restClientImpl) UpdateSelfNick(guildID api.Snowflake, nick string) (new func (r *restClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, channelID *api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) if rErr == nil { @@ -444,7 +444,7 @@ func (r *restClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, func (r *restClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.AddMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -460,7 +460,7 @@ func (r *restClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowfla func (r *restClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.RemoveMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -481,7 +481,7 @@ func (r *restClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snow func (r *restClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &roles) if rErr == nil { @@ -496,7 +496,7 @@ func (r *restClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, rEr func (r *restClientImpl) CreateRole(guildID api.Snowflake, createRole api.CreateRole) (newRole *api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.CreateRole.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, createRole, &newRole) if rErr == nil { @@ -509,7 +509,7 @@ func (r *restClientImpl) CreateRole(guildID api.Snowflake, createRole api.Create func (r *restClientImpl) UpdateRole(guildID api.Snowflake, roleID api.Snowflake, role api.UpdateRole) (newRole *api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, role, &newRole) if rErr == nil { @@ -522,7 +522,7 @@ func (r *restClientImpl) UpdateRole(guildID api.Snowflake, roleID api.Snowflake, func (r *restClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates ...api.UpdateRolePosition) (roles []*api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, roleUpdates, &roles) if rErr == nil { @@ -537,7 +537,7 @@ func (r *restClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates func (r *restClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -550,7 +550,7 @@ func (r *restClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) func (r *restClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.AddReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -559,7 +559,7 @@ func (r *restClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snow func (r *restClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.RemoveOwnReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -568,7 +568,7 @@ func (r *restClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID ap func (r *restClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string, userID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.RemoveUserReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji), userID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -577,7 +577,7 @@ func (r *restClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID a func (r *restClientImpl) GetGlobalCommands(applicationID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &commands) if rErr == nil { @@ -592,7 +592,7 @@ func (r *restClientImpl) GetGlobalCommands(applicationID api.Snowflake) (command func (r *restClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmd) if rErr == nil { @@ -605,7 +605,7 @@ func (r *restClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID func (r *restClientImpl) CreateGlobalCommand(applicationID api.Snowflake, command api.CommandCreate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGlobalCommand.Compile(nil, applicationID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -618,7 +618,7 @@ func (r *restClientImpl) CreateGlobalCommand(applicationID api.Snowflake, comman func (r *restClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.SetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands @@ -637,7 +637,7 @@ func (r *restClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands func (r *restClientImpl) UpdateGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -650,7 +650,7 @@ func (r *restClientImpl) UpdateGlobalCommand(applicationID api.Snowflake, comman func (r *restClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -663,7 +663,7 @@ func (r *restClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, comman func (r *restClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &commands) if rErr == nil { @@ -678,7 +678,7 @@ func (r *restClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID a func (r *restClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, command api.CommandCreate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuildCommand.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -691,7 +691,7 @@ func (r *restClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID func (r *restClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands @@ -710,7 +710,7 @@ func (r *restClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID a func (r *restClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmd) if rErr == nil { @@ -723,7 +723,7 @@ func (r *restClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID ap func (r *restClientImpl) UpdateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -736,7 +736,7 @@ func (r *restClientImpl) UpdateGuildCommand(applicationID api.Snowflake, guildID func (r *restClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -749,7 +749,7 @@ func (r *restClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID func (r *restClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake) (cmdsPerms []*api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmdsPerms) if rErr == nil { @@ -764,7 +764,7 @@ func (r *restClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake func (r *restClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmdPerms *api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermission.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmdPerms) if rErr == nil { @@ -777,7 +777,7 @@ func (r *restClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, func (r *restClientImpl) SetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandsPermissions ...api.SetGuildCommandPermissions) (cmdsPerms []*api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandsPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.SetGuildCommandsPermissions(commandsPermissions), &cmdsPerms) if rErr == nil { @@ -792,7 +792,7 @@ func (r *restClientImpl) SetGuildCommandsPermissions(applicationID api.Snowflake func (r *restClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, commandPermissions api.SetGuildCommandPermissions) (cmdPerms *api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandPermissions.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, commandPermissions, &cmdPerms) if rErr == nil { @@ -805,12 +805,12 @@ func (r *restClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, func (r *restClientImpl) SendInteractionResponse(interactionID api.Snowflake, interactionToken string, interactionResponse api.InteractionResponse) restclient.RestError { compiledRoute, err := restclient.CreateInteractionResponse.Compile(nil, interactionID, interactionToken) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } body, err := interactionResponse.ToBody() if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, body, nil) @@ -820,12 +820,12 @@ func (r *restClientImpl) SendInteractionResponse(interactionID api.Snowflake, in func (r *restClientImpl) UpdateInteractionResponse(applicationID api.Snowflake, interactionToken string, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -840,7 +840,7 @@ func (r *restClientImpl) UpdateInteractionResponse(applicationID api.Snowflake, func (r *restClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, interactionToken string) restclient.RestError { compiledRoute, err := restclient.DeleteInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -849,12 +849,12 @@ func (r *restClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, func (r *restClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateFollowupMessage.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -870,12 +870,12 @@ func (r *restClientImpl) SendFollowupMessage(applicationID api.Snowflake, intera func (r *restClientImpl) UpdateFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -891,7 +891,7 @@ func (r *restClientImpl) UpdateFollowupMessage(applicationID api.Snowflake, inte func (r *restClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.DeleteFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } From 54bc3797d068229989ded6efdbc618c0011684ef Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 18 Jun 2021 19:28:27 +0200 Subject: [PATCH 18/64] wtf --- api/message_update.go | 59 ------------------------------------------- 1 file changed, 59 deletions(-) diff --git a/api/message_update.go b/api/message_update.go index 866197e6..fc4d88bb 100644 --- a/api/message_update.go +++ b/api/message_update.go @@ -160,65 +160,6 @@ func (b *MessageUpdateBuilder) RetainAttachmentsByID(attachmentIDs ...Snowflake) 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, - Reader: reader, - Flags: restclient.FileFlagNone.Add(flags...), - }) - b.updateFlags |= updateFlagFiles - 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:]...) - } - b.updateFlags |= updateFlagFiles - 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{ - ID: attachmentID, - }) - } - b.updateFlags |= updateFlagRetainAttachment - return b -} - // SetAllowedMentions sets the AllowedMentions of the Message func (b *MessageUpdateBuilder) SetAllowedMentions(allowedMentions *AllowedMentions) *MessageUpdateBuilder { b.AllowedMentions = allowedMentions From bfc5dcbbce48e3367902215f16d21ff73e79b627 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sun, 20 Jun 2021 21:08:45 +0200 Subject: [PATCH 19/64] implemented roles, permission utility --- api/guild.go | 14 ++++++++-- api/member.go | 53 ++++++++++++++++++++++++------------- api/permissions.go | 18 +++++++++++++ internal/restclient_impl.go | 6 ++--- 4 files changed, 67 insertions(+), 24 deletions(-) diff --git a/api/guild.go b/api/guild.go index ce604f9e..ca74de11 100644 --- a/api/guild.go +++ b/api/guild.go @@ -172,8 +172,18 @@ 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 { +// PublicRole returns the @everyone Role +func (g *Guild) PublicRole() *Role { + return g.Disgo.Cache().Role(g.ID) +} + +// Roles return all Role(s) in this Guild +func (g *Guild) Roles() []*Role { + return g.Disgo.Cache().Roles(g.ID) +} + +// SelfMember returns the Member for the current logged in User for this Guild +func (g *Guild) SelfMember() *SelfMember { return &SelfMember{ Member: g.Disgo.Cache().Member(g.ID, g.Disgo.SelfUserID()), } diff --git a/api/member.go b/api/member.go index 5c0e5e93..1e78c20b 100644 --- a/api/member.go +++ b/api/member.go @@ -4,26 +4,41 @@ import "time" // Member is a discord GuildMember type Member struct { - Disgo Disgo - GuildID Snowflake `json:"guild_id"` - User *User `json:"user"` - Nick *string `json:"nick"` - Roles []Snowflake `json:"roles,omitempty"` - JoinedAt time.Time `json:"joined_at"` - PremiumSince *time.Time `json:"premium_since,omitempty"` - Deaf *bool `json:"deaf,omitempty"` - Mute *bool `json:"mute,omitempty"` - Pending bool `json:"pending"` - Permissions *Permissions `json:"permissions,omitempty"` + Disgo Disgo + GuildID Snowflake `json:"guild_id"` + User *User `json:"user"` + Nick *string `json:"nick"` + RoleIDs []Snowflake `json:"roles,omitempty"` + JoinedAt time.Time `json:"joined_at"` + PremiumSince *time.Time `json:"premium_since,omitempty"` + Deaf *bool `json:"deaf,omitempty"` + Mute *bool `json:"mute,omitempty"` + Pending bool `json:"pending"` + ChannelPermissions *Permissions `json:"permissions,omitempty"` +} + +// Permissions returns the Permissions the Member has in the Guild +func (m *Member) Permissions() Permissions { + return GetMemberPermissions(m) +} + +// Roles return all Role(s)the Member has +func (m *Member) Roles() []*Role { + var roles []*Role + allRoles := m.Disgo.Cache().RoleCache(m.GuildID) + for _, roleID := range m.RoleIDs { + roles = append(roles, allRoles[roleID]) + } + return roles } // VoiceState returns the VoiceState for this Member from the Cache(requires CacheFlagVoiceState and GatewayIntentsGuildVoiceStates) -func (m Member) VoiceState() *VoiceState { +func (m *Member) VoiceState() *VoiceState { return m.Disgo.Cache().VoiceState(m.GuildID, m.User.ID) } // EffectiveName returns either the nickname or username depending on if the user has a nickname -func (m Member) EffectiveName() string { +func (m *Member) EffectiveName() string { if m.Nick != nil { return *m.Nick } @@ -31,32 +46,32 @@ func (m Member) EffectiveName() string { } // Guild returns the members guild from the cache -func (m Member) Guild() *Guild { +func (m *Member) Guild() *Guild { return m.Disgo.Cache().Guild(m.GuildID) } // IsOwner returns whether the member is the owner of the guild_events that it belongs to -func (m Member) IsOwner() bool { +func (m *Member) IsOwner() bool { return m.Guild().OwnerID == m.User.ID } // 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) } // Move moves/kicks the member to/from a voice channel -func (m Member) Move(channelID *Snowflake) (*Member, error) { +func (m *Member) Move(channelID *Snowflake) (*Member, error) { return m.Disgo.RestClient().MoveMember(m.GuildID, m.User.ID, channelID) } // AddRole adds a specific role the member -func (m Member) AddRole(roleID Snowflake) error { +func (m *Member) AddRole(roleID Snowflake) error { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } // RemoveRole removes a specific role the member -func (m Member) RemoveRole(roleID Snowflake) error { +func (m *Member) RemoveRole(roleID Snowflake) error { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } diff --git a/api/permissions.go b/api/permissions.go index 88590da4..0fd9bd63 100644 --- a/api/permissions.go +++ b/api/permissions.go @@ -181,3 +181,21 @@ func (p Permissions) MissingAny(bits ...Permissions) bool { func (p Permissions) Missing(bit Permissions) bool { return !p.Has(bit) } + +// GetMemberPermissions returns all Permissions from the provided Member +func GetMemberPermissions(member *Member) Permissions { + if member.IsOwner() { + return PermissionsAll + } + if guild := member.Guild(); guild != nil { + var permissions Permissions + for _, role := range member.Roles() { + permissions = permissions.Add(role.Permissions) + if permissions.Has(PermissionAdministrator) { + return PermissionsAll + } + } + return permissions + } + return PermissionsNone +} diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index aedd8f37..901972fc 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -280,7 +280,7 @@ func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowfla if err == nil && api.CacheStrategyNoWs(r.Disgo()) { member := r.Disgo().Cache().Member(guildID, userID) if member != nil { - member.Roles = append(member.Roles, roleID) + member.RoleIDs = append(member.RoleIDs, roleID) } } return @@ -296,9 +296,9 @@ func (r *RestClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snow if err == nil && api.CacheStrategyNoWs(r.Disgo()) { member := r.Disgo().Cache().Member(guildID, userID) if member != nil { - for i, id := range member.Roles { + for i, id := range member.RoleIDs { if id == roleID { - member.Roles = append(member.Roles[:i], member.Roles[i+1:]...) + member.RoleIDs = append(member.RoleIDs[:i], member.RoleIDs[i+1:]...) break } } From 638a9abfa305343bd43d8e23b17a94663a65e3be Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 21 Jun 2021 17:12:27 +0200 Subject: [PATCH 20/64] fixed nil-pointer on isOwner --- api/member.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/api/member.go b/api/member.go index 5c0e5e93..03116d0b 100644 --- a/api/member.go +++ b/api/member.go @@ -37,7 +37,10 @@ func (m Member) Guild() *Guild { // IsOwner returns whether the member is the owner of the guild_events that it belongs to func (m Member) IsOwner() bool { - return m.Guild().OwnerID == m.User.ID + if guild := m.Guild(); guild != nil { + return guild.OwnerID == m.User.ID + } + return false } // Update updates the member From 236bbd106518a962972a439c32d8e0b59ca7a951 Mon Sep 17 00:00:00 2001 From: Eve Date: Mon, 21 Jun 2021 18:30:06 +0100 Subject: [PATCH 21/64] Guild Templates --- api/disgo.go | 3 ++ api/guild.go | 20 +++++++++ api/restclient.go | 8 ++++ api/template.go | 36 +++++++++++++++++ go.mod | 2 +- go.sum | 4 +- internal/disgo_impl.go | 10 +++++ internal/restclient_impl.go | 81 +++++++++++++++++++++++++++++++++++++ 8 files changed, 161 insertions(+), 3 deletions(-) create mode 100644 api/template.go diff --git a/api/disgo.go b/api/disgo.go index 70c15e78..6402e563 100644 --- a/api/disgo.go +++ b/api/disgo.go @@ -52,6 +52,9 @@ type Disgo interface { GetGuildCommandPermissions(guildID Snowflake, commandID Snowflake) (*GuildCommandPermissions, restclient.RestError) SetGuildCommandsPermissions(guildID Snowflake, commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, restclient.RestError) SetGuildCommandPermissions(guildID Snowflake, commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, restclient.RestError) + + GetTemplate(code string) (*GuildTemplate, restclient.RestError) + CreateGuildFromTemplate(templateCode string, data CreateGuildFromTemplate) (*Guild, restclient.RestError) } // GetOS returns the simplified version of the operating system for sending to Discord in the IdentifyCommandDataProperties.OS payload diff --git a/api/guild.go b/api/guild.go index 2f44206f..a0fb29d1 100644 --- a/api/guild.go +++ b/api/guild.go @@ -299,6 +299,26 @@ func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildC return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } +func (g *Guild) GetTemplates() ([]*GuildTemplate, error) { + return g.Disgo.RestClient().GetGuildTemplates(g.ID) +} + +func (g *Guild) CreateTemplate(data CreateGuildTemplate) (*GuildTemplate, error) { + return g.Disgo.RestClient().CreateGuildTemplate(g.ID, data) +} + +func (g *Guild) SyncTemplate(code string) (*GuildTemplate, error) { + return g.Disgo.RestClient().SyncGuildTemplate(g.ID, code) +} + +func (g *Guild) UpdateTemplate(code string, data UpdateGuildTemplate) (*GuildTemplate, error) { + return g.Disgo.RestClient().UpdateGuildTemplate(g.ID, code, data) +} + +func (g *Guild) DeleteTemplate(code string) (*GuildTemplate, error) { + return g.Disgo.RestClient().DeleteGuildTemplate(g.ID, code) +} + // PartialGuild is returned on the restclient.GetGuilds route type PartialGuild struct { ID Snowflake `json:"id"` diff --git a/api/restclient.go b/api/restclient.go index 8a21efaa..c3ee458f 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -92,4 +92,12 @@ type RestClient interface { SendFollowupMessage(applicationID Snowflake, interactionToken string, messageCreate MessageCreate) (*Message, restclient.RestError) UpdateFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, messageUpdate MessageUpdate) (*Message, restclient.RestError) DeleteFollowupMessage(applicationID Snowflake, interactionToken string, followupMessageID Snowflake) restclient.RestError + + GetGuildTemplate(templateCode string) (*GuildTemplate, restclient.RestError) + GetGuildTemplates(guildID Snowflake) ([]*GuildTemplate, restclient.RestError) + CreateGuildTemplate(guildID Snowflake, data CreateGuildTemplate) (*GuildTemplate, restclient.RestError) + CreateGuildFromTemplate(templateCode string, data CreateGuildFromTemplate) (*Guild, restclient.RestError) + SyncGuildTemplate(guildID Snowflake, templateCode string) (*GuildTemplate, restclient.RestError) + UpdateGuildTemplate(guildID Snowflake, templateCode string, data UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) + DeleteGuildTemplate(guildID Snowflake, templateCode string) (*GuildTemplate, restclient.RestError) } diff --git a/api/template.go b/api/template.go new file mode 100644 index 00000000..7520d39a --- /dev/null +++ b/api/template.go @@ -0,0 +1,36 @@ +package api + +import "time" + +// GuildTemplate is a template used for copying guilds https://discord.com/developers/docs/resources/guild-template +type GuildTemplate struct { + Code string `json:"code"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + UsageCount int `json:"usage_count"` + CreatorID Snowflake `json:"creator_id"` + Creator User `json:"creator"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + SourceGuildID Snowflake `json:"source_guild_id"` + SourceGuild Guild `json:"serialized_source_guild"` + IsDirty *bool `json:"is_dirty,omitempty"` +} + +// CreateGuildTemplate is the data used to create a GuildTemplate +type CreateGuildTemplate struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` +} + +// UpdateGuildTemplate is the data used to update a GuildTemplate +type UpdateGuildTemplate struct { + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` +} + +// CreateGuildFromTemplate is the data used to create a Guild from a GuildTemplate +type CreateGuildFromTemplate struct { + Name string `json:"name"` + ImageData []*byte `json:"icon,omitempty"` +} diff --git a/go.mod b/go.mod index fb5141cf..291d427a 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.16 require ( github.com/DisgoOrg/log v1.0.3 - github.com/DisgoOrg/restclient v1.2.0 + github.com/DisgoOrg/restclient v1.2.2 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/stretchr/testify v1.7.0 diff --git a/go.sum b/go.sum index c1098959..88451fc1 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.2.0 h1:M2GXPf5Ja+Ynt7DBTLv+TQ4iMVLQX17FRHXQ0gqAExw= -github.com/DisgoOrg/restclient v1.2.0/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= +github.com/DisgoOrg/restclient v1.2.2 h1:75SGqqN/9lqJ3GQOpPY99f1ihZMzSXDcLNF+biDp+Pk= +github.com/DisgoOrg/restclient v1.2.2/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= diff --git a/internal/disgo_impl.go b/internal/disgo_impl.go index 35b958db..6d201057 100644 --- a/internal/disgo_impl.go +++ b/internal/disgo_impl.go @@ -281,3 +281,13 @@ func (d *DisgoImpl) SetGuildCommandsPermissions(guildID api.Snowflake, commandPe func (d *DisgoImpl) SetGuildCommandPermissions(guildID api.Snowflake, commandID api.Snowflake, permissions api.SetGuildCommandPermissions) (*api.GuildCommandPermissions, restclient.RestError) { return d.RestClient().SetGuildCommandPermissions(d.ApplicationID(), guildID, commandID, permissions) } + +// GetTemplate gets a api.GuildTemplate by it's code +func (d *DisgoImpl) GetTemplate(code string) (*api.GuildTemplate, restclient.RestError) { + return d.RestClient().GetGuildTemplate(code) +} + +// CreateGuildFromTemplate creates an api.Guild using a api.Template code +func (d *DisgoImpl) CreateGuildFromTemplate(templateCode string, data api.CreateGuildFromTemplate) (*api.Guild, restclient.RestError) { + return d.RestClient().CreateGuildFromTemplate(templateCode, data) +} \ No newline at end of file diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 259bcf09..f5c73619 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -896,6 +896,87 @@ func (r *restClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, inte return r.Do(compiledRoute, nil, nil) } +func (r *restClientImpl) GetGuildTemplate(templateCode string) (guildTemplate *api.GuildTemplate, rErr restclient.RestError) { + compiledRoute, err := restclient.GetGuildTemplate.Compile(nil, templateCode) + if err != nil { + return nil, restclient.NewError(nil, err) + } + + rErr = r.Do(compiledRoute, nil, &guildTemplate) + + return +} + +func (r *restClientImpl) GetGuildTemplates(guildID api.Snowflake) (guildTemplates []*api.GuildTemplate, rErr restclient.RestError) { + compiledRoute, err := restclient.GetGuildTemplates.Compile(nil, guildID) + if err != nil { + return nil, restclient.NewError(nil, err) + } + + rErr = r.Do(compiledRoute, nil, &guildTemplates) + + return +} + +func (r *restClientImpl) CreateGuildTemplate(guildID api.Snowflake, createTemplate api.CreateGuildTemplate) (guildTemplate *api.GuildTemplate, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateGuildTemplate.Compile(nil, guildID) + if err != nil { + return nil, restclient.NewError(nil, err) + } + + rErr = r.Do(compiledRoute, createTemplate, &guildTemplate) + + return +} + +func (r *restClientImpl) CreateGuildFromTemplate(templateCode string, createGuildFromTemplate api.CreateGuildFromTemplate) (guild *api.Guild, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateGuildFromTemplate.Compile(nil, templateCode) + if err != nil { + return nil, restclient.NewError(nil, err) + } + + var fullGuild *api.FullGuild + rErr = r.Do(compiledRoute, createGuildFromTemplate, &fullGuild) + if rErr == nil { + guild = r.Disgo().EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNoWs) + } + + return +} + +func (r *restClientImpl) SyncGuildTemplate(guildID api.Snowflake, templateCode string) (guildTemplate *api.GuildTemplate, rErr restclient.RestError) { + compiledRoute, err := restclient.SyncGuildTemplate.Compile(nil, guildID, templateCode) + if err != nil { + return nil, restclient.NewError(nil, err) + } + + rErr = r.Do(compiledRoute, nil, &guildTemplate) + + return +} + +func (r *restClientImpl) UpdateGuildTemplate(guildID api.Snowflake, templateCode string, updateGuildTemplate api.UpdateGuildTemplate) (guildTemplate *api.GuildTemplate, rErr restclient.RestError) { + compiledRoute, err := restclient.UpdateGuildTemplate.Compile(nil, guildID, templateCode) + if err != nil { + return nil, restclient.NewError(nil, err) + } + + rErr = r.Do(compiledRoute, updateGuildTemplate, &guildTemplate) + + return +} + +func (r *restClientImpl) DeleteGuildTemplate(guildID api.Snowflake, templateCode string) (guildTemplate *api.GuildTemplate, rErr restclient.RestError) { + compiledRoute, err := restclient.DeleteGuildTemplate.Compile(nil, guildID, templateCode) + if err != nil { + return nil, restclient.NewError(nil, err) + } + + rErr = r.Do(compiledRoute, nil, &guildTemplate) + + return +} + func normalizeEmoji(emoji string) string { return strings.Replace(emoji, "#", "%23", -1) } From 3ed8a1f84efc63e88bc352e51264a219ad49447d Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:06:21 +0100 Subject: [PATCH 22/64] Update api/template.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/template.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/template.go b/api/template.go index 7520d39a..22e870f4 100644 --- a/api/template.go +++ b/api/template.go @@ -32,5 +32,5 @@ type UpdateGuildTemplate struct { // CreateGuildFromTemplate is the data used to create a Guild from a GuildTemplate type CreateGuildFromTemplate struct { Name string `json:"name"` - ImageData []*byte `json:"icon,omitempty"` + ImageData []byte `json:"icon,omitempty"` } From 8c4af82ca95fcf7b536d6801f8fc53a1f70d162b Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:06:34 +0100 Subject: [PATCH 23/64] Update api/template.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/template.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/template.go b/api/template.go index 22e870f4..05a3d285 100644 --- a/api/template.go +++ b/api/template.go @@ -13,7 +13,7 @@ type GuildTemplate struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` SourceGuildID Snowflake `json:"source_guild_id"` - SourceGuild Guild `json:"serialized_source_guild"` + SourceGuild PartialGuild `json:"serialized_source_guild"` IsDirty *bool `json:"is_dirty,omitempty"` } From 16b3a426b92bcdfcbe27829e1bcc9ae2b2040d87 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:06:46 +0100 Subject: [PATCH 24/64] Update api/guild.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/guild.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/guild.go b/api/guild.go index a0fb29d1..78bafc85 100644 --- a/api/guild.go +++ b/api/guild.go @@ -303,7 +303,7 @@ func (g *Guild) GetTemplates() ([]*GuildTemplate, error) { return g.Disgo.RestClient().GetGuildTemplates(g.ID) } -func (g *Guild) CreateTemplate(data CreateGuildTemplate) (*GuildTemplate, error) { +func (g *Guild) CreateTemplate(createGuildTemplate CreateGuildTemplate) (*GuildTemplate, restclient.restError) { return g.Disgo.RestClient().CreateGuildTemplate(g.ID, data) } From 0d8965b2c72298d61075762057ad72cb5217675b Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:06:53 +0100 Subject: [PATCH 25/64] Update api/guild.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/guild.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/guild.go b/api/guild.go index 78bafc85..d73fdadb 100644 --- a/api/guild.go +++ b/api/guild.go @@ -311,7 +311,7 @@ func (g *Guild) SyncTemplate(code string) (*GuildTemplate, error) { return g.Disgo.RestClient().SyncGuildTemplate(g.ID, code) } -func (g *Guild) UpdateTemplate(code string, data UpdateGuildTemplate) (*GuildTemplate, error) { +func (g *Guild) UpdateTemplate(code string, updateGuildTemplate UpdateGuildTemplate) (*GuildTemplate, restclient.restError) { return g.Disgo.RestClient().UpdateGuildTemplate(g.ID, code, data) } From c3c2646a6361da9424a0c62697cf06145e0e3c94 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:07:00 +0100 Subject: [PATCH 26/64] Update api/guild.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/guild.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/guild.go b/api/guild.go index d73fdadb..3aae5048 100644 --- a/api/guild.go +++ b/api/guild.go @@ -299,7 +299,7 @@ func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildC return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } -func (g *Guild) GetTemplates() ([]*GuildTemplate, error) { +func (g *Guild) GetTemplates() ([]*GuildTemplate, restclient.restError) { return g.Disgo.RestClient().GetGuildTemplates(g.ID) } From 7f9188627fc16595f6aa8d65ba32c6a961c97800 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:07:11 +0100 Subject: [PATCH 27/64] Update api/template.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/template.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/template.go b/api/template.go index 05a3d285..2b786236 100644 --- a/api/template.go +++ b/api/template.go @@ -9,7 +9,7 @@ type GuildTemplate struct { Description *string `json:"description,omitempty"` UsageCount int `json:"usage_count"` CreatorID Snowflake `json:"creator_id"` - Creator User `json:"creator"` + Creator *User `json:"creator"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` SourceGuildID Snowflake `json:"source_guild_id"` From 0df5428d1a58169a8e0800621d235f4e373f7f6f Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:07:22 +0100 Subject: [PATCH 28/64] Update internal/disgo_impl.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- internal/disgo_impl.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/disgo_impl.go b/internal/disgo_impl.go index 6d201057..0218438a 100644 --- a/internal/disgo_impl.go +++ b/internal/disgo_impl.go @@ -288,6 +288,6 @@ func (d *DisgoImpl) GetTemplate(code string) (*api.GuildTemplate, restclient.Res } // CreateGuildFromTemplate creates an api.Guild using a api.Template code -func (d *DisgoImpl) CreateGuildFromTemplate(templateCode string, data api.CreateGuildFromTemplate) (*api.Guild, restclient.RestError) { +func (d *DisgoImpl) CreateGuildFromTemplate(templateCode string, createGuildFromTemplate api.CreateGuildFromTemplate) (*api.Guild, restclient.RestError) { return d.RestClient().CreateGuildFromTemplate(templateCode, data) -} \ No newline at end of file +} From 86c15d9d27466b74ea3926e0bb9eb8873a1591c6 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:07:33 +0100 Subject: [PATCH 29/64] Update internal/restclient_impl.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@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 f5c73619..95736039 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -918,7 +918,7 @@ func (r *restClientImpl) GetGuildTemplates(guildID api.Snowflake) (guildTemplate return } -func (r *restClientImpl) CreateGuildTemplate(guildID api.Snowflake, createTemplate api.CreateGuildTemplate) (guildTemplate *api.GuildTemplate, rErr restclient.RestError) { +func (r *restClientImpl) CreateGuildTemplate(guildID api.Snowflake, createGuildTemplate api.CreateGuildTemplate) (guildTemplate *api.GuildTemplate, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuildTemplate.Compile(nil, guildID) if err != nil { return nil, restclient.NewError(nil, err) From 8700587c75d35ee9ca154dd721b4afb79ab739e4 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:07:48 +0100 Subject: [PATCH 30/64] Update api/disgo.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/disgo.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/disgo.go b/api/disgo.go index 6402e563..34642daa 100644 --- a/api/disgo.go +++ b/api/disgo.go @@ -54,7 +54,7 @@ type Disgo interface { SetGuildCommandPermissions(guildID Snowflake, commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, restclient.RestError) GetTemplate(code string) (*GuildTemplate, restclient.RestError) - CreateGuildFromTemplate(templateCode string, data CreateGuildFromTemplate) (*Guild, restclient.RestError) + CreateGuildFromTemplate(templateCode string, createGuildFromTemplate CreateGuildFromTemplate) (*Guild, restclient.RestError) } // GetOS returns the simplified version of the operating system for sending to Discord in the IdentifyCommandDataProperties.OS payload From c3843bb5c912dbc1891d97ef6917e0a067737337 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:07:58 +0100 Subject: [PATCH 31/64] Update api/restclient.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/restclient.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/restclient.go b/api/restclient.go index c3ee458f..24567e33 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -95,7 +95,7 @@ type RestClient interface { GetGuildTemplate(templateCode string) (*GuildTemplate, restclient.RestError) GetGuildTemplates(guildID Snowflake) ([]*GuildTemplate, restclient.RestError) - CreateGuildTemplate(guildID Snowflake, data CreateGuildTemplate) (*GuildTemplate, restclient.RestError) + CreateGuildTemplate(guildID Snowflake, createGuildTemplate CreateGuildTemplate) (*GuildTemplate, restclient.RestError) CreateGuildFromTemplate(templateCode string, data CreateGuildFromTemplate) (*Guild, restclient.RestError) SyncGuildTemplate(guildID Snowflake, templateCode string) (*GuildTemplate, restclient.RestError) UpdateGuildTemplate(guildID Snowflake, templateCode string, data UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) From 5e41262a1a8f4e6210027b872bbfa45bc5923014 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:25:40 +0100 Subject: [PATCH 32/64] Update api/restclient.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/restclient.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/restclient.go b/api/restclient.go index 24567e33..ca78e20b 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -98,6 +98,6 @@ type RestClient interface { CreateGuildTemplate(guildID Snowflake, createGuildTemplate CreateGuildTemplate) (*GuildTemplate, restclient.RestError) CreateGuildFromTemplate(templateCode string, data CreateGuildFromTemplate) (*Guild, restclient.RestError) SyncGuildTemplate(guildID Snowflake, templateCode string) (*GuildTemplate, restclient.RestError) - UpdateGuildTemplate(guildID Snowflake, templateCode string, data UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) + UpdateGuildTemplate(guildID Snowflake, templateCode string, updateGuildTemplate UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) DeleteGuildTemplate(guildID Snowflake, templateCode string) (*GuildTemplate, restclient.RestError) } From b966e930de3139a9d74afe23f4c297fd5e7862f4 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:25:49 +0100 Subject: [PATCH 33/64] Update api/restclient.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/restclient.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/restclient.go b/api/restclient.go index ca78e20b..5124b845 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -96,7 +96,7 @@ type RestClient interface { GetGuildTemplate(templateCode string) (*GuildTemplate, restclient.RestError) GetGuildTemplates(guildID Snowflake) ([]*GuildTemplate, restclient.RestError) CreateGuildTemplate(guildID Snowflake, createGuildTemplate CreateGuildTemplate) (*GuildTemplate, restclient.RestError) - CreateGuildFromTemplate(templateCode string, data CreateGuildFromTemplate) (*Guild, restclient.RestError) + CreateGuildFromTemplate(templateCode string, createGuildFromTemplate CreateGuildFromTemplate) (*Guild, restclient.RestError) SyncGuildTemplate(guildID Snowflake, templateCode string) (*GuildTemplate, restclient.RestError) UpdateGuildTemplate(guildID Snowflake, templateCode string, updateGuildTemplate UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) DeleteGuildTemplate(guildID Snowflake, templateCode string) (*GuildTemplate, restclient.RestError) From dc5809244b7d6069027ed39f2b39b5b294751f8b Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:26:00 +0100 Subject: [PATCH 34/64] Update api/guild.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/guild.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/guild.go b/api/guild.go index 3aae5048..79ce3834 100644 --- a/api/guild.go +++ b/api/guild.go @@ -307,7 +307,7 @@ func (g *Guild) CreateTemplate(createGuildTemplate CreateGuildTemplate) (*GuildT return g.Disgo.RestClient().CreateGuildTemplate(g.ID, data) } -func (g *Guild) SyncTemplate(code string) (*GuildTemplate, error) { +func (g *Guild) SyncTemplate(code string) (*GuildTemplate, restclient.restError) { return g.Disgo.RestClient().SyncGuildTemplate(g.ID, code) } From 52d9b145e022004c8e797dfaa9c01c4c69595ce4 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Mon, 21 Jun 2021 19:26:12 +0100 Subject: [PATCH 35/64] Update api/guild.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/guild.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/guild.go b/api/guild.go index 79ce3834..1369cde9 100644 --- a/api/guild.go +++ b/api/guild.go @@ -315,7 +315,7 @@ func (g *Guild) UpdateTemplate(code string, updateGuildTemplate UpdateGuildTempl return g.Disgo.RestClient().UpdateGuildTemplate(g.ID, code, data) } -func (g *Guild) DeleteTemplate(code string) (*GuildTemplate, error) { +func (g *Guild) DeleteTemplate(code string) (*GuildTemplate, restclient.restError) { return g.Disgo.RestClient().DeleteGuildTemplate(g.ID, code) } From 8d56602ece5e347da7c7cc18fba36e15a2f33ede Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 21 Jun 2021 20:37:38 +0200 Subject: [PATCH 36/64] reformat & fixed errors from suggestions --- api/guild.go | 14 +++++++------- api/template.go | 28 ++++++++++++++-------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/api/guild.go b/api/guild.go index 1369cde9..d8048ef0 100644 --- a/api/guild.go +++ b/api/guild.go @@ -299,23 +299,23 @@ func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildC return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } -func (g *Guild) GetTemplates() ([]*GuildTemplate, restclient.restError) { +func (g *Guild) GetTemplates() ([]*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().GetGuildTemplates(g.ID) } -func (g *Guild) CreateTemplate(createGuildTemplate CreateGuildTemplate) (*GuildTemplate, restclient.restError) { - return g.Disgo.RestClient().CreateGuildTemplate(g.ID, data) +func (g *Guild) CreateTemplate(createGuildTemplate CreateGuildTemplate) (*GuildTemplate, restclient.RestError) { + return g.Disgo.RestClient().CreateGuildTemplate(g.ID, createGuildTemplate) } -func (g *Guild) SyncTemplate(code string) (*GuildTemplate, restclient.restError) { +func (g *Guild) SyncTemplate(code string) (*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().SyncGuildTemplate(g.ID, code) } -func (g *Guild) UpdateTemplate(code string, updateGuildTemplate UpdateGuildTemplate) (*GuildTemplate, restclient.restError) { - return g.Disgo.RestClient().UpdateGuildTemplate(g.ID, code, data) +func (g *Guild) UpdateTemplate(code string, updateGuildTemplate UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) { + return g.Disgo.RestClient().UpdateGuildTemplate(g.ID, code, updateGuildTemplate) } -func (g *Guild) DeleteTemplate(code string) (*GuildTemplate, restclient.restError) { +func (g *Guild) DeleteTemplate(code string) (*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().DeleteGuildTemplate(g.ID, code) } diff --git a/api/template.go b/api/template.go index 2b786236..844c631a 100644 --- a/api/template.go +++ b/api/template.go @@ -4,17 +4,17 @@ import "time" // GuildTemplate is a template used for copying guilds https://discord.com/developers/docs/resources/guild-template type GuildTemplate struct { - Code string `json:"code"` - Name string `json:"name"` - Description *string `json:"description,omitempty"` - UsageCount int `json:"usage_count"` - CreatorID Snowflake `json:"creator_id"` - Creator *User `json:"creator"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - SourceGuildID Snowflake `json:"source_guild_id"` - SourceGuild PartialGuild `json:"serialized_source_guild"` - IsDirty *bool `json:"is_dirty,omitempty"` + Code string `json:"code"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + UsageCount int `json:"usage_count"` + CreatorID Snowflake `json:"creator_id"` + Creator *User `json:"creator"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + SourceGuildID Snowflake `json:"source_guild_id"` + SourceGuild PartialGuild `json:"serialized_source_guild"` + IsDirty *bool `json:"is_dirty,omitempty"` } // CreateGuildTemplate is the data used to create a GuildTemplate @@ -25,12 +25,12 @@ type CreateGuildTemplate struct { // UpdateGuildTemplate is the data used to update a GuildTemplate type UpdateGuildTemplate struct { - Name *string `json:"name,omitempty"` + Name *string `json:"name,omitempty"` Description *string `json:"description,omitempty"` } // CreateGuildFromTemplate is the data used to create a Guild from a GuildTemplate type CreateGuildFromTemplate struct { - Name string `json:"name"` - ImageData []byte `json:"icon,omitempty"` + Name string `json:"name"` + ImageData []byte `json:"icon,omitempty"` } From 62ecacc34e5a6f9e09e2423ee5e248405ff32430 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 21 Jun 2021 20:53:04 +0200 Subject: [PATCH 37/64] added entity builder for guild templates & renamed file --- api/entity_builder.go | 1 + api/guild_template.go | 56 +++++++++++++++++++++++++++++++++ api/template.go | 36 --------------------- internal/entity_builder_impl.go | 10 ++++++ internal/restclient_impl.go | 32 ++++++++++++------- internal/util.go | 4 +++ 6 files changed, 92 insertions(+), 47 deletions(-) create mode 100644 api/guild_template.go delete mode 100644 api/template.go diff --git a/api/entity_builder.go b/api/entity_builder.go index fa51a164..36fb301a 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -24,6 +24,7 @@ type EntityBuilder interface { CreateMessage(message *FullMessage, updateCache CacheStrategy) *Message + CreateGuildTemplate(guildTemplate *GuildTemplate, updateCache CacheStrategy) *GuildTemplate CreateGuild(fullGuild *FullGuild, updateCache CacheStrategy) *Guild CreateMember(guildID Snowflake, member *Member, updateCache CacheStrategy) *Member CreateGuildCommand(guildID Snowflake, command *Command, updateCache CacheStrategy) *Command diff --git a/api/guild_template.go b/api/guild_template.go new file mode 100644 index 00000000..80be9b0b --- /dev/null +++ b/api/guild_template.go @@ -0,0 +1,56 @@ +package api + +import ( + "time" + + "github.com/DisgoOrg/restclient" +) + +// GuildTemplate is a template used for copying guilds https://discord.com/developers/docs/resources/guild-template +type GuildTemplate struct { + Disgo Disgo + Code string `json:"code"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + UsageCount int `json:"usage_count"` + CreatorID Snowflake `json:"creator_id"` + Creator *User `json:"creator"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + GuildID Snowflake `json:"source_guild_id"` + PartialGuild PartialGuild `json:"serialized_source_guild"` + IsDirty *bool `json:"is_dirty,omitempty"` +} + +// Guild returns the full Guild of the GuildTemplate if in cache +func (t *GuildTemplate) Guild() *Guild { + return t.Disgo.Cache().Guild(t.GuildID) +} + +// Update updates the GuildTemplate with the provided UpdateGuildTemplate +func (t *GuildTemplate) Update(updateGuildTemplate UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) { + return t.Disgo.RestClient().UpdateGuildTemplate(t.GuildID, t.Code, updateGuildTemplate) +} + +// Delete deletes the GuildTemplate +func (t *GuildTemplate) Delete() (*GuildTemplate, restclient.RestError) { + return t.Disgo.RestClient().DeleteGuildTemplate(t.GuildID, t.Code) +} + +// CreateGuildTemplate is the data used to create a GuildTemplate +type CreateGuildTemplate struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` +} + +// UpdateGuildTemplate is the data used to update a GuildTemplate +type UpdateGuildTemplate struct { + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` +} + +// CreateGuildFromTemplate is the data used to create a Guild from a GuildTemplate +type CreateGuildFromTemplate struct { + Name string `json:"name"` + ImageData []byte `json:"icon,omitempty"` +} diff --git a/api/template.go b/api/template.go deleted file mode 100644 index 844c631a..00000000 --- a/api/template.go +++ /dev/null @@ -1,36 +0,0 @@ -package api - -import "time" - -// GuildTemplate is a template used for copying guilds https://discord.com/developers/docs/resources/guild-template -type GuildTemplate struct { - Code string `json:"code"` - Name string `json:"name"` - Description *string `json:"description,omitempty"` - UsageCount int `json:"usage_count"` - CreatorID Snowflake `json:"creator_id"` - Creator *User `json:"creator"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - SourceGuildID Snowflake `json:"source_guild_id"` - SourceGuild PartialGuild `json:"serialized_source_guild"` - IsDirty *bool `json:"is_dirty,omitempty"` -} - -// CreateGuildTemplate is the data used to create a GuildTemplate -type CreateGuildTemplate struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` -} - -// UpdateGuildTemplate is the data used to update a GuildTemplate -type UpdateGuildTemplate struct { - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` -} - -// CreateGuildFromTemplate is the data used to create a Guild from a GuildTemplate -type CreateGuildFromTemplate struct { - Name string `json:"name"` - ImageData []byte `json:"icon,omitempty"` -} diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index c7a5ba9e..0774f245 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -172,6 +172,16 @@ func (b *EntityBuilderImpl) CreateMessage(fullMessage *api.FullMessage, updateCa return message } +// CreateGuildTemplate returns a new api.GuildTemplate entity +func (b *EntityBuilderImpl) CreateGuildTemplate(guildTemplate *api.GuildTemplate, updateCache api.CacheStrategy) *api.GuildTemplate { + guildTemplate.Disgo = b.Disgo() + + if guildTemplate.Creator != nil { + guildTemplate.Creator = b.CreateUser(guildTemplate.Creator, updateCache) + } + return guildTemplate +} + // CreateGuild returns a new api.Guild entity func (b *EntityBuilderImpl) CreateGuild(fullGuild *api.FullGuild, updateCache api.CacheStrategy) *api.Guild { guild := fullGuild.Guild diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 95736039..a962da25 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -903,7 +903,9 @@ func (r *restClientImpl) GetGuildTemplate(templateCode string) (guildTemplate *a } rErr = r.Do(compiledRoute, nil, &guildTemplate) - + if rErr == nil { + guildTemplate = r.Disgo().EntityBuilder().CreateGuildTemplate(guildTemplate, api.CacheStrategyNoWs) + } return } @@ -914,7 +916,11 @@ func (r *restClientImpl) GetGuildTemplates(guildID api.Snowflake) (guildTemplate } rErr = r.Do(compiledRoute, nil, &guildTemplates) - + if rErr == nil { + for _, guildTemplate := range guildTemplates { + guildTemplate = r.Disgo().EntityBuilder().CreateGuildTemplate(guildTemplate, api.CacheStrategyNoWs) + } + } return } @@ -924,8 +930,10 @@ func (r *restClientImpl) CreateGuildTemplate(guildID api.Snowflake, createGuildT return nil, restclient.NewError(nil, err) } - rErr = r.Do(compiledRoute, createTemplate, &guildTemplate) - + rErr = r.Do(compiledRoute, createGuildTemplate, &guildTemplate) + if rErr == nil { + guildTemplate = r.Disgo().EntityBuilder().CreateGuildTemplate(guildTemplate, api.CacheStrategyNoWs) + } return } @@ -951,7 +959,9 @@ func (r *restClientImpl) SyncGuildTemplate(guildID api.Snowflake, templateCode s } rErr = r.Do(compiledRoute, nil, &guildTemplate) - + if rErr == nil { + guildTemplate = r.Disgo().EntityBuilder().CreateGuildTemplate(guildTemplate, api.CacheStrategyNoWs) + } return } @@ -962,7 +972,9 @@ func (r *restClientImpl) UpdateGuildTemplate(guildID api.Snowflake, templateCode } rErr = r.Do(compiledRoute, updateGuildTemplate, &guildTemplate) - + if rErr == nil { + guildTemplate = r.Disgo().EntityBuilder().CreateGuildTemplate(guildTemplate, api.CacheStrategyNoWs) + } return } @@ -973,10 +985,8 @@ func (r *restClientImpl) DeleteGuildTemplate(guildID api.Snowflake, templateCode } rErr = r.Do(compiledRoute, nil, &guildTemplate) - + if rErr == nil { + guildTemplate = r.Disgo().EntityBuilder().CreateGuildTemplate(guildTemplate, api.CacheStrategyNoWs) + } return } - -func normalizeEmoji(emoji string) string { - return strings.Replace(emoji, "#", "%23", -1) -} diff --git a/internal/util.go b/internal/util.go index 92be3dbb..82589252 100644 --- a/internal/util.go +++ b/internal/util.go @@ -21,3 +21,7 @@ func IDFromToken(token string) (*api.Snowflake, error) { strID := api.Snowflake(byteID) return &strID, nil } + +func normalizeEmoji(emoji string) string { + return strings.Replace(emoji, "#", "%23", -1) +} From ef588b3a6be82872286e6818fdc54d42b4ee7a47 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 22 Jun 2021 00:42:39 +0200 Subject: [PATCH 38/64] cleanup --- internal/restclient_impl.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index a962da25..9b65255c 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -2,7 +2,6 @@ package internal import ( "net/http" - "strings" "github.com/DisgoOrg/disgo/api" "github.com/DisgoOrg/restclient" From 95728c94b4f50cf6915351d2c80af6a550d66441 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Mon, 14 Jun 2021 18:17:19 +0200 Subject: [PATCH 39/64] added more methods for restroutes --- api/guild.go | 75 +++++++++++++++++++++++++++++++++++-- api/member.go | 24 +++++++----- api/restclient.go | 14 +++++-- api/role.go | 19 +++++++--- internal/restclient_impl.go | 34 ++++++++++++++--- 5 files changed, 139 insertions(+), 27 deletions(-) diff --git a/api/guild.go b/api/guild.go index ca74de11..e7263800 100644 --- a/api/guild.go +++ b/api/guild.go @@ -194,14 +194,44 @@ func (g *Guild) Disconnect() error { return g.Disgo.AudioController().Disconnect(g.ID) } +// Update updates the current Guild +func (g *Guild) Update(updateGuild UpdateGuild) (*Guild, error) { + return g.Disgo.RestClient().UpdateGuild(g.ID, updateGuild) +} + +// Delete deletes the current Guild +func (g *Guild) Delete() error { + return g.Disgo.RestClient().DeleteGuild(g.ID) +} + // CreateRole allows you to create a new Role -func (g *Guild) CreateRole(role UpdateRole) (*Role, error) { - return g.Disgo.RestClient().CreateRole(g.ID, role) +func (g *Guild) CreateRole(createRole CreateRole) (*Role, error) { + return g.Disgo.RestClient().CreateRole(g.ID, createRole) +} + +// UpdateRole allows you to update a Role +func (g *Guild) UpdateRole(roleID Snowflake, role UpdateRole) (*Role, error) { + return g.Disgo.RestClient().UpdateRole(g.ID, roleID, role) +} + +// DeleteRole allows you to delete a Role +func (g *Guild) DeleteRole(roleID Snowflake) error { + return g.Disgo.RestClient().DeleteRole(g.ID, roleID) } // AddMember adds a member to the Guild with the oauth2 access token -func (g *Guild) AddMember(userID Snowflake, addGuildMemberData AddGuildMemberData) (*Member, error) { - return g.Disgo.RestClient().AddMember(g.ID, userID, addGuildMemberData) +func (g *Guild) AddMember(userID Snowflake, addMember AddMember) (*Member, error) { + return g.Disgo.RestClient().AddMember(g.ID, userID, addMember) +} + +// UpdateMember updates an existing member of the Guild +func (g *Guild) UpdateMember(userID Snowflake, updateMember UpdateMember) (*Member, error) { + return g.Disgo.RestClient().UpdateMember(g.ID, userID, updateMember) +} + +// KickMember kicks an existing member from the Guild +func (g *Guild) KickMember(userID Snowflake, reason *string) error { + return g.Disgo.RestClient().KickMember(g.ID, userID, reason) } // IconURL returns the Icon of a Guild @@ -271,3 +301,40 @@ func (g *Guild) SetCommandsPermissions(commandPermissions ...SetGuildCommandPerm func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, error) { return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } + +type CreateGuild struct { + Name string `json:"name"` + Region string `json:"region,omitempty"` + Icon string `json:"icon,omitempty"` + VerificationLevel VerificationLevel `json:"verification_level,omitempty"` + DefaultMessageNotificationLevel MessageNotifications `json:"default_message_notification_level"` + ExplicitContentFilterLevel ExplicitContentFilterLevel `json:"explicit_content_filter_level"` + Roles []CreateRole `json:"roles,omitempty"` + Channels []interface{} `json:"channels,omitempty"` + AFKChannelID Snowflake `json:"afk_channel_id,omitempty"` + AFKTimeout int `json:"afk_timeout,omitempty"` + SystemChannelID Snowflake `json:"system_channel_id,omitempty"` + SystemChannelFlags SystemChannelFlag `json:"system_channel_flags,omitempty"` +} + +type UpdateGuild struct { + Name string `json:"name"` + Region *string `json:"region"` + VerificationLevel *VerificationLevel `json:"verification_level"` + DefaultMessageNotificationLevel *MessageNotifications `json:"default_message_notification_level"` + ExplicitContentFilterLevel *ExplicitContentFilterLevel `json:"explicit_content_filter_level"` + AFKChannelID *Snowflake `json:"afk_channel_id"` + AFKTimeout int `json:"afk_timeout"` + Icon *string `json:"icon"` + OwnerID Snowflake `json:"owner_id"` + Splash interface{} `json:"splash"` + DiscoverySplash interface{} `json:"discovery_splash"` + Banner interface{} `json:"banner"` + SystemChannelID *Snowflake `json:"system_channel_id"` + SystemChannelFlags *SystemChannelFlag `json:"system_channel_flags"` + RulesChannelID *Snowflake `json:"rules_channel_id"` + PublicUpdatesChannelID *Snowflake `json:"public_updates_channel_id"` + PreferredLocale *string `json:"preferred_locale"` + Features []GuildFeature `json:"features"` + Description *string `json:"description"` +} diff --git a/api/member.go b/api/member.go index 1e78c20b..ff37d415 100644 --- a/api/member.go +++ b/api/member.go @@ -55,9 +55,14 @@ func (m *Member) IsOwner() bool { return m.Guild().OwnerID == m.User.ID } -// Update updates the member -func (m *Member) Update(updateGuildMemberData UpdateGuildMemberData) (*Member, error) { - return m.Disgo.RestClient().UpdateMember(m.GuildID, m.User.ID, updateGuildMemberData) +// Update updates the Member +func (m *Member) Update(updateGuildMember UpdateMember) (*Member, error) { + return m.Disgo.RestClient().UpdateMember(m.GuildID, m.User.ID, updateGuildMember) +} + +// Kick kicks the Member from the Guild +func (m *Member) Kick(reason *string) error { + return m.Disgo.RestClient().KickMember(m.GuildID, m.User.ID, reason) } // Move moves/kicks the member to/from a voice channel @@ -75,8 +80,8 @@ func (m *Member) RemoveRole(roleID Snowflake) error { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } -// AddGuildMemberData is used to add a member via the oauth2 access token to a guild -type AddGuildMemberData struct { +// AddMember is used to add a member via the oauth2 access token to a guild +type AddMember struct { AccessToken string `json:"access_token"` Nick *string `json:"nick,omitempty"` Roles []Snowflake `json:"roles,omitempty"` @@ -84,16 +89,17 @@ type AddGuildMemberData struct { Deaf *bool `json:"deaf,omitempty"` } -// UpdateGuildMemberData is used to modify -type UpdateGuildMemberData struct { +// UpdateMember is used to modify +type UpdateMember struct { + *MoveMember Nick *string `json:"nick,omitempty"` Roles []Snowflake `json:"roles,omitempty"` Mute *bool `json:"mute,omitempty"` Deaf *bool `json:"deaf,omitempty"` } -// MoveGuildMemberData is used to move a member -type MoveGuildMemberData struct { +// MoveMember is used to move a member +type MoveMember struct { ChannelID *Snowflake `json:"channel_id"` } diff --git a/api/restclient.go b/api/restclient.go index 2484b0eb..68e19303 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -37,16 +37,22 @@ 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, addMember AddMember) (*Member, error) KickMember(guildID Snowflake, userID Snowflake, reason *string) error - UpdateMember(guildID Snowflake, userID Snowflake, updateGuildMemberData UpdateGuildMemberData) (*Member, error) + UpdateMember(guildID Snowflake, userID Snowflake, updateMember UpdateMember) (*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 + GetGuild(guildID Snowflake, withCounts bool) (*Guild, error) + GetGuildPreview(guildID Snowflake) (*GuildPreview, error) + CreateGuild(guildID Snowflake, createGuild CreateGuild) (*Guild, error) + UpdateGuild(guildID Snowflake, updateGuild UpdateGuild) (*Guild, error) + DeleteGuild(guildID Snowflake) error + GetRoles(guildID Snowflake) ([]*Role, error) - CreateRole(guildID Snowflake, role UpdateRole) (*Role, error) - UpdateRole(guildID Snowflake, roleID Snowflake, role UpdateRole) (*Role, error) + CreateRole(guildID Snowflake, createRole CreateRole) (*Role, error) + UpdateRole(guildID Snowflake, roleID Snowflake, updateRole UpdateRole) (*Role, error) UpdateRolePositions(guildID Snowflake, roleUpdates ...UpdateRolePosition) ([]*Role, error) DeleteRole(guildID Snowflake, roleID Snowflake) error diff --git a/api/role.go b/api/role.go index 79cad9af..0f591786 100644 --- a/api/role.go +++ b/api/role.go @@ -52,13 +52,22 @@ type RoleTag struct { PremiumSubscriber bool `json:"premium_subscriber"` } +// CreateRole is the payload to create a Role +type CreateRole struct { + Name string `json:"name,omitempty"` + Permissions Permissions `json:"permissions,omitempty"` + Color int `json:"color,omitempty"` + Hoist bool `json:"hoist,omitempty"` + Mentionable bool `json:"mentionable,omitempty"` +} + // UpdateRole is the payload to update a Role type UpdateRole struct { - Name *string `json:"name,omitempty"` - Permissions *Permissions `json:"permissions,omitempty"` - Color *int `json:"color,omitempty"` - Hoist *bool `json:"hoist,omitempty"` - Mentionable *bool `json:"mentionable,omitempty"` + Name *string `json:"name"` + Permissions *Permissions `json:"permissions"` + Color *int `json:"color"` + Hoist *bool `json:"hoist"` + Mentionable *bool `json:"mentionable"` } // UpdateRolePosition is the payload to update a Role(s) position diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 901972fc..3cc6be71 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -24,6 +24,30 @@ type RestClientImpl struct { disgo api.Disgo } +func (r *RestClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (*api.Guild, error) { + panic("implement me") +} + +func (r *RestClientImpl) GetGuildPreview(guildID api.Snowflake) (*api.GuildPreview, error) { + panic("implement me") +} + +func (r *RestClientImpl) CreateGuild(guildID api.Snowflake, createGuild api.CreateGuild) (*api.Guild, error) { + panic("implement me") +} + +func (r *RestClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (*api.Guild, error) { + panic("implement me") +} + +func (r *RestClientImpl) DeleteGuild(guildID api.Snowflake) error { + panic("implement me") +} + +func (r *RestClientImpl) CreateRole(guildID api.Snowflake, createRole api.CreateRole) (*api.Role, error) { + panic("implement me") +} + // Disgo returns the api.Disgo instance func (r *RestClientImpl) Disgo() api.Disgo { return r.disgo @@ -214,12 +238,12 @@ 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, addMember api.AddMember) (member *api.Member, err error) { compiledRoute, err := restclient.AddMember.Compile(nil, guildID, userID) if err != nil { return nil, err } - err = r.Do(compiledRoute, addGuildMemberData, &member) + err = r.Do(compiledRoute, addMember, &member) if err == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } @@ -245,12 +269,12 @@ func (r *RestClientImpl) KickMember(guildID api.Snowflake, userID api.Snowflake, } // UpdateMember updates a api.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, updateMember api.UpdateMember) (member *api.Member, err error) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { return nil, err } - err = r.Do(compiledRoute, updateGuildMemberData, &member) + err = r.Do(compiledRoute, updateMember, &member) if err == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } @@ -263,7 +287,7 @@ func (r *RestClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, if err != nil { return nil, err } - err = r.Do(compiledRoute, api.MoveGuildMemberData{ChannelID: channelID}, &member) + err = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) if err == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } From 6f0415e65eb5a51b1fd60e618a4389ee0c3b2ffc Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 15 Jun 2021 15:33:25 +0200 Subject: [PATCH 40/64] new rest routes & cleanup --- api/channels.go | 28 +- api/command.go | 4 +- api/disgo.go | 74 +-- api/entity_builder.go | 2 +- api/event_manager.go | 41 ++ api/gateway.go | 31 +- api/guild.go | 61 ++- api/interaction.go | 26 +- api/member.go | 28 +- api/message.go | 22 +- api/restclient.go | 132 ++--- api/role.go | 8 +- api/self_user.go | 21 +- api/user.go | 8 +- example/examplebot.go | 4 +- go.mod | 4 + internal/audio_controller_impl.go | 16 +- internal/disgo_builder_impl.go | 3 +- internal/disgo_impl.go | 51 +- internal/entity_builder_impl.go | 41 +- internal/gateway_impl.go | 91 ++-- internal/handlers/guild_create_handler.go | 39 +- internal/handlers/guild_delete_handler.go | 8 +- internal/handlers/guild_update_handler.go | 8 +- internal/restclient_impl.go | 622 +++++++++++++--------- internal/util.go | 1 - 26 files changed, 805 insertions(+), 569 deletions(-) create mode 100644 api/event_manager.go diff --git a/api/channels.go b/api/channels.go index 29e473ce..53048c89 100644 --- a/api/channels.go +++ b/api/channels.go @@ -1,6 +1,10 @@ package api -import "errors" +import ( + "errors" + + "github.com/DisgoOrg/restclient" +) // ChannelType for interacting with discord's channels type ChannelType int @@ -45,30 +49,29 @@ type MessageChannel struct { } // SendMessage sends a Message to a TextChannel -func (c MessageChannel) SendMessage(message MessageCreate) (*Message, error) { - // Todo: attachments - return c.Disgo.RestClient().SendMessage(c.ID, message) +func (c MessageChannel) SendMessage(message MessageCreate) (*Message, restclient.RestError) { + return c.Disgo.RestClient().CreateMessage(c.ID, message) } // EditMessage edits a Message in this TextChannel -func (c MessageChannel) EditMessage(messageID Snowflake, message MessageUpdate) (*Message, error) { - return c.Disgo.RestClient().EditMessage(c.ID, messageID, message) +func (c MessageChannel) EditMessage(messageID Snowflake, message MessageUpdate) (*Message, restclient.RestError) { + return c.Disgo.RestClient().UpdateMessage(c.ID, messageID, message) } // DeleteMessage allows you to edit an existing Message sent by you -func (c MessageChannel) DeleteMessage(messageID Snowflake) error { +func (c MessageChannel) DeleteMessage(messageID Snowflake) restclient.RestError { return c.Disgo.RestClient().DeleteMessage(c.ID, messageID) } // BulkDeleteMessages allows you bulk delete Message(s) -func (c MessageChannel) BulkDeleteMessages(messageIDs ...Snowflake) error { +func (c MessageChannel) BulkDeleteMessages(messageIDs ...Snowflake) restclient.RestError { return c.Disgo.RestClient().BulkDeleteMessages(c.ID, messageIDs...) } // CrosspostMessage crossposts an existing Message -func (c MessageChannel) CrosspostMessage(messageID Snowflake) (*Message, error) { +func (c MessageChannel) CrosspostMessage(messageID Snowflake) (*Message, restclient.RestError) { if c.Type != ChannelTypeNews { - return nil, errors.New("channel type is not NEWS") + return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) } return c.Disgo.RestClient().CrosspostMessage(c.ID, messageID) } @@ -78,6 +81,11 @@ type DMChannel struct { MessageChannel } +// CreateDMChannel is the payload used to create a DMChannel +type CreateDMChannel struct { + RecipientID Snowflake `json:"recipient_id"` +} + // GuildChannel is a generic type for all server channels type GuildChannel struct { Channel diff --git a/api/command.go b/api/command.go index 4c013c0b..4ae3b0ae 100644 --- a/api/command.go +++ b/api/command.go @@ -68,10 +68,10 @@ func (c *Command) Update(command CommandUpdate) error { var rC *Command var err error if c.GuildID == nil { - rC, err = c.Disgo.RestClient().EditGlobalCommand(c.Disgo.ApplicationID(), c.ID, command) + rC, err = c.Disgo.RestClient().UpdateGlobalCommand(c.Disgo.ApplicationID(), c.ID, command) } else { - rC, err = c.Disgo.RestClient().EditGuildCommand(c.Disgo.ApplicationID(), *c.GuildID, c.ID, command) + rC, err = c.Disgo.RestClient().UpdateGuildCommand(c.Disgo.ApplicationID(), *c.GuildID, c.ID, command) } if err != nil { return err diff --git a/api/disgo.go b/api/disgo.go index 6967d900..70c15e78 100644 --- a/api/disgo.go +++ b/api/disgo.go @@ -1,12 +1,12 @@ package api import ( - "encoding/json" "runtime" "strings" "time" "github.com/DisgoOrg/log" + "github.com/DisgoOrg/restclient" ) // Disgo is the main discord interface @@ -23,8 +23,8 @@ type Disgo interface { GatewayIntents() GatewayIntents RawGatewayEventsEnabled() bool ApplicationID() Snowflake + ClientID() Snowflake SelfUser() *SelfUser - SelfUserID() Snowflake EntityBuilder() EntityBuilder EventManager() EventManager VoiceDispatchInterceptor() VoiceDispatchInterceptor @@ -34,62 +34,24 @@ type Disgo interface { LargeThreshold() int HasGateway() bool - GetCommand(commandID Snowflake) (*Command, error) - GetCommands() ([]*Command, error) - CreateCommand(command CommandCreate) (*Command, error) - EditCommand(commandID Snowflake, command CommandUpdate) (*Command, error) - DeleteCommand(commandID Snowflake) error - SetCommands(commands ...CommandCreate) ([]*Command, error) + GetCommand(commandID Snowflake) (*Command, restclient.RestError) + GetCommands() ([]*Command, restclient.RestError) + CreateCommand(command CommandCreate) (*Command, restclient.RestError) + EditCommand(commandID Snowflake, command CommandUpdate) (*Command, restclient.RestError) + DeleteCommand(commandID Snowflake) restclient.RestError + SetCommands(commands ...CommandCreate) ([]*Command, restclient.RestError) - 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) - DeleteGuildCommand(guildID Snowflake, commandID Snowflake) error - SetGuildCommands(guildID Snowflake, commands ...CommandCreate) ([]*Command, error) + GetGuildCommand(guildID Snowflake, commandID Snowflake) (*Command, restclient.RestError) + GetGuildCommands(guildID Snowflake) ([]*Command, restclient.RestError) + CreateGuildCommand(guildID Snowflake, commandCreate CommandCreate) (*Command, restclient.RestError) + EditGuildCommand(guildID Snowflake, commandID Snowflake, commandUpdate CommandUpdate) (*Command, restclient.RestError) + DeleteGuildCommand(guildID Snowflake, commandID Snowflake) restclient.RestError + SetGuildCommands(guildID Snowflake, commandCreates ...CommandCreate) ([]*Command, restclient.RestError) - 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) -} - -// EventHandler provides info about the EventHandler -type EventHandler interface { - Event() GatewayEventType - New() interface{} -} - -// GatewayEventHandler is used to handle raw gateway events -type GatewayEventHandler interface { - EventHandler - HandleGatewayEvent(disgo Disgo, eventManager EventManager, sequenceNumber int, payload interface{}) -} - -// WebhookEventHandler is used to handle raw webhook events -type WebhookEventHandler interface { - EventHandler - HandleWebhookEvent(disgo Disgo, eventManager EventManager, replyChannel chan InteractionResponse, payload interface{}) -} - -// EventListener is used to create new EventListener to listen to events -type EventListener interface { - OnEvent(event interface{}) -} - -// Event the basic interface each event implement -type Event interface { - Disgo() Disgo - SequenceNumber() int -} - -// EventManager lets you listen for specific events triggered by raw gateway events -type EventManager interface { - Disgo() Disgo - Close() - AddEventListeners(eventListeners ...EventListener) - Handle(eventType GatewayEventType, replyChannel chan InteractionResponse, sequenceNumber int, payload json.RawMessage) - Dispatch(event Event) + GetGuildCommandsPermissions(guildID Snowflake) ([]*GuildCommandPermissions, restclient.RestError) + GetGuildCommandPermissions(guildID Snowflake, commandID Snowflake) (*GuildCommandPermissions, restclient.RestError) + SetGuildCommandsPermissions(guildID Snowflake, commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, restclient.RestError) + SetGuildCommandPermissions(guildID Snowflake, commandID Snowflake, permissions SetGuildCommandPermissions) (*GuildCommandPermissions, restclient.RestError) } // GetOS returns the simplified version of the operating system for sending to Discord in the IdentifyCommandDataProperties.OS payload diff --git a/api/entity_builder.go b/api/entity_builder.go index b328876f..fa51a164 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -24,7 +24,7 @@ type EntityBuilder interface { CreateMessage(message *FullMessage, updateCache CacheStrategy) *Message - CreateGuild(guild *Guild, updateCache CacheStrategy) *Guild + CreateGuild(fullGuild *FullGuild, updateCache CacheStrategy) *Guild CreateMember(guildID Snowflake, member *Member, updateCache CacheStrategy) *Member CreateGuildCommand(guildID Snowflake, command *Command, updateCache CacheStrategy) *Command CreateGuildCommandPermissions(guildCommandPermissions *GuildCommandPermissions, updateCache CacheStrategy) *GuildCommandPermissions diff --git a/api/event_manager.go b/api/event_manager.go new file mode 100644 index 00000000..d22e28a8 --- /dev/null +++ b/api/event_manager.go @@ -0,0 +1,41 @@ +package api + +import "encoding/json" + +// EventManager lets you listen for specific events triggered by raw gateway events +type EventManager interface { + Disgo() Disgo + Close() + AddEventListeners(eventListeners ...EventListener) + Handle(eventType GatewayEventType, replyChannel chan InteractionResponse, sequenceNumber int, payload json.RawMessage) + Dispatch(event Event) +} + +// EventListener is used to create new EventListener to listen to events +type EventListener interface { + OnEvent(event interface{}) +} + +// Event the basic interface each event implement +type Event interface { + Disgo() Disgo + SequenceNumber() int +} + +// EventHandler provides info about the EventHandler +type EventHandler interface { + Event() GatewayEventType + New() interface{} +} + +// GatewayEventHandler is used to handle raw gateway events +type GatewayEventHandler interface { + EventHandler + HandleGatewayEvent(disgo Disgo, eventManager EventManager, sequenceNumber int, payload interface{}) +} + +// WebhookEventHandler is used to handle raw webhook events +type WebhookEventHandler interface { + EventHandler + HandleWebhookEvent(disgo Disgo, eventManager EventManager, replyChannel chan InteractionResponse, payload interface{}) +} diff --git a/api/gateway.go b/api/gateway.go index e617ca80..e91ae78b 100644 --- a/api/gateway.go +++ b/api/gateway.go @@ -9,18 +9,28 @@ import ( // GatewayStatus is the state that the client is currently in type GatewayStatus int +// IsConnected returns weather you can send payloads to the Gateway +func (s GatewayStatus) IsConnected() bool { + switch s { + case GatewayStatusWaitingForGuilds, GatewayStatusReady: + return true + default: + return false + } +} + // Indicates how far along the client is to connecting const ( - Ready GatewayStatus = iota - Unconnected - Connecting - Reconnecting - WaitingForHello - WaitingForReady - Disconnected - WaitingForGuilds - Identifying - Resuming + GatewayStatusUnconnected GatewayStatus = iota + GatewayStatusConnecting + GatewayStatusReconnecting + GatewayStatusIdentifying + GatewayStatusWaitingForHello + GatewayStatusWaitingForReady + GatewayStatusWaitingForGuilds + GatewayStatusReady + GatewayStatusDisconnected + GatewayStatusResuming ) // Gateway is what is used to connect to discord @@ -28,6 +38,7 @@ type Gateway interface { Disgo() Disgo Open() error Status() GatewayStatus + Send(command GatewayCommand) error Close() Conn() *websocket.Conn Latency() time.Duration diff --git a/api/guild.go b/api/guild.go index e7263800..311c5209 100644 --- a/api/guild.go +++ b/api/guild.go @@ -105,7 +105,6 @@ type GuildWelcomeChannel struct { // GuildPreview is used for previewing public Guild(s) before joining them type GuildPreview struct { - Disgo Disgo ID Snowflake `json:"id"` Name string `json:"name"` Icon *string `json:"icon"` @@ -195,43 +194,58 @@ func (g *Guild) Disconnect() error { } // Update updates the current Guild -func (g *Guild) Update(updateGuild UpdateGuild) (*Guild, error) { +func (g *Guild) Update(updateGuild UpdateGuild) (*Guild, restclient.RestError) { return g.Disgo.RestClient().UpdateGuild(g.ID, updateGuild) } // Delete deletes the current Guild -func (g *Guild) Delete() error { +func (g *Guild) Delete() restclient.RestError { return g.Disgo.RestClient().DeleteGuild(g.ID) } // CreateRole allows you to create a new Role -func (g *Guild) CreateRole(createRole CreateRole) (*Role, error) { +func (g *Guild) CreateRole(createRole CreateRole) (*Role, restclient.RestError) { return g.Disgo.RestClient().CreateRole(g.ID, createRole) } // UpdateRole allows you to update a Role -func (g *Guild) UpdateRole(roleID Snowflake, role UpdateRole) (*Role, error) { +func (g *Guild) UpdateRole(roleID Snowflake, role UpdateRole) (*Role, restclient.RestError) { return g.Disgo.RestClient().UpdateRole(g.ID, roleID, role) } // DeleteRole allows you to delete a Role -func (g *Guild) DeleteRole(roleID Snowflake) error { +func (g *Guild) DeleteRole(roleID Snowflake) restclient.RestError { return g.Disgo.RestClient().DeleteRole(g.ID, roleID) } +// GetSelfMember returns the SelfMember for this Guild +func (g *Guild) GetSelfMember() *SelfMember { + return &SelfMember{Member: g.GetMember(g.Disgo.ClientID())} +} + +// Leave leaves the Guild +func (g *Guild) Leave() restclient.RestError { + return g.Disgo.RestClient().LeaveGuild(g.ID) +} + +// GetMember returns the Member for the current logged in User for this Guild +func (g *Guild) GetMember(userID Snowflake) *Member { + return g.Disgo.Cache().Member(g.ID, userID) +} + // AddMember adds a member to the Guild with the oauth2 access token -func (g *Guild) AddMember(userID Snowflake, addMember AddMember) (*Member, error) { +func (g *Guild) AddMember(userID Snowflake, addMember AddMember) (*Member, restclient.RestError) { return g.Disgo.RestClient().AddMember(g.ID, userID, addMember) } // UpdateMember updates an existing member of the Guild -func (g *Guild) UpdateMember(userID Snowflake, updateMember UpdateMember) (*Member, error) { +func (g *Guild) UpdateMember(userID Snowflake, updateMember UpdateMember) (*Member, restclient.RestError) { return g.Disgo.RestClient().UpdateMember(g.ID, userID, updateMember) } // KickMember kicks an existing member from the Guild -func (g *Guild) KickMember(userID Snowflake, reason *string) error { - return g.Disgo.RestClient().KickMember(g.ID, userID, reason) +func (g *Guild) KickMember(userID Snowflake, reason string) restclient.RestError { + return g.Disgo.RestClient().RemoveMember(g.ID, userID, reason) } // IconURL returns the Icon of a Guild @@ -253,42 +267,42 @@ func (g *Guild) IconURL(size int) *string { } // GetCommand fetches a specific Guild Command -func (g *Guild) GetCommand(commandID Snowflake) (*Command, error) { +func (g *Guild) GetCommand(commandID Snowflake) (*Command, restclient.RestError) { return g.Disgo.GetGuildCommand(g.ID, commandID) } // GetCommands fetches all Guild Command(s) -func (g *Guild) GetCommands() ([]*Command, error) { +func (g *Guild) GetCommands() ([]*Command, restclient.RestError) { return g.Disgo.GetGuildCommands(g.ID) } // CreateCommand creates a new Command for this Guild -func (g *Guild) CreateCommand(command CommandCreate) (*Command, error) { +func (g *Guild) CreateCommand(command CommandCreate) (*Command, restclient.RestError) { 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, restclient.RestError) { return g.Disgo.EditGuildCommand(g.ID, commandID, command) } // DeleteCommand creates a new Command for this Guild -func (g *Guild) DeleteCommand(commandID Snowflake) error { +func (g *Guild) DeleteCommand(commandID Snowflake) restclient.RestError { return g.Disgo.DeleteGuildCommand(g.ID, commandID) } // SetCommands overrides all Command(s) for this Guild -func (g *Guild) SetCommands(commands ...CommandCreate) ([]*Command, error) { +func (g *Guild) SetCommands(commands ...CommandCreate) ([]*Command, restclient.RestError) { return g.Disgo.SetGuildCommands(g.ID, commands...) } // GetCommandsPermissions returns the GuildCommandPermissions for a all Command(s) in a Guild -func (g *Guild) GetCommandsPermissions() ([]*GuildCommandPermissions, error) { +func (g *Guild) GetCommandsPermissions() ([]*GuildCommandPermissions, restclient.RestError) { return g.Disgo.GetGuildCommandsPermissions(g.ID) } // GetCommandPermissions returns the GuildCommandPermissions for a specific Command in a Guild -func (g *Guild) GetCommandPermissions(commandID Snowflake) (*GuildCommandPermissions, error) { +func (g *Guild) GetCommandPermissions(commandID Snowflake) (*GuildCommandPermissions, restclient.RestError) { return g.Disgo.GetGuildCommandPermissions(g.ID, commandID) } @@ -302,6 +316,17 @@ func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildC return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } +// PartialGuild is returned on the restclient.GetGuilds route +type PartialGuild struct { + ID Snowflake `json:"id"` + Name string `json:"name"` + Icon string `json:"icon"` + Owner bool `json:"owner"` + Permissions Permissions `json:"permissions"` + Features []GuildFeature `json:"features"` +} + +// CreateGuild is the payload used to create a Guild type CreateGuild struct { Name string `json:"name"` Region string `json:"region,omitempty"` diff --git a/api/interaction.go b/api/interaction.go index 5cb360b0..037eda67 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -59,11 +59,11 @@ func (r InteractionResponse) ToBody() (interface{}, error) { } switch v := r.Data.(type) { case MessageCreate: - if len(v.Files) > 0 { + if len(v.Files) > 0 { return restclient.PayloadWithFiles(r, v.Files...) } case MessageUpdate: - if len(v.Files) > 0 { + if len(v.Files) > 0 { return restclient.PayloadWithFiles(r, v.Files...) } } @@ -71,13 +71,13 @@ func (r InteractionResponse) ToBody() (interface{}, error) { } // Respond responds to the api.Interaction with the provided api.InteractionResponse -func (i *Interaction) Respond(responseType InteractionResponseType, data interface{}) error { +func (i *Interaction) Respond(responseType InteractionResponseType, data interface{}) restclient.RestError { response := InteractionResponse{ Type: responseType, Data: data, } if i.Replied { - return errors.New("you already replied to this interaction") + return restclient.NewRestError(nil, errors.New("you already replied to this interaction")) } i.Replied = true @@ -90,7 +90,7 @@ 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 { +func (i *Interaction) DeferReply(ephemeral bool) restclient.RestError { var messageCreate interface{} if ephemeral { messageCreate = MessageCreate{Flags: MessageFlagEphemeral} @@ -99,32 +99,32 @@ func (i *Interaction) DeferReply(ephemeral bool) error { } // Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.MessageCreate -func (i *Interaction) Reply(messageCreate MessageCreate) error { +func (i *Interaction) Reply(messageCreate MessageCreate) restclient.RestError { return i.Respond(InteractionResponseTypeChannelMessageWithSource, messageCreate) } // EditOriginal edits the original api.InteractionResponse -func (i *Interaction) EditOriginal(messageUpdate MessageUpdate) (*Message, error) { - return i.Disgo.RestClient().EditInteractionResponse(i.Disgo.ApplicationID(), i.Token, messageUpdate) +func (i *Interaction) EditOriginal(messageUpdate MessageUpdate) (*Message, restclient.RestError) { + return i.Disgo.RestClient().UpdateInteractionResponse(i.Disgo.ApplicationID(), i.Token, messageUpdate) } // DeleteOriginal deletes the original api.InteractionResponse -func (i *Interaction) DeleteOriginal() error { +func (i *Interaction) DeleteOriginal() restclient.RestError { return i.Disgo.RestClient().DeleteInteractionResponse(i.Disgo.ApplicationID(), i.Token) } // SendFollowup used to send a api.MessageCreate to an api.Interaction -func (i *Interaction) SendFollowup(messageCreate MessageCreate) (*Message, error) { +func (i *Interaction) SendFollowup(messageCreate MessageCreate) (*Message, restclient.RestError) { return i.Disgo.RestClient().SendFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageCreate) } // 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) +func (i *Interaction) EditFollowup(messageID Snowflake, messageUpdate MessageUpdate) (*Message, restclient.RestError) { + return i.Disgo.RestClient().UpdateFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID, messageUpdate) } // DeleteFollowup used to delete a api.Message from an api.Interaction -func (i *Interaction) DeleteFollowup(messageID Snowflake) error { +func (i *Interaction) DeleteFollowup(messageID Snowflake) restclient.RestError { return i.Disgo.RestClient().DeleteFollowupMessage(i.Disgo.ApplicationID(), i.Token, messageID) } diff --git a/api/member.go b/api/member.go index ff37d415..a24006df 100644 --- a/api/member.go +++ b/api/member.go @@ -1,6 +1,10 @@ package api -import "time" +import ( + "time" + + "github.com/DisgoOrg/restclient" +) // Member is a discord GuildMember type Member struct { @@ -56,37 +60,37 @@ func (m *Member) IsOwner() bool { } // Update updates the Member -func (m *Member) Update(updateGuildMember UpdateMember) (*Member, error) { +func (m *Member) Update(updateGuildMember UpdateMember) (*Member, restclient.RestError) { return m.Disgo.RestClient().UpdateMember(m.GuildID, m.User.ID, updateGuildMember) } // Kick kicks the Member from the Guild -func (m *Member) Kick(reason *string) error { - return m.Disgo.RestClient().KickMember(m.GuildID, m.User.ID, reason) +func (m *Member) Kick(reason string) restclient.RestError { + return m.Disgo.RestClient().RemoveMember(m.GuildID, m.User.ID, reason) } // Move moves/kicks the member to/from a voice channel -func (m *Member) Move(channelID *Snowflake) (*Member, error) { +func (m *Member) Move(channelID *Snowflake) (*Member, restclient.RestError) { return m.Disgo.RestClient().MoveMember(m.GuildID, m.User.ID, channelID) } // AddRole adds a specific role the member -func (m *Member) AddRole(roleID Snowflake) error { +func (m *Member) AddRole(roleID Snowflake) restclient.RestError { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } // RemoveRole removes a specific role the member -func (m *Member) RemoveRole(roleID Snowflake) error { +func (m *Member) RemoveRole(roleID Snowflake) restclient.RestError { return m.Disgo.RestClient().AddMemberRole(m.GuildID, m.User.ID, roleID) } // AddMember is used to add a member via the oauth2 access token to a guild type AddMember struct { AccessToken string `json:"access_token"` - Nick *string `json:"nick,omitempty"` + Nick string `json:"nick,omitempty"` Roles []Snowflake `json:"roles,omitempty"` - Mute *bool `json:"mute,omitempty"` - Deaf *bool `json:"deaf,omitempty"` + Mute bool `json:"mute,omitempty"` + Deaf bool `json:"deaf,omitempty"` } // UpdateMember is used to modify @@ -100,10 +104,10 @@ type UpdateMember struct { // MoveMember is used to move a member type MoveMember struct { - ChannelID *Snowflake `json:"channel_id"` + ChannelID *Snowflake `json:"channel_id,omitempty"` } // UpdateSelfNick is used to update your own nick type UpdateSelfNick struct { - Nick *string `json:"nick"` + Nick string `json:"nick"` } diff --git a/api/message.go b/api/message.go index e1b6bc14..498cec60 100644 --- a/api/message.go +++ b/api/message.go @@ -3,6 +3,8 @@ package api import ( "errors" "time" + + "github.com/DisgoOrg/restclient" ) // The MessageType indicates the Message type @@ -226,40 +228,40 @@ func (m *Message) Channel() *MessageChannel { } // AddReactionByEmote allows you to add an Emoji to a message_events via reaction -func (m *Message) AddReactionByEmote(emote Emoji) error { +func (m *Message) AddReactionByEmote(emote Emoji) restclient.RestError { return m.AddReaction(emote.Reaction()) } // AddReaction allows you to add a reaction to a message_events from a string, for example a custom emoji ID, or a native emoji -func (m *Message) AddReaction(emoji string) error { +func (m *Message) AddReaction(emoji string) restclient.RestError { return m.Disgo.RestClient().AddReaction(m.ChannelID, m.ID, emoji) } -// Edit allows you to edit an existing Message sent by you -func (m *Message) Edit(message MessageUpdate) (*Message, error) { - return m.Disgo.RestClient().EditMessage(m.ChannelID, m.ID, message) +// Update allows you to edit an existing Message sent by you +func (m *Message) Update(message MessageUpdate) (*Message, restclient.RestError) { + return m.Disgo.RestClient().UpdateMessage(m.ChannelID, m.ID, message) } // Delete allows you to edit an existing Message sent by you -func (m *Message) Delete() error { +func (m *Message) Delete() restclient.RestError { return m.Disgo.RestClient().DeleteMessage(m.ChannelID, m.ID) } // Crosspost crossposts an existing message -func (m *Message) Crosspost() (*Message, error) { +func (m *Message) Crosspost() (*Message, restclient.RestError) { channel := m.Channel() if channel != nil && channel.Type != ChannelTypeNews { - return nil, errors.New("channel type is not NEWS") + return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) } return m.Disgo.RestClient().CrosspostMessage(m.ChannelID, m.ID) } // Reply allows you to reply to an existing Message -func (m *Message) Reply(message MessageCreate) (*Message, error) { +func (m *Message) Reply(message MessageCreate) (*Message, restclient.RestError) { message.MessageReference = &MessageReference{ MessageID: &m.ID, } - return m.Disgo.RestClient().SendMessage(m.ChannelID, message) + return m.Disgo.RestClient().CreateMessage(m.ChannelID, message) } // MessageReaction contains information about the reactions of a message_events diff --git a/api/restclient.go b/api/restclient.go index 68e19303..8a21efaa 100644 --- a/api/restclient.go +++ b/api/restclient.go @@ -18,72 +18,78 @@ type ErrorResponse struct { Message string } -// RestClient is a manager for all of disgo's HTTP requests +// RestClient is a manager for all of Disgo's HTTP requests type RestClient interface { restclient.RestClient Close() Disgo() Disgo - SendMessage(channelID Snowflake, message MessageCreate) (*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) - - OpenDMChannel(userID Snowflake) (*DMChannel, error) - - UpdateSelfNick(guildID Snowflake, nick *string) (*string, error) - - GetUser(userID Snowflake) (*User, error) - GetMember(guildID Snowflake, userID Snowflake) (*Member, error) - GetMembers(guildID Snowflake) ([]*Member, error) - AddMember(guildID Snowflake, userID Snowflake, addMember AddMember) (*Member, error) - KickMember(guildID Snowflake, userID Snowflake, reason *string) error - UpdateMember(guildID Snowflake, userID Snowflake, updateMember UpdateMember) (*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 - - GetGuild(guildID Snowflake, withCounts bool) (*Guild, error) - GetGuildPreview(guildID Snowflake) (*GuildPreview, error) - CreateGuild(guildID Snowflake, createGuild CreateGuild) (*Guild, error) - UpdateGuild(guildID Snowflake, updateGuild UpdateGuild) (*Guild, error) - DeleteGuild(guildID Snowflake) error - - GetRoles(guildID Snowflake) ([]*Role, error) - CreateRole(guildID Snowflake, createRole CreateRole) (*Role, error) - UpdateRole(guildID Snowflake, roleID Snowflake, updateRole UpdateRole) (*Role, error) - UpdateRolePositions(guildID Snowflake, roleUpdates ...UpdateRolePosition) ([]*Role, error) - DeleteRole(guildID Snowflake, roleID Snowflake) error - - AddReaction(channelID Snowflake, messageID Snowflake, emoji string) error - RemoveOwnReaction(channelID Snowflake, messageID Snowflake, emoji string) error - RemoveUserReaction(channelID Snowflake, messageID Snowflake, emoji string, userID Snowflake) error - - 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) - 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) - 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) - - SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse InteractionResponse) error - EditInteractionResponse(applicationID Snowflake, interactionToken string, messageUpdate MessageUpdate) (*Message, error) - DeleteInteractionResponse(applicationID Snowflake, interactionToken string) 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 + GetUser(userID Snowflake) (*User, restclient.RestError) + GetSelfUser() (*SelfUser, restclient.RestError) + UpdateSelfUser(updateSelfUser UpdateSelfUser) (*SelfUser, restclient.RestError) + GetGuilds(before int, after int, limit int) ([]*PartialGuild, restclient.RestError) + LeaveGuild(guildID Snowflake) restclient.RestError + GetDMChannels() ([]*DMChannel, restclient.RestError) + CreateDMChannel(userID Snowflake) (*DMChannel, restclient.RestError) + + GetMessage(channelID Snowflake, messageID Snowflake) (*Message, restclient.RestError) + CreateMessage(channelID Snowflake, message MessageCreate) (*Message, restclient.RestError) + UpdateMessage(channelID Snowflake, messageID Snowflake, messageUpdate MessageUpdate) (*Message, restclient.RestError) + DeleteMessage(channelID Snowflake, messageID Snowflake) restclient.RestError + BulkDeleteMessages(channelID Snowflake, messageIDs ...Snowflake) restclient.RestError + CrosspostMessage(channelID Snowflake, messageID Snowflake) (*Message, restclient.RestError) + + GetGuild(guildID Snowflake, withCounts bool) (*Guild, restclient.RestError) + GetGuildPreview(guildID Snowflake) (*GuildPreview, restclient.RestError) + CreateGuild(createGuild CreateGuild) (*Guild, restclient.RestError) + UpdateGuild(guildID Snowflake, updateGuild UpdateGuild) (*Guild, restclient.RestError) + DeleteGuild(guildID Snowflake) restclient.RestError + + GetMember(guildID Snowflake, userID Snowflake) (*Member, restclient.RestError) + GetMembers(guildID Snowflake) ([]*Member, restclient.RestError) + SearchMembers(guildID Snowflake, query string, limit int) ([]*Member, restclient.RestError) + AddMember(guildID Snowflake, userID Snowflake, addMember AddMember) (*Member, restclient.RestError) + RemoveMember(guildID Snowflake, userID Snowflake, reason string) restclient.RestError + UpdateMember(guildID Snowflake, userID Snowflake, updateMember UpdateMember) (*Member, restclient.RestError) + UpdateSelfNick(guildID Snowflake, nick string) (*string, restclient.RestError) + MoveMember(guildID Snowflake, userID Snowflake, channelID *Snowflake) (*Member, restclient.RestError) + AddMemberRole(guildID Snowflake, userID Snowflake, roleID Snowflake) restclient.RestError + RemoveMemberRole(guildID Snowflake, userID Snowflake, roleID Snowflake) restclient.RestError + + GetRoles(guildID Snowflake) ([]*Role, restclient.RestError) + CreateRole(guildID Snowflake, createRole CreateRole) (*Role, restclient.RestError) + UpdateRole(guildID Snowflake, roleID Snowflake, updateRole UpdateRole) (*Role, restclient.RestError) + UpdateRolePositions(guildID Snowflake, roleUpdates ...UpdateRolePosition) ([]*Role, restclient.RestError) + DeleteRole(guildID Snowflake, roleID Snowflake) restclient.RestError + + AddReaction(channelID Snowflake, messageID Snowflake, emoji string) restclient.RestError + RemoveOwnReaction(channelID Snowflake, messageID Snowflake, emoji string) restclient.RestError + RemoveUserReaction(channelID Snowflake, messageID Snowflake, emoji string, userID Snowflake) restclient.RestError + + GetGlobalCommands(applicationID Snowflake) ([]*Command, restclient.RestError) + GetGlobalCommand(applicationID Snowflake, commandID Snowflake) (*Command, restclient.RestError) + CreateGlobalCommand(applicationID Snowflake, command CommandCreate) (*Command, restclient.RestError) + SetGlobalCommands(applicationID Snowflake, commands ...CommandCreate) ([]*Command, restclient.RestError) + UpdateGlobalCommand(applicationID Snowflake, commandID Snowflake, command CommandUpdate) (*Command, restclient.RestError) + DeleteGlobalCommand(applicationID Snowflake, commandID Snowflake) restclient.RestError + + GetGuildCommands(applicationID Snowflake, guildID Snowflake) ([]*Command, restclient.RestError) + GetGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake) (*Command, restclient.RestError) + CreateGuildCommand(applicationID Snowflake, guildID Snowflake, command CommandCreate) (*Command, restclient.RestError) + SetGuildCommands(applicationID Snowflake, guildID Snowflake, commands ...CommandCreate) ([]*Command, restclient.RestError) + UpdateGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake, command CommandUpdate) (*Command, restclient.RestError) + DeleteGuildCommand(applicationID Snowflake, guildID Snowflake, commandID Snowflake) restclient.RestError + + GetGuildCommandsPermissions(applicationID Snowflake, guildID Snowflake) ([]*GuildCommandPermissions, restclient.RestError) + GetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake) (*GuildCommandPermissions, restclient.RestError) + SetGuildCommandsPermissions(applicationID Snowflake, guildID Snowflake, commandPermissions ...SetGuildCommandPermissions) ([]*GuildCommandPermissions, restclient.RestError) + SetGuildCommandPermissions(applicationID Snowflake, guildID Snowflake, commandID Snowflake, commandPermissions SetGuildCommandPermissions) (*GuildCommandPermissions, restclient.RestError) + + SendInteractionResponse(interactionID Snowflake, interactionToken string, interactionResponse InteractionResponse) restclient.RestError + UpdateInteractionResponse(applicationID Snowflake, interactionToken string, messageUpdate MessageUpdate) (*Message, restclient.RestError) + DeleteInteractionResponse(applicationID Snowflake, interactionToken string) restclient.RestError + + SendFollowupMessage(applicationID Snowflake, interactionToken string, messageCreate MessageCreate) (*Message, restclient.RestError) + UpdateFollowupMessage(applicationID Snowflake, interactionToken string, messageID Snowflake, messageUpdate MessageUpdate) (*Message, restclient.RestError) + DeleteFollowupMessage(applicationID Snowflake, interactionToken string, followupMessageID Snowflake) restclient.RestError } diff --git a/api/role.go b/api/role.go index 0f591786..a62741e8 100644 --- a/api/role.go +++ b/api/role.go @@ -1,5 +1,7 @@ package api +import "github.com/DisgoOrg/restclient" + // Role is a Guild Role object type Role struct { Disgo Disgo @@ -31,17 +33,17 @@ func (r *Role) Guild() *Guild { } // Update updates the Role with specific values -func (r *Role) Update(roleUpdate UpdateRole) (*Role, error) { +func (r *Role) Update(roleUpdate UpdateRole) (*Role, restclient.RestError) { 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, restclient.RestError) { return r.Disgo.RestClient().UpdateRolePositions(r.GuildID, rolePositionUpdate) } // Delete deletes the Role -func (r *Role) Delete() error { +func (r *Role) Delete() restclient.RestError { return r.Disgo.RestClient().DeleteRole(r.GuildID, r.ID) } diff --git a/api/self_user.go b/api/self_user.go index 61d436c5..a39d5fe3 100644 --- a/api/self_user.go +++ b/api/self_user.go @@ -1,16 +1,31 @@ package api -import "errors" +import ( + "errors" + + "github.com/DisgoOrg/restclient" +) // ErrDMChannelToYourself occurs when opening a DMChannel to yourself -var ErrDMChannelToYourself = errors.New("can't open a dm channel to yourself") +var ErrDMChannelToYourself = restclient.NewRestError(nil, errors.New("can't open a dm channel to yourself")) // SelfUser represents the current logged in User type SelfUser struct { *User } +// Update updates the SelfUser with the given payload +func (u *SelfUser) Update(updateSelfUser UpdateSelfUser) (*SelfUser, restclient.RestError) { + return u.Disgo.RestClient().UpdateSelfUser(updateSelfUser) +} + // OpenDMChannel creates a DMChannel between the user and the Disgo client -func (u *SelfUser) OpenDMChannel() (*DMChannel, error) { +func (u *SelfUser) OpenDMChannel() (*DMChannel, restclient.RestError) { return nil, ErrDMChannelToYourself } + +// UpdateSelfUser is the payload used to update the SelfUser +type UpdateSelfUser struct { + Username string `json:"username"` + Avatar interface{} +} diff --git a/api/user.go b/api/user.go index 45e7b941..78c9bc9c 100644 --- a/api/user.go +++ b/api/user.go @@ -29,8 +29,8 @@ type User struct { // AvatarURL returns the Avatar URL of the User func (u *User) AvatarURL(size int) string { if u.Avatar == nil { - discrim, _ := strconv.Atoi(u.Discriminator) - route, err := restclient.DefaultUserAvatar.Compile(nil, restclient.PNG, size, discrim%5) + discriminator, _ := strconv.Atoi(u.Discriminator) + route, err := restclient.DefaultUserAvatar.Compile(nil, restclient.PNG, size, discriminator%5) if err != nil { return "" } @@ -62,6 +62,6 @@ func (u *User) String() string { } // OpenDMChannel creates a DMChannel between the user and the Disgo client -func (u *User) OpenDMChannel() (*DMChannel, error) { - return u.Disgo.RestClient().OpenDMChannel(u.ID) +func (u *User) OpenDMChannel() (*DMChannel, restclient.RestError) { + return u.Disgo.RestClient().CreateDMChannel(u.ID) } diff --git a/example/examplebot.go b/example/examplebot.go index ddaada0d..f59f79cc 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -334,11 +334,11 @@ func messageListener(event events.GuildMessageCreateEvent) { time.Sleep(time.Second * 2) embed := api.NewEmbedBuilder().SetDescription("edit").Build() - message, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbeds(embed, embed).Build()) + message, _ = message.Update(api.NewMessageUpdateBuilder().SetContent("edit").SetEmbeds(embed, embed).Build()) time.Sleep(time.Second * 2) - _, _ = message.Edit(api.NewMessageUpdateBuilder().SetContent("").SetEmbeds(api.NewEmbedBuilder().SetDescription("edit2").Build()).Build()) + _, _ = message.Update(api.NewMessageUpdateBuilder().SetContent("").SetEmbeds(api.NewEmbedBuilder().SetDescription("edit2").Build()).Build()) }() case "dm": diff --git a/go.mod b/go.mod index fbb451bd..42971df3 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +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.5 diff --git a/internal/audio_controller_impl.go b/internal/audio_controller_impl.go index 6b201ff5..ef1337df 100644 --- a/internal/audio_controller_impl.go +++ b/internal/audio_controller_impl.go @@ -2,7 +2,6 @@ package internal import ( "github.com/DisgoOrg/disgo/api" - "github.com/gorilla/websocket" ) func newAudioControllerImpl(disgo api.Disgo) api.AudioController { @@ -21,11 +20,11 @@ func (c *AudioControllerImpl) Disgo() api.Disgo { // Connect sends a api.GatewayCommand to connect to a api.VoiceChannel func (c *AudioControllerImpl) Connect(guildID api.Snowflake, channelID api.Snowflake) error { - conn, err := c.getConn() + gateway, err := c.getGateway() if err != nil { return err } - return conn.WriteJSON(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ + return gateway.Send(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ GuildID: guildID, ChannelID: &channelID, })) @@ -33,24 +32,23 @@ func (c *AudioControllerImpl) Connect(guildID api.Snowflake, channelID api.Snowf // Disconnect sends a api.GatewayCommand to disconnect from a api.VoiceChannel func (c *AudioControllerImpl) Disconnect(guildID api.Snowflake) error { - conn, err := c.getConn() + gateway, err := c.getGateway() if err != nil { return err } - return conn.WriteJSON(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ + return gateway.Send(api.NewGatewayCommand(api.OpVoiceStateUpdate, api.UpdateVoiceStateCommand{ GuildID: guildID, ChannelID: nil, })) } -func (c *AudioControllerImpl) getConn() (*websocket.Conn, error) { +func (c *AudioControllerImpl) getGateway() (api.Gateway, error) { gateway := c.Disgo().Gateway() if gateway == nil { return nil, api.ErrNoGateway } - conn := gateway.Conn() - if conn == nil { + if !gateway.Status().IsConnected() { return nil, api.ErrNoGatewayConn } - return conn, nil + return gateway, nil } diff --git a/internal/disgo_builder_impl.go b/internal/disgo_builder_impl.go index a608679c..e6273bc2 100644 --- a/internal/disgo_builder_impl.go +++ b/internal/disgo_builder_impl.go @@ -183,7 +183,8 @@ func (b *DisgoBuilderImpl) Build() (api.Disgo, error) { return nil, err } - disgo.selfUserID = *id + disgo.applicationID = *id + disgo.clientID = *id if b.gateway == nil { b.gateway = newGatewayImpl(disgo) diff --git a/internal/disgo_impl.go b/internal/disgo_impl.go index c65c69bb..35b958db 100644 --- a/internal/disgo_impl.go +++ b/internal/disgo_impl.go @@ -4,6 +4,7 @@ import ( "time" "github.com/DisgoOrg/log" + "github.com/DisgoOrg/restclient" "github.com/DisgoOrg/disgo/api" ) @@ -30,7 +31,8 @@ func New(token string, options api.Options) (api.Disgo, error) { return nil, err } - disgo.selfUserID = *id + disgo.applicationID = *id + disgo.clientID = *id disgo.restClient = newRestClientImpl(disgo, options.HTTPClient) @@ -63,7 +65,8 @@ type DisgoImpl struct { audioController api.AudioController webhookServer api.WebhookServer cache api.Cache - selfUserID api.Snowflake + applicationID api.Snowflake + clientID api.Snowflake selfUser *api.SelfUser largeThreshold int } @@ -171,7 +174,7 @@ func (d *DisgoImpl) RawGatewayEventsEnabled() bool { // ApplicationID returns the current application id func (d *DisgoImpl) ApplicationID() api.Snowflake { - return d.selfUserID + return d.applicationID } // SelfUser returns a api.SelfUser for the client, if available @@ -179,9 +182,9 @@ func (d *DisgoImpl) SelfUser() *api.SelfUser { return d.selfUser } -// SelfUserID returns the current user id -func (d *DisgoImpl) SelfUserID() api.Snowflake { - return d.selfUserID +// ClientID returns the current user id +func (d *DisgoImpl) ClientID() api.Snowflake { + return d.clientID } // HeartbeatLatency returns the heartbeat latency @@ -200,81 +203,81 @@ func (d *DisgoImpl) HasGateway() bool { } // GetCommand fetches a specific global api.Command -func (d *DisgoImpl) GetCommand(commandID api.Snowflake) (*api.Command, error) { +func (d *DisgoImpl) GetCommand(commandID api.Snowflake) (*api.Command, restclient.RestError) { return d.RestClient().GetGlobalCommand(d.ApplicationID(), commandID) } // GetCommands fetches all global api.Command(s) -func (d *DisgoImpl) GetCommands() ([]*api.Command, error) { +func (d *DisgoImpl) GetCommands() ([]*api.Command, restclient.RestError) { return d.RestClient().GetGlobalCommands(d.ApplicationID()) } // 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, restclient.RestError) { 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) { - return d.RestClient().EditGlobalCommand(d.ApplicationID(), commandID, command) +func (d *DisgoImpl) EditCommand(commandID api.Snowflake, command api.CommandUpdate) (*api.Command, restclient.RestError) { + return d.RestClient().UpdateGlobalCommand(d.ApplicationID(), commandID, command) } // DeleteCommand creates a new global api.Command -func (d *DisgoImpl) DeleteCommand(commandID api.Snowflake) error { +func (d *DisgoImpl) DeleteCommand(commandID api.Snowflake) restclient.RestError { return d.RestClient().DeleteGlobalCommand(d.ApplicationID(), commandID) } // 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, restclient.RestError) { return d.RestClient().SetGlobalCommands(d.ApplicationID(), commands...) } // GetGuildCommand fetches a specific api.Guild api.Command -func (d *DisgoImpl) GetGuildCommand(guildID api.Snowflake, commandID api.Snowflake) (*api.Command, error) { +func (d *DisgoImpl) GetGuildCommand(guildID api.Snowflake, commandID api.Snowflake) (*api.Command, restclient.RestError) { return d.RestClient().GetGuildCommand(d.ApplicationID(), guildID, commandID) } // GetGuildCommands fetches all api.Guild api.Command(s) -func (d *DisgoImpl) GetGuildCommands(guildID api.Snowflake, ) ([]*api.Command, error) { +func (d *DisgoImpl) GetGuildCommands(guildID api.Snowflake) ([]*api.Command, restclient.RestError) { return d.RestClient().GetGuildCommands(d.ApplicationID(), guildID) } // 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, restclient.RestError) { 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) { - return d.RestClient().EditGuildCommand(d.ApplicationID(), guildID, commandID, command) +func (d *DisgoImpl) EditGuildCommand(guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (*api.Command, restclient.RestError) { + return d.RestClient().UpdateGuildCommand(d.ApplicationID(), guildID, commandID, command) } // DeleteGuildCommand creates a new api.Command for this api.Guild -func (d *DisgoImpl) DeleteGuildCommand(guildID api.Snowflake, commandID api.Snowflake) error { +func (d *DisgoImpl) DeleteGuildCommand(guildID api.Snowflake, commandID api.Snowflake) restclient.RestError { return d.RestClient().DeleteGuildCommand(d.ApplicationID(), guildID, commandID) } // 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, restclient.RestError) { return d.RestClient().SetGuildCommands(d.ApplicationID(), guildID, commands...) } // GetGuildCommandsPermissions returns the api.GuildCommandPermissions for a all api.Command(s) in a api.Guild -func (d *DisgoImpl) GetGuildCommandsPermissions(guildID api.Snowflake) ([]*api.GuildCommandPermissions, error) { +func (d *DisgoImpl) GetGuildCommandsPermissions(guildID api.Snowflake) ([]*api.GuildCommandPermissions, restclient.RestError) { return d.RestClient().GetGuildCommandsPermissions(d.ApplicationID(), guildID) } // GetGuildCommandPermissions returns the api.GuildCommandPermissions for a specific api.Command in a api.Guild -func (d *DisgoImpl) GetGuildCommandPermissions(guildID api.Snowflake, commandID api.Snowflake) (*api.GuildCommandPermissions, error) { +func (d *DisgoImpl) GetGuildCommandPermissions(guildID api.Snowflake, commandID api.Snowflake) (*api.GuildCommandPermissions, restclient.RestError) { return d.RestClient().GetGuildCommandPermissions(d.ApplicationID(), guildID, 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, restclient.RestError) { 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, restclient.RestError) { return d.RestClient().SetGuildCommandPermissions(d.ApplicationID(), guildID, commandID, permissions) } diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 0473af65..c7a5ba9e 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -173,8 +173,47 @@ func (b *EntityBuilderImpl) CreateMessage(fullMessage *api.FullMessage, updateCa } // CreateGuild returns a new api.Guild entity -func (b *EntityBuilderImpl) CreateGuild(guild *api.Guild, updateCache api.CacheStrategy) *api.Guild { +func (b *EntityBuilderImpl) CreateGuild(fullGuild *api.FullGuild, updateCache api.CacheStrategy) *api.Guild { + guild := fullGuild.Guild guild.Disgo = b.Disgo() + + for _, channel := range fullGuild.Channels { + channel.GuildID = &guild.ID + switch channel.Type { + case api.ChannelTypeText, api.ChannelTypeNews: + b.Disgo().EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes) + case api.ChannelTypeVoice: + b.Disgo().EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes) + case api.ChannelTypeCategory: + b.Disgo().EntityBuilder().CreateCategory(channel, api.CacheStrategyYes) + case api.ChannelTypeStore: + b.Disgo().EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes) + } + } + + for _, role := range fullGuild.Roles { + b.Disgo().EntityBuilder().CreateRole(guild.ID, role, api.CacheStrategyYes) + } + + for _, member := range fullGuild.Members { + b.Disgo().EntityBuilder().CreateMember(guild.ID, member, api.CacheStrategyYes) + } + + for _, voiceState := range fullGuild.VoiceStates { + b.Disgo().EntityBuilder().CreateVoiceState(guild.ID, voiceState, api.CacheStrategyYes) + } + + for _, emote := range fullGuild.Emojis { + b.Disgo().EntityBuilder().CreateEmoji(guild.ID, emote, api.CacheStrategyYes) + } + + // TODO: presence + /*for i := range fullGuild.Presences { + presence := fullGuild.Presences[i] + presence.Disgo = disgo + b.Disgo().Cache().CachePresence(presence) + }*/ + if updateCache(b.Disgo()) { return b.Disgo().Cache().CacheGuild(guild) } diff --git a/internal/gateway_impl.go b/internal/gateway_impl.go index 8ba97913..d516079c 100644 --- a/internal/gateway_impl.go +++ b/internal/gateway_impl.go @@ -1,12 +1,12 @@ package internal import ( - "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" + "net/http" "runtime/debug" "time" @@ -20,7 +20,7 @@ import ( func newGatewayImpl(disgo api.Disgo) api.Gateway { return &GatewayImpl{ disgo: disgo, - status: api.Unconnected, + status: api.GatewayStatusUnconnected, } } @@ -47,14 +47,14 @@ func (g *GatewayImpl) reconnect(delay time.Duration) { go func() { time.Sleep(delay) - if g.Status() == api.Connecting || g.Status() == api.Reconnecting { + if g.Status() == api.GatewayStatusConnecting || g.Status() == api.GatewayStatusReconnecting { g.Disgo().Logger().Error("tried to reconnect gateway while connecting/reconnecting") return } g.Disgo().Logger().Info("reconnecting gateway...") if err := g.Open(); err != nil { g.Disgo().Logger().Errorf("failed to reconnect gateway: %s", err) - g.status = api.Disconnected + g.status = api.GatewayStatusDisconnected g.reconnect(delay * 2) } }() @@ -63,9 +63,9 @@ func (g *GatewayImpl) reconnect(delay time.Duration) { // Open initializes the client and connection to discord func (g *GatewayImpl) Open() error { if g.lastSequenceReceived == nil || g.sessionID == nil { - g.status = api.Connecting + g.status = api.GatewayStatusConnecting } else { - g.status = api.Reconnecting + g.status = api.GatewayStatusReconnecting } g.Disgo().Logger().Info("starting ws...") @@ -84,41 +84,44 @@ func (g *GatewayImpl) Open() error { } gatewayURL := *g.url + "?v=" + restclient.APIVersion + "&encoding=json" - wsConn, rs, err := websocket.DefaultDialer.Dial(gatewayURL, nil) + var rs *http.Response + var err error + g.conn, rs, err = websocket.DefaultDialer.Dial(gatewayURL, nil) if err != nil { g.Close() - var body string + var body []byte if rs != nil && rs.Body != nil { - rawBody, err := ioutil.ReadAll(rs.Body) + body, err = ioutil.ReadAll(rs.Body) if err != nil { g.Disgo().Logger().Errorf("error while reading response body: %s", err) g.url = nil return err } - body = string(rawBody) } else { - body = "null" + body = []byte("null") } - g.Disgo().Logger().Errorf("error connecting to gateway. url: %s, error: %s, body: %s", gatewayURL, err.Error(), body) + g.Disgo().Logger().Errorf("error connecting to gateway. url: %s, error: %s, body: %s", gatewayURL, err, string(body)) return err } - wsConn.SetCloseHandler(func(code int, error string) error { + + g.conn.SetCloseHandler(func(code int, error string) error { g.Disgo().Logger().Infof("connection to websocket closed with code: %d, error: %s", code, error) return nil }) - g.conn = wsConn - g.status = api.WaitingForHello + g.status = api.GatewayStatusWaitingForHello - mt, data, err := g.conn.ReadMessage() + mt, reader, err := g.conn.NextReader() if err != nil { return err } - event, err := g.parseGatewayEvent(mt, data) + + event, err := g.parseGatewayEvent(mt, reader) if err != nil { return err } + if event.Op != api.OpHello { return fmt.Errorf("expected op: hello type: 10, received: %d", mt) } @@ -133,9 +136,9 @@ func (g *GatewayImpl) Open() error { g.heartbeatInterval = eventData.HeartbeatInterval * time.Millisecond if g.lastSequenceReceived == nil || g.sessionID == nil { - g.status = api.Identifying - g.Disgo().Logger().Infof("sending Identifying command...") - if err = wsConn.WriteJSON( + g.status = api.GatewayStatusIdentifying + g.Disgo().Logger().Infof("sending GatewayStatusIdentifying command...") + if err = g.Send( api.NewGatewayCommand(api.OpIdentify, api.IdentifyCommand{ Token: g.Disgo().Token(), Properties: api.IdentifyCommandDataProperties{ @@ -150,17 +153,17 @@ func (g *GatewayImpl) Open() error { ); err != nil { return err } - g.status = api.WaitingForReady + g.status = api.GatewayStatusWaitingForReady } else { - g.status = api.Resuming + g.status = api.GatewayStatusResuming cmd := api.NewGatewayCommand(api.OpResume, api.ResumeCommand{ Token: g.Disgo().Token(), SessionID: *g.sessionID, Seq: *g.lastSequenceReceived, }) - g.Disgo().Logger().Infof("sending Resuming command...") + g.Disgo().Logger().Infof("sending GatewayStatusResuming command...") - if err = wsConn.WriteJSON(cmd); err != nil { + if err = g.Send(cmd); err != nil { return err } } @@ -178,6 +181,11 @@ func (g *GatewayImpl) Status() api.GatewayStatus { return g.status } +// Send sends a payload to the Gateway +func (g *GatewayImpl) Send(command api.GatewayCommand) error { + return g.conn.WriteJSON(command) +} + // Latency returns the api.Gateway latency func (g *GatewayImpl) Latency() time.Duration { return g.lastHeartbeatReceived.Sub(g.lastHeartbeatSent) @@ -248,7 +256,7 @@ func (g *GatewayImpl) sendHeartbeat() { OldPing: g.Latency(), } - if err := g.conn.WriteJSON(api.NewGatewayCommand(api.OpHeartbeat, g.lastSequenceReceived)); err != nil { + if err := g.Send(api.NewGatewayCommand(api.OpHeartbeat, g.lastSequenceReceived)); err != nil { g.Disgo().Logger().Errorf("failed to send heartbeat with error: %s", err) g.closeWithCode(websocket.CloseServiceRestart) g.reconnect(1 * time.Second) @@ -269,6 +277,7 @@ func (g *GatewayImpl) listen() { } g.Disgo().Logger().Info("shut down listen goroutine") }() + for { select { case <-g.quit: @@ -278,7 +287,7 @@ func (g *GatewayImpl) listen() { if g.conn == nil { return } - mt, data, err := g.conn.ReadMessage() + mt, reader, err := g.conn.NextReader() if err != nil { g.Disgo().Logger().Errorf("error while reading from ws. error: %s", err) g.closeWithCode(websocket.CloseServiceRestart) @@ -286,7 +295,7 @@ func (g *GatewayImpl) listen() { return } - event, err := g.parseGatewayEvent(mt, data) + event, err := g.parseGatewayEvent(mt, reader) if err != nil { g.Disgo().Logger().Errorf("error while unpacking gateway event. error: %s", err) } @@ -299,7 +308,7 @@ func (g *GatewayImpl) listen() { g.lastSequenceReceived = event.S } if event.T == nil { - g.Disgo().Logger().Errorf("received event without T. playload: %s", string(data)) + g.Disgo().Logger().Errorf("received event without T. payload: %+v", event) continue } @@ -307,12 +316,12 @@ func (g *GatewayImpl) listen() { if *event.T == api.GatewayEventReady { var readyEvent api.ReadyGatewayEvent - if err := g.parseEventToStruct(event, &readyEvent); err != nil { + if err = g.parseEventToStruct(event, &readyEvent); err != nil { g.Disgo().Logger().Errorf("Error parsing ready event: %s", err) continue } g.sessionID = &readyEvent.SessionID - + g.status = api.GatewayStatusWaitingForGuilds g.Disgo().Logger().Info("ready event received") } @@ -343,12 +352,12 @@ func (g *GatewayImpl) listen() { g.reconnect(1 * time.Second) case api.OpInvalidSession: - var resumable bool - if err = g.parseEventToStruct(event, &resumable); err != nil { + var canResume bool + if err = g.parseEventToStruct(event, &canResume); err != nil { g.Disgo().Logger().Errorf("Error parsing invalid session data: %s", err) } - g.Disgo().Logger().Debugf("received: OpInvalidSession, resumable: %b", resumable) - if resumable { + g.Disgo().Logger().Debugf("received: OpInvalidSession, canResume: %b", canResume) + if canResume { g.closeWithCode(websocket.CloseServiceRestart) } else { g.Close() @@ -370,27 +379,25 @@ func (g *GatewayImpl) listen() { func (g *GatewayImpl) parseEventToStruct(event *api.RawGatewayEvent, v interface{}) error { if err := json.Unmarshal(event.D, v); err != nil { - g.Disgo().Logger().Errorf("error while unmarshaling event. error: %s", err) + g.Disgo().Logger().Errorf("error while unmarshalling event. error: %s", err) return err } return nil } -func (g *GatewayImpl) parseGatewayEvent(mt int, data []byte) (*api.RawGatewayEvent, error) { - - var reader io.Reader = bytes.NewBuffer(data) - +func (g *GatewayImpl) parseGatewayEvent(mt int, reader io.Reader) (*api.RawGatewayEvent, error) { if mt == websocket.BinaryMessage { return nil, errors.New("we don't handle compressed yet") } + if mt != websocket.TextMessage { - return nil, fmt.Errorf("recieved unexpected message_events type: %d", mt) + return nil, fmt.Errorf("recieved unexpected message type: %d", mt) } - var event api.RawGatewayEvent decoder := json.NewDecoder(reader) + var event api.RawGatewayEvent if err := decoder.Decode(&event); err != nil { - g.Disgo().Logger().Errorf("error decoding websocket message_events, %s", err) + g.Disgo().Logger().Errorf("error decoding websocket message, %s", err) return nil, err } return &event, nil diff --git a/internal/handlers/guild_create_handler.go b/internal/handlers/guild_create_handler.go index 917fa4cc..0902df42 100644 --- a/internal/handlers/guild_create_handler.go +++ b/internal/handlers/guild_create_handler.go @@ -31,44 +31,7 @@ func (h GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api oldGuild = &*oldGuild wasUnavailable = oldGuild.Unavailable } - guild := disgo.EntityBuilder().CreateGuild(fullGuild.Guild, api.CacheStrategyYes) - - for _, channel := range fullGuild.Channels { - channel.GuildID = &guild.ID - switch channel.Type { - case api.ChannelTypeText, api.ChannelTypeNews: - disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes) - case api.ChannelTypeVoice: - disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes) - case api.ChannelTypeCategory: - disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes) - case api.ChannelTypeStore: - disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes) - } - } - - for _, role := range fullGuild.Roles { - disgo.EntityBuilder().CreateRole(guild.ID, role, api.CacheStrategyYes) - } - - for _, member := range fullGuild.Members { - disgo.EntityBuilder().CreateMember(guild.ID, member, api.CacheStrategyYes) - } - - for _, voiceState := range fullGuild.VoiceStates { - disgo.EntityBuilder().CreateVoiceState(guild.ID, voiceState, api.CacheStrategyYes) - } - - for _, emote := range fullGuild.Emojis { - disgo.EntityBuilder().CreateEmoji(guild.ID, emote, api.CacheStrategyYes) - } - - // TODO: presence - /*for i := range fullGuild.Presences { - presence := fullGuild.Presences[i] - presence.Disgo = disgo - disgo.Cache().CachePresence(presence) - }*/ + guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyYes) genericGuildEvent := events.GenericGuildEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), diff --git a/internal/handlers/guild_delete_handler.go b/internal/handlers/guild_delete_handler.go index 1c4add1e..f33061ad 100644 --- a/internal/handlers/guild_delete_handler.go +++ b/internal/handlers/guild_delete_handler.go @@ -15,17 +15,17 @@ func (h GuildDeleteHandler) Event() api.GatewayEventType { // New constructs a new payload receiver for the raw gateway event func (h GuildDeleteHandler) New() interface{} { - return &api.Guild{} + return &api.FullGuild{} } // HandleGatewayEvent handles the specific raw gateway event func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { - guild, ok := i.(*api.Guild) + fullGuild, ok := i.(*api.FullGuild) if !ok { return } - guild = disgo.EntityBuilder().CreateGuild(guild, api.CacheStrategyNo) + guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNo) genericGuildEvent := events.GenericGuildEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), @@ -34,7 +34,7 @@ func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api eventManager.Dispatch(genericGuildEvent) if guild.Unavailable { - // set guild to unavail for now + // set guild to unavailable for now disgo.Cache().Guild(guild.ID).Unavailable = true eventManager.Dispatch(events.GuildUnavailableEvent{ diff --git a/internal/handlers/guild_update_handler.go b/internal/handlers/guild_update_handler.go index 0179d101..836b0a9b 100644 --- a/internal/handlers/guild_update_handler.go +++ b/internal/handlers/guild_update_handler.go @@ -15,21 +15,21 @@ func (h GuildUpdateHandler) Event() api.GatewayEventType { // New constructs a new payload receiver for the raw gateway event func (h GuildUpdateHandler) New() interface{} { - return &api.Guild{} + return &api.FullGuild{} } // HandleGatewayEvent handles the specific raw gateway event func (h GuildUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { - guild, ok := i.(*api.Guild) + fullGuild, ok := i.(*api.FullGuild) if !ok { return } - oldGuild := disgo.Cache().Guild(guild.ID) + oldGuild := disgo.Cache().Guild(fullGuild.ID) if oldGuild != nil { oldGuild = &*oldGuild } - guild = disgo.EntityBuilder().CreateGuild(guild, api.CacheStrategyYes) + guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyYes) genericGuildEvent := events.GenericGuildEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 3cc6be71..a88ab242 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -12,56 +12,33 @@ func newRestClientImpl(disgo api.Disgo, httpClient *http.Client) api.RestClient if httpClient == nil { httpClient = http.DefaultClient } - return &RestClientImpl{ + return &restClientImpl{ RestClient: restclient.NewRestClient(httpClient, disgo.Logger(), api.UserAgent, http.Header{"Authorization": []string{"Bot " + disgo.Token()}}), disgo: disgo, } } -// RestClientImpl is the rest client implementation used for HTTP requests to discord -type RestClientImpl struct { +// restClientImpl is the rest client implementation used for HTTP requests to discord +type restClientImpl struct { restclient.RestClient disgo api.Disgo } -func (r *RestClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (*api.Guild, error) { - panic("implement me") -} - -func (r *RestClientImpl) GetGuildPreview(guildID api.Snowflake) (*api.GuildPreview, error) { - panic("implement me") -} - -func (r *RestClientImpl) CreateGuild(guildID api.Snowflake, createGuild api.CreateGuild) (*api.Guild, error) { - panic("implement me") -} - -func (r *RestClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (*api.Guild, error) { - panic("implement me") -} - -func (r *RestClientImpl) DeleteGuild(guildID api.Snowflake) error { - panic("implement me") -} - -func (r *RestClientImpl) CreateRole(guildID api.Snowflake, createRole api.CreateRole) (*api.Role, error) { - panic("implement me") -} - // Disgo returns the api.Disgo instance -func (r *RestClientImpl) Disgo() api.Disgo { +func (r *restClientImpl) Disgo() api.Disgo { return r.disgo } // Close cleans up the http managers connections -func (r *RestClientImpl) Close() { +func (r *restClientImpl) Close() { r.HTTPClient().CloseIdleConnections() } // DoWithHeaders executes a rest request with custom headers -func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBody interface{}, rsBody interface{}, customHeader http.Header) (err restclient.RestError) { - err = r.RestClient.DoWithHeaders(route, rqBody, rsBody, customHeader) - // TODO reimplement events.HTTPRequestEvent +func (r *restClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBody interface{}, rsBody interface{}, customHeader http.Header) (rErr restclient.RestError) { + err := r.RestClient.DoWithHeaders(route, rqBody, rsBody, customHeader) + rErr = restclient.NewRestError(nil, err) + // TODO reimplement events.HTTPRequestEvent /*r.Disgo().EventManager().Dispatch(events.HTTPRequestEvent{ GenericEvent: events.NewEvent(r.Disgo(), 0), Request: rq, @@ -72,7 +49,7 @@ func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod /* 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) + r.Disgo().Logger().Errorf("restclient.RestError unmarshalling restclient.RestError response. code: %d, restclient.RestError: %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) @@ -80,67 +57,179 @@ func (r *RestClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod return } -// SendMessage lets you send a api.Message to a api.MessageChannel -func (r *RestClientImpl) SendMessage(channelID api.Snowflake, messageCreate api.MessageCreate) (message *api.Message, err error) { +// GetUser fetches the specific user +func (r *restClientImpl) GetUser(userID api.Snowflake) (user *api.User, rErr restclient.RestError) { + compiledRoute, err := restclient.GetUser.Compile(nil, userID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + rErr = r.Do(compiledRoute, nil, &user) + if rErr == nil { + user = r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs) + } + return +} + +func (r *restClientImpl) GetSelfUser() (selfUser *api.SelfUser, rErr restclient.RestError) { + compiledRoute, err := restclient.GetSelfUser.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + var user *api.User + rErr = r.Do(compiledRoute, nil, &user) + if rErr == nil { + selfUser = &api.SelfUser{User: r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs)} + } + return +} + +func (r *restClientImpl) UpdateSelfUser(updateSelfUser api.UpdateSelfUser) (selfUser *api.SelfUser, rErr restclient.RestError) { + compiledRoute, err := restclient.GetSelfUser.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + var user *api.User + rErr = r.Do(compiledRoute, updateSelfUser, &user) + if rErr == nil { + selfUser = &api.SelfUser{User: r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs)} + } + return +} + +func (r *restClientImpl) GetGuilds(before int, after int, limit int) (guilds []*api.PartialGuild, rErr restclient.RestError) { + queryParams := restclient.QueryValues{} + if before > 0 { + queryParams["before"] = before + } + if after > 0 { + queryParams["after"] = after + } + if limit > 0 { + queryParams["limit"] = limit + } + compiledRoute, err := restclient.GetGuilds.Compile(queryParams) + if err != nil { + return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + } + + rErr = r.Do(compiledRoute, nil, &guilds) + return +} + +func (r *restClientImpl) LeaveGuild(guildID api.Snowflake) restclient.RestError { + compiledRoute, err := restclient.LeaveGuild.Compile(nil, guildID) + if err != nil { + return restclient.NewRestError(nil, err) + } + return r.Do(compiledRoute, nil, nil) +} + +func (r *restClientImpl) GetDMChannels() (dmChannels []*api.DMChannel, rErr restclient.RestError) { + compiledRoute, err := restclient.GetDMChannels.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + + var channels []*api.Channel + rErr = r.Do(compiledRoute, nil, &channels) + if rErr == nil { + dmChannels = make([]*api.DMChannel, len(channels)) + for i, channel := range channels { + dmChannels[i] = r.Disgo().EntityBuilder().CreateDMChannel(channel, api.CacheStrategyNoWs) + } + } + return +} + +// CreateDMChannel opens a new api.DMChannel to a api.User +func (r *restClientImpl) CreateDMChannel(userID api.Snowflake) (channel *api.DMChannel, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateDMChannel.Compile(nil) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + + rErr = r.Do(compiledRoute, api.CreateDMChannel{RecipientID: userID}, &channel) + if rErr == nil { + channel = r.Disgo().EntityBuilder().CreateDMChannel(&channel.MessageChannel.Channel, api.CacheStrategyNoWs) + } + return +} + +func (r *restClientImpl) GetMessage(channelID api.Snowflake, messageID api.Snowflake) (message *api.Message, rErr restclient.RestError) { + compiledRoute, err := restclient.GetMessage.Compile(nil, channelID, messageID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + + var fullMessage *api.FullMessage + rErr = r.Do(compiledRoute, nil, &fullMessage) + if rErr == nil { + message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + } + return +} + +// CreateMessage lets you send a api.Message to a api.MessageChannel +func (r *restClientImpl) CreateMessage(channelID api.Snowflake, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateMessage.Compile(nil, channelID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } -// EditMessage lets you edit a api.Message -func (r *RestClientImpl) EditMessage(channelID api.Snowflake, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, err error) { +// UpdateMessage lets you edit a api.Message +func (r *restClientImpl) UpdateMessage(channelID api.Snowflake, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } // DeleteMessage lets you delete a api.Message -func (r *RestClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Snowflake) (err error) { +func (r *restClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteMessage.Compile(nil, channelID, messageID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheMessage(channelID, messageID) } return } // BulkDeleteMessages lets you bulk delete api.Message(s) -func (r *RestClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs ...api.Snowflake) (err error) { +func (r *restClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs ...api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.BulkDeleteMessage.Compile(nil, channelID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, api.MessageBulkDelete{Messages: messageIDs}, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, api.MessageBulkDelete{Messages: messageIDs}, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { // TODO: check here if no err means all messages deleted for _, messageID := range messageIDs { r.Disgo().Cache().UncacheMessage(channelID, messageID) @@ -150,86 +239,103 @@ func (r *RestClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs } // CrosspostMessage lets you crosspost a api.Message in a channel with type api.ChannelTypeNews -func (r *RestClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (msg *api.Message, err error) { +func (r *restClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (msg *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CrosspostMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMsg *api.FullMessage - err = r.Do(compiledRoute, nil, &fullMsg) - if err == nil { + rErr = r.Do(compiledRoute, nil, &fullMsg) + if rErr == nil { msg = r.Disgo().EntityBuilder().CreateMessage(fullMsg, api.CacheStrategyNoWs) } return } -// OpenDMChannel opens a new dm channel a user -func (r *RestClientImpl) OpenDMChannel(userID api.Snowflake) (channel *api.DMChannel, err error) { - compiledRoute, err := restclient.CreateDMChannel.Compile(nil) +func (r *restClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (guild *api.Guild, rErr restclient.RestError) { + var queryParams = restclient.QueryValues{ + "with_counts": withCounts, + } + compiledRoute, err := restclient.GetGuild.Compile(queryParams, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) } - body := struct { - RecipientID api.Snowflake `json:"recipient_id"` - }{ - RecipientID: userID, + + var fullGuild *api.FullGuild + rErr = r.Do(compiledRoute, nil, &fullGuild) + if rErr == nil { + guild = r.Disgo().EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNoWs) } - err = r.Do(compiledRoute, body, &channel) - if err == nil { - channel = r.Disgo().EntityBuilder().CreateDMChannel(&channel.MessageChannel.Channel, api.CacheStrategyNoWs) + return +} + +func (r *restClientImpl) GetGuildPreview(guildID api.Snowflake) (guildPreview *api.GuildPreview, rErr restclient.RestError) { + compiledRoute, err := restclient.GetGuildPreview.Compile(nil, guildID) + if err != nil { + return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) } + + rErr = r.Do(compiledRoute, nil, &guildPreview) return } -// UpdateSelfNick updates the bots nickname in a guild -func (r *RestClientImpl) UpdateSelfNick(guildID api.Snowflake, nick *string) (newNick *string, err error) { - compiledRoute, err := restclient.UpdateSelfNick.Compile(nil, guildID) +func (r *restClientImpl) CreateGuild(createGuild api.CreateGuild) (guild *api.Guild, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateGuild.Compile(nil) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - var updateNick *api.UpdateSelfNick - err = r.Do(compiledRoute, &api.UpdateSelfNick{Nick: nick}, &updateNick) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { - r.Disgo().Cache().Member(guildID, r.Disgo().ApplicationID()).Nick = updateNick.Nick - newNick = updateNick.Nick + + var fullGuild *api.FullGuild + rErr = r.Do(compiledRoute, createGuild, &fullGuild) + if rErr == nil { + guild = r.Disgo().EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNoWs) } return } -// GetUser fetches the specific user -func (r *RestClientImpl) GetUser(userID api.Snowflake) (user *api.User, err error) { - compiledRoute, err := restclient.GetUser.Compile(nil, userID) +func (r *restClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (guild *api.Guild, rErr restclient.RestError) { + compiledRoute, err := restclient.CreateGuild.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &user) - if err == nil { - user = r.Disgo().EntityBuilder().CreateUser(user, api.CacheStrategyNoWs) + + var fullGuild *api.FullGuild + rErr = r.Do(compiledRoute, updateGuild, &fullGuild) + if rErr == nil { + guild = r.Disgo().EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNoWs) } return } +func (r *restClientImpl) DeleteGuild(guildID api.Snowflake) restclient.RestError { + compiledRoute, err := restclient.DeleteGuild.Compile(nil, guildID) + if err != nil { + return restclient.NewRestError(nil, err) + } + return r.Do(compiledRoute, nil, nil) +} + // GetMember fetches the specific member -func (r *RestClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) (member *api.Member, err error) { +func (r *restClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &member) - if err == nil { + rErr = r.Do(compiledRoute, nil, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } // GetMembers fetches all members for a guild -func (r *RestClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Member, err error) { +func (r *restClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMembers.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &members) - if err == nil { + rErr = r.Do(compiledRoute, nil, &members) + if rErr == nil { for _, member := range members { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } @@ -237,71 +343,111 @@ func (r *RestClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Membe return } +func (r *restClientImpl) SearchMembers(guildID api.Snowflake, query string, limit int) (members []*api.Member, rErr restclient.RestError) { + queryParams := restclient.QueryValues{} + if query != "" { + queryParams["query"] = query + } + if limit > 0 { + queryParams["limit"] = limit + } + compiledRoute, err := restclient.GetMembers.Compile(queryParams, guildID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + rErr = r.Do(compiledRoute, nil, &members) + if rErr == nil { + members = make([]*api.Member, len(members)) + for i, member := range members { + members[i] = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) + } + } + return +} + // 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, addMember api.AddMember) (member *api.Member, err error) { +func (r *restClientImpl) AddMember(guildID api.Snowflake, userID api.Snowflake, addMember api.AddMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.AddMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, addMember, &member) - if err == nil { + rErr = r.Do(compiledRoute, addMember, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } -// 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{} - if reason != nil { - params = map[string]interface{}{"reason": *reason} +// RemoveMember kicks a api.Member from the api.Guild. requires api.PermissionKickMembers +func (r *restClientImpl) RemoveMember(guildID api.Snowflake, userID api.Snowflake, reason string) (rErr restclient.RestError) { + var params restclient.QueryValues + if reason != "" { + params = restclient.QueryValues{"reason": reason} } - compiledRoute, err = restclient.RemoveMember.Compile(params, guildID, userID) + compiledRoute, err := restclient.RemoveMember.Compile(params, guildID, userID) if err != nil { - return + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheMember(guildID, userID) } return } // UpdateMember updates a api.Member -func (r *RestClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateMember api.UpdateMember) (member *api.Member, err error) { +func (r *restClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateMember api.UpdateMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, updateMember, &member) - if err == nil { + rErr = r.Do(compiledRoute, updateMember, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } +// UpdateSelfNick updates the bots nickname in a guild +func (r *restClientImpl) UpdateSelfNick(guildID api.Snowflake, nick string) (newNick *string, rErr restclient.RestError) { + compiledRoute, err := restclient.UpdateSelfNick.Compile(nil, guildID) + if err != nil { + return nil, restclient.NewRestError(nil, err) + } + var updateNick *api.UpdateSelfNick + rErr = r.Do(compiledRoute, &api.UpdateSelfNick{Nick: nick}, &updateNick) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { + var nick *string + if updateNick.Nick == "" { + nick = nil + } + r.Disgo().Cache().Member(guildID, r.Disgo().ClientID()).Nick = nick + newNick = nick + } + return +} + // 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) { +func (r *restClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, channelID *api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) - if err == nil { + rErr = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) + if rErr == nil { member = r.Disgo().EntityBuilder().CreateMember(guildID, member, api.CacheStrategyNoWs) } return } // AddMemberRole adds a api.Role to a api.Member -func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (err error) { +func (r *restClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.AddMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { member := r.Disgo().Cache().Member(guildID, userID) if member != nil { member.RoleIDs = append(member.RoleIDs, roleID) @@ -311,13 +457,13 @@ func (r *RestClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowfla } // 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) { +func (r *restClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.RemoveMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { member := r.Disgo().Cache().Member(guildID, userID) if member != nil { for i, id := range member.RoleIDs { @@ -332,13 +478,13 @@ func (r *RestClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snow } // GetRoles fetches all api.Role(s) from a api.Guild -func (r *RestClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, err error) { +func (r *restClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &roles) - if err == nil { + rErr = r.Do(compiledRoute, nil, &roles) + if rErr == nil { for _, role := range roles { role = r.Disgo().EntityBuilder().CreateRole(guildID, role, api.CacheStrategyNoWs) } @@ -347,39 +493,39 @@ 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, createRole api.CreateRole) (newRole *api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.CreateRole.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, role, &newRole) - if err == nil { + rErr = r.Do(compiledRoute, createRole, &newRole) + if rErr == nil { newRole = r.Disgo().EntityBuilder().CreateRole(guildID, newRole, api.CacheStrategyNoWs) } return } // 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, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, role, &newRole) - if err == nil { + rErr = r.Do(compiledRoute, role, &newRole) + if rErr == nil { newRole = r.Disgo().EntityBuilder().CreateRole(guildID, newRole, api.CacheStrategyNoWs) } return } // 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, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, roleUpdates, &roles) - if err == nil { + rErr = r.Do(compiledRoute, roleUpdates, &roles) + if rErr == nil { for _, role := range roles { role = r.Disgo().EntityBuilder().CreateRole(guildID, role, api.CacheStrategyNoWs) } @@ -388,53 +534,53 @@ func (r *RestClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates } // DeleteRole deletes a role from a guild. Requires api.PermissionManageRoles -func (r *RestClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) (err error) { +func (r *restClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.disgo.Cache().UncacheRole(guildID, roleID) } return } // AddReaction lets you add a reaction to a api.Message -func (r *RestClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) error { +func (r *restClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.AddReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // RemoveOwnReaction lets you remove your own reaction from a api.Message -func (r *RestClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) error { +func (r *restClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.RemoveOwnReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // 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 { +func (r *restClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string, userID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.RemoveUserReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji), userID) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // GetGlobalCommands gets you all global api.Command(s) -func (r *RestClientImpl) GetGlobalCommands(applicationID api.Snowflake) (commands []*api.Command, err error) { +func (r *restClientImpl) GetGlobalCommands(applicationID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &commands) - if err == nil { + rErr = r.Do(compiledRoute, nil, &commands) + if rErr == nil { for _, cmd := range commands { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } @@ -443,43 +589,43 @@ func (r *RestClientImpl) GetGlobalCommands(applicationID api.Snowflake) (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) { +func (r *restClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } return } // CreateGlobalCommand lets you create a new global api.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, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGlobalCommand.Compile(nil, applicationID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } return } // SetGlobalCommands lets you override all global api.Command -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, rErr restclient.RestError) { compiledRoute, err := restclient.SetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands return } - err = r.Do(compiledRoute, commands, &cmds) - if err == nil { + rErr = r.Do(compiledRoute, commands, &cmds) + if rErr == nil { for _, cmd := range cmds { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } @@ -487,40 +633,40 @@ func (r *RestClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands return } -// 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) { +// UpdateGlobalCommand lets you edit a specific global api.Command +func (r *restClientImpl) UpdateGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGlobalCommand(cmd, api.CacheStrategyNoWs) } return } // DeleteGlobalCommand lets you delete a specific global api.Command -func (r *RestClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (err error) { +func (r *restClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheCommand(commandID) } return } // 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) { +func (r *restClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &commands) - if err == nil { + rErr = r.Do(compiledRoute, nil, &commands) + if rErr == nil { for _, cmd := range commands { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } @@ -529,30 +675,30 @@ func (r *RestClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID a } // 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) { +func (r *restClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, command api.CommandCreate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuildCommand.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } return } // 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) { +func (r *restClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands return } - err = r.Do(compiledRoute, commands, &cmds) - if err == nil { + rErr = r.Do(compiledRoute, commands, &cmds) + if rErr == nil { for _, cmd := range cmds { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } @@ -561,52 +707,52 @@ func (r *RestClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID a } // 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) { +func (r *restClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } return } -// 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) { +// UpdateGuildCommand lets you edit a specific api.Command in a api.Guild +func (r *restClientImpl) UpdateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, command, &cmd) - if err == nil { + rErr = r.Do(compiledRoute, command, &cmd) + if rErr == nil { cmd = r.Disgo().EntityBuilder().CreateGuildCommand(guildID, cmd, api.CacheStrategyNoWs) } return } // 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) { +func (r *restClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return err + return restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, nil) - if err == nil && api.CacheStrategyNoWs(r.Disgo()) { + rErr = r.Do(compiledRoute, nil, nil) + if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { r.Disgo().Cache().UncacheCommand(commandID) } return } // 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) { +func (r *restClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake) (cmdsPerms []*api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmdsPerms) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmdsPerms) + if rErr == nil { for _, cmdPerms := range cmdsPerms { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } @@ -615,26 +761,26 @@ func (r *RestClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake } // 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) { +func (r *restClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmdPerms *api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermission.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, nil, &cmdPerms) - if err == nil { + rErr = r.Do(compiledRoute, nil, &cmdPerms) + if rErr == nil { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } return } // 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, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandsPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, api.SetGuildCommandsPermissions(commandsPermissions), &cmdsPerms) - if err == nil { + rErr = r.Do(compiledRoute, api.SetGuildCommandsPermissions(commandsPermissions), &cmdsPerms) + if rErr == nil { for _, cmdPerms := range cmdsPerms { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } @@ -643,98 +789,98 @@ 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, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandPermissions.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } - err = r.Do(compiledRoute, commandPermissions, &cmdPerms) - if err == nil { + rErr = r.Do(compiledRoute, commandPermissions, &cmdPerms) + if rErr == nil { cmdPerms = r.Disgo().EntityBuilder().CreateGuildCommandPermissions(cmdPerms, api.CacheStrategyNoWs) } return } // SendInteractionResponse used to send the initial response on an api.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) restclient.RestError { compiledRoute, err := restclient.CreateInteractionResponse.Compile(nil, interactionID, interactionToken) if err != nil { - return err + return restclient.NewRestError(nil, err) } body, err := interactionResponse.ToBody() if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, body, nil) } -// 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) { +// UpdateInteractionResponse used to edit the initial response on an api.Interaction +func (r *restClientImpl) UpdateInteractionResponse(applicationID api.Snowflake, interactionToken string, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } // DeleteInteractionResponse used to delete the initial response on an api.Interaction -func (r *RestClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, interactionToken string) error { +func (r *restClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, interactionToken string) restclient.RestError { compiledRoute, err := restclient.DeleteInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } // 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) { +func (r *restClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateFollowupMessage.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } return } -// 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) { +// UpdateFollowupMessage used to edit a followup api.Message from an api.Interaction +func (r *restClientImpl) UpdateFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, err + return nil, restclient.NewRestError(nil, err) } var fullMessage *api.FullMessage - err = r.Do(compiledRoute, body, &fullMessage) - if err == nil { + rErr = r.Do(compiledRoute, body, &fullMessage) + if rErr == nil { message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) } @@ -742,10 +888,10 @@ func (r *RestClientImpl) EditFollowupMessage(applicationID api.Snowflake, intera } // 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 { +func (r *restClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.DeleteFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return err + return restclient.NewRestError(nil, err) } return r.Do(compiledRoute, nil, nil) } diff --git a/internal/util.go b/internal/util.go index df890a80..92be3dbb 100644 --- a/internal/util.go +++ b/internal/util.go @@ -21,4 +21,3 @@ func IDFromToken(token string) (*api.Snowflake, error) { strID := api.Snowflake(byteID) return &strID, nil } - From f5edee20cb925daca69070c8be69ee5d57b6c9a4 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 16 Jun 2021 00:42:26 +0200 Subject: [PATCH 41/64] bump restclient --- go.mod | 6 +----- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 42971df3..fb5141cf 100644 --- a/go.mod +++ b/go.mod @@ -2,13 +2,9 @@ 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.5 + github.com/DisgoOrg/restclient v1.2.0 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/stretchr/testify v1.7.0 diff --git a/go.sum b/go.sum index 7ede71b2..c1098959 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.5 h1:qjYNUeFo2NcqaMS+lLxyQIwED1gomn5TIub88wrA2mI= -github.com/DisgoOrg/restclient v1.1.5/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= +github.com/DisgoOrg/restclient v1.2.0 h1:M2GXPf5Ja+Ynt7DBTLv+TQ4iMVLQX17FRHXQ0gqAExw= +github.com/DisgoOrg/restclient v1.2.0/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 f80afeb52963f41aaeb219d767d1e5e69b398478 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Wed, 16 Jun 2021 00:46:15 +0200 Subject: [PATCH 42/64] fixed compile errors caused by restcleint dump --- api/channels.go | 2 +- api/interaction.go | 2 +- api/message.go | 2 +- api/self_user.go | 2 +- example/go.sum | 2 + internal/restclient_impl.go | 130 ++++++++++++++++++------------------ 6 files changed, 71 insertions(+), 69 deletions(-) diff --git a/api/channels.go b/api/channels.go index 53048c89..2a92ee9b 100644 --- a/api/channels.go +++ b/api/channels.go @@ -71,7 +71,7 @@ func (c MessageChannel) BulkDeleteMessages(messageIDs ...Snowflake) restclient.R // CrosspostMessage crossposts an existing Message func (c MessageChannel) CrosspostMessage(messageID Snowflake) (*Message, restclient.RestError) { if c.Type != ChannelTypeNews { - return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) + return nil, restclient.NewError(nil, errors.New("channel type is not NEWS")) } return c.Disgo.RestClient().CrosspostMessage(c.ID, messageID) } diff --git a/api/interaction.go b/api/interaction.go index 037eda67..89722e62 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -77,7 +77,7 @@ func (i *Interaction) Respond(responseType InteractionResponseType, data interfa Data: data, } if i.Replied { - return restclient.NewRestError(nil, errors.New("you already replied to this interaction")) + return restclient.NewError(nil, errors.New("you already replied to this interaction")) } i.Replied = true diff --git a/api/message.go b/api/message.go index 498cec60..0294294e 100644 --- a/api/message.go +++ b/api/message.go @@ -251,7 +251,7 @@ func (m *Message) Delete() restclient.RestError { func (m *Message) Crosspost() (*Message, restclient.RestError) { channel := m.Channel() if channel != nil && channel.Type != ChannelTypeNews { - return nil, restclient.NewRestError(nil, errors.New("channel type is not NEWS")) + return nil, restclient.NewError(nil, errors.New("channel type is not NEWS")) } return m.Disgo.RestClient().CrosspostMessage(m.ChannelID, m.ID) } diff --git a/api/self_user.go b/api/self_user.go index a39d5fe3..69a3185a 100644 --- a/api/self_user.go +++ b/api/self_user.go @@ -7,7 +7,7 @@ import ( ) // ErrDMChannelToYourself occurs when opening a DMChannel to yourself -var ErrDMChannelToYourself = restclient.NewRestError(nil, errors.New("can't open a dm channel to yourself")) +var ErrDMChannelToYourself = restclient.NewError(nil, errors.New("can't open a dm channel to yourself")) // SelfUser represents the current logged in User type SelfUser struct { diff --git a/example/go.sum b/example/go.sum index da0ba1cf..e9fca82e 100644 --- a/example/go.sum +++ b/example/go.sum @@ -2,6 +2,8 @@ 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/DisgoOrg/restclient v1.2.0 h1:M2GXPf5Ja+Ynt7DBTLv+TQ4iMVLQX17FRHXQ0gqAExw= +github.com/DisgoOrg/restclient v1.2.0/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/internal/restclient_impl.go b/internal/restclient_impl.go index a88ab242..3e8584b3 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -37,7 +37,7 @@ func (r *restClientImpl) Close() { // DoWithHeaders executes a rest request with custom headers func (r *restClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBody interface{}, rsBody interface{}, customHeader http.Header) (rErr restclient.RestError) { err := r.RestClient.DoWithHeaders(route, rqBody, rsBody, customHeader) - rErr = restclient.NewRestError(nil, err) + rErr = restclient.NewError(nil, err) // TODO reimplement events.HTTPRequestEvent /*r.Disgo().EventManager().Dispatch(events.HTTPRequestEvent{ GenericEvent: events.NewEvent(r.Disgo(), 0), @@ -61,7 +61,7 @@ func (r *restClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod func (r *restClientImpl) GetUser(userID api.Snowflake) (user *api.User, rErr restclient.RestError) { compiledRoute, err := restclient.GetUser.Compile(nil, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &user) if rErr == nil { @@ -73,7 +73,7 @@ func (r *restClientImpl) GetUser(userID api.Snowflake) (user *api.User, rErr res func (r *restClientImpl) GetSelfUser() (selfUser *api.SelfUser, rErr restclient.RestError) { compiledRoute, err := restclient.GetSelfUser.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var user *api.User rErr = r.Do(compiledRoute, nil, &user) @@ -86,7 +86,7 @@ func (r *restClientImpl) GetSelfUser() (selfUser *api.SelfUser, rErr restclient. func (r *restClientImpl) UpdateSelfUser(updateSelfUser api.UpdateSelfUser) (selfUser *api.SelfUser, rErr restclient.RestError) { compiledRoute, err := restclient.GetSelfUser.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var user *api.User rErr = r.Do(compiledRoute, updateSelfUser, &user) @@ -109,7 +109,7 @@ func (r *restClientImpl) GetGuilds(before int, after int, limit int) (guilds []* } compiledRoute, err := restclient.GetGuilds.Compile(queryParams) if err != nil { - return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + return nil, restclient.NewError(nil, restclient.NewError(nil, err)) } rErr = r.Do(compiledRoute, nil, &guilds) @@ -119,7 +119,7 @@ func (r *restClientImpl) GetGuilds(before int, after int, limit int) (guilds []* func (r *restClientImpl) LeaveGuild(guildID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.LeaveGuild.Compile(nil, guildID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -127,7 +127,7 @@ func (r *restClientImpl) LeaveGuild(guildID api.Snowflake) restclient.RestError func (r *restClientImpl) GetDMChannels() (dmChannels []*api.DMChannel, rErr restclient.RestError) { compiledRoute, err := restclient.GetDMChannels.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var channels []*api.Channel @@ -145,7 +145,7 @@ func (r *restClientImpl) GetDMChannels() (dmChannels []*api.DMChannel, rErr rest func (r *restClientImpl) CreateDMChannel(userID api.Snowflake) (channel *api.DMChannel, rErr restclient.RestError) { compiledRoute, err := restclient.CreateDMChannel.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.CreateDMChannel{RecipientID: userID}, &channel) @@ -158,7 +158,7 @@ func (r *restClientImpl) CreateDMChannel(userID api.Snowflake) (channel *api.DMC func (r *restClientImpl) GetMessage(channelID api.Snowflake, messageID api.Snowflake) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.GetMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -173,12 +173,12 @@ func (r *restClientImpl) GetMessage(channelID api.Snowflake, messageID api.Snowf func (r *restClientImpl) CreateMessage(channelID api.Snowflake, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateMessage.Compile(nil, channelID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -193,12 +193,12 @@ func (r *restClientImpl) CreateMessage(channelID api.Snowflake, messageCreate ap func (r *restClientImpl) UpdateMessage(channelID api.Snowflake, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -213,7 +213,7 @@ func (r *restClientImpl) UpdateMessage(channelID api.Snowflake, messageID api.Sn func (r *restClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteMessage.Compile(nil, channelID, messageID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -226,7 +226,7 @@ func (r *restClientImpl) DeleteMessage(channelID api.Snowflake, messageID api.Sn func (r *restClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs ...api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.BulkDeleteMessage.Compile(nil, channelID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.MessageBulkDelete{Messages: messageIDs}, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -242,7 +242,7 @@ func (r *restClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs func (r *restClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (msg *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CrosspostMessage.Compile(nil, channelID, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMsg *api.FullMessage rErr = r.Do(compiledRoute, nil, &fullMsg) @@ -258,7 +258,7 @@ func (r *restClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (guild } compiledRoute, err := restclient.GetGuild.Compile(queryParams, guildID) if err != nil { - return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + return nil, restclient.NewError(nil, restclient.NewError(nil, err)) } var fullGuild *api.FullGuild @@ -272,7 +272,7 @@ func (r *restClientImpl) GetGuild(guildID api.Snowflake, withCounts bool) (guild func (r *restClientImpl) GetGuildPreview(guildID api.Snowflake) (guildPreview *api.GuildPreview, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildPreview.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, restclient.NewRestError(nil, err)) + return nil, restclient.NewError(nil, restclient.NewError(nil, err)) } rErr = r.Do(compiledRoute, nil, &guildPreview) @@ -282,7 +282,7 @@ func (r *restClientImpl) GetGuildPreview(guildID api.Snowflake) (guildPreview *a func (r *restClientImpl) CreateGuild(createGuild api.CreateGuild) (guild *api.Guild, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuild.Compile(nil) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullGuild *api.FullGuild @@ -296,7 +296,7 @@ func (r *restClientImpl) CreateGuild(createGuild api.CreateGuild) (guild *api.Gu func (r *restClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.UpdateGuild) (guild *api.Guild, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuild.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullGuild *api.FullGuild @@ -310,7 +310,7 @@ func (r *restClientImpl) UpdateGuild(guildID api.Snowflake, updateGuild api.Upda func (r *restClientImpl) DeleteGuild(guildID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.DeleteGuild.Compile(nil, guildID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -319,7 +319,7 @@ func (r *restClientImpl) DeleteGuild(guildID api.Snowflake) restclient.RestError func (r *restClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &member) if rErr == nil { @@ -332,7 +332,7 @@ func (r *restClientImpl) GetMember(guildID api.Snowflake, userID api.Snowflake) func (r *restClientImpl) GetMembers(guildID api.Snowflake) (members []*api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.GetMembers.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &members) if rErr == nil { @@ -353,7 +353,7 @@ func (r *restClientImpl) SearchMembers(guildID api.Snowflake, query string, limi } compiledRoute, err := restclient.GetMembers.Compile(queryParams, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &members) if rErr == nil { @@ -369,7 +369,7 @@ func (r *restClientImpl) SearchMembers(guildID api.Snowflake, query string, limi func (r *restClientImpl) AddMember(guildID api.Snowflake, userID api.Snowflake, addMember api.AddMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.AddMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, addMember, &member) if rErr == nil { @@ -386,7 +386,7 @@ func (r *restClientImpl) RemoveMember(guildID api.Snowflake, userID api.Snowflak } compiledRoute, err := restclient.RemoveMember.Compile(params, guildID, userID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -399,7 +399,7 @@ func (r *restClientImpl) RemoveMember(guildID api.Snowflake, userID api.Snowflak func (r *restClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflake, updateMember api.UpdateMember) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, updateMember, &member) if rErr == nil { @@ -412,7 +412,7 @@ func (r *restClientImpl) UpdateMember(guildID api.Snowflake, userID api.Snowflak func (r *restClientImpl) UpdateSelfNick(guildID api.Snowflake, nick string) (newNick *string, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateSelfNick.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var updateNick *api.UpdateSelfNick rErr = r.Do(compiledRoute, &api.UpdateSelfNick{Nick: nick}, &updateNick) @@ -431,7 +431,7 @@ func (r *restClientImpl) UpdateSelfNick(guildID api.Snowflake, nick string) (new func (r *restClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, channelID *api.Snowflake) (member *api.Member, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateMember.Compile(nil, guildID, userID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.MoveMember{ChannelID: channelID}, &member) if rErr == nil { @@ -444,7 +444,7 @@ func (r *restClientImpl) MoveMember(guildID api.Snowflake, userID api.Snowflake, func (r *restClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.AddMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -460,7 +460,7 @@ func (r *restClientImpl) AddMemberRole(guildID api.Snowflake, userID api.Snowfla func (r *restClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.RemoveMemberRole.Compile(nil, guildID, userID, roleID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -481,7 +481,7 @@ func (r *restClientImpl) RemoveMemberRole(guildID api.Snowflake, userID api.Snow func (r *restClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &roles) if rErr == nil { @@ -496,7 +496,7 @@ func (r *restClientImpl) GetRoles(guildID api.Snowflake) (roles []*api.Role, rEr func (r *restClientImpl) CreateRole(guildID api.Snowflake, createRole api.CreateRole) (newRole *api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.CreateRole.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, createRole, &newRole) if rErr == nil { @@ -509,7 +509,7 @@ func (r *restClientImpl) CreateRole(guildID api.Snowflake, createRole api.Create func (r *restClientImpl) UpdateRole(guildID api.Snowflake, roleID api.Snowflake, role api.UpdateRole) (newRole *api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, role, &newRole) if rErr == nil { @@ -522,7 +522,7 @@ func (r *restClientImpl) UpdateRole(guildID api.Snowflake, roleID api.Snowflake, func (r *restClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates ...api.UpdateRolePosition) (roles []*api.Role, rErr restclient.RestError) { compiledRoute, err := restclient.GetRoles.Compile(nil, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, roleUpdates, &roles) if rErr == nil { @@ -537,7 +537,7 @@ func (r *restClientImpl) UpdateRolePositions(guildID api.Snowflake, roleUpdates func (r *restClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.UpdateRole.Compile(nil, guildID, roleID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -550,7 +550,7 @@ func (r *restClientImpl) DeleteRole(guildID api.Snowflake, roleID api.Snowflake) func (r *restClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.AddReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -559,7 +559,7 @@ func (r *restClientImpl) AddReaction(channelID api.Snowflake, messageID api.Snow func (r *restClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string) restclient.RestError { compiledRoute, err := restclient.RemoveOwnReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji)) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -568,7 +568,7 @@ func (r *restClientImpl) RemoveOwnReaction(channelID api.Snowflake, messageID ap func (r *restClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID api.Snowflake, emoji string, userID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.RemoveUserReaction.Compile(nil, channelID, messageID, normalizeEmoji(emoji), userID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -577,7 +577,7 @@ func (r *restClientImpl) RemoveUserReaction(channelID api.Snowflake, messageID a func (r *restClientImpl) GetGlobalCommands(applicationID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &commands) if rErr == nil { @@ -592,7 +592,7 @@ func (r *restClientImpl) GetGlobalCommands(applicationID api.Snowflake) (command func (r *restClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmd) if rErr == nil { @@ -605,7 +605,7 @@ func (r *restClientImpl) GetGlobalCommand(applicationID api.Snowflake, commandID func (r *restClientImpl) CreateGlobalCommand(applicationID api.Snowflake, command api.CommandCreate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGlobalCommand.Compile(nil, applicationID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -618,7 +618,7 @@ func (r *restClientImpl) CreateGlobalCommand(applicationID api.Snowflake, comman func (r *restClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.SetGlobalCommands.Compile(nil, applicationID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands @@ -637,7 +637,7 @@ func (r *restClientImpl) SetGlobalCommands(applicationID api.Snowflake, commands func (r *restClientImpl) UpdateGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -650,7 +650,7 @@ func (r *restClientImpl) UpdateGlobalCommand(applicationID api.Snowflake, comman func (r *restClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGlobalCommand.Compile(nil, applicationID, commandID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -663,7 +663,7 @@ func (r *restClientImpl) DeleteGlobalCommand(applicationID api.Snowflake, comman func (r *restClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake) (commands []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &commands) if rErr == nil { @@ -678,7 +678,7 @@ func (r *restClientImpl) GetGuildCommands(applicationID api.Snowflake, guildID a func (r *restClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, command api.CommandCreate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.CreateGuildCommand.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -691,7 +691,7 @@ func (r *restClientImpl) CreateGuildCommand(applicationID api.Snowflake, guildID func (r *restClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID api.Snowflake, commands ...api.CommandCreate) (cmds []*api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommands.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } if len(commands) > 100 { err = api.ErrMaxCommands @@ -710,7 +710,7 @@ func (r *restClientImpl) SetGuildCommands(applicationID api.Snowflake, guildID a func (r *restClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmd) if rErr == nil { @@ -723,7 +723,7 @@ func (r *restClientImpl) GetGuildCommand(applicationID api.Snowflake, guildID ap func (r *restClientImpl) UpdateGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, command api.CommandUpdate) (cmd *api.Command, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, command, &cmd) if rErr == nil { @@ -736,7 +736,7 @@ func (r *restClientImpl) UpdateGuildCommand(applicationID api.Snowflake, guildID func (r *restClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (rErr restclient.RestError) { compiledRoute, err := restclient.DeleteGuildCommand.Compile(nil, applicationID, guildID, commandID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, nil) if rErr == nil && api.CacheStrategyNoWs(r.Disgo()) { @@ -749,7 +749,7 @@ func (r *restClientImpl) DeleteGuildCommand(applicationID api.Snowflake, guildID func (r *restClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake) (cmdsPerms []*api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmdsPerms) if rErr == nil { @@ -764,7 +764,7 @@ func (r *restClientImpl) GetGuildCommandsPermissions(applicationID api.Snowflake func (r *restClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake) (cmdPerms *api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.GetGuildCommandPermission.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, nil, &cmdPerms) if rErr == nil { @@ -777,7 +777,7 @@ func (r *restClientImpl) GetGuildCommandPermissions(applicationID api.Snowflake, func (r *restClientImpl) SetGuildCommandsPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandsPermissions ...api.SetGuildCommandPermissions) (cmdsPerms []*api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandsPermissions.Compile(nil, applicationID, guildID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, api.SetGuildCommandsPermissions(commandsPermissions), &cmdsPerms) if rErr == nil { @@ -792,7 +792,7 @@ func (r *restClientImpl) SetGuildCommandsPermissions(applicationID api.Snowflake func (r *restClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, guildID api.Snowflake, commandID api.Snowflake, commandPermissions api.SetGuildCommandPermissions) (cmdPerms *api.GuildCommandPermissions, rErr restclient.RestError) { compiledRoute, err := restclient.SetGuildCommandPermissions.Compile(nil, applicationID, guildID, commandID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } rErr = r.Do(compiledRoute, commandPermissions, &cmdPerms) if rErr == nil { @@ -805,12 +805,12 @@ func (r *restClientImpl) SetGuildCommandPermissions(applicationID api.Snowflake, func (r *restClientImpl) SendInteractionResponse(interactionID api.Snowflake, interactionToken string, interactionResponse api.InteractionResponse) restclient.RestError { compiledRoute, err := restclient.CreateInteractionResponse.Compile(nil, interactionID, interactionToken) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } body, err := interactionResponse.ToBody() if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, body, nil) @@ -820,12 +820,12 @@ func (r *restClientImpl) SendInteractionResponse(interactionID api.Snowflake, in func (r *restClientImpl) UpdateInteractionResponse(applicationID api.Snowflake, interactionToken string, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -840,7 +840,7 @@ func (r *restClientImpl) UpdateInteractionResponse(applicationID api.Snowflake, func (r *restClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, interactionToken string) restclient.RestError { compiledRoute, err := restclient.DeleteInteractionResponse.Compile(nil, applicationID, interactionToken) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } @@ -849,12 +849,12 @@ func (r *restClientImpl) DeleteInteractionResponse(applicationID api.Snowflake, func (r *restClientImpl) SendFollowupMessage(applicationID api.Snowflake, interactionToken string, messageCreate api.MessageCreate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CreateFollowupMessage.Compile(nil, applicationID, interactionToken) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageCreate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -870,12 +870,12 @@ func (r *restClientImpl) SendFollowupMessage(applicationID api.Snowflake, intera func (r *restClientImpl) UpdateFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake, messageUpdate api.MessageUpdate) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.UpdateFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } body, err := messageUpdate.ToBody() if err != nil { - return nil, restclient.NewRestError(nil, err) + return nil, restclient.NewError(nil, err) } var fullMessage *api.FullMessage @@ -891,7 +891,7 @@ func (r *restClientImpl) UpdateFollowupMessage(applicationID api.Snowflake, inte func (r *restClientImpl) DeleteFollowupMessage(applicationID api.Snowflake, interactionToken string, messageID api.Snowflake) restclient.RestError { compiledRoute, err := restclient.DeleteFollowupMessage.Compile(nil, applicationID, interactionToken, messageID) if err != nil { - return restclient.NewRestError(nil, err) + return restclient.NewError(nil, err) } return r.Do(compiledRoute, nil, nil) } From 060f8170620be7641da1c6de5e5b8857565e816f Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sun, 20 Jun 2021 16:21:56 +0200 Subject: [PATCH 43/64] added interface implementation check --- api/action_row.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/api/action_row.go b/api/action_row.go index 65dc6cec..c6d5b713 100644 --- a/api/action_row.go +++ b/api/action_row.go @@ -1,5 +1,7 @@ package api +var _ Component = (*ActionRow)(nil) + // NewActionRow creates a new ActionRow holding th provided Component(s) func NewActionRow(components ...Component) ActionRow { return ActionRow{ From f808ba30be5bd05218ce7f7e629580fa0114a584 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 22 Jun 2021 11:24:21 +0200 Subject: [PATCH 44/64] fixed rename of UserID --- api/guild.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/guild.go b/api/guild.go index 311c5209..28415486 100644 --- a/api/guild.go +++ b/api/guild.go @@ -184,7 +184,7 @@ func (g *Guild) Roles() []*Role { // SelfMember returns the Member for the current logged in User for this Guild func (g *Guild) SelfMember() *SelfMember { return &SelfMember{ - Member: g.Disgo.Cache().Member(g.ID, g.Disgo.SelfUserID()), + Member: g.Disgo.Cache().Member(g.ID, g.Disgo.ClientID()), } } From e159a1028bb5f3f987a8bf795c9dbad732a14303 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 22 Jun 2021 11:27:06 +0200 Subject: [PATCH 45/64] fixed disgo version in go.sum --- example/go.sum | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/example/go.sum b/example/go.sum index e9fca82e..daa590e9 100644 --- a/example/go.sum +++ b/example/go.sum @@ -1,9 +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/DisgoOrg/restclient v1.2.0 h1:M2GXPf5Ja+Ynt7DBTLv+TQ4iMVLQX17FRHXQ0gqAExw= -github.com/DisgoOrg/restclient v1.2.0/go.mod h1:PIhyYsT52w5T6m4LT+HTdKqY6NOIqo71Ai0rgaq9ZtM= +github.com/DisgoOrg/restclient v1.2.2 h1:75SGqqN/9lqJ3GQOpPY99f1ihZMzSXDcLNF+biDp+Pk= +github.com/DisgoOrg/restclient v1.2.2/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= @@ -25,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 671734f2387afe01752b2adc5b26e4e6ac975ee3 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 22 Jun 2021 12:01:51 +0200 Subject: [PATCH 46/64] fixed merge stuff --- api/member.go | 37 ++++++++++++++++++++++++++----------- internal/disgo_impl.go | 2 +- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/api/member.go b/api/member.go index 11dd29fb..0254e592 100644 --- a/api/member.go +++ b/api/member.go @@ -8,17 +8,32 @@ import ( // Member is a discord GuildMember type Member struct { - Disgo Disgo - GuildID Snowflake `json:"guild_id"` - User *User `json:"user"` - Nick *string `json:"nick"` - Roles []Snowflake `json:"roles,omitempty"` - JoinedAt time.Time `json:"joined_at"` - PremiumSince *time.Time `json:"premium_since,omitempty"` - Deaf *bool `json:"deaf,omitempty"` - Mute *bool `json:"mute,omitempty"` - Pending bool `json:"pending"` - Permissions *Permissions `json:"permissions,omitempty"` + Disgo Disgo + GuildID Snowflake `json:"guild_id"` + User *User `json:"user"` + Nick *string `json:"nick"` + RoleIDs []Snowflake `json:"roles,omitempty"` + JoinedAt time.Time `json:"joined_at"` + PremiumSince *time.Time `json:"premium_since,omitempty"` + Deaf *bool `json:"deaf,omitempty"` + Mute *bool `json:"mute,omitempty"` + Pending bool `json:"pending"` + ChannelPermissions *Permissions `json:"permissions,omitempty"` +} + +// Permissions returns the Permissions the Member has in the Guild +func (m *Member) Permissions() Permissions { + return GetMemberPermissions(m) +} + +// Roles return all Role(s)the Member has +func (m *Member) Roles() []*Role { + var roles []*Role + allRoles := m.Disgo.Cache().RoleCache(m.GuildID) + for _, roleID := range m.RoleIDs { + roles = append(roles, allRoles[roleID]) + } + return roles } // VoiceState returns the VoiceState for this Member from the Cache(requires CacheFlagVoiceState and GatewayIntentsGuildVoiceStates) diff --git a/internal/disgo_impl.go b/internal/disgo_impl.go index 0218438a..a2aafd0c 100644 --- a/internal/disgo_impl.go +++ b/internal/disgo_impl.go @@ -289,5 +289,5 @@ func (d *DisgoImpl) GetTemplate(code string) (*api.GuildTemplate, restclient.Res // CreateGuildFromTemplate creates an api.Guild using a api.Template code func (d *DisgoImpl) CreateGuildFromTemplate(templateCode string, createGuildFromTemplate api.CreateGuildFromTemplate) (*api.Guild, restclient.RestError) { - return d.RestClient().CreateGuildFromTemplate(templateCode, data) + return d.RestClient().CreateGuildFromTemplate(templateCode, createGuildFromTemplate) } From 336cc4b04a6097a9846cf4d73c73f6ad1a299ca8 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 22 Jun 2021 18:50:45 +0200 Subject: [PATCH 47/64] added missing docs & updatzed UpdateGuild --- api/guild.go | 44 +++++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/api/guild.go b/api/guild.go index e50062dd..3ca28b21 100644 --- a/api/guild.go +++ b/api/guild.go @@ -316,22 +316,27 @@ func (g *Guild) SetCommandPermissions(commandID Snowflake, permissions SetGuildC return g.Disgo.SetGuildCommandPermissions(g.ID, commandID, permissions) } +// GetTemplates gets a specific GuildTemplate func (g *Guild) GetTemplates() ([]*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().GetGuildTemplates(g.ID) } +// CreateTemplate creates a new GuildTemplate func (g *Guild) CreateTemplate(createGuildTemplate CreateGuildTemplate) (*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().CreateGuildTemplate(g.ID, createGuildTemplate) } +// SyncTemplate syncs the current Guild status to an existing GuildTemplate func (g *Guild) SyncTemplate(code string) (*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().SyncGuildTemplate(g.ID, code) } +// UpdateTemplate updates a specific GuildTemplate func (g *Guild) UpdateTemplate(code string, updateGuildTemplate UpdateGuildTemplate) (*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().UpdateGuildTemplate(g.ID, code, updateGuildTemplate) } +// DeleteTemplate deletes a specific GuildTemplate func (g *Guild) DeleteTemplate(code string) (*GuildTemplate, restclient.RestError) { return g.Disgo.RestClient().DeleteGuildTemplate(g.ID, code) } @@ -362,24 +367,25 @@ type CreateGuild struct { SystemChannelFlags SystemChannelFlag `json:"system_channel_flags,omitempty"` } +// UpdateGuild type UpdateGuild struct { - Name string `json:"name"` - Region *string `json:"region"` - VerificationLevel *VerificationLevel `json:"verification_level"` - DefaultMessageNotificationLevel *MessageNotifications `json:"default_message_notification_level"` - ExplicitContentFilterLevel *ExplicitContentFilterLevel `json:"explicit_content_filter_level"` - AFKChannelID *Snowflake `json:"afk_channel_id"` - AFKTimeout int `json:"afk_timeout"` - Icon *string `json:"icon"` - OwnerID Snowflake `json:"owner_id"` - Splash interface{} `json:"splash"` - DiscoverySplash interface{} `json:"discovery_splash"` - Banner interface{} `json:"banner"` - SystemChannelID *Snowflake `json:"system_channel_id"` - SystemChannelFlags *SystemChannelFlag `json:"system_channel_flags"` - RulesChannelID *Snowflake `json:"rules_channel_id"` - PublicUpdatesChannelID *Snowflake `json:"public_updates_channel_id"` - PreferredLocale *string `json:"preferred_locale"` - Features []GuildFeature `json:"features"` - Description *string `json:"description"` + Name *string `json:"name,omitempty"` + Region *string `json:"region,omitempty"` + VerificationLevel *VerificationLevel `json:"verification_level,omitempty"` + DefaultMessageNotificationLevel *MessageNotifications `json:"default_message_notification_level,omitempty"` + ExplicitContentFilterLevel *ExplicitContentFilterLevel `json:"explicit_content_filter_level,omitempty"` + AFKChannelID *Snowflake `json:"afk_channel_id,omitempty"` + AFKTimeout *int `json:"afk_timeout,omitempty"` + Icon *string `json:"icon,omitempty"` + OwnerID *Snowflake `json:"owner_id,omitempty"` + Splash []byte `json:"splash,omitempty"` + DiscoverySplash []byte `json:"discovery_splash,omitempty"` + Banner []byte `json:"banner,omitempty"` + SystemChannelID *Snowflake `json:"system_channel_id,omitempty"` + SystemChannelFlags *SystemChannelFlag `json:"system_channel_flags,omitempty"` + RulesChannelID *Snowflake `json:"rules_channel_id,omitempty"` + PublicUpdatesChannelID *Snowflake `json:"public_updates_channel_id,omitempty"` + PreferredLocale *string `json:"preferred_locale,omitempty"` + Features *[]GuildFeature `json:"features,omitempty"` + Description *string `json:"description,omitempty"` } From 82cd498c3caebc93f0fccd20f99a1e9e4a95bfe9 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Thu, 1 Jul 2021 12:39:12 +0200 Subject: [PATCH 48/64] some message refactor --- api/entity_builder.go | 2 +- api/interaction.go | 20 ++++---- api/message.go | 51 ++++++++++++++++++-- internal/entity_builder_impl.go | 47 +----------------- internal/handlers/message_create_handler.go | 6 +-- internal/handlers/message_update_handler.go | 53 +++++++++++++++++++-- internal/restclient_impl.go | 37 ++++++-------- 7 files changed, 128 insertions(+), 88 deletions(-) diff --git a/api/entity_builder.go b/api/entity_builder.go index fa51a164..a4932f3a 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -22,7 +22,7 @@ type EntityBuilder interface { CreateUser(user *User, updateCache CacheStrategy) *User - CreateMessage(message *FullMessage, updateCache CacheStrategy) *Message + CreateMessage(message *Message, updateCache CacheStrategy) *Message CreateGuild(fullGuild *FullGuild, updateCache CacheStrategy) *Guild CreateMember(guildID Snowflake, member *Member, updateCache CacheStrategy) *Member diff --git a/api/interaction.go b/api/interaction.go index 89722e62..8980397f 100644 --- a/api/interaction.go +++ b/api/interaction.go @@ -175,14 +175,14 @@ func (i *Interaction) GuildChannel() *GuildChannel { // FullInteraction is used for easier unmarshalling of different Interaction(s) type FullInteraction struct { - ID Snowflake `json:"id"` - Type InteractionType `json:"type"` - GuildID *Snowflake `json:"guild_id,omitempty"` - ChannelID *Snowflake `json:"channel_id,omitempty"` - FullMessage *FullMessage `json:"message,omitempty"` - Member *Member `json:"member,omitempty"` - User *User `json:"User,omitempty"` - Token string `json:"token"` - Version int `json:"version"` - Data json.RawMessage `json:"data,omitempty"` + ID Snowflake `json:"id"` + Type InteractionType `json:"type"` + GuildID *Snowflake `json:"guild_id,omitempty"` + ChannelID *Snowflake `json:"channel_id,omitempty"` + Message *Message `json:"message,omitempty"` + Member *Member `json:"member,omitempty"` + User *User `json:"User,omitempty"` + Token string `json:"token"` + Version int `json:"version"` + Data json.RawMessage `json:"data,omitempty"` } diff --git a/api/message.go b/api/message.go index 0294294e..758659c1 100644 --- a/api/message.go +++ b/api/message.go @@ -1,6 +1,7 @@ package api import ( + "encoding/json" "errors" "time" @@ -192,10 +193,52 @@ type Message struct { 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"` +func (m *Message) Unmarshal(data []byte) error { + var fullM struct { + *Message + UnmarshalComponents []UnmarshalComponent `json:"components,omitempty"` + } + err := json.Unmarshal(data, &fullM) + if err != nil { + return err + } + *m = *fullM.Message + for _, component := range fullM.UnmarshalComponents { + m.Components = append(m.Components, createComponent(component)) + } + return nil +} + +func createComponent(unmarshalComponent UnmarshalComponent) Component { + switch unmarshalComponent.ComponentType { + case ComponentTypeActionRow: + components := make([]Component, len(unmarshalComponent.Components)) + for i, unmarshalC := range unmarshalComponent.Components { + components[i] = createComponent(unmarshalC) + } + return &ActionRow{ + ComponentImpl: ComponentImpl{ + ComponentType: ComponentTypeActionRow, + }, + Components: components, + } + + case ComponentTypeButton: + return &Button{ + ComponentImpl: ComponentImpl{ + ComponentType: ComponentTypeButton, + }, + Style: unmarshalComponent.Style, + Label: unmarshalComponent.Label, + Emoji: unmarshalComponent.Emoji, + CustomID: unmarshalComponent.CustomID, + URL: unmarshalComponent.URL, + Disabled: unmarshalComponent.Disabled, + } + + default: + return nil + } } // MessageReference is a reference to another message diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index c7a5ba9e..fd5bb6e2 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -49,7 +49,7 @@ func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInt return &api.ButtonInteraction{ Interaction: b.createInteraction(fullInteraction, c, updateCache), - Message: b.CreateMessage(fullInteraction.FullMessage, updateCache), + Message: b.CreateMessage(fullInteraction.Message, updateCache), Data: data, } } @@ -110,45 +110,8 @@ func (b *EntityBuilderImpl) CreateUser(user *api.User, updateCache api.CacheStra return user } -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)) - for i, unmarshalC := range unmarshalComponent.Components { - components[i] = b.createComponent(unmarshalC, updateCache) - } - return &api.ActionRow{ - ComponentImpl: api.ComponentImpl{ - ComponentType: api.ComponentTypeActionRow, - }, - Components: components, - } - - case api.ComponentTypeButton: - button := &api.Button{ - ComponentImpl: api.ComponentImpl{ - ComponentType: api.ComponentTypeButton, - }, - Style: unmarshalComponent.Style, - Label: unmarshalComponent.Label, - CustomID: unmarshalComponent.CustomID, - URL: unmarshalComponent.URL, - Disabled: unmarshalComponent.Disabled, - } - if unmarshalComponent.Emoji != nil { - button.Emoji = b.CreateEmoji("", unmarshalComponent.Emoji, updateCache) - } - return button - - default: - b.Disgo().Logger().Errorf("unexpected component type %d received", unmarshalComponent.ComponentType) - return nil - } -} - // CreateMessage returns a new api.Message entity -func (b *EntityBuilderImpl) CreateMessage(fullMessage *api.FullMessage, updateCache api.CacheStrategy) *api.Message { - message := fullMessage.Message +func (b *EntityBuilderImpl) CreateMessage(message *api.Message, updateCache api.CacheStrategy) *api.Message { message.Disgo = b.Disgo() if message.Member != nil { @@ -159,12 +122,6 @@ func (b *EntityBuilderImpl) CreateMessage(fullMessage *api.FullMessage, updateCa message.Author = b.CreateUser(message.Author, updateCache) } - if fullMessage.UnmarshalComponents != nil { - for _, component := range fullMessage.UnmarshalComponents { - message.Components = append(message.Components, b.createComponent(component, updateCache)) - } - } - // TODO: should we cache mentioned users, members, etc? if updateCache(b.Disgo()) { return b.Disgo().Cache().CacheMessage(message) diff --git a/internal/handlers/message_create_handler.go b/internal/handlers/message_create_handler.go index bd2a7471..13378e53 100644 --- a/internal/handlers/message_create_handler.go +++ b/internal/handlers/message_create_handler.go @@ -15,17 +15,17 @@ func (h MessageCreateHandler) Event() api.GatewayEventType { // New constructs a new payload receiver for the raw gateway event func (h MessageCreateHandler) New() interface{} { - return &api.FullMessage{} + return &api.Message{} } // HandleGatewayEvent handles the specific raw gateway event func (h MessageCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { - fullMessage, ok := i.(*api.FullMessage) + message, ok := i.(*api.Message) if !ok { return } - message := disgo.EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyYes) + message = disgo.EntityBuilder().CreateMessage(message, api.CacheStrategyYes) genericMessageEvent := events.GenericMessageEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), diff --git a/internal/handlers/message_update_handler.go b/internal/handlers/message_update_handler.go index f3764ce4..8bbd7cde 100644 --- a/internal/handlers/message_update_handler.go +++ b/internal/handlers/message_update_handler.go @@ -1,6 +1,9 @@ package handlers -import "github.com/DisgoOrg/disgo/api" +import ( + "github.com/DisgoOrg/disgo/api" + "github.com/DisgoOrg/disgo/api/events" +) // MessageUpdateHandler handles api.GatewayEventMessageUpdate type MessageUpdateHandler struct{} @@ -12,10 +15,54 @@ func (h MessageUpdateHandler) Event() api.GatewayEventType { // New constructs a new payload receiver for the raw gateway event func (h MessageUpdateHandler) New() interface{} { - return &api.FullMessage{} + return &api.Message{} } // HandleGatewayEvent handles the specific raw gateway event func (h MessageUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { - //fullMessage, ok := i.(*api.FullMessage) + message, ok := i.(*api.Message) + if !ok { + return + } + + oldMessage := disgo.Cache().Message(message.ChannelID, message.ID) + if oldMessage != nil { + oldMessage = &*oldMessage + } + + message = disgo.EntityBuilder().CreateMessage(message, api.CacheStrategyYes) + + genericMessageEvent := events.GenericMessageEvent{ + GenericEvent: events.NewEvent(disgo, sequenceNumber), + Message: message, + } + eventManager.Dispatch(genericMessageEvent) + + eventManager.Dispatch(events.MessageUpdateEvent{ + GenericMessageEvent: genericMessageEvent, + OldMessage: oldMessage, + }) + + if message.GuildID == nil { + genericDMMessageEvent := events.GenericDMMessageEvent{ + GenericMessageEvent: genericMessageEvent, + } + eventManager.Dispatch(genericDMMessageEvent) + + eventManager.Dispatch(events.DMMessageUpdateEvent{ + GenericDMMessageEvent: genericDMMessageEvent, + OldMessage: oldMessage, + }) + } else { + genericGuildMessageEvent := events.GenericGuildMessageEvent{ + GenericMessageEvent: genericMessageEvent, + GuildID: *message.GuildID, + } + eventManager.Dispatch(genericGuildMessageEvent) + + eventManager.Dispatch(events.GuildMessageUpdateEvent{ + GenericGuildMessageEvent: genericGuildMessageEvent, + OldMessage: oldMessage, + }) + } } diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index 3e8584b3..e53fbe37 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -161,10 +161,9 @@ func (r *restClientImpl) GetMessage(channelID api.Snowflake, messageID api.Snowf return nil, restclient.NewError(nil, err) } - var fullMessage *api.FullMessage - rErr = r.Do(compiledRoute, nil, &fullMessage) + rErr = r.Do(compiledRoute, nil, &message) if rErr == nil { - message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(message, api.CacheStrategyNoWs) } return } @@ -181,10 +180,9 @@ func (r *restClientImpl) CreateMessage(channelID api.Snowflake, messageCreate ap return nil, restclient.NewError(nil, err) } - var fullMessage *api.FullMessage - rErr = r.Do(compiledRoute, body, &fullMessage) + rErr = r.Do(compiledRoute, body, &message) if rErr == nil { - message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(message, api.CacheStrategyNoWs) } return } @@ -201,10 +199,9 @@ func (r *restClientImpl) UpdateMessage(channelID api.Snowflake, messageID api.Sn return nil, restclient.NewError(nil, err) } - var fullMessage *api.FullMessage - rErr = r.Do(compiledRoute, body, &fullMessage) + rErr = r.Do(compiledRoute, body, &message) if rErr == nil { - message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(message, api.CacheStrategyNoWs) } return } @@ -239,15 +236,14 @@ func (r *restClientImpl) BulkDeleteMessages(channelID api.Snowflake, messageIDs } // CrosspostMessage lets you crosspost a api.Message in a channel with type api.ChannelTypeNews -func (r *restClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (msg *api.Message, rErr restclient.RestError) { +func (r *restClientImpl) CrosspostMessage(channelID api.Snowflake, messageID api.Snowflake) (message *api.Message, rErr restclient.RestError) { compiledRoute, err := restclient.CrosspostMessage.Compile(nil, channelID, messageID) if err != nil { return nil, restclient.NewError(nil, err) } - var fullMsg *api.FullMessage - rErr = r.Do(compiledRoute, nil, &fullMsg) + rErr = r.Do(compiledRoute, nil, &message) if rErr == nil { - msg = r.Disgo().EntityBuilder().CreateMessage(fullMsg, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(message, api.CacheStrategyNoWs) } return } @@ -828,10 +824,9 @@ func (r *restClientImpl) UpdateInteractionResponse(applicationID api.Snowflake, return nil, restclient.NewError(nil, err) } - var fullMessage *api.FullMessage - rErr = r.Do(compiledRoute, body, &fullMessage) + rErr = r.Do(compiledRoute, body, &message) if rErr == nil { - message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(message, api.CacheStrategyNoWs) } return } @@ -857,10 +852,9 @@ func (r *restClientImpl) SendFollowupMessage(applicationID api.Snowflake, intera return nil, restclient.NewError(nil, err) } - var fullMessage *api.FullMessage - rErr = r.Do(compiledRoute, body, &fullMessage) + rErr = r.Do(compiledRoute, body, &message) if rErr == nil { - message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(message, api.CacheStrategyNoWs) } return @@ -878,10 +872,9 @@ func (r *restClientImpl) UpdateFollowupMessage(applicationID api.Snowflake, inte return nil, restclient.NewError(nil, err) } - var fullMessage *api.FullMessage - rErr = r.Do(compiledRoute, body, &fullMessage) + rErr = r.Do(compiledRoute, body, &message) if rErr == nil { - message = r.Disgo().EntityBuilder().CreateMessage(fullMessage, api.CacheStrategyNoWs) + message = r.Disgo().EntityBuilder().CreateMessage(message, api.CacheStrategyNoWs) } return From 3044dcfd9665e7ea89570cdad67fcb223205b195 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Thu, 1 Jul 2021 13:15:36 +0200 Subject: [PATCH 49/64] refactored entity builder & intercation handler --- api/component.go | 8 ++-- api/dropdown.go | 24 +++++----- api/dropdown_interaction.go | 16 +++---- api/entity_builder.go | 9 ++-- api/events/interaction_events.go | 12 ++--- api/events/listener_adapter.go | 6 +-- api/message.go | 26 +++++------ example/examplebot.go | 6 +-- internal/entity_builder_impl.go | 46 ++++++++++++------- .../handlers/interaction_create_handler.go | 30 ++++++------ 10 files changed, 97 insertions(+), 86 deletions(-) diff --git a/api/component.go b/api/component.go index 0f7d512c..941f8244 100644 --- a/api/component.go +++ b/api/component.go @@ -7,7 +7,7 @@ type ComponentType int const ( ComponentTypeActionRow = iota + 1 ComponentTypeButton - ComponentTypeDropdown + ComponentTypeSelectMenu ) // Component is a general interface each Component needs to implement @@ -33,7 +33,7 @@ func (t ComponentImpl) Type() ComponentType { type UnmarshalComponent struct { ComponentType ComponentType `json:"type"` - // Button && Dropdown + // Button && SelectMenu CustomID string `json:"custom_id"` // Button @@ -46,9 +46,9 @@ type UnmarshalComponent struct { // ActionRow Components []UnmarshalComponent `json:"components"` - // Dropdown + // SelectMenu Placeholder string `json:"placeholder"` MinValues int `json:"min_values,omitempty"` MaxValues int `json:"max_values,omitempty"` - Options []DropdownOption `json:"options"` + Options []SelectMenuOption `json:"options"` } diff --git a/api/dropdown.go b/api/dropdown.go index e4dc28a1..b9a7a88d 100644 --- a/api/dropdown.go +++ b/api/dropdown.go @@ -1,9 +1,9 @@ package api -// NewDropdown builds a new Dropdown from the provided values -func NewDropdown(customID string, placeholder string, minValues int, maxValues int, options ...DropdownOption) Dropdown { - return Dropdown{ - ComponentImpl: newComponentImpl(ComponentTypeDropdown), +// NewSelectMenu builds a new SelectMenu from the provided values +func NewSelectMenu(customID string, placeholder string, minValues int, maxValues int, options ...SelectMenuOption) SelectMenu { + return SelectMenu{ + ComponentImpl: newComponentImpl(ComponentTypeSelectMenu), CustomID: customID, Placeholder: placeholder, MinValues: minValues, @@ -12,26 +12,26 @@ func NewDropdown(customID string, placeholder string, minValues int, maxValues i } } -// Dropdown is a Component which lets the User select from various options -type Dropdown struct { +// SelectMenu is a Component which lets the User select from various options +type SelectMenu struct { ComponentImpl CustomID string `json:"custom_id"` Placeholder string `json:"placeholder"` MinValues int `json:"min_values,omitempty"` MaxValues int `json:"max_values,omitempty"` - Options []DropdownOption `json:"options"` + Options []SelectMenuOption `json:"options"` } -// NewDropdownOption builds a new DropdownOption -func NewDropdownOption(label string, value string) DropdownOption { - return DropdownOption{ +// NewSelectMenuOption builds a new SelectMenuOption +func NewSelectMenuOption(label string, value string) SelectMenuOption { + return SelectMenuOption{ Label: label, Value: value, } } -// DropdownOption represents an option in a Dropdown -type DropdownOption struct { +// SelectMenuOption represents an option in a SelectMenu +type SelectMenuOption struct { Label string `json:"label"` Value string `json:"value"` Description string `json:"description,omitempty"` diff --git a/api/dropdown_interaction.go b/api/dropdown_interaction.go index d899ee39..0683f6d6 100644 --- a/api/dropdown_interaction.go +++ b/api/dropdown_interaction.go @@ -1,19 +1,19 @@ package api -// DropdownInteraction is a specific Interaction when CLicked on Dropdown(s) -type DropdownInteraction struct { +// SelectMenuInteraction is a specific Interaction when CLicked on SelectMenu(s) +type SelectMenuInteraction struct { *ComponentInteraction - Data *DropdownInteractionData `json:"data,omitempty"` + Data *SelectMenuInteractionData `json:"data,omitempty"` } -// DropdownInteractionData is the Dropdown data payload -type DropdownInteractionData struct { +// SelectMenuInteractionData is the SelectMenu data payload +type SelectMenuInteractionData struct { *ComponentInteractionData Values []string `json:"values"` } -// Dropdown returns the Dropdown which issued this DropdownInteraction. nil for ephemeral Message(s) -func (i *DropdownInteraction) Dropdown() *Dropdown { - return i.Message.DropdownByID(i.Data.CustomID) +// SelectMenu returns the SelectMenu which issued this SelectMenuInteraction. nil for ephemeral Message(s) +func (i *SelectMenuInteraction) SelectMenu() *SelectMenu { + return i.Message.SelectMenuByID(i.Data.CustomID) } diff --git a/api/entity_builder.go b/api/entity_builder.go index c611dd64..7b698c9a 100644 --- a/api/entity_builder.go +++ b/api/entity_builder.go @@ -15,10 +15,11 @@ var ( type EntityBuilder interface { Disgo() Disgo - CreateCommandInteraction(fullInteraction *FullInteraction, c chan InteractionResponse, updateCache CacheStrategy) *CommandInteraction - CreateComponentInteraction(fullInteraction *FullInteraction, c chan InteractionResponse, updateCache CacheStrategy) *ComponentInteraction - CreateButtonInteraction(fullInteraction *FullInteraction, cInteraction *ComponentInteraction) *ButtonInteraction - CreateDropdownInteraction(fullInteraction *FullInteraction, cInteraction *ComponentInteraction) *DropdownInteraction + CreateInteraction(fullInteraction *FullInteraction, c chan InteractionResponse, updateCache CacheStrategy) *Interaction + CreateCommandInteraction(fullInteraction *FullInteraction, interaction *Interaction, updateCache CacheStrategy) *CommandInteraction + CreateComponentInteraction(fullInteraction *FullInteraction, interaction *Interaction, updateCache CacheStrategy) *ComponentInteraction + CreateButtonInteraction(fullInteraction *FullInteraction, componentInteraction *ComponentInteraction) *ButtonInteraction + CreateSelectMenuInteraction(fullInteraction *FullInteraction, componentInteraction *ComponentInteraction) *SelectMenuInteraction CreateGlobalCommand(command *Command, updateCache CacheStrategy) *Command diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index cab8dd08..8f37e455 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -136,13 +136,13 @@ type ButtonClickEvent struct { ButtonInteraction *api.ButtonInteraction } -// DropdownSubmitEvent indicates that a api.Dropdown was submitted -type DropdownSubmitEvent struct { +// SelectMenuSubmitEvent indicates that a api.SelectMenu was submitted +type SelectMenuSubmitEvent struct { GenericComponentEvent - DropdownInteraction *api.DropdownInteraction + SelectMenuInteraction *api.SelectMenuInteraction } -// Values returns the submitted values from the api.Dropdown -func (e *DropdownSubmitEvent) Values() []string { - return e.DropdownInteraction.Data.Values +// Values returns the submitted values from the api.SelectMenu +func (e *SelectMenuSubmitEvent) Values() []string { + return e.SelectMenuInteraction.Data.Values } diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index 978f43e6..60a32c2d 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -132,7 +132,7 @@ type ListenerAdapter struct { OnCommand func(event CommandEvent) OnGenericComponentEvent func(event GenericComponentEvent) OnButtonClick func(event ButtonClickEvent) - OnDropdownSubmit func(event DropdownSubmitEvent) + OnSelectMenuSubmit func(event SelectMenuSubmitEvent) // api.Message Events OnGenericMessageEvent func(event GenericMessageEvent) @@ -545,8 +545,8 @@ func (l ListenerAdapter) OnEvent(event interface{}) { if listener := l.OnButtonClick; listener != nil { listener(e) } - case DropdownSubmitEvent: - if listener := l.OnDropdownSubmit; listener != nil { + case SelectMenuSubmitEvent: + if listener := l.OnSelectMenuSubmit; listener != nil { listener(e) } diff --git a/api/message.go b/api/message.go index 840353d7..5f25cb1c 100644 --- a/api/message.go +++ b/api/message.go @@ -307,7 +307,7 @@ func (m *Message) Reply(message MessageCreate) (*Message, restclient.RestError) return m.Disgo.RestClient().CreateMessage(m.ChannelID, message) } -// ComponentByID returns the first Button or Dropdown with the specific customID +// ComponentByID returns the first Button or SelectMenu with the specific customID func (m *Message) ComponentByID(customID string) Component { for _, actionRow := range m.ActionRows() { for _, component := range actionRow.Components { @@ -316,7 +316,7 @@ func (m *Message) ComponentByID(customID string) Component { if c.CustomID == customID { return c } - case Dropdown: + case SelectMenu: if c.CustomID == customID { return c } @@ -362,24 +362,24 @@ func (m *Message) ButtonByID(customID string) *Button { return nil } -// Dropdowns returns all Dropdown(s) from this Message -func (m *Message) Dropdowns() []Dropdown { - var dropdowns []Dropdown +// SelectMenus returns all SelectMenu(s) from this Message +func (m *Message) SelectMenus() []SelectMenu { + var selectMenus []SelectMenu for _, actionRow := range m.ActionRows() { for _, component := range actionRow.Components { - if dropdown, ok := component.(Dropdown); ok { - dropdowns = append(dropdowns, dropdown) + if selectMenu, ok := component.(SelectMenu); ok { + selectMenus = append(selectMenus, selectMenu) } } } - return dropdowns + return selectMenus } -// DropdownByID returns a Dropdown with the specific customID from this Message -func (m *Message) DropdownByID(customID string) *Dropdown { - for _, dropdown := range m.Dropdowns() { - if dropdown.CustomID == customID { - return &dropdown +// SelectMenuByID returns a SelectMenu with the specific customID from this Message +func (m *Message) SelectMenuByID(customID string) *SelectMenu { + for _, selectMenu := range m.SelectMenus() { + if selectMenu.CustomID == customID { + return &selectMenu } } return nil diff --git a/example/examplebot.go b/example/examplebot.go index 8973edf1..163221e1 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -47,7 +47,7 @@ func main() { OnGuildMessageCreate: messageListener, OnCommand: commandListener, OnButtonClick: buttonClickListener, - OnDropdownSubmit: dropdownSubmitListener, + OnSelectMenuSubmit: selectMenuSubmitListener, }). Build() if err != nil { @@ -209,7 +209,7 @@ func buttonClickListener(event events.ButtonClickEvent) { } } -func dropdownSubmitListener(event events.DropdownSubmitEvent) { +func selectMenuSubmitListener(event events.SelectMenuSubmitEvent) { switch event.CustomID() { case "test3": if err := event.DeferEdit(); err != nil { @@ -295,7 +295,7 @@ func commandListener(event events.CommandEvent) { api.NewPrimaryButton("test4", "test4", nil, false), ), api.NewActionRow( - api.NewDropdown("test3", "test", 1, 1, api.NewDropdownOption("test1", "1"), api.NewDropdownOption("test2", "2"), api.NewDropdownOption("test3", "3")), + api.NewSelectMenu("test3", "test", 1, 1, api.NewSelectMenuOption("test1", "1"), api.NewSelectMenuOption("test2", "2"), api.NewSelectMenuOption("test3", "3")), ), ). Build(), diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 3457bad0..45962855 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,9 +43,12 @@ func (b EntityBuilderImpl) createInteraction(fullInteraction *api.FullInteractio } // 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, interaction *api.Interaction, updateCache api.CacheStrategy) *api.CommandInteraction { var data *api.CommandInteractionData - _ = json.Unmarshal(fullInteraction.Data, &data) + err := json.Unmarshal(fullInteraction.Data, &data) + if err != nil { + b.Disgo().Logger().Errorf("error while unmarshalling api.CommandInteractionData: %s", err) + } if data.Resolved != nil { resolved := data.Resolved @@ -75,19 +78,22 @@ func (b *EntityBuilderImpl) CreateCommandInteraction(fullInteraction *api.FullIn } return &api.CommandInteraction{ - Interaction: b.createInteraction(fullInteraction, c, updateCache), + Interaction: interaction, Data: data, } } // CreateComponentInteraction creates a api.ComponentInteraction from the api.FullInteraction response -func (b *EntityBuilderImpl) CreateComponentInteraction(fullInteraction *api.FullInteraction, c chan api.InteractionResponse, updateCache api.CacheStrategy) *api.ComponentInteraction { +func (b *EntityBuilderImpl) CreateComponentInteraction(fullInteraction *api.FullInteraction, interaction *api.Interaction, updateCache api.CacheStrategy) *api.ComponentInteraction { var data *api.ComponentInteractionData - _ = json.Unmarshal(fullInteraction.Data, &data) + err := json.Unmarshal(fullInteraction.Data, &data) + if err != nil { + b.Disgo().Logger().Errorf("error while unmarshalling api.ComponentInteractionData: %s", err) + } return &api.ComponentInteraction{ - Interaction: b.createInteraction(fullInteraction, c, updateCache), - Message: b.CreateMessage(fullInteraction.FullMessage, updateCache), + Interaction: interaction, + Message: b.CreateMessage(fullInteraction.Message, updateCache), Data: &api.ComponentInteractionData{ ComponentType: data.ComponentType, CustomID: data.CustomID, @@ -96,23 +102,29 @@ func (b *EntityBuilderImpl) CreateComponentInteraction(fullInteraction *api.Full } // CreateButtonInteraction creates a api.ButtonInteraction from the api.FullInteraction response -func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInteraction, cInteraction *api.ComponentInteraction) *api.ButtonInteraction { +func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInteraction, componentInteraction *api.ComponentInteraction) *api.ButtonInteraction { var data *api.ButtonInteractionData - _ = json.Unmarshal(fullInteraction.Data, &data) + err := json.Unmarshal(fullInteraction.Data, &data) + if err != nil { + b.Disgo().Logger().Errorf("error while unmarshalling api.ButtonInteractionData: %s", err) + } return &api.ButtonInteraction{ - ComponentInteraction: cInteraction, + ComponentInteraction: componentInteraction, Data: data, } } -// CreateDropdownInteraction creates a api.DropdownInteraction from the full interaction response -func (b *EntityBuilderImpl) CreateDropdownInteraction(fullInteraction *api.FullInteraction, cInteraction *api.ComponentInteraction) *api.DropdownInteraction { - var data *api.DropdownInteractionData - _ = json.Unmarshal(fullInteraction.Data, &data) +// CreateSelectMenuInteraction creates a api.SelectMenuInteraction from the full interaction response +func (b *EntityBuilderImpl) CreateSelectMenuInteraction(fullInteraction *api.FullInteraction, componentInteraction *api.ComponentInteraction) *api.SelectMenuInteraction { + var data *api.SelectMenuInteractionData + err := json.Unmarshal(fullInteraction.Data, &data) + if err != nil { + b.Disgo().Logger().Errorf("error while unmarshalling api.SelectMenuInteractionData: %s", err) + } - return &api.DropdownInteraction{ - ComponentInteraction: cInteraction, + return &api.SelectMenuInteraction{ + ComponentInteraction: componentInteraction, Data: data, } } diff --git a/internal/handlers/interaction_create_handler.go b/internal/handlers/interaction_create_handler.go index 54980f27..c3ccdc16 100644 --- a/internal/handlers/interaction_create_handler.go +++ b/internal/handlers/interaction_create_handler.go @@ -28,18 +28,19 @@ func (h InteractionCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManag } func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, fullInteraction *api.FullInteraction, c chan api.InteractionResponse) { + interaction := disgo.EntityBuilder().CreateInteraction(fullInteraction, c, api.CacheStrategyYes) + genericInteractionEvent := events.GenericInteractionEvent{ GenericEvent: events.NewEvent(disgo, sequenceNumber), + Interaction: interaction, } + eventManager.Dispatch(genericInteractionEvent) switch fullInteraction.Type { case api.InteractionTypeCommand: - interaction := disgo.EntityBuilder().CreateCommandInteraction(fullInteraction, c, api.CacheStrategyYes) - - genericInteractionEvent.Interaction = interaction.Interaction - eventManager.Dispatch(genericInteractionEvent) + commandInteraction := disgo.EntityBuilder().CreateCommandInteraction(fullInteraction, interaction, api.CacheStrategyYes) - options := interaction.Data.Options + options := commandInteraction.Data.Options var subCommandName *string var subCommandGroupName *string if len(options) == 1 { @@ -58,7 +59,7 @@ func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceN var newOptions []*api.Option for _, optionData := range options { newOptions = append(newOptions, &api.Option{ - Resolved: interaction.Data.Resolved, + Resolved: commandInteraction.Data.Resolved, Name: optionData.Name, Type: optionData.Type, Value: optionData.Value, @@ -67,19 +68,16 @@ func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceN eventManager.Dispatch(events.CommandEvent{ GenericInteractionEvent: genericInteractionEvent, - CommandInteraction: interaction, - CommandID: interaction.Data.ID, - CommandName: interaction.Data.Name, + CommandInteraction: commandInteraction, + CommandID: commandInteraction.Data.ID, + CommandName: commandInteraction.Data.Name, SubCommandName: subCommandName, SubCommandGroupName: subCommandGroupName, Options: newOptions, }) case api.InteractionTypeComponent: - componentInteraction := disgo.EntityBuilder().CreateComponentInteraction(fullInteraction, c, api.CacheStrategyYes) - - genericInteractionEvent.Interaction = componentInteraction.Interaction - eventManager.Dispatch(genericInteractionEvent) + componentInteraction := disgo.EntityBuilder().CreateComponentInteraction(fullInteraction, interaction, api.CacheStrategyYes) genericComponentEvent := events.GenericComponentEvent{ GenericInteractionEvent: genericInteractionEvent, @@ -94,10 +92,10 @@ func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceN ButtonInteraction: disgo.EntityBuilder().CreateButtonInteraction(fullInteraction, componentInteraction), }) - case api.ComponentTypeDropdown: - eventManager.Dispatch(events.DropdownSubmitEvent{ + case api.ComponentTypeSelectMenu: + eventManager.Dispatch(events.SelectMenuSubmitEvent{ GenericComponentEvent: genericComponentEvent, - DropdownInteraction: disgo.EntityBuilder().CreateDropdownInteraction(fullInteraction, componentInteraction), + SelectMenuInteraction: disgo.EntityBuilder().CreateSelectMenuInteraction(fullInteraction, componentInteraction), }) } From 4018af7a707e82a5e149de2bdb8570c519bf373d Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Thu, 1 Jul 2021 19:21:40 +0200 Subject: [PATCH 50/64] fixed user being nil --- internal/entity_builder_impl.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index fd5bb6e2..416f7b24 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -39,6 +39,9 @@ func (b EntityBuilderImpl) createInteraction(fullInteraction *api.FullInteractio if fullInteraction.User != nil { interaction.User = b.CreateUser(fullInteraction.User, updateCache) } + if fullInteraction.User == nil && fullInteraction.Member != nil { + interaction.User = interaction.Member.User + } return interaction } From 3641b35717e00114f12a98d66ed1e0112c457caf Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 2 Jul 2021 03:20:20 +0200 Subject: [PATCH 51/64] added some convenient methods to actoin row, button & select menu --- api/action_row.go | 41 ++++++ api/button.go | 70 ++++++++-- api/component.go | 8 +- api/dropdown.go | 40 ------ api/select_menu.go | 125 ++++++++++++++++++ ...eraction.go => select_menu_interaction.go} | 0 example/examplebot.go | 8 +- 7 files changed, 233 insertions(+), 59 deletions(-) delete mode 100644 api/dropdown.go create mode 100644 api/select_menu.go rename api/{dropdown_interaction.go => select_menu_interaction.go} (100%) diff --git a/api/action_row.go b/api/action_row.go index c6d5b713..ac5e7bf4 100644 --- a/api/action_row.go +++ b/api/action_row.go @@ -15,3 +15,44 @@ type ActionRow struct { ComponentImpl Components []Component `json:"components"` } + +// SetComponents returns a new ActionRow with the provided Component(s) +func (r ActionRow) SetComponents(components ...Component) ActionRow { + r.Components = components + return r +} + +// SetComponent returns a new ActionRow with the Component which has the customID replaced +func (r ActionRow) SetComponent(customID string, component Component) ActionRow { + for i, c := range r.Components { + switch com := c.(type) { + case Button: + if com.CustomID == customID { + r.Components[i] = component + break + } + case SelectMenu: + if com.CustomID == customID { + r.Components[i] = component + break + } + default: + continue + } + } + return r +} + +// AddComponents returns a new ActionRow with the provided Component(s) added +func (r ActionRow) AddComponents(components ...Component) ActionRow { + r.Components = append(r.Components, components...) + return r +} + +// RemoveComponent returns a new ActionRow with the provided Component at the index removed +func (r ActionRow) RemoveComponent(index int) ActionRow { + if len(r.Components) > index { + r.Components = append(r.Components[:index], r.Components[index+1:]...) + } + return r +} diff --git a/api/button.go b/api/button.go index 8ccf5261..7e453eff 100644 --- a/api/button.go +++ b/api/button.go @@ -13,7 +13,7 @@ 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, emoji *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, @@ -26,37 +26,85 @@ 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, emoji *Emoji, disabled bool) Button { - return NewButton(ButtonStylePrimary, &label, customID, "", emoji, disabled) +func NewPrimaryButton(label string, customID string, emoji *Emoji) Button { + return NewButton(ButtonStylePrimary, label, customID, "", emoji, false) } // NewSecondaryButton creates a new Button with ButtonStyleSecondary & the provided parameters -func NewSecondaryButton(label string, customID string, emoji *Emoji, disabled bool) Button { - return NewButton(ButtonStyleSecondary, &label, customID, "", emoji, disabled) +func NewSecondaryButton(label string, customID string, emoji *Emoji) Button { + return NewButton(ButtonStyleSecondary, label, customID, "", emoji, false) } // NewSuccessButton creates a new Button with ButtonStyleSuccess & the provided parameters -func NewSuccessButton(label string, customID string, emoji *Emoji, disabled bool) Button { - return NewButton(ButtonStyleSuccess, &label, customID, "", emoji, disabled) +func NewSuccessButton(label string, customID string, emoji *Emoji) Button { + return NewButton(ButtonStyleSuccess, label, customID, "", emoji, false) } // NewDangerButton creates a new Button with ButtonStyleDanger & the provided parameters -func NewDangerButton(label string, customID string, emoji *Emoji, disabled bool) Button { - return NewButton(ButtonStyleDanger, &label, customID, "", emoji, disabled) +func NewDangerButton(label string, customID string, emoji *Emoji) Button { + return NewButton(ButtonStyleDanger, label, customID, "", emoji, false) } // NewLinkButton creates a new link Button with ButtonStyleLink & the provided parameters func NewLinkButton(label string, url string, emoji *Emoji, disabled bool) Button { - return NewButton(ButtonStyleLink, &label, "", url, emoji, disabled) + 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 type Button struct { ComponentImpl Style ButtonStyle `json:"style,omitempty"` - Label *string `json:"label,omitempty"` + Label string `json:"label,omitempty"` Emoji *Emoji `json:"emoji,omitempty"` CustomID string `json:"custom_id,omitempty"` URL string `json:"url,omitempty"` Disabled bool `json:"disabled,omitempty"` } + +// AsDisabled returns a new Button but disabled +func (b Button) AsDisabled() Button { + b.Disabled = true + return b +} + +// AsEnabled returns a new Button but enabled +func (b Button) AsEnabled() Button { + b.Disabled = true + return b +} + +// WithDisabled returns a new Button but disabled/enabled +func (b Button) WithDisabled(disabled bool) Button { + b.Disabled = disabled + return b +} + +// WithEmoji returns a new Button with the provided Emoji +func (b Button) WithEmoji(emoji *Emoji) Button { + b.Emoji = emoji + return b +} + +// WithCustomID returns a new Button with the provided custom id +func (b Button) WithCustomID(customID string) Button { + b.CustomID = customID + return b +} + +// WithStyle returns a new Button with the provided style +func (b Button) WithStyle(style ButtonStyle) Button { + b.Style = style + return b +} + +// WithLabel returns a new Button with the provided label +func (b Button) WithLabel(label string) Button { + b.Label = label + return b +} + +// WithURL returns a new Button with the provided url +func (b Button) WithURL(url string) Button { + b.URL = url + return b +} diff --git a/api/component.go b/api/component.go index 941f8244..19473236 100644 --- a/api/component.go +++ b/api/component.go @@ -38,7 +38,7 @@ type UnmarshalComponent struct { // Button Style ButtonStyle `json:"style"` - Label *string `json:"label"` + Label string `json:"label"` Emoji *Emoji `json:"emoji"` URL string `json:"url"` Disabled bool `json:"disabled"` @@ -47,8 +47,8 @@ type UnmarshalComponent struct { Components []UnmarshalComponent `json:"components"` // SelectMenu - Placeholder string `json:"placeholder"` - MinValues int `json:"min_values,omitempty"` - MaxValues int `json:"max_values,omitempty"` + Placeholder string `json:"placeholder"` + MinValues int `json:"min_values,omitempty"` + MaxValues int `json:"max_values,omitempty"` Options []SelectMenuOption `json:"options"` } diff --git a/api/dropdown.go b/api/dropdown.go deleted file mode 100644 index b9a7a88d..00000000 --- a/api/dropdown.go +++ /dev/null @@ -1,40 +0,0 @@ -package api - -// NewSelectMenu builds a new SelectMenu from the provided values -func NewSelectMenu(customID string, placeholder string, minValues int, maxValues int, options ...SelectMenuOption) SelectMenu { - return SelectMenu{ - ComponentImpl: newComponentImpl(ComponentTypeSelectMenu), - CustomID: customID, - Placeholder: placeholder, - MinValues: minValues, - MaxValues: maxValues, - Options: options, - } -} - -// SelectMenu is a Component which lets the User select from various options -type SelectMenu struct { - ComponentImpl - CustomID string `json:"custom_id"` - Placeholder string `json:"placeholder"` - MinValues int `json:"min_values,omitempty"` - MaxValues int `json:"max_values,omitempty"` - Options []SelectMenuOption `json:"options"` -} - -// NewSelectMenuOption builds a new SelectMenuOption -func NewSelectMenuOption(label string, value string) SelectMenuOption { - return SelectMenuOption{ - Label: label, - Value: value, - } -} - -// SelectMenuOption represents an option in a SelectMenu -type SelectMenuOption struct { - Label string `json:"label"` - Value string `json:"value"` - Description string `json:"description,omitempty"` - Default bool `json:"default"` - Emoji *Emoji `json:"emoji"` -} diff --git a/api/select_menu.go b/api/select_menu.go new file mode 100644 index 00000000..e119ce9e --- /dev/null +++ b/api/select_menu.go @@ -0,0 +1,125 @@ +package api + +// NewSelectMenu builds a new SelectMenu from the provided values +func NewSelectMenu(customID string, placeholder string, minValues int, maxValues int, options ...SelectOption) SelectMenu { + return SelectMenu{ + ComponentImpl: newComponentImpl(ComponentTypeSelectMenu), + CustomID: customID, + Placeholder: placeholder, + MinValues: minValues, + MaxValues: maxValues, + Options: options, + } +} + +// SelectMenu is a Component which lets the User select from various options +type SelectMenu struct { + ComponentImpl + CustomID string `json:"custom_id"` + Placeholder string `json:"placeholder"` + MinValues int `json:"min_values,omitempty"` + MaxValues int `json:"max_values,omitempty"` + Options []SelectOption `json:"options"` +} + +// WithCustomID returns a new SelectMenu with the provided customID +func (m SelectMenu) WithCustomID(customID string) SelectMenu { + m.CustomID = customID + return m +} + +// WithPlaceholder returns a new SelectMenu with the provided placeholder +func (m SelectMenu) WithPlaceholder(placeholder string) SelectMenu { + m.Placeholder = placeholder + return m +} + +// WithMinValues returns a new SelectMenu with the provided minValue +func (m SelectMenu) WithMinValues(minValue int) SelectMenu { + m.MinValues = minValue + return m +} + +// WithMaxValues returns a new SelectMenu with the provided maxValue +func (m SelectMenu) WithMaxValues(maxValue int) SelectMenu { + m.MaxValues = maxValue + return m +} + +// SetOptions returns a new SelectMenu with the provided SelectOption(s) +func (m SelectMenu) SetOptions(options ...SelectOption) SelectMenu { + m.Options = options + return m +} + +// AddOptions returns a new SelectMenu with the provided SelectOption(s) added +func (m SelectMenu) AddOptions(options ...SelectOption) SelectMenu { + m.Options = append(m.Options, options...) + return m +} + +// SetOption returns a new SelectMenu with the SelectOption which has the value replaced +func (m SelectMenu) SetOption(value string, option SelectOption) SelectMenu { + for i, o := range m.Options { + if o.Value == value { + m.Options[i] = option + break + } + } + return m +} + +// RemoveOption returns a new SelectMenu with the provided SelectOption at the index removed +func (m SelectMenu) RemoveOption(index int) SelectMenu { + if len(m.Options) > index { + m.Options = append(m.Options[:index], m.Options[index+1:]...) + } + return m +} + +// NewSelectOption builds a new SelectOption +func NewSelectOption(label string, value string) SelectOption { + return SelectOption{ + Label: label, + Value: value, + } +} + +// SelectOption represents an option in a SelectMenu +type SelectOption struct { + Label string `json:"label"` + Value string `json:"value"` + Description string `json:"description,omitempty"` + Default bool `json:"default,omitempty"` + Emoji *Emoji `json:"emoji,omitempty"` +} + +// WithLabel returns a new SelectOption with the provided label +func (o SelectOption) WithLabel(label string) SelectOption { + o.Label = label + return o +} + +// WithValue returns a new SelectOption with the provided value +func (o SelectOption) WithValue(value string) SelectOption { + o.Value = value + return o +} + +// WithDescription returns a new SelectOption with the provided description +func (o SelectOption) WithDescription(description string) SelectOption { + o.Description = description + return o +} + +// WithDefault returns a new SelectOption as default/non-default +func (o SelectOption) WithDefault(defaultOption bool) SelectOption { + o.Default = defaultOption + return o +} + +// WithEmoji returns a new SelectOption with the provided Emoji +func (o SelectOption) WithEmoji(emoji *Emoji) SelectOption { + o.Emoji = emoji + return o +} diff --git a/api/dropdown_interaction.go b/api/select_menu_interaction.go similarity index 100% rename from api/dropdown_interaction.go rename to api/select_menu_interaction.go diff --git a/example/examplebot.go b/example/examplebot.go index 163221e1..951e707e 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -289,10 +289,10 @@ func commandListener(event events.CommandEvent) { AddFile("gopher.png", reader). SetComponents( api.NewActionRow( - api.NewPrimaryButton("test1", "test1", nil, false), - api.NewPrimaryButton("test2", "test2", nil, false), - api.NewPrimaryButton("test3", "test3", nil, false), - api.NewPrimaryButton("test4", "test4", nil, false), + api.NewPrimaryButton("test1", "test1", nil), + api.NewPrimaryButton("test2", "test2", nil), + api.NewPrimaryButton("test3", "test3", nil), + api.NewPrimaryButton("test4", "test4", nil), ), api.NewActionRow( api.NewSelectMenu("test3", "test", 1, 1, api.NewSelectMenuOption("test1", "1"), api.NewSelectMenuOption("test2", "2"), api.NewSelectMenuOption("test3", "3")), From 10ec49d0d6150ceb0182156f4488155eb7ef46ef Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 2 Jul 2021 03:22:17 +0200 Subject: [PATCH 52/64] added missing comments --- api/guild.go | 1 + api/message.go | 2 ++ internal/entity_builder_impl.go | 5 +++-- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/api/guild.go b/api/guild.go index 28415486..747833a9 100644 --- a/api/guild.go +++ b/api/guild.go @@ -342,6 +342,7 @@ type CreateGuild struct { SystemChannelFlags SystemChannelFlag `json:"system_channel_flags,omitempty"` } +// UpdateGuild is the payload used to update a Guild type UpdateGuild struct { Name string `json:"name"` Region *string `json:"region"` diff --git a/api/message.go b/api/message.go index 5f25cb1c..3272afaf 100644 --- a/api/message.go +++ b/api/message.go @@ -193,6 +193,8 @@ type Message struct { LastUpdated *time.Time `json:"last_updated,omitempty"` } + +// Unmarshal is used to unmarshal a Message we received from discord func (m *Message) Unmarshal(data []byte) error { var fullM struct { *Message diff --git a/internal/entity_builder_impl.go b/internal/entity_builder_impl.go index 378ca482..acf24f73 100644 --- a/internal/entity_builder_impl.go +++ b/internal/entity_builder_impl.go @@ -20,6 +20,7 @@ func (b *EntityBuilderImpl) Disgo() api.Disgo { return b.disgo } +// CreateInteraction creates a api.Interaction from the api.FullInteraction response func (b EntityBuilderImpl) CreateInteraction(fullInteraction *api.FullInteraction, c chan api.InteractionResponse, updateCache api.CacheStrategy) *api.Interaction { interaction := &api.Interaction{ Disgo: b.disgo, @@ -45,7 +46,7 @@ func (b EntityBuilderImpl) CreateInteraction(fullInteraction *api.FullInteractio return interaction } -// CreateCommandInteraction creates a api.CommandInteraction from the full interaction response +// CreateCommandInteraction creates a api.CommandInteraction from the api.FullInteraction response func (b *EntityBuilderImpl) CreateCommandInteraction(fullInteraction *api.FullInteraction, interaction *api.Interaction, updateCache api.CacheStrategy) *api.CommandInteraction { var data *api.CommandInteractionData err := json.Unmarshal(fullInteraction.Data, &data) @@ -118,7 +119,7 @@ func (b *EntityBuilderImpl) CreateButtonInteraction(fullInteraction *api.FullInt } } -// CreateSelectMenuInteraction creates a api.SelectMenuInteraction from the full interaction response +// CreateSelectMenuInteraction creates a api.SelectMenuInteraction from the api.FullInteraction response func (b *EntityBuilderImpl) CreateSelectMenuInteraction(fullInteraction *api.FullInteraction, componentInteraction *api.ComponentInteraction) *api.SelectMenuInteraction { var data *api.SelectMenuInteractionData err := json.Unmarshal(fullInteraction.Data, &data) From a48b6e4c4ac69289973f8c3495f83185fb75b43d Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 2 Jul 2021 03:25:00 +0200 Subject: [PATCH 53/64] fixed renamed stuff --- api/component.go | 8 ++++---- example/examplebot.go | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/api/component.go b/api/component.go index 19473236..3cdef7b4 100644 --- a/api/component.go +++ b/api/component.go @@ -47,8 +47,8 @@ type UnmarshalComponent struct { Components []UnmarshalComponent `json:"components"` // SelectMenu - Placeholder string `json:"placeholder"` - MinValues int `json:"min_values,omitempty"` - MaxValues int `json:"max_values,omitempty"` - Options []SelectMenuOption `json:"options"` + Placeholder string `json:"placeholder"` + MinValues int `json:"min_values,omitempty"` + MaxValues int `json:"max_values,omitempty"` + Options []SelectOption `json:"options"` } diff --git a/example/examplebot.go b/example/examplebot.go index 951e707e..357d1b4b 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -295,7 +295,7 @@ func commandListener(event events.CommandEvent) { api.NewPrimaryButton("test4", "test4", nil), ), api.NewActionRow( - api.NewSelectMenu("test3", "test", 1, 1, api.NewSelectMenuOption("test1", "1"), api.NewSelectMenuOption("test2", "2"), api.NewSelectMenuOption("test3", "3")), + api.NewSelectMenu("test3", "test", 1, 1, api.NewSelectOption("test1", "1"), api.NewSelectOption("test2", "2"), api.NewSelectOption("test3", "3")), ), ). Build(), From 76cff18efcda9791b6f5e5da5941b6668f085367 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Sat, 3 Jul 2021 13:34:11 +0100 Subject: [PATCH 54/64] Update guild_delete_handler.go --- internal/handlers/guild_delete_handler.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/internal/handlers/guild_delete_handler.go b/internal/handlers/guild_delete_handler.go index f33061ad..27e1cf3f 100644 --- a/internal/handlers/guild_delete_handler.go +++ b/internal/handlers/guild_delete_handler.go @@ -35,7 +35,10 @@ func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api if guild.Unavailable { // set guild to unavailable for now - disgo.Cache().Guild(guild.ID).Unavailable = true + g := disgo.Cache().Guild(guild.ID) + if g != nil { + g.Unavailable = true + } eventManager.Dispatch(events.GuildUnavailableEvent{ GenericGuildEvent: genericGuildEvent, From c0f01880b988971e5f721bda3f527f09be3a7246 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 3 Jul 2021 16:28:20 +0200 Subject: [PATCH 55/64] fixed unmarshalling of components --- api/message.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/api/message.go b/api/message.go index 3272afaf..fb39b440 100644 --- a/api/message.go +++ b/api/message.go @@ -193,19 +193,18 @@ type Message struct { LastUpdated *time.Time `json:"last_updated,omitempty"` } - // Unmarshal is used to unmarshal a Message we received from discord func (m *Message) Unmarshal(data []byte) error { var fullM struct { + Components []UnmarshalComponent `json:"components,omitempty"` *Message - UnmarshalComponents []UnmarshalComponent `json:"components,omitempty"` } err := json.Unmarshal(data, &fullM) if err != nil { return err } *m = *fullM.Message - for _, component := range fullM.UnmarshalComponents { + for _, component := range fullM.Components { m.Components = append(m.Components, createComponent(component)) } return nil @@ -218,7 +217,7 @@ func createComponent(unmarshalComponent UnmarshalComponent) Component { for i, unmarshalC := range unmarshalComponent.Components { components[i] = createComponent(unmarshalC) } - return &ActionRow{ + return ActionRow{ ComponentImpl: ComponentImpl{ ComponentType: ComponentTypeActionRow, }, @@ -226,7 +225,7 @@ func createComponent(unmarshalComponent UnmarshalComponent) Component { } case ComponentTypeButton: - return &Button{ + return Button{ ComponentImpl: ComponentImpl{ ComponentType: ComponentTypeButton, }, From 81425563b29b3583a4c83c150cb2a2da559afb57 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 3 Jul 2021 16:40:18 +0200 Subject: [PATCH 56/64] finally fixed components marshalling/unmarshalling --- api/message.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/api/message.go b/api/message.go index fb39b440..62da363c 100644 --- a/api/message.go +++ b/api/message.go @@ -169,7 +169,7 @@ type Message struct { Attachments []Attachment `json:"attachments"` TTS bool `json:"tts"` Embeds []Embed `json:"embeds,omitempty"` - Components []Component `json:"components,omitempty"` + Components []Component `json:"-"` CreatedAt time.Time `json:"timestamp"` Mentions []interface{} `json:"mentions"` MentionEveryone bool `json:"mention_everyone"` @@ -196,8 +196,8 @@ type Message struct { // Unmarshal is used to unmarshal a Message we received from discord func (m *Message) Unmarshal(data []byte) error { var fullM struct { - Components []UnmarshalComponent `json:"components,omitempty"` *Message + Components []UnmarshalComponent `json:"components,omitempty"` } err := json.Unmarshal(data, &fullM) if err != nil { @@ -210,6 +210,23 @@ func (m *Message) Unmarshal(data []byte) error { return nil } +// Marshal is used to marshal a Message we send to discord +func (m *Message) Marshal() ([]byte, error) { + fullM := struct { + *Message + Components []Component `json:"components,omitempty"` + }{ + Message: m, + Components: m.Components, + } + fullM.Message = m + data, err := json.Marshal(fullM) + if err != nil { + return nil, err + } + return data, nil +} + func createComponent(unmarshalComponent UnmarshalComponent) Component { switch unmarshalComponent.ComponentType { case ComponentTypeActionRow: From 5195a2ac58c1665d197582358a9db8db1f87b5f8 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Sat, 3 Jul 2021 20:57:51 +0200 Subject: [PATCH 57/64] added convient methods to interactions & interaction events --- api/button_interaction.go | 10 +++---- api/component_interaction.go | 27 +++++++++++++----- api/events/interaction_events.go | 33 +++++++++++++++++++--- api/events/listener_adapter.go | 2 +- api/message.go | 47 ++++++++++++++++++++++++-------- api/select_menu_interaction.go | 36 ++++++++++++++++++++---- example/examplebot.go | 2 +- 7 files changed, 121 insertions(+), 36 deletions(-) diff --git a/api/button_interaction.go b/api/button_interaction.go index 3c69cf03..18da06c7 100644 --- a/api/button_interaction.go +++ b/api/button_interaction.go @@ -6,12 +6,12 @@ type ButtonInteraction struct { Data *ButtonInteractionData `json:"data,omitempty"` } +// Button returns the Button which issued this ButtonInteraction. nil for ephemeral Message(s) +func (i *ButtonInteraction) Button() *Button { + return i.Message.ButtonByID(i.CustomID()) +} + // ButtonInteractionData is the Button data payload type ButtonInteractionData struct { *ComponentInteractionData } - -// Button returns the Button which issued this ButtonInteraction. nil for ephemeral Message(s) -func (i *ButtonInteraction) Button() *Button { - return i.Message.ButtonByID(i.Data.CustomID) -} diff --git a/api/component_interaction.go b/api/component_interaction.go index 7ce52cfb..d298419c 100644 --- a/api/component_interaction.go +++ b/api/component_interaction.go @@ -7,12 +7,6 @@ type ComponentInteraction struct { Data *ComponentInteractionData `json:"data,omitempty"` } -// ComponentInteractionData is the Component data payload -type ComponentInteractionData struct { - CustomID string `json:"custom_id"` - ComponentType ComponentType `json:"component_type"` -} - // DeferEdit replies to the api.ComponentInteraction with api.InteractionResponseTypeDeferredUpdateMessage and cancels the loading state func (i *ComponentInteraction) DeferEdit() error { return i.Respond(InteractionResponseTypeDeferredUpdateMessage, nil) @@ -23,7 +17,26 @@ func (i *ComponentInteraction) Edit(messageUpdate MessageUpdate) error { return i.Respond(InteractionResponseTypeUpdateMessage, messageUpdate) } +// CustomID returns the Custom ID of the ComponentInteraction +func (i *ComponentInteraction) CustomID() string { + return i.Data.CustomID +} + +// ComponentType returns the ComponentType of a Component +func (i *ComponentInteraction) ComponentType() ComponentType { + return i.Data.ComponentType +} + // Component returns the Component which issued this ComponentInteraction. nil for ephemeral Message(s) func (i *ComponentInteraction) Component() Component { - return i.Message.ComponentByID(i.Data.CustomID) + if i.Message.IsEphemeral() { + return nil + } + return i.Message.ComponentByID(i.CustomID()) +} + +// ComponentInteractionData is the Component data payload +type ComponentInteractionData struct { + CustomID string `json:"custom_id"` + ComponentType ComponentType `json:"component_type"` } diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index 8f37e455..02dff099 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -122,12 +122,22 @@ func (e *GenericComponentEvent) Edit(messageUpdate api.MessageUpdate) error { // CustomID returns the customID from the called api.Component func (e *GenericComponentEvent) CustomID() string { - return e.ComponentInteraction.Data.CustomID + return e.ComponentInteraction.CustomID() } // ComponentType returns the api.ComponentType from the called api.Component -func (e *GenericComponentEvent) ComponentType() string { - return e.ComponentInteraction.Data.CustomID +func (e *GenericComponentEvent) ComponentType() api.ComponentType { + return e.ComponentInteraction.ComponentType() +} + +// Component returns the api.Component from the event +func (e *GenericComponentEvent) Component() api.Component { + return e.ComponentInteraction.Component() +} + +// Message returns the api.Message of a GenericComponentEvent +func (e *GenericComponentEvent) Message() *api.Message { + return e.ComponentInteraction.Message } // ButtonClickEvent indicates that a api.Button was clicked @@ -136,13 +146,28 @@ type ButtonClickEvent struct { ButtonInteraction *api.ButtonInteraction } +// Button returns the api.Button that was clicked on a ButtonClickEvent +func (e *ButtonClickEvent) Button() *api.Button { + return e.ButtonInteraction.Button() +} + // SelectMenuSubmitEvent indicates that a api.SelectMenu was submitted type SelectMenuSubmitEvent struct { GenericComponentEvent SelectMenuInteraction *api.SelectMenuInteraction } +// SelectMenu returns the api.SelectMenu of a SelectMenuSubmitEvent +func (e *SelectMenuSubmitEvent) SelectMenu() *api.SelectMenu { + return e.SelectMenuInteraction.SelectMenu() +} + // Values returns the submitted values from the api.SelectMenu func (e *SelectMenuSubmitEvent) Values() []string { - return e.SelectMenuInteraction.Data.Values + return e.SelectMenuInteraction.Values() +} + +// SelectedOptions returns a slice of api.SelectOption(s) that were chosen in an api.SelectMenu +func (e *SelectMenuSubmitEvent) SelectedOptions() []api.SelectOption { + return e.SelectMenuInteraction.SelectedOptions() } diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index 60a32c2d..b1a440cd 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -132,7 +132,7 @@ type ListenerAdapter struct { OnCommand func(event CommandEvent) OnGenericComponentEvent func(event GenericComponentEvent) OnButtonClick func(event ButtonClickEvent) - OnSelectMenuSubmit func(event SelectMenuSubmitEvent) + OnSelectMenuSubmit func(event SelectMenuSubmitEvent) // api.Message Events OnGenericMessageEvent func(event GenericMessageEvent) diff --git a/api/message.go b/api/message.go index 62da363c..1ad2da83 100644 --- a/api/message.go +++ b/api/message.go @@ -325,8 +325,25 @@ func (m *Message) Reply(message MessageCreate) (*Message, restclient.RestError) return m.Disgo.RestClient().CreateMessage(m.ChannelID, message) } -// ComponentByID returns the first Button or SelectMenu with the specific customID +// ActionRows returns all ActionRow(s) from this Message +func (m *Message) ActionRows() []ActionRow { + if m.IsEphemeral() { + return nil + } + var actionRows []ActionRow + for _, component := range m.Components { + if actionRow, ok := component.(ActionRow); ok { + actionRows = append(actionRows, actionRow) + } + } + return actionRows +} + +// ComponentByID returns the first Component with the specific customID func (m *Message) ComponentByID(customID string) Component { + if m.IsEphemeral() { + return nil + } for _, actionRow := range m.ActionRows() { for _, component := range actionRow.Components { switch c := component.(type) { @@ -346,19 +363,11 @@ func (m *Message) ComponentByID(customID string) Component { return nil } -// ActionRows returns all ActionRow(s) from this Message -func (m *Message) ActionRows() []ActionRow { - var actionRows []ActionRow - for _, component := range m.Components { - if actionRow, ok := component.(ActionRow); ok { - actionRows = append(actionRows, actionRow) - } - } - return actionRows -} - // Buttons returns all Button(s) from this Message func (m *Message) Buttons() []Button { + if m.IsEphemeral() { + return nil + } var buttons []Button for _, actionRow := range m.ActionRows() { for _, component := range actionRow.Components { @@ -372,6 +381,9 @@ func (m *Message) Buttons() []Button { // ButtonByID returns a Button with the specific customID from this Message func (m *Message) ButtonByID(customID string) *Button { + if m.IsEphemeral() { + return nil + } for _, button := range m.Buttons() { if button.CustomID == customID { return &button @@ -382,6 +394,9 @@ func (m *Message) ButtonByID(customID string) *Button { // SelectMenus returns all SelectMenu(s) from this Message func (m *Message) SelectMenus() []SelectMenu { + if m.IsEphemeral() { + return nil + } var selectMenus []SelectMenu for _, actionRow := range m.ActionRows() { for _, component := range actionRow.Components { @@ -395,6 +410,9 @@ func (m *Message) SelectMenus() []SelectMenu { // SelectMenuByID returns a SelectMenu with the specific customID from this Message func (m *Message) SelectMenuByID(customID string) *SelectMenu { + if m.IsEphemeral() { + return nil + } for _, selectMenu := range m.SelectMenus() { if selectMenu.CustomID == customID { return &selectMenu @@ -403,6 +421,11 @@ func (m *Message) SelectMenuByID(customID string) *SelectMenu { return nil } +// IsEphemeral returns true if the Message has MessageFlagEphemeral +func (m *Message) IsEphemeral() bool { + return m.Flags.Has(MessageFlagEphemeral) +} + // MessageReaction contains information about the reactions of a message_events type MessageReaction struct { Count int `json:"count"` diff --git a/api/select_menu_interaction.go b/api/select_menu_interaction.go index 0683f6d6..b3f242d4 100644 --- a/api/select_menu_interaction.go +++ b/api/select_menu_interaction.go @@ -6,14 +6,38 @@ type SelectMenuInteraction struct { Data *SelectMenuInteractionData `json:"data,omitempty"` } +// SelectMenu returns the SelectMenu which issued this SelectMenuInteraction. nil for ephemeral Message(s) +func (i *SelectMenuInteraction) SelectMenu() *SelectMenu { + if i.Message.IsEphemeral() { + return nil + } + return i.Message.SelectMenuByID(i.CustomID()) +} + +// Values returns the selected values +func (i *SelectMenuInteraction) Values() []string { + return i.Data.Values +} + +// SelectedOptions returns the selected SelectedOption(s) +func (i *SelectMenuInteraction) SelectedOptions() []SelectOption { + if i.Message.IsEphemeral() { + return nil + } + options := make([]SelectOption, len(i.Values())) + for ii, option := range i.SelectMenu().Options { + for _, value := range i.Values() { + if value == option.Value { + options[ii] = option + break + } + } + } + return options +} + // SelectMenuInteractionData is the SelectMenu data payload type SelectMenuInteractionData struct { *ComponentInteractionData Values []string `json:"values"` } - -// SelectMenu returns the SelectMenu which issued this SelectMenuInteraction. nil for ephemeral Message(s) -func (i *SelectMenuInteraction) SelectMenu() *SelectMenu { - return i.Message.SelectMenuByID(i.Data.CustomID) -} - diff --git a/example/examplebot.go b/example/examplebot.go index 357d1b4b..b34f27d1 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -295,7 +295,7 @@ func commandListener(event events.CommandEvent) { api.NewPrimaryButton("test4", "test4", nil), ), api.NewActionRow( - api.NewSelectMenu("test3", "test", 1, 1, api.NewSelectOption("test1", "1"), api.NewSelectOption("test2", "2"), api.NewSelectOption("test3", "3")), + api.NewSelectMenu("test3", "test", 0, 1, api.NewSelectOption("test1", "1"), api.NewSelectOption("test2", "2"), api.NewSelectOption("test3", "3")), ), ). Build(), From 106f16dd0b057d3cdc90a5850351c33f4006628a Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 6 Jul 2021 16:33:35 +0200 Subject: [PATCH 58/64] moved events to pointers --- api/command_interaction.go | 31 +- api/events/application_command_events.go | 16 +- api/events/category_events.go | 8 +- api/events/channel_events.go | 2 +- api/events/dm_events.go | 10 +- api/events/dm_message_event.go | 8 +- api/events/dm_message_reaction_events.go | 10 +- api/events/emote_events.go | 8 +- api/events/gateway_status_event.go | 10 +- api/events/generic_event.go | 14 +- api/events/guild_channel_events.go | 8 +- api/events/guild_events.go | 18 +- api/events/guild_invite_events.go | 6 +- api/events/guild_member_events.go | 10 +- api/events/guild_message_events.go | 8 +- api/events/guild_message_reaction_events.go | 10 +- api/events/guild_voice_events.go | 8 +- api/events/heartbeat_event.go | 2 +- api/events/http_request_events.go | 2 +- api/events/interaction_events.go | 75 +-- api/events/listener_adapter.go | 449 +++++++----------- api/events/message_events.go | 8 +- api/events/message_reaction_events.go | 10 +- api/events/raw_gateway_event.go | 2 +- api/events/ready_event.go | 2 +- api/events/role_events.go | 8 +- api/events/self_update_events.go | 2 +- api/events/store_channel_events.go | 8 +- api/events/text_channel_events.go | 10 +- api/events/user_activity_events.go | 8 +- api/events/user_events.go | 12 +- api/events/voice_channel_events.go | 8 +- api/voice_dispatch_interceptor.go | 16 +- example/examplebot.go | 16 +- internal/gateway_impl.go | 8 +- internal/handlers/all_handlers.go | 48 +- .../handlers/application_command_create.go | 19 +- .../handlers/application_command_delete.go | 13 +- .../handlers/application_command_update.go | 13 +- internal/handlers/channel_create_handler.go | 87 ++-- internal/handlers/channel_delete_handler.go | 73 ++- internal/handlers/channel_update_handler.go | 87 ++-- internal/handlers/guild_create_handler.go | 17 +- internal/handlers/guild_delete_handler.go | 15 +- internal/handlers/guild_member_add_handler.go | 26 +- .../handlers/guild_member_remove_handler.go | 26 +- .../handlers/guild_member_update_handler.go | 28 +- .../handlers/guild_role_create_handler.go | 30 +- .../handlers/guild_role_delete_handler.go | 28 +- .../handlers/guild_role_update_handler.go | 30 +- internal/handlers/guild_update_handler.go | 19 +- .../handlers/interaction_create_handler.go | 20 +- .../interaction_create_webhook_handler.go | 2 + internal/handlers/message_create_handler.go | 31 +- internal/handlers/message_delete_handler.go | 6 +- internal/handlers/message_update_handler.go | 34 +- internal/handlers/ready_handler.go | 10 +- .../handlers/voice_server_update_handler.go | 8 +- .../handlers/voice_state_update_handler.go | 44 +- internal/handlers/webhooks_update_handler.go | 39 +- 60 files changed, 672 insertions(+), 912 deletions(-) diff --git a/api/command_interaction.go b/api/command_interaction.go index 48045567..f8290a12 100644 --- a/api/command_interaction.go +++ b/api/command_interaction.go @@ -6,12 +6,35 @@ type CommandInteraction struct { Data *CommandInteractionData `json:"data,omitempty"` } +func (i *CommandInteraction) CommandID() Snowflake { + return i.Data.ID +} + +func (i *CommandInteraction) CommandName() string { + return i.Data.CommandName +} + +func (i *CommandInteraction) SubCommandName() *string { + return i.Data.SubCommandName +} + +func (i *CommandInteraction) SubCommandGroupName() *string { + return i.Data.SubCommandGroupName +} + +func (i *CommandInteraction) Options() []*Option { + return i.Data.Options +} + // 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"` + ID Snowflake `json:"id"` + CommandName string `json:"name"` + SubCommandName *string `json:"-"` + SubCommandGroupName *string `json:"-"` + Resolved *Resolved `json:"resolved,omitempty"` + RawOptions []OptionData `json:"options,omitempty"` + Options []*Option `json:"-"` } // Resolved contains resolved mention data diff --git a/api/events/application_command_events.go b/api/events/application_command_events.go index ba6101f1..059a7087 100644 --- a/api/events/application_command_events.go +++ b/api/events/application_command_events.go @@ -6,32 +6,30 @@ import ( // GenericCommandEvent is called upon receiving either CommandCreateEvent, CommandUpdateEvent or CommandDeleteEvent type GenericCommandEvent struct { - GenericEvent - CommandID api.Snowflake - Command *api.Command - GuildID *api.Snowflake + *GenericEvent + Command *api.Command } // Guild returns the api.Guild the api.Event got called or nil for global api.Command(s) func (e GenericCommandEvent) Guild() *api.Guild { - if e.GuildID == nil { + if e.Command.GuildID == nil { return nil } - return e.Disgo().Cache().Guild(*e.GuildID) + return e.Disgo().Cache().Guild(*e.Command.GuildID) } // CommandCreateEvent indicates that a new api.Command got created(this can come from any bot!) type CommandCreateEvent struct { - GenericCommandEvent + *GenericCommandEvent } // CommandUpdateEvent indicates that a api.Command got updated(this can come from any bot!) type CommandUpdateEvent struct { - GenericCommandEvent + *GenericCommandEvent OldCommand *api.Command } // CommandDeleteEvent indicates that a api.Command got deleted(this can come from any bot!) type CommandDeleteEvent struct { - GenericCommandEvent + *GenericCommandEvent } diff --git a/api/events/category_events.go b/api/events/category_events.go index 90e17e07..521a5d06 100644 --- a/api/events/category_events.go +++ b/api/events/category_events.go @@ -6,22 +6,22 @@ import ( // GenericCategoryEvent is called upon receiving CategoryCreateEvent, CategoryUpdateEvent or CategoryDeleteEvent type GenericCategoryEvent struct { - GenericGuildChannelEvent + *GenericGuildChannelEvent Category *api.Category } // CategoryCreateEvent indicates that a new api.Category got created in a api.Guild type CategoryCreateEvent struct { - GenericCategoryEvent + *GenericCategoryEvent } // CategoryUpdateEvent indicates that a api.Category got updated in a api.Guild type CategoryUpdateEvent struct { - GenericCategoryEvent + *GenericCategoryEvent OldCategory *api.Category } // CategoryDeleteEvent indicates that a api.Category got deleted in a api.Guild type CategoryDeleteEvent struct { - GenericCategoryEvent + *GenericCategoryEvent } diff --git a/api/events/channel_events.go b/api/events/channel_events.go index 6e2f0d85..f07020f2 100644 --- a/api/events/channel_events.go +++ b/api/events/channel_events.go @@ -6,7 +6,7 @@ import ( // GenericChannelEvent is called upon receiving any api.Channel api.Event type GenericChannelEvent struct { - GenericEvent + *GenericEvent ChannelID api.Snowflake Channel *api.Channel } diff --git a/api/events/dm_events.go b/api/events/dm_events.go index 88d06db3..4a6b9dd6 100644 --- a/api/events/dm_events.go +++ b/api/events/dm_events.go @@ -6,27 +6,27 @@ import ( // GenericDMChannelEvent is called upon receiving DMChannelCreateEvent, DMChannelUpdateEvent, DMChannelDeleteEvent or DMUserTypingEvent type GenericDMChannelEvent struct { - GenericChannelEvent + *GenericChannelEvent DMChannel *api.DMChannel } // DMChannelCreateEvent indicates that a new api.DMChannel got created type DMChannelCreateEvent struct { - GenericDMChannelEvent + *GenericDMChannelEvent } // DMChannelUpdateEvent indicates that a api.DMChannel got updated type DMChannelUpdateEvent struct { - GenericDMChannelEvent + *GenericDMChannelEvent OldDMChannel *api.DMChannel } // DMChannelDeleteEvent indicates that a api.DMChannel got deleted type DMChannelDeleteEvent struct { - GenericDMChannelEvent + *GenericDMChannelEvent } // DMUserTypingEvent indicates that a api.User started typing in a api.DMChannel(requires api.GatewayIntentsDirectMessageTyping) type DMUserTypingEvent struct { - GenericDMChannelEvent + *GenericDMChannelEvent } diff --git a/api/events/dm_message_event.go b/api/events/dm_message_event.go index 2488a62f..3b3461ad 100644 --- a/api/events/dm_message_event.go +++ b/api/events/dm_message_event.go @@ -6,7 +6,7 @@ import ( // GenericDMMessageEvent is called upon receiving DMMessageCreateEvent, DMMessageUpdateEvent, DMMessageDeleteEvent, GenericDMMessageReactionEvent, DMMessageReactionAddEvent, DMMessageReactionRemoveEvent, DMMessageReactionRemoveEmojiEvent or DMMessageReactionRemoveAllEvent(requires api.GatewayIntentsDirectMessages) type GenericDMMessageEvent struct { - GenericMessageEvent + *GenericMessageEvent } // DMChannel returns the api.DMChannel where the GenericDMMessageEvent happened @@ -16,16 +16,16 @@ func (e GenericDMMessageEvent) DMChannel() *api.DMChannel { // DMMessageCreateEvent is called upon receiving a api.Message in a api.DMChannel(requires api.GatewayIntentsDirectMessages) type DMMessageCreateEvent struct { - GenericDMMessageEvent + *GenericDMMessageEvent } // DMMessageUpdateEvent is called upon editing a api.Message in a api.DMChannel(requires api.GatewayIntentsDirectMessages) type DMMessageUpdateEvent struct { - GenericDMMessageEvent + *GenericDMMessageEvent OldMessage *api.Message } // DMMessageDeleteEvent is called upon deleting a api.Message in a api.DMChannel(requires api.GatewayIntentsDirectMessages) type DMMessageDeleteEvent struct { - GenericDMMessageEvent + *GenericDMMessageEvent } diff --git a/api/events/dm_message_reaction_events.go b/api/events/dm_message_reaction_events.go index acb22aae..27b88cb1 100644 --- a/api/events/dm_message_reaction_events.go +++ b/api/events/dm_message_reaction_events.go @@ -4,7 +4,7 @@ import "github.com/DisgoOrg/disgo/api" // GenericDMMessageReactionEvent is called upon receiving DMMessageReactionAddEvent or DMMessageReactionRemoveEvent(requires the api.GatewayIntentsDirectMessageReactions) type GenericDMMessageReactionEvent struct { - GenericGuildMessageEvent + *GenericGuildMessageEvent UserID api.Snowflake User *api.User MessageReaction api.MessageReaction @@ -12,21 +12,21 @@ type GenericDMMessageReactionEvent struct { // DMMessageReactionAddEvent indicates that a api.User added a api.MessageReaction to a api.Message in a api.DMChannel(requires the api.GatewayIntentsDirectMessageReactions) type DMMessageReactionAddEvent struct { - GenericDMMessageReactionEvent + *GenericDMMessageReactionEvent } // DMMessageReactionRemoveEvent indicates that a api.User removed a api.MessageReaction from a api.Message in a api.DMChannel(requires the api.GatewayIntentsDirectMessageReactions) type DMMessageReactionRemoveEvent struct { - GenericDMMessageReactionEvent + *GenericDMMessageReactionEvent } // 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 + *GenericDMMessageEvent MessageReaction api.MessageReaction } // DMMessageReactionRemoveAllEvent indicates someone removed all api.MessageReaction(s) from a api.Message in a api.DMChannel(requires the api.GatewayIntentsDirectMessageReactions) type DMMessageReactionRemoveAllEvent struct { - GenericDMMessageEvent + *GenericDMMessageEvent } diff --git a/api/events/emote_events.go b/api/events/emote_events.go index ead85b0d..52b939ec 100644 --- a/api/events/emote_events.go +++ b/api/events/emote_events.go @@ -6,22 +6,22 @@ import ( // GenericEmoteEvent is called upon receiving EmoteCreateEvent, EmoteUpdateEvent or EmoteDeleteEvent(requires api.GatewayIntentsGuildEmojis) type GenericEmoteEvent struct { - GenericGuildEvent + *GenericGuildEvent Emote *api.Emoji } // EmoteCreateEvent indicates that a new api.Emoji got created in a api.Guild(requires api.GatewayIntentsGuildEmojis) type EmoteCreateEvent struct { - GenericEmoteEvent + *GenericEmoteEvent } // EmoteUpdateEvent indicates that a api.Emoji got updated in a api.Guild(requires api.GatewayIntentsGuildEmojis) type EmoteUpdateEvent struct { - GenericEmoteEvent + *GenericEmoteEvent OldEmote *api.Emoji } // EmoteDeleteEvent indicates that a api.Emoji got deleted in a api.Guild(requires api.GatewayIntentsGuildEmojis) type EmoteDeleteEvent struct { - GenericEmoteEvent + *GenericEmoteEvent } diff --git a/api/events/gateway_status_event.go b/api/events/gateway_status_event.go index 17ad0f5e..8b3027a5 100644 --- a/api/events/gateway_status_event.go +++ b/api/events/gateway_status_event.go @@ -6,26 +6,26 @@ import ( // GenericGatewayStatusEvent is called upon receiving ConnectedEvent, ReconnectedEvent, ResumedEvent, DisconnectedEvent or ShutdownEvent type GenericGatewayStatusEvent struct { - GenericEvent + *GenericEvent Status api.GatewayStatus } // ConnectedEvent indicates disgo connected to the api.Gateway type ConnectedEvent struct { - GenericGatewayStatusEvent + *GenericGatewayStatusEvent } // ReconnectedEvent indicates disgo reconnected to the api.Gateway type ReconnectedEvent struct { - GenericGatewayStatusEvent + *GenericGatewayStatusEvent } // ResumedEvent indicates disgo resumed to the api.Gateway type ResumedEvent struct { - GenericGatewayStatusEvent + *GenericGatewayStatusEvent } // DisconnectedEvent indicates disgo disconnected to the api.Gateway type DisconnectedEvent struct { - GenericGatewayStatusEvent + *GenericGatewayStatusEvent } diff --git a/api/events/generic_event.go b/api/events/generic_event.go index 0561e8e8..18cc974c 100644 --- a/api/events/generic_event.go +++ b/api/events/generic_event.go @@ -2,9 +2,9 @@ package events import "github.com/DisgoOrg/disgo/api" -// NewEvent constructs a new GenericEvent with the provided Disgo instance -func NewEvent(disgo api.Disgo, sequenceNumber int) GenericEvent { - event := GenericEvent{disgo: disgo, sequenceNumber: sequenceNumber} +// NewGenericEvent constructs a new GenericEvent with the provided Disgo instance +func NewGenericEvent(disgo api.Disgo, sequenceNumber int) *GenericEvent { + event := &GenericEvent{disgo: disgo, sequenceNumber: sequenceNumber} disgo.EventManager().Dispatch(event) return event } @@ -16,11 +16,11 @@ type GenericEvent struct { } // Disgo returns the Disgo instance for this event -func (d GenericEvent) Disgo() api.Disgo { - return d.disgo +func (e GenericEvent) Disgo() api.Disgo { + return e.disgo } // SequenceNumber returns the sequence number of the gateway event -func (d GenericEvent) SequenceNumber() int { - return d.sequenceNumber +func (e GenericEvent) SequenceNumber() int { + return e.sequenceNumber } diff --git a/api/events/guild_channel_events.go b/api/events/guild_channel_events.go index 5d430147..fd19cb59 100644 --- a/api/events/guild_channel_events.go +++ b/api/events/guild_channel_events.go @@ -4,7 +4,7 @@ import "github.com/DisgoOrg/disgo/api" // GenericGuildChannelEvent is called upon receiving GuildChannelCreateEvent, GuildChannelUpdateEvent or GuildChannelDeleteEvent type GenericGuildChannelEvent struct { - GenericChannelEvent + *GenericChannelEvent GuildID api.Snowflake GuildChannel *api.GuildChannel } @@ -16,16 +16,16 @@ func (e GenericGuildChannelEvent) Guild() *api.Guild { // GuildChannelCreateEvent indicates that a new api.GuildChannel got created in a api.Guild type GuildChannelCreateEvent struct { - GenericGuildChannelEvent + *GenericGuildChannelEvent } // GuildChannelUpdateEvent indicates that a api.GuildChannel got updated in a api.Guild type GuildChannelUpdateEvent struct { - GenericGuildChannelEvent + *GenericGuildChannelEvent OldGuildChannel *api.GuildChannel } // GuildChannelDeleteEvent indicates that a api.GuildChannel got deleted in a api.Guild type GuildChannelDeleteEvent struct { - GenericGuildChannelEvent + *GenericGuildChannelEvent } diff --git a/api/events/guild_events.go b/api/events/guild_events.go index d5257a40..f517fcb7 100644 --- a/api/events/guild_events.go +++ b/api/events/guild_events.go @@ -6,50 +6,50 @@ import ( // GenericGuildEvent is called upon receiving GuildUpdateEvent, GuildAvailableEvent, GuildUnavailableEvent, GuildJoinEvent, GuildLeaveEvent, GuildReadyEvent, GuildBanEvent, GuildUnbanEvent type GenericGuildEvent struct { - GenericEvent + *GenericEvent GuildID api.Snowflake Guild *api.Guild } // GuildUpdateEvent is called upon receiving api.Guild updates type GuildUpdateEvent struct { - GenericGuildEvent + *GenericGuildEvent OldGuild *api.Guild } // GuildAvailableEvent is called when an unavailable api.Guild becomes available type GuildAvailableEvent struct { - GenericGuildEvent + *GenericGuildEvent } // GuildUnavailableEvent is called when an available api.Guild becomes unavailable type GuildUnavailableEvent struct { - GenericGuildEvent + *GenericGuildEvent } // GuildJoinEvent is called when the bot joins a api.Guild type GuildJoinEvent struct { - GenericGuildEvent + *GenericGuildEvent } // GuildLeaveEvent is called when the bot leaves a api.Guild type GuildLeaveEvent struct { - GenericGuildEvent + *GenericGuildEvent } // GuildReadyEvent is called when the loaded the api.Guild in login phase type GuildReadyEvent struct { - GenericGuildEvent + *GenericGuildEvent } // GuildBanEvent is called when a api.Member/api.User is banned from the api.Guild type GuildBanEvent struct { - GenericGuildEvent + *GenericGuildEvent User *api.User } // GuildUnbanEvent is called when a api.Member/api.User is unbanned from the api.Guild type GuildUnbanEvent struct { - GenericGuildEvent + *GenericGuildEvent User *api.User } diff --git a/api/events/guild_invite_events.go b/api/events/guild_invite_events.go index fc66ca8d..af68eb35 100644 --- a/api/events/guild_invite_events.go +++ b/api/events/guild_invite_events.go @@ -6,7 +6,7 @@ import ( // GenericGuildInviteEvent is called upon receiving GuildInviteCreateEvent or GuildInviteDeleteEvent(requires api.GatewayIntentsGuildInvites) type GenericGuildInviteEvent struct { - GenericGuildEvent + *GenericGuildEvent Code string ChannelID api.Snowflake } @@ -48,11 +48,11 @@ func (e GenericGuildInviteEvent) Category() *api.Category { // GuildInviteCreateEvent is called upon creation of a new api.Invite in a api.Guild(requires api.GatewayIntentsGuildInvites) type GuildInviteCreateEvent struct { - GenericGuildInviteEvent + *GenericGuildInviteEvent Invite *api.Invite } // GuildInviteDeleteEvent is called upon deletion of a new api.Invite in a api.Guild(requires api.GatewayIntentsGuildInvites) type GuildInviteDeleteEvent struct { - GenericGuildInviteEvent + *GenericGuildInviteEvent } diff --git a/api/events/guild_member_events.go b/api/events/guild_member_events.go index 7d8c16b4..362fe3da 100644 --- a/api/events/guild_member_events.go +++ b/api/events/guild_member_events.go @@ -6,7 +6,7 @@ import ( // GenericGuildMemberEvent generic api.Member event type GenericGuildMemberEvent struct { - GenericGuildEvent + *GenericGuildEvent Member *api.Member } @@ -20,24 +20,24 @@ func (e GenericGuildMemberEvent) User() *api.User { // GuildMemberJoinEvent indicates that a api.Member joined the api.Guild type GuildMemberJoinEvent struct { - GenericGuildMemberEvent + *GenericGuildMemberEvent } // GuildMemberUpdateEvent indicates that a api.Member updated type GuildMemberUpdateEvent struct { - GenericGuildMemberEvent + *GenericGuildMemberEvent OldMember *api.Member } // GuildMemberLeaveEvent indicates that a api.Member left the api.Guild type GuildMemberLeaveEvent struct { - GenericGuildMemberEvent + *GenericGuildMemberEvent User *api.User } // GuildMemberTypingEvent indicates that a api.Member started typing in a api.TextChannel(requires api.GatewayIntentsGuildMessageTyping) type GuildMemberTypingEvent struct { - GenericGuildMemberEvent + *GenericGuildMemberEvent ChannelID api.Snowflake } diff --git a/api/events/guild_message_events.go b/api/events/guild_message_events.go index 15407c44..dbc5f9b9 100644 --- a/api/events/guild_message_events.go +++ b/api/events/guild_message_events.go @@ -6,7 +6,7 @@ import ( // GenericGuildMessageEvent is called upon receiving GuildMessageCreateEvent, GuildMessageUpdateEvent or GuildMessageDeleteEvent type GenericGuildMessageEvent struct { - GenericMessageEvent + *GenericMessageEvent GuildID api.Snowflake } @@ -22,16 +22,16 @@ func (e GenericGuildMessageEvent) TextChannel() *api.TextChannel { // GuildMessageCreateEvent is called upon receiving a api.Message in a api.DMChannel type GuildMessageCreateEvent struct { - GenericGuildMessageEvent + *GenericGuildMessageEvent } // GuildMessageUpdateEvent is called upon editing a api.Message in a api.DMChannel type GuildMessageUpdateEvent struct { - GenericGuildMessageEvent + *GenericGuildMessageEvent OldMessage *api.Message } // GuildMessageDeleteEvent is called upon deleting a api.Message in a api.DMChannel type GuildMessageDeleteEvent struct { - GenericGuildMessageEvent + *GenericGuildMessageEvent } diff --git a/api/events/guild_message_reaction_events.go b/api/events/guild_message_reaction_events.go index ffd70d70..16be522d 100644 --- a/api/events/guild_message_reaction_events.go +++ b/api/events/guild_message_reaction_events.go @@ -4,7 +4,7 @@ import "github.com/DisgoOrg/disgo/api" // GenericGuildMessageReactionEvent is called upon receiving DMMessageReactionAddEvent or DMMessageReactionRemoveEvent type GenericGuildMessageReactionEvent struct { - GenericGuildMessageEvent + *GenericGuildMessageEvent UserID api.Snowflake Member *api.Member MessageReaction api.MessageReaction @@ -12,21 +12,21 @@ type GenericGuildMessageReactionEvent struct { // GuildMessageReactionAddEvent indicates that a api.Member added a api.MessageReaction to a api.Message in a api.TextChannel(requires the api.GatewayIntentsGuildMessageReactions) type GuildMessageReactionAddEvent struct { - GenericGuildMessageReactionEvent + *GenericGuildMessageReactionEvent } // GuildMessageReactionRemoveEvent indicates that a api.Member removed a api.MessageReaction from a api.Message in a api.TextChannel(requires the api.GatewayIntentsGuildMessageReactions) type GuildMessageReactionRemoveEvent struct { - GenericGuildMessageReactionEvent + *GenericGuildMessageReactionEvent } // 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 + *GenericGuildMessageEvent MessageReaction api.MessageReaction } // GuildMessageReactionRemoveAllEvent indicates someone removed all api.MessageReaction(s) from a api.Message in a api.TextChannel(requires the api.GatewayIntentsGuildMessageReactions) type GuildMessageReactionRemoveAllEvent struct { - GenericGuildMessageEvent + *GenericGuildMessageEvent } diff --git a/api/events/guild_voice_events.go b/api/events/guild_voice_events.go index cd6ca213..74bae1cb 100644 --- a/api/events/guild_voice_events.go +++ b/api/events/guild_voice_events.go @@ -6,22 +6,22 @@ import ( // GenericGuildVoiceEvent is called upon receiving GuildVoiceJoinEvent, GuildVoiceUpdateEvent, GuildVoiceLeaveEvent type GenericGuildVoiceEvent struct { - GenericGuildMemberEvent + *GenericGuildMemberEvent VoiceState *api.VoiceState } // GuildVoiceJoinEvent indicates that a api.Member joined a api.VoiceChannel(requires api.GatewayIntentsGuildVoiceStates) type GuildVoiceJoinEvent struct { - GenericGuildVoiceEvent + *GenericGuildVoiceEvent } // GuildVoiceUpdateEvent indicates that a api.Member moved a api.VoiceChannel(requires api.GatewayIntentsGuildVoiceStates) type GuildVoiceUpdateEvent struct { - GenericGuildVoiceEvent + *GenericGuildVoiceEvent OldVoiceState *api.VoiceState } // GuildVoiceLeaveEvent indicates that a api.Member left a api.VoiceChannel(requires api.GatewayIntentsGuildVoiceStates) type GuildVoiceLeaveEvent struct { - GenericGuildVoiceEvent + *GenericGuildVoiceEvent } diff --git a/api/events/heartbeat_event.go b/api/events/heartbeat_event.go index 7ab07a74..c656a80b 100644 --- a/api/events/heartbeat_event.go +++ b/api/events/heartbeat_event.go @@ -4,7 +4,7 @@ import "time" // HeartbeatEvent is called upon sending a heartbeat to the api.Gateway type HeartbeatEvent struct { - GenericEvent + *GenericEvent NewPing time.Duration OldPing time.Duration } diff --git a/api/events/http_request_events.go b/api/events/http_request_events.go index 29185042..881be5ff 100644 --- a/api/events/http_request_events.go +++ b/api/events/http_request_events.go @@ -6,7 +6,7 @@ import ( // HTTPRequestEvent indicates a new http.Request was made and can be used to collect data of StatusCodes as an example type HTTPRequestEvent struct { - GenericEvent + *GenericEvent Request *http.Request Response *http.Response } diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index 02dff099..a2b1ece9 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -6,75 +6,90 @@ import ( // GenericInteractionEvent generic api.Interaction event type GenericInteractionEvent struct { - GenericEvent + *GenericEvent Interaction *api.Interaction } // Respond replies to the api.Interaction with the provided api.InteractionResponse -func (e *GenericInteractionEvent) Respond(responseType api.InteractionResponseType, data interface{}) error { +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 { +func (e GenericInteractionEvent) DeferReply(ephemeral bool) error { return e.Interaction.DeferReply(ephemeral) } // Reply replies to the api.Interaction with api.InteractionResponseTypeDeferredChannelMessageWithSource & api.MessageCreate -func (e *GenericInteractionEvent) Reply(messageCreate api.MessageCreate) error { +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.MessageUpdate) (*api.Message, error) { +func (e GenericInteractionEvent) EditOriginal(messageUpdate api.MessageUpdate) (*api.Message, error) { return e.Interaction.EditOriginal(messageUpdate) } // DeleteOriginal deletes the original api.InteractionResponse -func (e *GenericInteractionEvent) DeleteOriginal() error { +func (e GenericInteractionEvent) DeleteOriginal() error { return e.Interaction.DeleteOriginal() } // SendFollowup used to send a followup api.MessageCreate to an api.Interaction -func (e *GenericInteractionEvent) SendFollowup(messageCreate api.MessageCreate) (*api.Message, error) { +func (e GenericInteractionEvent) SendFollowup(messageCreate api.MessageCreate) (*api.Message, error) { return e.Interaction.SendFollowup(messageCreate) } // 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) { +func (e GenericInteractionEvent) EditFollowup(messageID api.Snowflake, messageUpdate api.MessageUpdate) (*api.Message, error) { return e.Interaction.EditFollowup(messageID, messageUpdate) } // DeleteFollowup used to delete a followup api.Message from an api.Interaction -func (e *GenericInteractionEvent) DeleteFollowup(messageID api.Snowflake) error { +func (e GenericInteractionEvent) DeleteFollowup(messageID api.Snowflake) error { return e.Interaction.DeleteFollowup(messageID) } // CommandEvent indicates that a slash api.Command was ran type CommandEvent struct { - GenericInteractionEvent - CommandInteraction *api.CommandInteraction - CommandID api.Snowflake - CommandName string - SubCommandName *string - SubCommandGroupName *string - Options []*api.Option + *GenericInteractionEvent + CommandInteraction *api.CommandInteraction +} + +func (e *CommandEvent) CommandID() api.Snowflake { + return e.CommandInteraction.CommandID() +} + +func (e *CommandEvent) CommandName() string { + return e.CommandInteraction.CommandName() +} + +func (e *CommandEvent) SubCommandName() *string { + return e.CommandInteraction.SubCommandName() +} + +func (e *CommandEvent) SubCommandGroupName() *string { + return e.CommandInteraction.SubCommandGroupName() } // CommandPath returns the api.Command path -func (e CommandEvent) CommandPath() string { - path := e.CommandName - if e.SubCommandName != nil { - path += "/" + *e.SubCommandName +func (e *CommandEvent) CommandPath() string { + path := e.CommandName() + if name := e.SubCommandName(); name != nil { + path += "/" + *name } - if e.SubCommandGroupName != nil { - path += "/" + *e.SubCommandGroupName + if name := e.SubCommandGroupName(); name != nil { + path += "/" + *name } return path } +func (e *CommandEvent) Options() []*api.Option { + return e.CommandInteraction.Options() +} + // Option returns an Option by name -func (e CommandEvent) Option(name string) *api.Option { +func (e *CommandEvent) Option(name string) *api.Option { options := e.OptionN(name) if len(options) == 0 { return nil @@ -83,9 +98,9 @@ func (e CommandEvent) Option(name string) *api.Option { } // OptionN returns Option(s) by name -func (e CommandEvent) OptionN(name string) []*api.Option { +func (e *CommandEvent) OptionN(name string) []*api.Option { options := make([]*api.Option, 0) - for _, option := range e.Options { + for _, option := range e.Options() { if option.Name == name { options = append(options, option) } @@ -94,9 +109,9 @@ func (e CommandEvent) OptionN(name string) []*api.Option { } // OptionsT returns Option(s) by api.CommandOptionType -func (e CommandEvent) OptionsT(optionType api.CommandOptionType) []*api.Option { +func (e *CommandEvent) OptionsT(optionType api.CommandOptionType) []*api.Option { options := make([]*api.Option, 0) - for _, option := range e.Options { + for _, option := range e.Options() { if option.Type == optionType { options = append(options, option) } @@ -106,7 +121,7 @@ func (e CommandEvent) OptionsT(optionType api.CommandOptionType) []*api.Option { // GenericComponentEvent generic api.ComponentInteraction event type GenericComponentEvent struct { - GenericInteractionEvent + *GenericInteractionEvent ComponentInteraction *api.ComponentInteraction } @@ -142,7 +157,7 @@ func (e *GenericComponentEvent) Message() *api.Message { // ButtonClickEvent indicates that a api.Button was clicked type ButtonClickEvent struct { - GenericComponentEvent + *GenericComponentEvent ButtonInteraction *api.ButtonInteraction } @@ -153,7 +168,7 @@ func (e *ButtonClickEvent) Button() *api.Button { // SelectMenuSubmitEvent indicates that a api.SelectMenu was submitted type SelectMenuSubmitEvent struct { - GenericComponentEvent + *GenericComponentEvent SelectMenuInteraction *api.SelectMenuInteraction } diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index b1a440cd..322c0122 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -9,629 +9,500 @@ 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) + 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) - - // api.Channel Events - OnGenericChannelEvent func(event GenericChannelEvent) + OnCommandCreate func(event *CommandCreateEvent) + OnCommandUpdate func(event *CommandUpdateEvent) + OnCommandDelete func(event *CommandDeleteEvent) // api.GuildChannel Events - OnGenericGuildChannelEvent func(event GenericGuildChannelEvent) - OnGuildChannelCreate func(event GuildChannelCreateEvent) - OnGuildChannelUpdate func(event GuildChannelUpdateEvent) - OnGuildChannelDelete func(event GuildChannelDeleteEvent) + OnGuildChannelCreate func(event *GuildChannelCreateEvent) + OnGuildChannelUpdate func(event *GuildChannelUpdateEvent) + OnGuildChannelDelete func(event *GuildChannelDeleteEvent) // api.Category Events - OnGenericCategoryEvent func(event GenericCategoryEvent) - OnCategoryCreate func(event CategoryCreateEvent) - OnCategoryUpdate func(event CategoryUpdateEvent) - OnCategoryDelete func(event CategoryDeleteEvent) + 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) + 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) - OnDMMessageReactionRemoveEmoji func(event DMMessageReactionRemoveEmojiEvent) - OnDMMessageReactionRemoveAll func(event DMMessageReactionRemoveAllEvent) + OnDMMessageReactionAdd func(event *DMMessageReactionAddEvent) + OnDMMessageReactionRemove func(event *DMMessageReactionRemoveEvent) + OnDMMessageReactionRemoveEmoji func(event *DMMessageReactionRemoveEmojiEvent) + OnDMMessageReactionRemoveAll func(event *DMMessageReactionRemoveAllEvent) // api.StoreChannel Events - OnGenericStoreChannelEvent func(event GenericStoreChannelEvent) - OnStoreChannelCreate func(event StoreChannelCreateEvent) - OnStoreChannelUpdate func(event StoreChannelUpdateEvent) - OnStoreChannelDelete func(event StoreChannelDeleteEvent) + 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) + 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) + OnVoiceChannelCreate func(event *VoiceChannelCreateEvent) + OnVoiceChannelUpdate func(event *VoiceChannelUpdateEvent) + OnVoiceChannelDelete func(event *VoiceChannelDeleteEvent) // api.Emoji Events - OnGenericEmoteEvent func(event GenericEmoteEvent) - OnEmoteCreate func(event EmoteCreateEvent) - OnEmoteUpdate func(event EmoteUpdateEvent) - OnEmoteDelete func(event EmoteDeleteEvent) + 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) + 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) + 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) + 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) + 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) + 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) - OnGuildMessageReactionRemoveEmoji func(event GuildMessageReactionRemoveEmojiEvent) - OnGuildMessageReactionRemoveAll func(event GuildMessageReactionRemoveAllEvent) + OnGuildMessageReactionAdd func(event *GuildMessageReactionAddEvent) + OnGuildMessageReactionRemove func(event *GuildMessageReactionRemoveEvent) + OnGuildMessageReactionRemoveEmoji func(event *GuildMessageReactionRemoveEmojiEvent) + OnGuildMessageReactionRemoveAll func(event *GuildMessageReactionRemoveAllEvent) // api.Guild Voice Events - OnGenericGuildVoiceEvent func(event GenericGuildVoiceEvent) - OnGuildVoiceUpdate func(event GuildVoiceUpdateEvent) - OnGuildVoiceJoin func(event GuildVoiceJoinEvent) - OnGuildVoiceLeave func(event GuildVoiceLeaveEvent) + 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) + OnRoleCreate func(event *RoleCreateEvent) + OnRoleUpdate func(event *RoleUpdateEvent) + OnRoleDelete func(event *RoleDeleteEvent) // api.Interaction Events - OnGenericInteractionEvent func(event GenericInteractionEvent) - OnCommand func(event CommandEvent) - OnGenericComponentEvent func(event GenericComponentEvent) - OnButtonClick func(event ButtonClickEvent) - OnSelectMenuSubmit func(event SelectMenuSubmitEvent) + OnCommand func(event *CommandEvent) + OnButtonClick func(event *ButtonClickEvent) + OnSelectMenuSubmit func(event *SelectMenuSubmitEvent) // api.Message Events - OnGenericMessageEvent func(event GenericMessageEvent) - OnMessageCreate func(event MessageCreateEvent) - OnMessageUpdate func(event MessageUpdateEvent) - OnMessageDelete func(event MessageDeleteEvent) + 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) - OnMessageReactionRemoveEmoji func(event MessageReactionRemoveEmojiEvent) - OnMessageReactionRemoveAll func(event MessageReactionRemoveAllEvent) + OnMessageReactionAdd func(event *MessageReactionAddEvent) + OnMessageReactionRemove func(event *MessageReactionRemoveEvent) + OnMessageReactionRemoveEmoji func(event *MessageReactionRemoveEmojiEvent) + 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) + 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) + OnUserActivityStart func(event *UserActivityStartEvent) + OnUserActivityUpdate func(event *UserActivityUpdateEvent) + OnUserActivityEnd func(event *UserActivityEndEvent) } // OnEvent is getting called everytime we receive an event func (l ListenerAdapter) OnEvent(event interface{}) { switch e := event.(type) { - case GenericEvent: - if listener := l.OnGenericEvent; listener != nil { - listener(e) - } - case HeartbeatEvent: + case *HeartbeatEvent: if listener := l.OnHeartbeat; listener != nil { listener(e) } - case HTTPRequestEvent: + case *HTTPRequestEvent: if listener := l.OnHTTPRequest; listener != nil { listener(e) } - case RawGatewayEvent: + case *RawGatewayEvent: if listener := l.OnRawGateway; listener != nil { listener(e) } - case ReadyEvent: + case *ReadyEvent: if listener := l.OnReadyEvent; listener != nil { listener(e) } // api.Command Events - case GenericCommandEvent: - if listener := l.OnGenericCommandEvent; listener != nil { - listener(e) - } - case CommandCreateEvent: + case *CommandCreateEvent: if listener := l.OnCommandCreate; listener != nil { listener(e) } - case CommandUpdateEvent: + case *CommandUpdateEvent: if listener := l.OnCommandUpdate; listener != nil { listener(e) } - case CommandDeleteEvent: + case *CommandDeleteEvent: if listener := l.OnCommandDelete; listener != nil { listener(e) } - // api.Channel Events - case GenericChannelEvent: - if listener := l.OnGenericChannelEvent; listener != nil { - listener(e) - } - // api.GuildChannel Events - case GenericGuildChannelEvent: - if listener := l.OnGenericGuildChannelEvent; listener != nil { - listener(e) - } - case GuildChannelCreateEvent: + case *GuildChannelCreateEvent: if listener := l.OnGuildChannelCreate; listener != nil { listener(e) } - case GuildChannelUpdateEvent: + case *GuildChannelUpdateEvent: if listener := l.OnGuildChannelUpdate; listener != nil { listener(e) } - case GuildChannelDeleteEvent: + case *GuildChannelDeleteEvent: if listener := l.OnGuildChannelDelete; listener != nil { listener(e) } // api.Category Events - case GenericCategoryEvent: - if listener := l.OnGenericCategoryEvent; listener != nil { - listener(e) - } - case CategoryCreateEvent: + case *CategoryCreateEvent: if listener := l.OnCategoryCreate; listener != nil { listener(e) } - case CategoryUpdateEvent: + case *CategoryUpdateEvent: if listener := l.OnCategoryUpdate; listener != nil { listener(e) } - case CategoryDeleteEvent: + case *CategoryDeleteEvent: if listener := l.OnCategoryDelete; listener != nil { listener(e) } // api.DMChannel Events// api.Category Events - case GenericDMChannelEvent: - if listener := l.OnGenericDMChannelEvent; listener != nil { - listener(e) - } - case DMChannelCreateEvent: + case *DMChannelCreateEvent: if listener := l.OnDMChannelCreate; listener != nil { listener(e) } - case DMChannelUpdateEvent: + case *DMChannelUpdateEvent: if listener := l.OnDMChannelUpdate; listener != nil { listener(e) } - case DMChannelDeleteEvent: + case *DMChannelDeleteEvent: if listener := l.OnDMChannelDelete; listener != nil { listener(e) } // api.DMChannel Events// api.Category Events - case GenericDMMessageReactionEvent: - if listener := l.OnGenericDMMessageReactionEventEvent; listener != nil { - listener(e) - } - case DMMessageReactionAddEvent: + case *DMMessageReactionAddEvent: if listener := l.OnDMMessageReactionAdd; listener != nil { listener(e) } - case DMMessageReactionRemoveEvent: + case *DMMessageReactionRemoveEvent: if listener := l.OnDMMessageReactionRemove; listener != nil { listener(e) } - case DMMessageReactionRemoveEmojiEvent: + case *DMMessageReactionRemoveEmojiEvent: if listener := l.OnDMMessageReactionRemoveEmoji; listener != nil { listener(e) } - case DMMessageReactionRemoveAllEvent: + case *DMMessageReactionRemoveAllEvent: if listener := l.OnDMMessageReactionRemoveAll; listener != nil { listener(e) } // api.StoreChannel Events - case GenericStoreChannelEvent: - if listener := l.OnGenericStoreChannelEvent; listener != nil { - listener(e) - } - case StoreChannelCreateEvent: + case *StoreChannelCreateEvent: if listener := l.OnStoreChannelCreate; listener != nil { listener(e) } - case StoreChannelUpdateEvent: + case *StoreChannelUpdateEvent: if listener := l.OnStoreChannelUpdate; listener != nil { listener(e) } - case StoreChannelDeleteEvent: + case *StoreChannelDeleteEvent: if listener := l.OnStoreChannelDelete; listener != nil { listener(e) } // api.TextChannel Events - case GenericTextChannelEvent: - if listener := l.OnGenericTextChannelEvent; listener != nil { - listener(e) - } - case TextChannelCreateEvent: + case *TextChannelCreateEvent: if listener := l.OnTextChannelCreate; listener != nil { listener(e) } - case TextChannelUpdateEvent: + case *TextChannelUpdateEvent: if listener := l.OnTextChannelUpdate; listener != nil { listener(e) } - case TextChannelDeleteEvent: + case *TextChannelDeleteEvent: if listener := l.OnTextChannelDelete; listener != nil { listener(e) } // api.VoiceChannel Events - case GenericVoiceChannelEvent: - if listener := l.OnGenericVoiceChannelEvent; listener != nil { - listener(e) - } - case VoiceChannelCreateEvent: + case *VoiceChannelCreateEvent: if listener := l.OnVoiceChannelCreate; listener != nil { listener(e) } - case VoiceChannelUpdateEvent: + case *VoiceChannelUpdateEvent: if listener := l.OnVoiceChannelUpdate; listener != nil { listener(e) } - case VoiceChannelDeleteEvent: + case *VoiceChannelDeleteEvent: if listener := l.OnVoiceChannelDelete; listener != nil { listener(e) } // api.emote Events - case GenericEmoteEvent: - if listener := l.OnGenericEmoteEvent; listener != nil { - listener(e) - } - case EmoteCreateEvent: + case *EmoteCreateEvent: if listener := l.OnEmoteCreate; listener != nil { listener(e) } - case EmoteUpdateEvent: + case *EmoteUpdateEvent: if listener := l.OnEmoteUpdate; listener != nil { listener(e) } - case EmoteDeleteEvent: + case *EmoteDeleteEvent: if listener := l.OnEmoteDelete; listener != nil { listener(e) } // api.GatewayStatus Events - case GenericGatewayStatusEvent: - if listener := l.OnGenericGatewayStatusEvent; listener != nil { - listener(e) - } - case ConnectedEvent: + case *ConnectedEvent: if listener := l.OnConnected; listener != nil { listener(e) } - case ReconnectedEvent: + case *ReconnectedEvent: if listener := l.OnReconnected; listener != nil { listener(e) } - case ResumedEvent: + case *ResumedEvent: if listener := l.OnResumed; listener != nil { listener(e) } - case DisconnectedEvent: + case *DisconnectedEvent: if listener := l.OnDisconnected; listener != nil { listener(e) } // api.Guild Events - case GenericGuildEvent: - if listener := l.OnGenericGuildEvent; listener != nil { - listener(e) - } - case GuildJoinEvent: + case *GuildJoinEvent: if listener := l.OnGuildJoin; listener != nil { listener(e) } - case GuildUpdateEvent: + case *GuildUpdateEvent: if listener := l.OnGuildUpdate; listener != nil { listener(e) } - case GuildLeaveEvent: + case *GuildLeaveEvent: if listener := l.OnGuildLeave; listener != nil { listener(e) } - case GuildAvailableEvent: + case *GuildAvailableEvent: if listener := l.OnGuildAvailable; listener != nil { listener(e) } - case GuildUnavailableEvent: + case *GuildUnavailableEvent: if listener := l.OnGuildUnavailable; listener != nil { listener(e) } - case GuildReadyEvent: + case *GuildReadyEvent: if listener := l.OnGuildReady; listener != nil { listener(e) } - case GuildBanEvent: + case *GuildBanEvent: if listener := l.OnGuildBan; listener != nil { listener(e) } - case GuildUnbanEvent: + case *GuildUnbanEvent: if listener := l.OnGuildUnban; listener != nil { listener(e) } // api.Guild api.Invite Events - case GenericGuildInviteEvent: - if listener := l.OnGenericGuildInviteEvent; listener != nil { - listener(e) - } - case GuildInviteCreateEvent: + case *GuildInviteCreateEvent: if listener := l.OnGuildInviteCreate; listener != nil { listener(e) } - case GuildInviteDeleteEvent: + case *GuildInviteDeleteEvent: if listener := l.OnGuildInviteDelete; listener != nil { listener(e) } // api.Member Events - case GenericGuildMemberEvent: - if listener := l.OnGenericGuildMemberEvent; listener != nil { - listener(e) - } - case GuildMemberJoinEvent: + case *GuildMemberJoinEvent: if listener := l.OnGuildMemberJoin; listener != nil { listener(e) } - case GuildMemberUpdateEvent: + case *GuildMemberUpdateEvent: if listener := l.OnGuildMemberUpdate; listener != nil { listener(e) } - case GuildMemberLeaveEvent: + case *GuildMemberLeaveEvent: if listener := l.OnGuildMemberLeave; listener != nil { listener(e) } // api.Guild api.Message Events - case GenericGuildMessageEvent: - if listener := l.OnGenericGuildMessageEvent; listener != nil { - listener(e) - } - case GuildMessageCreateEvent: + case *GuildMessageCreateEvent: if listener := l.OnGuildMessageCreate; listener != nil { listener(e) } - case GuildMessageUpdateEvent: + case *GuildMessageUpdateEvent: if listener := l.OnGuildMessageUpdate; listener != nil { listener(e) } - case GuildMessageDeleteEvent: + case *GuildMessageDeleteEvent: if listener := l.OnGuildMessageDelete; listener != nil { listener(e) } // api.Guild api.Message Reaction Events - case GenericGuildMessageReactionEvent: - if listener := l.OnGenericGuildMessageReactionEvent; listener != nil { - listener(e) - } - case GuildMessageReactionAddEvent: + case *GuildMessageReactionAddEvent: if listener := l.OnGuildMessageReactionAdd; listener != nil { listener(e) } - case GuildMessageReactionRemoveEvent: + case *GuildMessageReactionRemoveEvent: if listener := l.OnGuildMessageReactionRemove; listener != nil { listener(e) } - case GuildMessageReactionRemoveEmojiEvent: + case *GuildMessageReactionRemoveEmojiEvent: if listener := l.OnGuildMessageReactionRemoveEmoji; listener != nil { listener(e) } - case GuildMessageReactionRemoveAllEvent: + case *GuildMessageReactionRemoveAllEvent: if listener := l.OnGuildMessageReactionRemoveAll; listener != nil { listener(e) } // api.Guild Voice Events - case GenericGuildVoiceEvent: - if listener := l.OnGenericGuildVoiceEvent; listener != nil { - listener(e) - } - case GuildVoiceUpdateEvent: + case *GuildVoiceUpdateEvent: if listener := l.OnGuildVoiceUpdate; listener != nil { listener(e) } - case GuildVoiceJoinEvent: + case *GuildVoiceJoinEvent: if listener := l.OnGuildVoiceJoin; listener != nil { listener(e) } - case GuildVoiceLeaveEvent: + case *GuildVoiceLeaveEvent: if listener := l.OnGuildVoiceLeave; listener != nil { listener(e) } // api.Guild api.Role Events - case GenericRoleEvent: - if listener := l.OnGenericRoleEvent; listener != nil { - listener(e) - } - case RoleCreateEvent: + case *RoleCreateEvent: if listener := l.OnRoleCreate; listener != nil { listener(e) } - case RoleUpdateEvent: + case *RoleUpdateEvent: if listener := l.OnRoleUpdate; listener != nil { listener(e) } - case RoleDeleteEvent: + case *RoleDeleteEvent: if listener := l.OnRoleDelete; listener != nil { listener(e) } // Interaction Events - case GenericInteractionEvent: - if listener := l.OnGenericInteractionEvent; listener != nil { - listener(e) - } - case CommandEvent: + case *CommandEvent: if listener := l.OnCommand; listener != nil { listener(e) } - case GenericComponentEvent: - if listener := l.OnGenericComponentEvent; listener != nil { - listener(e) - } - case ButtonClickEvent: + case *ButtonClickEvent: if listener := l.OnButtonClick; listener != nil { listener(e) } - case SelectMenuSubmitEvent: + case *SelectMenuSubmitEvent: if listener := l.OnSelectMenuSubmit; listener != nil { listener(e) } // api.Message Events - case GenericMessageEvent: - if listener := l.OnGenericMessageEvent; listener != nil { - listener(e) - } - case MessageCreateEvent: + case *MessageCreateEvent: if listener := l.OnMessageCreate; listener != nil { listener(e) } - case MessageUpdateEvent: + case *MessageUpdateEvent: if listener := l.OnMessageUpdate; listener != nil { listener(e) } - case MessageDeleteEvent: + case *MessageDeleteEvent: if listener := l.OnMessageDelete; listener != nil { listener(e) } // api.Message Reaction Events - case GenericReactionEvents: - if listener := l.OnGenericReactionEvent; listener != nil { - listener(e) - } - case MessageReactionAddEvent: + case *MessageReactionAddEvent: if listener := l.OnMessageReactionAdd; listener != nil { listener(e) } - case MessageReactionRemoveEvent: + case *MessageReactionRemoveEvent: if listener := l.OnMessageReactionRemove; listener != nil { listener(e) } - case MessageReactionRemoveEmojiEvent: + case *MessageReactionRemoveEmojiEvent: if listener := l.OnMessageReactionRemoveEmoji; listener != nil { listener(e) } - case MessageReactionRemoveAllEvent: + case *MessageReactionRemoveAllEvent: if listener := l.OnMessageReactionRemoveAll; listener != nil { listener(e) } // Self Events - case SelfUpdateEvent: + case *SelfUpdateEvent: if listener := l.OnSelfUpdate; listener != nil { listener(e) } // api.User Events - case GenericUserEvent: - if listener := l.OnGenericUserEvent; listener != nil { - listener(e) - } - case UserUpdateEvent: + case *UserUpdateEvent: if listener := l.OnUserUpdate; listener != nil { listener(e) } - case UserTypingEvent: + case *UserTypingEvent: if listener := l.OnUserTyping; listener != nil { listener(e) } - case GuildMemberTypingEvent: + case *GuildMemberTypingEvent: if listener := l.OnGuildUserTyping; listener != nil { listener(e) } - case DMUserTypingEvent: + case *DMUserTypingEvent: if listener := l.OnDMUserTyping; listener != nil { listener(e) } // api.User api.Activity Events - case GenericUserActivityEvent: - if listener := l.OnGenericUserActivityEvent; listener != nil { - listener(e) - } - case UserActivityStartEvent: + case *UserActivityStartEvent: if listener := l.OnUserActivityStart; listener != nil { listener(e) } - case UserActivityUpdateEvent: + case *UserActivityUpdateEvent: if listener := l.OnUserActivityUpdate; listener != nil { listener(e) } - case UserActivityEndEvent: + case *UserActivityEndEvent: if listener := l.OnUserActivityEnd; listener != nil { listener(e) } diff --git a/api/events/message_events.go b/api/events/message_events.go index e1e22c76..70d05ef8 100644 --- a/api/events/message_events.go +++ b/api/events/message_events.go @@ -6,7 +6,7 @@ import ( // GenericMessageEvent generic api.Message event type GenericMessageEvent struct { - GenericEvent + *GenericEvent MessageID api.Snowflake Message *api.Message ChannelID api.Snowflake @@ -19,16 +19,16 @@ func (e *GenericMessageEvent) MessageChannel() *api.MessageChannel { // MessageDeleteEvent indicates that a api.Message got deleted type MessageDeleteEvent struct { - GenericMessageEvent + *GenericMessageEvent } // MessageCreateEvent indicates that a api.Message got received type MessageCreateEvent struct { - GenericMessageEvent + *GenericMessageEvent } // MessageUpdateEvent indicates that a api.Message got update type MessageUpdateEvent struct { - GenericMessageEvent + *GenericMessageEvent OldMessage *api.Message } diff --git a/api/events/message_reaction_events.go b/api/events/message_reaction_events.go index 58086961..9f0cf1a2 100644 --- a/api/events/message_reaction_events.go +++ b/api/events/message_reaction_events.go @@ -4,7 +4,7 @@ import "github.com/DisgoOrg/disgo/api" // GenericReactionEvents is called upon receiving MessageReactionAddEvent or MessageReactionRemoveEvent type GenericReactionEvents struct { - GenericMessageEvent + *GenericMessageEvent UserID api.Snowflake User *api.User MessageReaction api.MessageReaction @@ -12,21 +12,21 @@ type GenericReactionEvents struct { // MessageReactionAddEvent indicates that a api.User added a api.MessageReaction to a api.Message in a api.Channel(this+++ requires the api.GatewayIntentsGuildMessageReactions and/or api.GatewayIntentsDirectMessageReactions) type MessageReactionAddEvent struct { - GenericReactionEvents + *GenericReactionEvents } // MessageReactionRemoveEvent indicates that a api.User removed a api.MessageReaction from a api.Message in a api.Channel(requires the api.GatewayIntentsGuildMessageReactions and/or api.GatewayIntentsDirectMessageReactions) type MessageReactionRemoveEvent struct { - GenericReactionEvents + *GenericReactionEvents } // 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 + *GenericMessageEvent MessageReaction api.MessageReaction } // MessageReactionRemoveAllEvent indicates someone removed all api.MessageReaction(s) from a api.Message in a api.Channel(requires the api.GatewayIntentsGuildMessageReactions and/or api.GatewayIntentsDirectMessageReactionss) type MessageReactionRemoveAllEvent struct { - GenericMessageEvent + *GenericMessageEvent } diff --git a/api/events/raw_gateway_event.go b/api/events/raw_gateway_event.go index bb632eea..db0cbbb3 100644 --- a/api/events/raw_gateway_event.go +++ b/api/events/raw_gateway_event.go @@ -8,7 +8,7 @@ import ( // RawGatewayEvent is called for any api.GatewayEventType we receive if enabled in the api.DisgoBuilder/api.Options type RawGatewayEvent struct { - GenericEvent + *GenericEvent Type api.GatewayEventType RawPayload json.RawMessage Payload map[string]interface{} diff --git a/api/events/ready_event.go b/api/events/ready_event.go index 88fb3631..9fc77bfd 100644 --- a/api/events/ready_event.go +++ b/api/events/ready_event.go @@ -4,6 +4,6 @@ import "github.com/DisgoOrg/disgo/api" // ReadyEvent indicates we received the ReadyEvent from the api.Gateway type ReadyEvent struct { - GenericEvent + *GenericEvent *api.ReadyGatewayEvent } diff --git a/api/events/role_events.go b/api/events/role_events.go index f245f3ef..c646cda0 100644 --- a/api/events/role_events.go +++ b/api/events/role_events.go @@ -6,23 +6,23 @@ import ( // GenericRoleEvent generic api.Role event type GenericRoleEvent struct { - GenericGuildEvent + *GenericGuildEvent RoleID api.Snowflake Role *api.Role } // RoleCreateEvent indicates that a api.Role got created type RoleCreateEvent struct { - GenericGuildEvent + *GenericRoleEvent } // RoleUpdateEvent indicates that a api.Role got updated type RoleUpdateEvent struct { - GenericGuildEvent + *GenericRoleEvent OldRole *api.Role } // RoleDeleteEvent indicates that a api.Role got deleted type RoleDeleteEvent struct { - GenericGuildEvent + *GenericRoleEvent } diff --git a/api/events/self_update_events.go b/api/events/self_update_events.go index 61221f1c..088f3245 100644 --- a/api/events/self_update_events.go +++ b/api/events/self_update_events.go @@ -6,7 +6,7 @@ import ( // SelfUpdateEvent is called when something about this api.User updates type SelfUpdateEvent struct { - GenericEvent + *GenericEvent Self *api.User OldSelf *api.User } diff --git a/api/events/store_channel_events.go b/api/events/store_channel_events.go index 28dbdae3..22b3ee22 100644 --- a/api/events/store_channel_events.go +++ b/api/events/store_channel_events.go @@ -6,22 +6,22 @@ import ( // GenericStoreChannelEvent is called upon receiving StoreChannelCreateEvent, StoreChannelUpdateEvent or StoreChannelDeleteEvent type GenericStoreChannelEvent struct { - GenericGuildChannelEvent + *GenericGuildChannelEvent StoreChannel *api.StoreChannel } // StoreChannelCreateEvent indicates that a new api.StoreChannel got created in a api.Guild type StoreChannelCreateEvent struct { - GenericStoreChannelEvent + *GenericStoreChannelEvent } // StoreChannelUpdateEvent indicates that a api.StoreChannel got updated in a api.Guild type StoreChannelUpdateEvent struct { - GenericStoreChannelEvent + *GenericStoreChannelEvent OldStoreChannel *api.StoreChannel } // StoreChannelDeleteEvent indicates that a api.StoreChannel got deleted in a api.Guild type StoreChannelDeleteEvent struct { - GenericStoreChannelEvent + *GenericStoreChannelEvent } diff --git a/api/events/text_channel_events.go b/api/events/text_channel_events.go index 2de076fa..b71c01bf 100644 --- a/api/events/text_channel_events.go +++ b/api/events/text_channel_events.go @@ -6,27 +6,27 @@ import ( // GenericTextChannelEvent is called upon receiving TextChannelCreateEvent, TextChannelUpdateEvent or TextChannelDeleteEvent type GenericTextChannelEvent struct { - GenericGuildChannelEvent + *GenericGuildChannelEvent TextChannel *api.TextChannel } // TextChannelCreateEvent indicates that a new api.TextChannel got created in a api.Guild type TextChannelCreateEvent struct { - GenericTextChannelEvent + *GenericTextChannelEvent } // TextChannelUpdateEvent indicates that a api.TextChannel got updated in a api.Guild type TextChannelUpdateEvent struct { - GenericTextChannelEvent + *GenericTextChannelEvent OldTextChannel *api.TextChannel } // TextChannelDeleteEvent indicates that a api.TextChannel got deleted in a api.Guild type TextChannelDeleteEvent struct { - GenericTextChannelEvent + *GenericTextChannelEvent } // WebhooksUpdateEvent indicates that a api.Webhook updated in this api.TextChannel type WebhooksUpdateEvent struct { - GenericTextChannelEvent + *GenericTextChannelEvent } diff --git a/api/events/user_activity_events.go b/api/events/user_activity_events.go index cd98991b..b0873a80 100644 --- a/api/events/user_activity_events.go +++ b/api/events/user_activity_events.go @@ -6,25 +6,25 @@ import ( // GenericUserActivityEvent is called upon receiving UserActivityStartEvent, UserActivityUpdateEvent or UserActivityEndEvent(requires the api.GatewayIntentsGuildPresences) type GenericUserActivityEvent struct { - GenericGuildMemberEvent + *GenericGuildMemberEvent Member *api.Member } // UserActivityStartEvent indicates that a api.User started a new api.Activity(requires the api.GatewayIntentsGuildPresences) type UserActivityStartEvent struct { - GenericUserActivityEvent + *GenericUserActivityEvent Activity *api.Activity } // UserActivityUpdateEvent indicates that a api.User's api.Activity(s) updated(requires the api.GatewayIntentsGuildPresences) type UserActivityUpdateEvent struct { - GenericUserActivityEvent + *GenericUserActivityEvent NewActivities *api.Activity OldActivities *api.Activity } // UserActivityEndEvent indicates that a api.User ended a api.Activity(requires the api.GatewayIntentsGuildPresences) type UserActivityEndEvent struct { - GenericUserActivityEvent + *GenericUserActivityEvent Activity *api.Activity } diff --git a/api/events/user_events.go b/api/events/user_events.go index 0ae3381a..06bd885f 100644 --- a/api/events/user_events.go +++ b/api/events/user_events.go @@ -6,34 +6,34 @@ import ( // GenericUserEvent is called upon receiving UserUpdateEvent or UserTypingEvent type GenericUserEvent struct { - GenericEvent + *GenericEvent UserID api.Snowflake User *api.User } // UserUpdateEvent indicates that a api.User updated type UserUpdateEvent struct { - GenericUserEvent + *GenericUserEvent OldUser *api.User } // UserTypingEvent indicates that a api.User started typing in a api.DMChannel or api.TextChannel(requires the api.GatewayIntentsDirectMessageTyping and/or api.GatewayIntentsGuildMessageTyping) type UserTypingEvent struct { - GenericUserEvent + *GenericUserEvent ChannelID api.Snowflake } // Channel returns the api.Channel the api.User started typing in -func (e UserTypingEvent) Channel() *api.Channel { +func (e *UserTypingEvent) Channel() *api.Channel { return e.Disgo().Cache().Channel(e.ChannelID) } // DMChannel returns the api.DMChannel the api.User started typing in -func (e UserTypingEvent) DMChannel() *api.DMChannel { +func (e *UserTypingEvent) DMChannel() *api.DMChannel { return e.Disgo().Cache().DMChannel(e.ChannelID) } // TextChannel returns the api.TextChannel the api.User started typing in -func (e UserTypingEvent) TextChannel() *api.TextChannel { +func (e *UserTypingEvent) TextChannel() *api.TextChannel { return e.Disgo().Cache().TextChannel(e.ChannelID) } diff --git a/api/events/voice_channel_events.go b/api/events/voice_channel_events.go index 3cd965db..fb9cc749 100644 --- a/api/events/voice_channel_events.go +++ b/api/events/voice_channel_events.go @@ -6,22 +6,22 @@ import ( // GenericVoiceChannelEvent is called upon receiving VoiceChannelCreateEvent, VoiceChannelUpdateEvent or VoiceChannelDeleteEvent type GenericVoiceChannelEvent struct { - GenericGuildChannelEvent + *GenericGuildChannelEvent VoiceChannel *api.VoiceChannel } // VoiceChannelCreateEvent indicates that a new api.VoiceChannel got created in a api.Guild type VoiceChannelCreateEvent struct { - GenericVoiceChannelEvent + *GenericVoiceChannelEvent } // VoiceChannelUpdateEvent indicates that a api.VoiceChannel got updated in a api.Guild type VoiceChannelUpdateEvent struct { - GenericVoiceChannelEvent + *GenericVoiceChannelEvent OldVoiceChannel *api.VoiceChannel } // VoiceChannelDeleteEvent indicates that a api.VoiceChannel got deleted in a api.Guild type VoiceChannelDeleteEvent struct { - GenericVoiceChannelEvent + *GenericVoiceChannelEvent } diff --git a/api/voice_dispatch_interceptor.go b/api/voice_dispatch_interceptor.go index 20b72a53..de974188 100644 --- a/api/voice_dispatch_interceptor.go +++ b/api/voice_dispatch_interceptor.go @@ -2,32 +2,32 @@ package api // VoiceServerUpdateEvent sent when a guilds voice server is updated type VoiceServerUpdateEvent struct { - VoiceServerUpdate - Disgo Disgo + VoiceServerUpdate *VoiceServerUpdate + Disgo Disgo } // Guild returns the Guild for this VoiceServerUpdate from the Cache func (u *VoiceServerUpdateEvent) Guild() *Guild { - return u.Disgo.Cache().Guild(u.GuildID) + return u.Disgo.Cache().Guild(u.VoiceServerUpdate.GuildID) } // VoiceStateUpdateEvent sent when someone joins/leaves/moves voice channels type VoiceStateUpdateEvent struct { - *VoiceState - Member *Member `json:"member"` + VoiceState *VoiceState + Member *Member `json:"member"` } // Guild returns the Guild for this VoiceStateUpdate from the Cache func (u *VoiceStateUpdateEvent) Guild() *Guild { - return u.Disgo.Cache().Guild(u.GuildID) + return u.VoiceState.Disgo.Cache().Guild(u.VoiceState.GuildID) } // VoiceChannel returns the VoiceChannel for this VoiceStateUpdate from the Cache func (u *VoiceStateUpdateEvent) VoiceChannel() *VoiceChannel { - if u.ChannelID == nil { + if u.VoiceState.ChannelID == nil { return nil } - return u.Disgo.Cache().VoiceChannel(*u.ChannelID) + return u.VoiceState.Disgo.Cache().VoiceChannel(*u.VoiceState.ChannelID) } // VoiceDispatchInterceptor lets you listen to VoiceServerUpdate & VoiceStateUpdate diff --git a/example/examplebot.go b/example/examplebot.go index b34f27d1..54be677e 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -47,7 +47,7 @@ func main() { OnGuildMessageCreate: messageListener, OnCommand: commandListener, OnButtonClick: buttonClickListener, - OnSelectMenuSubmit: selectMenuSubmitListener, + OnSelectMenuSubmit: selectMenuSubmitListener, }). Build() if err != nil { @@ -175,17 +175,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 "test1": _ = event.Respond(api.InteractionResponseTypeChannelMessageWithSource, @@ -209,7 +209,7 @@ func buttonClickListener(event events.ButtonClickEvent) { } } -func selectMenuSubmitListener(event events.SelectMenuSubmitEvent) { +func selectMenuSubmitListener(event *events.SelectMenuSubmitEvent) { switch event.CustomID() { case "test3": if err := event.DeferEdit(); err != nil { @@ -223,8 +223,8 @@ func selectMenuSubmitListener(event events.SelectMenuSubmitEvent) { } } -func commandListener(event events.CommandEvent) { - switch event.CommandName { +func commandListener(event *events.CommandEvent) { + switch event.CommandName() { case "eval": go func() { code := event.Option("code").String() @@ -333,7 +333,7 @@ func commandListener(event events.CommandEvent) { } } -func messageListener(event events.GuildMessageCreateEvent) { +func messageListener(event *events.GuildMessageCreateEvent) { if event.Message.Author.IsBot { return } diff --git a/internal/gateway_impl.go b/internal/gateway_impl.go index d516079c..0889b275 100644 --- a/internal/gateway_impl.go +++ b/internal/gateway_impl.go @@ -251,8 +251,8 @@ func (g *GatewayImpl) heartbeat() { func (g *GatewayImpl) sendHeartbeat() { g.Disgo().Logger().Debug("sending heartbeat...") - heartbeatEvent := events.HeartbeatEvent{ - GenericEvent: events.NewEvent(g.Disgo(), 0), + heartbeatEvent := &events.HeartbeatEvent{ + GenericEvent: events.NewGenericEvent(g.Disgo(), 0), OldPing: g.Latency(), } @@ -330,8 +330,8 @@ func (g *GatewayImpl) listen() { if err = g.parseEventToStruct(event, &payload); err != nil { g.Disgo().Logger().Errorf("Error parsing raw gateway event: %s", err) } - g.Disgo().EventManager().Dispatch(events.RawGatewayEvent{ - GenericEvent: events.NewEvent(g.Disgo(), *event.S), + g.Disgo().EventManager().Dispatch(&events.RawGatewayEvent{ + GenericEvent: events.NewGenericEvent(g.Disgo(), *event.S), Type: *event.T, RawPayload: event.D, Payload: payload, diff --git a/internal/handlers/all_handlers.go b/internal/handlers/all_handlers.go index 9d527781..da34d127 100644 --- a/internal/handlers/all_handlers.go +++ b/internal/handlers/all_handlers.go @@ -7,38 +7,38 @@ import ( // GetAllHandlers returns all api.GatewayEventHandler(s) func GetAllHandlers() []api.EventHandler { return []api.EventHandler{ - CommandCreateHandler{}, - CommandDeleteHandler{}, - CommandUpdateHandler{}, + &CommandCreateHandler{}, + &CommandDeleteHandler{}, + &CommandUpdateHandler{}, - ChannelCreateHandler{}, - ChannelDeleteHandler{}, - ChannelUpdateHandler{}, + &ChannelCreateHandler{}, + &ChannelDeleteHandler{}, + &ChannelUpdateHandler{}, - GuildCreateHandler{}, - GuildDeleteHandler{}, - GuildUpdateHandler{}, + &GuildCreateHandler{}, + &GuildDeleteHandler{}, + &GuildUpdateHandler{}, - GuildMemberAddHandler{}, - GuildMemberRemoveHandler{}, - GuildMemberUpdateHandler{}, + &GuildMemberAddHandler{}, + &GuildMemberRemoveHandler{}, + &GuildMemberUpdateHandler{}, - GuildRoleCreateHandler{}, - GuildRoleDeleteHandler{}, - GuildRoleUpdateHandler{}, + &GuildRoleCreateHandler{}, + &GuildRoleDeleteHandler{}, + &GuildRoleUpdateHandler{}, - WebhooksUpdateHandler{}, + &WebhooksUpdateHandler{}, - InteractionCreateHandler{}, - InteractionCreateWebhookHandler{}, + &InteractionCreateHandler{}, + &InteractionCreateWebhookHandler{}, - MessageCreateHandler{}, - MessageUpdateHandler{}, - MessageDeleteHandler{}, + &MessageCreateHandler{}, + &MessageUpdateHandler{}, + &MessageDeleteHandler{}, - ReadyHandler{}, + &ReadyHandler{}, - VoiceServerUpdateHandler{}, - VoiceStateUpdateHandler{}, + &VoiceServerUpdateHandler{}, + &VoiceStateUpdateHandler{}, } } diff --git a/internal/handlers/application_command_create.go b/internal/handlers/application_command_create.go index fd21d2db..37a08943 100644 --- a/internal/handlers/application_command_create.go +++ b/internal/handlers/application_command_create.go @@ -9,17 +9,17 @@ import ( type CommandCreateHandler struct{} // Event returns the raw gateway event Event -func (h CommandCreateHandler) Event() api.GatewayEventType { +func (h *CommandCreateHandler) Event() api.GatewayEventType { return api.GatewayEventCommandCreate } // New constructs a new payload receiver for the raw gateway event -func (h CommandCreateHandler) New() interface{} { +func (h *CommandCreateHandler) New() interface{} { return &api.Command{} } // HandleGatewayEvent handles the specific raw gateway event -func (h CommandCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *CommandCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { command, ok := i.(*api.Command) if !ok { return @@ -37,15 +37,10 @@ func (h CommandCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a command = disgo.EntityBuilder().CreateGlobalCommand(command, cacheStrategy) } - genericCommandEvent := events.GenericCommandEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - CommandID: command.ID, - Command: command, - GuildID: command.GuildID, - } - eventManager.Dispatch(genericCommandEvent) - eventManager.Dispatch(events.CommandCreateEvent{ - GenericCommandEvent: genericCommandEvent, + GenericCommandEvent: &events.GenericCommandEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Command: command, + }, }) } diff --git a/internal/handlers/application_command_delete.go b/internal/handlers/application_command_delete.go index 68cb449b..51cf9b8d 100644 --- a/internal/handlers/application_command_delete.go +++ b/internal/handlers/application_command_delete.go @@ -36,15 +36,10 @@ func (h CommandDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a command = disgo.EntityBuilder().CreateGlobalCommand(command, api.CacheStrategyNo) } - genericCommandEvent := events.GenericCommandEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - CommandID: command.ID, - Command: command, - GuildID: command.GuildID, - } - eventManager.Dispatch(genericCommandEvent) - eventManager.Dispatch(events.CommandDeleteEvent{ - GenericCommandEvent: genericCommandEvent, + GenericCommandEvent: &events.GenericCommandEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Command: command, + }, }) } diff --git a/internal/handlers/application_command_update.go b/internal/handlers/application_command_update.go index 8bca2b93..3ecc227e 100644 --- a/internal/handlers/application_command_update.go +++ b/internal/handlers/application_command_update.go @@ -39,16 +39,11 @@ func (h CommandUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a command = disgo.EntityBuilder().CreateGlobalCommand(command, api.CacheStrategyYes) } - genericCommandEvent := events.GenericCommandEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - CommandID: command.ID, - Command: command, - GuildID: command.GuildID, - } - eventManager.Dispatch(genericCommandEvent) - eventManager.Dispatch(events.CommandUpdateEvent{ - GenericCommandEvent: genericCommandEvent, + GenericCommandEvent: &events.GenericCommandEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Command: command, + }, // always nil for not our own commands OldCommand: oldCommand, }) diff --git a/internal/handlers/channel_create_handler.go b/internal/handlers/channel_create_handler.go index 556d0f84..29d532e7 100644 --- a/internal/handlers/channel_create_handler.go +++ b/internal/handlers/channel_create_handler.go @@ -27,96 +27,69 @@ func (h ChannelCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a channel.Disgo = disgo - genericChannelEvent := events.GenericChannelEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericChannelEvent := &events.GenericChannelEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), ChannelID: channel.ID, Channel: channel, } - eventManager.Dispatch(genericChannelEvent) - var genericGuildChannelEvent events.GenericGuildChannelEvent + var genericGuildChannelEvent *events.GenericGuildChannelEvent if channel.GuildID != nil { - genericGuildChannelEvent = events.GenericGuildChannelEvent{ + genericGuildChannelEvent = &events.GenericGuildChannelEvent{ GuildID: *channel.GuildID, GenericChannelEvent: genericChannelEvent, GuildChannel: &api.GuildChannel{ Channel: *channel, }, } - eventManager.Dispatch(genericGuildChannelEvent) - eventManager.Dispatch(events.GuildChannelCreateEvent{ + eventManager.Dispatch(&events.GuildChannelCreateEvent{ GenericGuildChannelEvent: genericGuildChannelEvent, }) } switch channel.Type { case api.ChannelTypeDM: - dmChannel := disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyYes) - - genericDMChannelEvent := events.GenericDMChannelEvent{ - GenericChannelEvent: genericChannelEvent, - DMChannel: dmChannel, - } - eventManager.Dispatch(genericDMChannelEvent) - - eventManager.Dispatch(events.DMChannelCreateEvent{ - GenericDMChannelEvent: genericDMChannelEvent, + eventManager.Dispatch(&events.DMChannelCreateEvent{ + GenericDMChannelEvent: &events.GenericDMChannelEvent{ + GenericChannelEvent: genericChannelEvent, + DMChannel: disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyYes), + }, }) case api.ChannelTypeGroupDM: disgo.Logger().Warnf("ChannelTypeGroupDM received what the hell discord") case api.ChannelTypeText, api.ChannelTypeNews: - textChannel := disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes) - - genericTextChannelEvent := events.GenericTextChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - TextChannel: textChannel, - } - eventManager.Dispatch(genericTextChannelEvent) - - eventManager.Dispatch(events.TextChannelCreateEvent{ - GenericTextChannelEvent: genericTextChannelEvent, + eventManager.Dispatch(&events.TextChannelCreateEvent{ + GenericTextChannelEvent: &events.GenericTextChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes), + }, }) case api.ChannelTypeStore: - storeChannel := disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes) - - genericStoreChannelEvent := events.GenericStoreChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - StoreChannel: storeChannel, - } - eventManager.Dispatch(genericStoreChannelEvent) - - eventManager.Dispatch(events.StoreChannelCreateEvent{ - GenericStoreChannelEvent: genericStoreChannelEvent, + eventManager.Dispatch(&events.StoreChannelCreateEvent{ + GenericStoreChannelEvent: &events.GenericStoreChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes), + }, }) case api.ChannelTypeCategory: - category := disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes) - - genericCategoryEvent := events.GenericCategoryEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - Category: category, - } - eventManager.Dispatch(genericCategoryEvent) - - eventManager.Dispatch(events.CategoryCreateEvent{ - GenericCategoryEvent: genericCategoryEvent, + eventManager.Dispatch(&events.CategoryCreateEvent{ + GenericCategoryEvent: &events.GenericCategoryEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes), + }, }) case api.ChannelTypeVoice: - voiceChannel := disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes) - - genericVoiceChannelEvent := events.GenericVoiceChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - VoiceChannel: voiceChannel, - } - eventManager.Dispatch(genericVoiceChannelEvent) - - eventManager.Dispatch(events.VoiceChannelCreateEvent{ - GenericVoiceChannelEvent: genericVoiceChannelEvent, + eventManager.Dispatch(&events.VoiceChannelCreateEvent{ + GenericVoiceChannelEvent: &events.GenericVoiceChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes), + }, }) default: diff --git a/internal/handlers/channel_delete_handler.go b/internal/handlers/channel_delete_handler.go index e4124d27..099942a6 100644 --- a/internal/handlers/channel_delete_handler.go +++ b/internal/handlers/channel_delete_handler.go @@ -9,17 +9,17 @@ import ( type ChannelDeleteHandler struct{} // Event returns the raw gateway event Event -func (h ChannelDeleteHandler) Event() api.GatewayEventType { +func (h *ChannelDeleteHandler) Event() api.GatewayEventType { return api.GatewayEventChannelDelete } // New constructs a new payload receiver for the raw gateway event -func (h ChannelDeleteHandler) New() interface{} { +func (h *ChannelDeleteHandler) New() interface{} { return &api.Channel{} } // HandleGatewayEvent handles the specific raw gateway event -func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { channel, ok := i.(*api.Channel) if !ok { return @@ -27,25 +27,23 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a channel.Disgo = disgo - genericChannelEvent := events.GenericChannelEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericChannelEvent := &events.GenericChannelEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), ChannelID: channel.ID, Channel: channel, } - eventManager.Dispatch(genericChannelEvent) - var genericGuildChannelEvent events.GenericGuildChannelEvent + var genericGuildChannelEvent *events.GenericGuildChannelEvent if channel.GuildID != nil { - genericGuildChannelEvent = events.GenericGuildChannelEvent{ + genericGuildChannelEvent = &events.GenericGuildChannelEvent{ GenericChannelEvent: genericChannelEvent, GuildID: *channel.GuildID, GuildChannel: &api.GuildChannel{ Channel: *channel, }, } - eventManager.Dispatch(genericGuildChannelEvent) - eventManager.Dispatch(events.GuildChannelDeleteEvent{ + eventManager.Dispatch(&events.GuildChannelDeleteEvent{ GenericGuildChannelEvent: genericGuildChannelEvent, }) } @@ -54,14 +52,11 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a case api.ChannelTypeDM: disgo.Cache().UncacheDMChannel(channel.ID) - genericDMChannelEvent := events.GenericDMChannelEvent{ - GenericChannelEvent: genericChannelEvent, - DMChannel: disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyNo), - } - eventManager.Dispatch(genericDMChannelEvent) - eventManager.Dispatch(events.DMChannelCreateEvent{ - GenericDMChannelEvent: genericDMChannelEvent, + GenericDMChannelEvent: &events.GenericDMChannelEvent{ + GenericChannelEvent: genericChannelEvent, + DMChannel: disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyNo), + }, }) case api.ChannelTypeGroupDM: @@ -70,53 +65,41 @@ func (h ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a case api.ChannelTypeText, api.ChannelTypeNews: disgo.Cache().UncacheTextChannel(*channel.GuildID, channel.ID) - genericTextChannelEvent := events.GenericTextChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyNo), - } - eventManager.Dispatch(genericTextChannelEvent) - eventManager.Dispatch(events.TextChannelCreateEvent{ - GenericTextChannelEvent: genericTextChannelEvent, + GenericTextChannelEvent: &events.GenericTextChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyNo), + }, }) case api.ChannelTypeStore: disgo.Cache().UncacheStoreChannel(*channel.GuildID, channel.ID) - genericStoreChannelEvent := events.GenericStoreChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyNo), - } - eventManager.Dispatch(genericStoreChannelEvent) - eventManager.Dispatch(events.StoreChannelCreateEvent{ - GenericStoreChannelEvent: genericStoreChannelEvent, + GenericStoreChannelEvent: &events.GenericStoreChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyNo), + }, }) case api.ChannelTypeCategory: disgo.Cache().UncacheCategory(*channel.GuildID, channel.ID) - genericCategoryEvent := events.GenericCategoryEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyNo), - } - eventManager.Dispatch(genericCategoryEvent) - eventManager.Dispatch(events.CategoryCreateEvent{ - GenericCategoryEvent: genericCategoryEvent, + GenericCategoryEvent: &events.GenericCategoryEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyNo), + }, }) case api.ChannelTypeVoice: disgo.Cache().UncacheVoiceChannel(*channel.GuildID, channel.ID) - genericVoiceChannelEvent := events.GenericVoiceChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyNo), - } - eventManager.Dispatch(genericVoiceChannelEvent) - eventManager.Dispatch(events.VoiceChannelCreateEvent{ - GenericVoiceChannelEvent: genericVoiceChannelEvent, + GenericVoiceChannelEvent: &events.GenericVoiceChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyNo), + }, }) default: diff --git a/internal/handlers/channel_update_handler.go b/internal/handlers/channel_update_handler.go index 2aaa7441..984b759b 100644 --- a/internal/handlers/channel_update_handler.go +++ b/internal/handlers/channel_update_handler.go @@ -27,25 +27,23 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a channel.Disgo = disgo - genericChannelEvent := events.GenericChannelEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericChannelEvent := &events.GenericChannelEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), ChannelID: channel.ID, Channel: channel, } - eventManager.Dispatch(genericChannelEvent) - var genericGuildChannelEvent events.GenericGuildChannelEvent + var genericGuildChannelEvent *events.GenericGuildChannelEvent if channel.GuildID != nil { - genericGuildChannelEvent = events.GenericGuildChannelEvent{ + genericGuildChannelEvent = &events.GenericGuildChannelEvent{ GenericChannelEvent: genericChannelEvent, GuildID: *channel.GuildID, GuildChannel: &api.GuildChannel{ Channel: *channel, }, } - eventManager.Dispatch(genericGuildChannelEvent) - eventManager.Dispatch(events.GuildChannelUpdateEvent{ + eventManager.Dispatch(&events.GuildChannelUpdateEvent{ GenericGuildChannelEvent: genericGuildChannelEvent, OldGuildChannel: disgo.Cache().GuildChannel(channel.ID), }) @@ -58,15 +56,12 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a oldDMChannel = &*oldDMChannel } - genericDMChannelEvent := events.GenericDMChannelEvent{ - GenericChannelEvent: genericChannelEvent, - DMChannel: disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyYes), - } - eventManager.Dispatch(genericDMChannelEvent) - - eventManager.Dispatch(events.DMChannelUpdateEvent{ - GenericDMChannelEvent: genericDMChannelEvent, - OldDMChannel: oldDMChannel, + eventManager.Dispatch(&events.DMChannelUpdateEvent{ + GenericDMChannelEvent: &events.GenericDMChannelEvent{ + GenericChannelEvent: genericChannelEvent, + DMChannel: disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyYes), + }, + OldDMChannel: oldDMChannel, }) case api.ChannelTypeGroupDM: @@ -78,15 +73,12 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a oldTextChannel = &*oldTextChannel } - genericTextChannelEvent := events.GenericTextChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes), - } - eventManager.Dispatch(genericTextChannelEvent) - - eventManager.Dispatch(events.TextChannelUpdateEvent{ - GenericTextChannelEvent: genericTextChannelEvent, - OldTextChannel: oldTextChannel, + eventManager.Dispatch(&events.TextChannelUpdateEvent{ + GenericTextChannelEvent: &events.GenericTextChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyYes), + }, + OldTextChannel: oldTextChannel, }) case api.ChannelTypeStore: @@ -95,15 +87,12 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a oldStoreChannel = &*oldStoreChannel } - genericStoreChannelEvent := events.GenericStoreChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes), - } - eventManager.Dispatch(genericStoreChannelEvent) - - eventManager.Dispatch(events.StoreChannelUpdateEvent{ - GenericStoreChannelEvent: genericStoreChannelEvent, - OldStoreChannel: oldStoreChannel, + eventManager.Dispatch(&events.StoreChannelUpdateEvent{ + GenericStoreChannelEvent: &events.GenericStoreChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyYes), + }, + OldStoreChannel: oldStoreChannel, }) case api.ChannelTypeCategory: @@ -112,15 +101,12 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a oldCategory = &*oldCategory } - genericCategoryEvent := events.GenericCategoryEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes), - } - eventManager.Dispatch(genericCategoryEvent) - - eventManager.Dispatch(events.CategoryUpdateEvent{ - GenericCategoryEvent: genericCategoryEvent, - OldCategory: oldCategory, + eventManager.Dispatch(&events.CategoryUpdateEvent{ + GenericCategoryEvent: &events.GenericCategoryEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyYes), + }, + OldCategory: oldCategory, }) case api.ChannelTypeVoice: @@ -129,15 +115,12 @@ func (h ChannelUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a oldVoiceChannel = &*oldVoiceChannel } - genericVoiceChannelEvent := events.GenericVoiceChannelEvent{ - GenericGuildChannelEvent: genericGuildChannelEvent, - VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes), - } - eventManager.Dispatch(genericVoiceChannelEvent) - - eventManager.Dispatch(events.VoiceChannelUpdateEvent{ - GenericVoiceChannelEvent: genericVoiceChannelEvent, - OldVoiceChannel: oldVoiceChannel, + eventManager.Dispatch(&events.VoiceChannelUpdateEvent{ + GenericVoiceChannelEvent: &events.GenericVoiceChannelEvent{ + GenericGuildChannelEvent: genericGuildChannelEvent, + VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyYes), + }, + OldVoiceChannel: oldVoiceChannel, }) default: diff --git a/internal/handlers/guild_create_handler.go b/internal/handlers/guild_create_handler.go index 0902df42..67f3b3e0 100644 --- a/internal/handlers/guild_create_handler.go +++ b/internal/handlers/guild_create_handler.go @@ -9,17 +9,17 @@ import ( type GuildCreateHandler struct{} // Event returns the raw gateway event Event -func (h GuildCreateHandler) Event() api.GatewayEventType { +func (h *GuildCreateHandler) Event() api.GatewayEventType { return api.GatewayEventGuildCreate } // New constructs a new payload receiver for the raw gateway event -func (h GuildCreateHandler) New() interface{} { +func (h *GuildCreateHandler) New() interface{} { return &api.FullGuild{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { fullGuild, ok := i.(*api.FullGuild) if !ok { return @@ -33,26 +33,25 @@ func (h GuildCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api } guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyYes) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericGuildEvent := &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), GuildID: guild.ID, Guild: guild, } - eventManager.Dispatch(genericGuildEvent) if !guild.Ready { guild.Ready = true - eventManager.Dispatch(events.GuildReadyEvent{ + eventManager.Dispatch(&events.GuildReadyEvent{ GenericGuildEvent: genericGuildEvent, }) } if wasUnavailable { - eventManager.Dispatch(events.GuildAvailableEvent{ + eventManager.Dispatch(&events.GuildAvailableEvent{ GenericGuildEvent: genericGuildEvent, }) } else { - eventManager.Dispatch(events.GuildJoinEvent{ + eventManager.Dispatch(&events.GuildJoinEvent{ GenericGuildEvent: genericGuildEvent, }) } diff --git a/internal/handlers/guild_delete_handler.go b/internal/handlers/guild_delete_handler.go index 27e1cf3f..be009c6e 100644 --- a/internal/handlers/guild_delete_handler.go +++ b/internal/handlers/guild_delete_handler.go @@ -9,17 +9,17 @@ import ( type GuildDeleteHandler struct{} // Event returns the raw gateway event Event -func (h GuildDeleteHandler) Event() api.GatewayEventType { +func (h *GuildDeleteHandler) Event() api.GatewayEventType { return api.GatewayEventGuildDelete } // New constructs a new payload receiver for the raw gateway event -func (h GuildDeleteHandler) New() interface{} { +func (h *GuildDeleteHandler) New() interface{} { return &api.FullGuild{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { fullGuild, ok := i.(*api.FullGuild) if !ok { return @@ -27,11 +27,10 @@ func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyNo) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericGuildEvent := &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), Guild: guild, } - eventManager.Dispatch(genericGuildEvent) if guild.Unavailable { // set guild to unavailable for now @@ -40,13 +39,13 @@ func (h GuildDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api g.Unavailable = true } - eventManager.Dispatch(events.GuildUnavailableEvent{ + eventManager.Dispatch(&events.GuildUnavailableEvent{ GenericGuildEvent: genericGuildEvent, }) } else { disgo.Cache().UncacheGuild(guild.ID) - eventManager.Dispatch(events.GuildLeaveEvent{ + eventManager.Dispatch(&events.GuildLeaveEvent{ GenericGuildEvent: genericGuildEvent, }) } diff --git a/internal/handlers/guild_member_add_handler.go b/internal/handlers/guild_member_add_handler.go index fc10eace..0060740a 100644 --- a/internal/handlers/guild_member_add_handler.go +++ b/internal/handlers/guild_member_add_handler.go @@ -9,17 +9,17 @@ import ( type GuildMemberAddHandler struct{} // Event returns the raw gateway event Event -func (h GuildMemberAddHandler) Event() api.GatewayEventType { +func (h *GuildMemberAddHandler) Event() api.GatewayEventType { return api.GatewayEventGuildMemberAdd } // New constructs a new payload receiver for the raw gateway event -func (h GuildMemberAddHandler) New() interface{} { +func (h *GuildMemberAddHandler) New() interface{} { return &api.Member{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildMemberAddHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildMemberAddHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { member, ok := i.(*api.Member) if !ok { return @@ -32,19 +32,13 @@ func (h GuildMemberAddHandler) HandleGatewayEvent(disgo api.Disgo, eventManager } member = disgo.EntityBuilder().CreateMember(member.GuildID, member, api.CacheStrategyYes) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - eventManager.Dispatch(genericGuildEvent) - - genericGuildMemberEvent := events.GenericGuildMemberEvent{ - GenericGuildEvent: genericGuildEvent, - Member: member, - } - eventManager.Dispatch(genericGuildMemberEvent) - eventManager.Dispatch(events.GuildMemberJoinEvent{ - GenericGuildMemberEvent: genericGuildMemberEvent, + GenericGuildMemberEvent: &events.GenericGuildMemberEvent{ + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + Member: member, + }, }) } diff --git a/internal/handlers/guild_member_remove_handler.go b/internal/handlers/guild_member_remove_handler.go index 6918e9e5..680d5d47 100644 --- a/internal/handlers/guild_member_remove_handler.go +++ b/internal/handlers/guild_member_remove_handler.go @@ -14,17 +14,17 @@ type guildMemberRemoveData struct { type GuildMemberRemoveHandler struct{} // Event returns the raw gateway event Event -func (h GuildMemberRemoveHandler) Event() api.GatewayEventType { +func (h *GuildMemberRemoveHandler) Event() api.GatewayEventType { return api.GatewayEventGuildMemberRemove } // New constructs a new payload receiver for the raw gateway event -func (h GuildMemberRemoveHandler) New() interface{} { +func (h *GuildMemberRemoveHandler) New() interface{} { return &guildMemberRemoveData{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildMemberRemoveHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildMemberRemoveHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { memberData, ok := i.(*guildMemberRemoveData) if !ok { return @@ -40,19 +40,13 @@ func (h GuildMemberRemoveHandler) HandleGatewayEvent(disgo api.Disgo, eventManag member := disgo.Cache().Member(memberData.GuildID, memberData.User.ID) disgo.Cache().UncacheMember(memberData.GuildID, memberData.User.ID) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - eventManager.Dispatch(genericGuildEvent) - - genericGuildMemberEvent := events.GenericGuildMemberEvent{ - GenericGuildEvent: genericGuildEvent, - Member: member, - } - eventManager.Dispatch(genericGuildMemberEvent) - eventManager.Dispatch(events.GuildMemberLeaveEvent{ - GenericGuildMemberEvent: genericGuildMemberEvent, + GenericGuildMemberEvent: &events.GenericGuildMemberEvent{ + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + Member: member, + }, }) } diff --git a/internal/handlers/guild_member_update_handler.go b/internal/handlers/guild_member_update_handler.go index 7fc6a6f0..d493b04d 100644 --- a/internal/handlers/guild_member_update_handler.go +++ b/internal/handlers/guild_member_update_handler.go @@ -9,17 +9,17 @@ import ( type GuildMemberUpdateHandler struct{} // Event returns the raw gateway event Event -func (h GuildMemberUpdateHandler) Event() api.GatewayEventType { +func (h *GuildMemberUpdateHandler) Event() api.GatewayEventType { return api.GatewayEventGuildMemberUpdate } // New constructs a new payload receiver for the raw gateway event -func (h GuildMemberUpdateHandler) New() interface{} { +func (h *GuildMemberUpdateHandler) New() interface{} { return &api.Member{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildMemberUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildMemberUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { member, ok := i.(*api.Member) if !ok { return @@ -37,20 +37,14 @@ func (h GuildMemberUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManag } member = disgo.EntityBuilder().CreateMember(member.GuildID, member, api.CacheStrategyYes) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - eventManager.Dispatch(genericGuildEvent) - - genericGuildMemberEvent := events.GenericGuildMemberEvent{ - GenericGuildEvent: genericGuildEvent, - Member: member, - } - eventManager.Dispatch(genericGuildMemberEvent) - eventManager.Dispatch(events.GuildMemberUpdateEvent{ - GenericGuildMemberEvent: genericGuildMemberEvent, - OldMember: oldMember, + GenericGuildMemberEvent: &events.GenericGuildMemberEvent{ + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + Member: member, + }, + OldMember: oldMember, }) } diff --git a/internal/handlers/guild_role_create_handler.go b/internal/handlers/guild_role_create_handler.go index 1116ba68..6385a200 100644 --- a/internal/handlers/guild_role_create_handler.go +++ b/internal/handlers/guild_role_create_handler.go @@ -14,17 +14,17 @@ type roleCreateData struct { type GuildRoleCreateHandler struct{} // Event returns the raw gateway event Event -func (h GuildRoleCreateHandler) Event() api.GatewayEventType { +func (h *GuildRoleCreateHandler) Event() api.GatewayEventType { return api.GatewayEventGuildRoleCreate } // New constructs a new payload receiver for the raw gateway event -func (h GuildRoleCreateHandler) New() interface{} { +func (h *GuildRoleCreateHandler) New() interface{} { return &roleCreateData{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildRoleCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildRoleCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { roleCreateData, ok := i.(*roleCreateData) if !ok { return @@ -34,20 +34,14 @@ func (h GuildRoleCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager role := disgo.EntityBuilder().CreateRole(roleCreateData.GuildID, roleCreateData.Role, api.CacheStrategyYes) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - eventManager.Dispatch(genericGuildEvent) - - genericRoleEvent := events.GenericRoleEvent{ - GenericGuildEvent: genericGuildEvent, - RoleID: role.ID, - Role: role, - } - eventManager.Dispatch(genericRoleEvent) - - eventManager.Dispatch(events.RoleCreateEvent{ - GenericGuildEvent: genericGuildEvent, + eventManager.Dispatch(&events.RoleCreateEvent{ + GenericRoleEvent: &events.GenericRoleEvent{ + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + RoleID: role.ID, + Role: role, + }, }) } diff --git a/internal/handlers/guild_role_delete_handler.go b/internal/handlers/guild_role_delete_handler.go index b835541d..a067db3b 100644 --- a/internal/handlers/guild_role_delete_handler.go +++ b/internal/handlers/guild_role_delete_handler.go @@ -14,17 +14,17 @@ type roleDeleteData struct { type GuildRoleDeleteHandler struct{} // Event returns the raw gateway event Event -func (h GuildRoleDeleteHandler) Event() api.GatewayEventType { +func (h *GuildRoleDeleteHandler) Event() api.GatewayEventType { return api.GatewayEventGuildRoleDelete } // New constructs a new payload receiver for the raw gateway event -func (h GuildRoleDeleteHandler) New() interface{} { +func (h *GuildRoleDeleteHandler) New() interface{} { return &roleCreateData{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildRoleDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildRoleDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { roleDeleteData, ok := i.(*roleDeleteData) if !ok { return @@ -41,20 +41,14 @@ func (h GuildRoleDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager disgo.Cache().UncacheRole(roleDeleteData.GuildID, roleDeleteData.RoleID) } - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - eventManager.Dispatch(genericGuildEvent) - - genericRoleEvent := events.GenericRoleEvent{ - GenericGuildEvent: genericGuildEvent, - RoleID: roleDeleteData.RoleID, - Role: role, - } - eventManager.Dispatch(genericRoleEvent) - eventManager.Dispatch(events.RoleDeleteEvent{ - GenericGuildEvent: genericGuildEvent, + GenericRoleEvent: &events.GenericRoleEvent{ + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + RoleID: roleDeleteData.RoleID, + Role: role, + }, }) } diff --git a/internal/handlers/guild_role_update_handler.go b/internal/handlers/guild_role_update_handler.go index 2182612e..3cf8c3ed 100644 --- a/internal/handlers/guild_role_update_handler.go +++ b/internal/handlers/guild_role_update_handler.go @@ -14,17 +14,17 @@ type roleUpdateData struct { type GuildRoleUpdateHandler struct{} // Event returns the raw gateway event Event -func (h GuildRoleUpdateHandler) Event() api.GatewayEventType { +func (h *GuildRoleUpdateHandler) Event() api.GatewayEventType { return api.GatewayEventGuildRoleUpdate } // New constructs a new payload receiver for the raw gateway event -func (h GuildRoleUpdateHandler) New() interface{} { +func (h *GuildRoleUpdateHandler) New() interface{} { return &roleUpdateData{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildRoleUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildRoleUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { roleUpdateData, ok := i.(*roleUpdateData) if !ok { return @@ -42,21 +42,15 @@ func (h GuildRoleUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager } role := disgo.EntityBuilder().CreateRole(roleUpdateData.GuildID, roleUpdateData.Role, api.CacheStrategyYes) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - eventManager.Dispatch(genericGuildEvent) - - genericRoleEvent := events.GenericRoleEvent{ - GenericGuildEvent: genericGuildEvent, - RoleID: roleUpdateData.Role.ID, - Role: role, - } - eventManager.Dispatch(genericRoleEvent) - eventManager.Dispatch(events.RoleUpdateEvent{ - GenericGuildEvent: genericGuildEvent, - OldRole: oldRole, + GenericRoleEvent: &events.GenericRoleEvent{ + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + RoleID: roleUpdateData.Role.ID, + Role: role, + }, + OldRole: oldRole, }) } diff --git a/internal/handlers/guild_update_handler.go b/internal/handlers/guild_update_handler.go index 836b0a9b..b1db2927 100644 --- a/internal/handlers/guild_update_handler.go +++ b/internal/handlers/guild_update_handler.go @@ -9,17 +9,17 @@ import ( type GuildUpdateHandler struct{} // Event returns the raw gateway event Event -func (h GuildUpdateHandler) Event() api.GatewayEventType { +func (h *GuildUpdateHandler) Event() api.GatewayEventType { return api.GatewayEventGuildUpdate } // New constructs a new payload receiver for the raw gateway event -func (h GuildUpdateHandler) New() interface{} { +func (h *GuildUpdateHandler) New() interface{} { return &api.FullGuild{} } // HandleGatewayEvent handles the specific raw gateway event -func (h GuildUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *GuildUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { fullGuild, ok := i.(*api.FullGuild) if !ok { return @@ -31,15 +31,12 @@ func (h GuildUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api } guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyYes) - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - eventManager.Dispatch(genericGuildEvent) - eventManager.Dispatch(events.GuildUpdateEvent{ - GenericGuildEvent: genericGuildEvent, - OldGuild: oldGuild, + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + OldGuild: oldGuild, }) } diff --git a/internal/handlers/interaction_create_handler.go b/internal/handlers/interaction_create_handler.go index c3ccdc16..5724824a 100644 --- a/internal/handlers/interaction_create_handler.go +++ b/internal/handlers/interaction_create_handler.go @@ -30,17 +30,16 @@ func (h InteractionCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManag func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, fullInteraction *api.FullInteraction, c chan api.InteractionResponse) { interaction := disgo.EntityBuilder().CreateInteraction(fullInteraction, c, api.CacheStrategyYes) - genericInteractionEvent := events.GenericInteractionEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericInteractionEvent := &events.GenericInteractionEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), Interaction: interaction, } - eventManager.Dispatch(genericInteractionEvent) switch fullInteraction.Type { case api.InteractionTypeCommand: commandInteraction := disgo.EntityBuilder().CreateCommandInteraction(fullInteraction, interaction, api.CacheStrategyYes) - options := commandInteraction.Data.Options + options := commandInteraction.Data.RawOptions var subCommandName *string var subCommandGroupName *string if len(options) == 1 { @@ -66,24 +65,21 @@ func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceN }) } - eventManager.Dispatch(events.CommandEvent{ + commandInteraction.Data.SubCommandName = subCommandName + commandInteraction.Data.SubCommandGroupName = subCommandGroupName + + eventManager.Dispatch(&events.CommandEvent{ GenericInteractionEvent: genericInteractionEvent, CommandInteraction: commandInteraction, - CommandID: commandInteraction.Data.ID, - CommandName: commandInteraction.Data.Name, - SubCommandName: subCommandName, - SubCommandGroupName: subCommandGroupName, - Options: newOptions, }) case api.InteractionTypeComponent: componentInteraction := disgo.EntityBuilder().CreateComponentInteraction(fullInteraction, interaction, api.CacheStrategyYes) - genericComponentEvent := events.GenericComponentEvent{ + genericComponentEvent := &events.GenericComponentEvent{ GenericInteractionEvent: genericInteractionEvent, ComponentInteraction: componentInteraction, } - eventManager.Dispatch(genericComponentEvent) switch componentInteraction.Data.ComponentType { case api.ComponentTypeButton: diff --git a/internal/handlers/interaction_create_webhook_handler.go b/internal/handlers/interaction_create_webhook_handler.go index ddc4660c..b0d445fa 100644 --- a/internal/handlers/interaction_create_webhook_handler.go +++ b/internal/handlers/interaction_create_webhook_handler.go @@ -24,6 +24,8 @@ func (h InteractionCreateWebhookHandler) HandleWebhookEvent(disgo api.Disgo, eve return } + // we just want to pong all pings + // no need for any event if fullInteraction.Type == api.InteractionTypePing { disgo.Logger().Debugf("received interaction ping") c <- api.InteractionResponse{ diff --git a/internal/handlers/message_create_handler.go b/internal/handlers/message_create_handler.go index 13378e53..aad8328a 100644 --- a/internal/handlers/message_create_handler.go +++ b/internal/handlers/message_create_handler.go @@ -9,17 +9,17 @@ import ( type MessageCreateHandler struct{} // Event returns the raw gateway event Event -func (h MessageCreateHandler) Event() api.GatewayEventType { +func (h *MessageCreateHandler) Event() api.GatewayEventType { return api.GatewayEventMessageCreate } // New constructs a new payload receiver for the raw gateway event -func (h MessageCreateHandler) New() interface{} { +func (h *MessageCreateHandler) New() interface{} { return &api.Message{} } // HandleGatewayEvent handles the specific raw gateway event -func (h MessageCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *MessageCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { message, ok := i.(*api.Message) if !ok { return @@ -27,36 +27,29 @@ func (h MessageCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a message = disgo.EntityBuilder().CreateMessage(message, api.CacheStrategyYes) - genericMessageEvent := events.GenericMessageEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericMessageEvent := &events.GenericMessageEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), MessageID: message.ID, Message: message, ChannelID: message.ChannelID, } - eventManager.Dispatch(genericMessageEvent) eventManager.Dispatch(events.MessageCreateEvent{ GenericMessageEvent: genericMessageEvent, }) if message.GuildID == nil { - genericDMMessageEvent := events.GenericDMMessageEvent{ - GenericMessageEvent: genericMessageEvent, - } - eventManager.Dispatch(genericDMMessageEvent) - eventManager.Dispatch(events.DMMessageCreateEvent{ - GenericDMMessageEvent: genericDMMessageEvent, + GenericDMMessageEvent: &events.GenericDMMessageEvent{ + GenericMessageEvent: genericMessageEvent, + }, }) } else { - genericGuildMessageEvent := events.GenericGuildMessageEvent{ - GenericMessageEvent: genericMessageEvent, - GuildID: *message.GuildID, - } - eventManager.Dispatch(genericGuildMessageEvent) - eventManager.Dispatch(events.GuildMessageCreateEvent{ - GenericGuildMessageEvent: genericGuildMessageEvent, + GenericGuildMessageEvent: &events.GenericGuildMessageEvent{ + GenericMessageEvent: genericMessageEvent, + GuildID: *message.GuildID, + }, }) } diff --git a/internal/handlers/message_delete_handler.go b/internal/handlers/message_delete_handler.go index 3dfad6e7..3e01855a 100644 --- a/internal/handlers/message_delete_handler.go +++ b/internal/handlers/message_delete_handler.go @@ -14,16 +14,16 @@ type messageDeletePayload struct { type MessageDeleteHandler struct{} // Event returns the raw gateway event Event -func (h MessageDeleteHandler) Event() api.GatewayEventType { +func (h *MessageDeleteHandler) Event() api.GatewayEventType { return api.GatewayEventMessageDelete } // New constructs a new payload receiver for the raw gateway event -func (h MessageDeleteHandler) New() interface{} { +func (h *MessageDeleteHandler) New() interface{} { return &messageDeletePayload{} } // HandleGatewayEvent handles the specific raw gateway event -func (h MessageDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *MessageDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { //payload, ok := i.(*api.messageDeletePayload) } diff --git a/internal/handlers/message_update_handler.go b/internal/handlers/message_update_handler.go index 8bbd7cde..c5dd4e5d 100644 --- a/internal/handlers/message_update_handler.go +++ b/internal/handlers/message_update_handler.go @@ -9,17 +9,17 @@ import ( type MessageUpdateHandler struct{} // Event returns the raw gateway event Event -func (h MessageUpdateHandler) Event() api.GatewayEventType { +func (h *MessageUpdateHandler) Event() api.GatewayEventType { return api.GatewayEventMessageUpdate } // New constructs a new payload receiver for the raw gateway event -func (h MessageUpdateHandler) New() interface{} { +func (h *MessageUpdateHandler) New() interface{} { return &api.Message{} } // HandleGatewayEvent handles the specific raw gateway event -func (h MessageUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *MessageUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { message, ok := i.(*api.Message) if !ok { return @@ -32,11 +32,10 @@ func (h MessageUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a message = disgo.EntityBuilder().CreateMessage(message, api.CacheStrategyYes) - genericMessageEvent := events.GenericMessageEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + genericMessageEvent := &events.GenericMessageEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), Message: message, } - eventManager.Dispatch(genericMessageEvent) eventManager.Dispatch(events.MessageUpdateEvent{ GenericMessageEvent: genericMessageEvent, @@ -44,25 +43,20 @@ func (h MessageUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a }) if message.GuildID == nil { - genericDMMessageEvent := events.GenericDMMessageEvent{ - GenericMessageEvent: genericMessageEvent, - } - eventManager.Dispatch(genericDMMessageEvent) - eventManager.Dispatch(events.DMMessageUpdateEvent{ - GenericDMMessageEvent: genericDMMessageEvent, - OldMessage: oldMessage, + GenericDMMessageEvent: &events.GenericDMMessageEvent{ + GenericMessageEvent: genericMessageEvent, + }, + OldMessage: oldMessage, }) } else { - genericGuildMessageEvent := events.GenericGuildMessageEvent{ - GenericMessageEvent: genericMessageEvent, - GuildID: *message.GuildID, - } - eventManager.Dispatch(genericGuildMessageEvent) eventManager.Dispatch(events.GuildMessageUpdateEvent{ - GenericGuildMessageEvent: genericGuildMessageEvent, - OldMessage: oldMessage, + GenericGuildMessageEvent: &events.GenericGuildMessageEvent{ + GenericMessageEvent: genericMessageEvent, + GuildID: *message.GuildID, + }, + OldMessage: oldMessage, }) } } diff --git a/internal/handlers/ready_handler.go b/internal/handlers/ready_handler.go index b1af4ad7..10bbea72 100644 --- a/internal/handlers/ready_handler.go +++ b/internal/handlers/ready_handler.go @@ -9,17 +9,17 @@ import ( type ReadyHandler struct{} // Event returns the raw gateway event Event -func (h ReadyHandler) Event() api.GatewayEventType { +func (h *ReadyHandler) Event() api.GatewayEventType { return api.GatewayEventReady } // New constructs a new payload receiver for the raw gateway event -func (h ReadyHandler) New() interface{} { +func (h *ReadyHandler) New() interface{} { return &api.ReadyGatewayEvent{} } // HandleGatewayEvent handles the specific raw gateway event -func (h ReadyHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *ReadyHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { readyEvent, ok := i.(*api.ReadyGatewayEvent) if !ok { return @@ -31,8 +31,8 @@ func (h ReadyHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.Event disgo.Cache().CacheGuild(readyEvent.Guilds[i]) } - disgo.EventManager().Dispatch(events.ReadyEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), + disgo.EventManager().Dispatch(&events.ReadyEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), ReadyGatewayEvent: readyEvent, }) diff --git a/internal/handlers/voice_server_update_handler.go b/internal/handlers/voice_server_update_handler.go index 33ee9fb1..31c7e1c6 100644 --- a/internal/handlers/voice_server_update_handler.go +++ b/internal/handlers/voice_server_update_handler.go @@ -6,17 +6,17 @@ import "github.com/DisgoOrg/disgo/api" type VoiceServerUpdateHandler struct{} // Event returns the raw gateway event Event -func (h VoiceServerUpdateHandler) Event() api.GatewayEventType { +func (h *VoiceServerUpdateHandler) Event() api.GatewayEventType { return api.GatewayEventVoiceServerUpdate } // New constructs a new payload receiver for the raw gateway event -func (h VoiceServerUpdateHandler) New() interface{} { +func (h *VoiceServerUpdateHandler) New() interface{} { return &api.VoiceServerUpdate{} } // HandleGatewayEvent handles the specific raw gateway event -func (h VoiceServerUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *VoiceServerUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { voiceServerUpdate, ok := i.(*api.VoiceServerUpdate) if !ok { return @@ -24,7 +24,7 @@ func (h VoiceServerUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManag if interceptor := disgo.VoiceDispatchInterceptor(); interceptor != nil { interceptor.OnVoiceServerUpdate(&api.VoiceServerUpdateEvent{ - VoiceServerUpdate: *voiceServerUpdate, + VoiceServerUpdate: voiceServerUpdate, Disgo: disgo, }) } diff --git a/internal/handlers/voice_state_update_handler.go b/internal/handlers/voice_state_update_handler.go index 0eae20ea..c115cdab 100644 --- a/internal/handlers/voice_state_update_handler.go +++ b/internal/handlers/voice_state_update_handler.go @@ -9,32 +9,32 @@ import ( type VoiceStateUpdateHandler struct{} // Event returns the raw gateway event Event -func (h VoiceStateUpdateHandler) Event() api.GatewayEventType { +func (h *VoiceStateUpdateHandler) Event() api.GatewayEventType { return api.GatewayEventVoiceStateUpdate } // New constructs a new payload receiver for the raw gateway event -func (h VoiceStateUpdateHandler) New() interface{} { +func (h *VoiceStateUpdateHandler) New() interface{} { return &api.VoiceStateUpdateEvent{} } // HandleGatewayEvent handles the specific raw gateway event -func (h VoiceStateUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { +func (h *VoiceStateUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager api.EventManager, sequenceNumber int, i interface{}) { voiceStateUpdate, ok := i.(*api.VoiceStateUpdateEvent) if !ok { return } - oldVoiceState := disgo.Cache().VoiceState(voiceStateUpdate.GuildID, voiceStateUpdate.UserID) + oldVoiceState := disgo.Cache().VoiceState(voiceStateUpdate.VoiceState.GuildID, voiceStateUpdate.VoiceState.UserID) if oldVoiceState != nil { oldVoiceState = &*oldVoiceState } member := disgo.EntityBuilder().CreateMember(voiceStateUpdate.Member.GuildID, voiceStateUpdate.Member, api.CacheStrategyYes) - voiceState := disgo.EntityBuilder().CreateVoiceState(voiceStateUpdate.GuildID, voiceStateUpdate.VoiceState, api.CacheStrategyYes) + voiceState := disgo.EntityBuilder().CreateVoiceState(voiceStateUpdate.VoiceState.GuildID, voiceStateUpdate.VoiceState, api.CacheStrategyYes) // voice state update for ourself received // execute voice VoiceDispatchInterceptor.OnVoiceStateUpdate - if disgo.ApplicationID() == voiceStateUpdate.UserID { + if disgo.ClientID() == voiceStateUpdate.VoiceState.UserID { if interceptor := disgo.VoiceDispatchInterceptor(); interceptor != nil { interceptor.OnVoiceStateUpdate(voiceStateUpdate) } @@ -42,33 +42,27 @@ func (h VoiceStateUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManage guild := voiceStateUpdate.Guild() if guild == nil { - disgo.Logger().Warnf("received guild voice state update for unknown guild: %s", voiceStateUpdate.GuildID) + disgo.Logger().Warnf("received guild voice state update for unknown guild: %s", voiceStateUpdate.VoiceState.GuildID) return } - genericGuildEvent := events.GenericGuildEvent{ - GenericEvent: events.NewEvent(disgo, sequenceNumber), - Guild: guild, - } - disgo.EventManager().Dispatch(genericGuildEvent) - - genericGuildMemberEvent := events.GenericGuildMemberEvent{ - GenericGuildEvent: genericGuildEvent, - Member: member, - } - disgo.EventManager().Dispatch(genericGuildMemberEvent) - - genericGuildVoiceEvent := events.GenericGuildVoiceEvent{ - GenericGuildMemberEvent: genericGuildMemberEvent, - VoiceState: voiceState, + genericGuildVoiceEvent := &events.GenericGuildVoiceEvent{ + GenericGuildMemberEvent: &events.GenericGuildMemberEvent{ + GenericGuildEvent: &events.GenericGuildEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + Guild: guild, + }, + Member: member, + }, + VoiceState: voiceState, } disgo.EventManager().Dispatch(genericGuildVoiceEvent) - if (oldVoiceState == nil || oldVoiceState.ChannelID == nil) && voiceStateUpdate.ChannelID != nil { + if (oldVoiceState == nil || oldVoiceState.ChannelID == nil) && voiceStateUpdate.VoiceState.ChannelID != nil { disgo.EventManager().Dispatch(events.GuildVoiceJoinEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent}) - } else if oldVoiceState != nil && oldVoiceState.ChannelID != nil && voiceStateUpdate.ChannelID == nil { + } else if oldVoiceState != nil && oldVoiceState.ChannelID != nil && voiceStateUpdate.VoiceState.ChannelID == nil { disgo.EventManager().Dispatch(events.GuildVoiceLeaveEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent}) - } else if oldVoiceState != nil && oldVoiceState.ChannelID != nil && voiceStateUpdate.ChannelID != nil { + } else if oldVoiceState != nil && oldVoiceState.ChannelID != nil && voiceStateUpdate.VoiceState.ChannelID != nil { disgo.EventManager().Dispatch(events.GuildVoiceUpdateEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent, OldVoiceState: oldVoiceState}) } else { disgo.Logger().Warnf("could not decide which GuildVoiceEvent to fire") diff --git a/internal/handlers/webhooks_update_handler.go b/internal/handlers/webhooks_update_handler.go index 3c81cb1c..6421b30d 100644 --- a/internal/handlers/webhooks_update_handler.go +++ b/internal/handlers/webhooks_update_handler.go @@ -14,43 +14,34 @@ type webhooksUpdateData struct { type WebhooksUpdateHandler struct{} // Event returns the raw api.GatewayEventType -func (h WebhooksUpdateHandler) Event() 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{} { +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{}) { +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, + GenericTextChannelEvent: &events.GenericTextChannelEvent{ + GenericGuildChannelEvent: &events.GenericGuildChannelEvent{ + GenericChannelEvent: &events.GenericChannelEvent{ + GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), + ChannelID: webhooksUpdateData.ChannelID, + Channel: disgo.Cache().Channel(webhooksUpdateData.ChannelID), + }, + GuildID: webhooksUpdateData.GuildID, + GuildChannel: disgo.Cache().GuildChannel(webhooksUpdateData.ChannelID), + }, + TextChannel: disgo.Cache().TextChannel(webhooksUpdateData.ChannelID), + }, }) } From a7da88aee7f2c9ffc98e21f55b7ab81cb4e8c166 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 6 Jul 2021 18:30:26 +0200 Subject: [PATCH 59/64] fixed non pointers --- api/events/generic_event.go | 4 +--- api/events/listener_adapter.go | 8 +++++++- internal/handlers/application_command_delete.go | 2 +- internal/handlers/application_command_update.go | 2 +- internal/handlers/channel_delete_handler.go | 10 +++++----- internal/handlers/guild_member_add_handler.go | 2 +- internal/handlers/guild_member_remove_handler.go | 2 +- internal/handlers/guild_member_update_handler.go | 2 +- internal/handlers/guild_role_delete_handler.go | 2 +- internal/handlers/guild_role_update_handler.go | 2 +- internal/handlers/guild_update_handler.go | 2 +- internal/handlers/interaction_create_handler.go | 4 ++-- internal/handlers/message_create_handler.go | 6 +++--- internal/handlers/message_update_handler.go | 6 +++--- internal/handlers/voice_state_update_handler.go | 7 +++---- internal/handlers/webhooks_update_handler.go | 2 +- internal/restclient_impl.go | 2 +- 17 files changed, 34 insertions(+), 31 deletions(-) diff --git a/api/events/generic_event.go b/api/events/generic_event.go index 18cc974c..e4f20ae1 100644 --- a/api/events/generic_event.go +++ b/api/events/generic_event.go @@ -4,9 +4,7 @@ import "github.com/DisgoOrg/disgo/api" // NewGenericEvent constructs a new GenericEvent with the provided Disgo instance func NewGenericEvent(disgo api.Disgo, sequenceNumber int) *GenericEvent { - event := &GenericEvent{disgo: disgo, sequenceNumber: sequenceNumber} - disgo.EventManager().Dispatch(event) - return event + return &GenericEvent{disgo: disgo, sequenceNumber: sequenceNumber} } // GenericEvent the base event structure diff --git a/api/events/listener_adapter.go b/api/events/listener_adapter.go index 322c0122..a2619225 100644 --- a/api/events/listener_adapter.go +++ b/api/events/listener_adapter.go @@ -509,7 +509,13 @@ func (l ListenerAdapter) OnEvent(event interface{}) { default: if e, ok := e.(api.Event); ok { - e.Disgo().Logger().Errorf("unexpected event received: \"%s\", event: \"%#e\"", reflect.TypeOf(event).Name(), event) + var name string + if t := reflect.TypeOf(e); t.Kind() == reflect.Ptr { + name = "*" + t.Elem().Name() + } else { + name = t.Name() + } + e.Disgo().Logger().Errorf("unexpected event received: \"%s\", event: \"%#e\"", name, event) } } } diff --git a/internal/handlers/application_command_delete.go b/internal/handlers/application_command_delete.go index 51cf9b8d..83be05a7 100644 --- a/internal/handlers/application_command_delete.go +++ b/internal/handlers/application_command_delete.go @@ -36,7 +36,7 @@ func (h CommandDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a command = disgo.EntityBuilder().CreateGlobalCommand(command, api.CacheStrategyNo) } - eventManager.Dispatch(events.CommandDeleteEvent{ + eventManager.Dispatch(&events.CommandDeleteEvent{ GenericCommandEvent: &events.GenericCommandEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), Command: command, diff --git a/internal/handlers/application_command_update.go b/internal/handlers/application_command_update.go index 3ecc227e..e24a7f62 100644 --- a/internal/handlers/application_command_update.go +++ b/internal/handlers/application_command_update.go @@ -39,7 +39,7 @@ func (h CommandUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager a command = disgo.EntityBuilder().CreateGlobalCommand(command, api.CacheStrategyYes) } - eventManager.Dispatch(events.CommandUpdateEvent{ + eventManager.Dispatch(&events.CommandUpdateEvent{ GenericCommandEvent: &events.GenericCommandEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), Command: command, diff --git a/internal/handlers/channel_delete_handler.go b/internal/handlers/channel_delete_handler.go index 099942a6..db0d4b1a 100644 --- a/internal/handlers/channel_delete_handler.go +++ b/internal/handlers/channel_delete_handler.go @@ -52,7 +52,7 @@ func (h *ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager case api.ChannelTypeDM: disgo.Cache().UncacheDMChannel(channel.ID) - eventManager.Dispatch(events.DMChannelCreateEvent{ + eventManager.Dispatch(&events.DMChannelCreateEvent{ GenericDMChannelEvent: &events.GenericDMChannelEvent{ GenericChannelEvent: genericChannelEvent, DMChannel: disgo.EntityBuilder().CreateDMChannel(channel, api.CacheStrategyNo), @@ -65,7 +65,7 @@ func (h *ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager case api.ChannelTypeText, api.ChannelTypeNews: disgo.Cache().UncacheTextChannel(*channel.GuildID, channel.ID) - eventManager.Dispatch(events.TextChannelCreateEvent{ + eventManager.Dispatch(&events.TextChannelCreateEvent{ GenericTextChannelEvent: &events.GenericTextChannelEvent{ GenericGuildChannelEvent: genericGuildChannelEvent, TextChannel: disgo.EntityBuilder().CreateTextChannel(channel, api.CacheStrategyNo), @@ -75,7 +75,7 @@ func (h *ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager case api.ChannelTypeStore: disgo.Cache().UncacheStoreChannel(*channel.GuildID, channel.ID) - eventManager.Dispatch(events.StoreChannelCreateEvent{ + eventManager.Dispatch(&events.StoreChannelCreateEvent{ GenericStoreChannelEvent: &events.GenericStoreChannelEvent{ GenericGuildChannelEvent: genericGuildChannelEvent, StoreChannel: disgo.EntityBuilder().CreateStoreChannel(channel, api.CacheStrategyNo), @@ -85,7 +85,7 @@ func (h *ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager case api.ChannelTypeCategory: disgo.Cache().UncacheCategory(*channel.GuildID, channel.ID) - eventManager.Dispatch(events.CategoryCreateEvent{ + eventManager.Dispatch(&events.CategoryCreateEvent{ GenericCategoryEvent: &events.GenericCategoryEvent{ GenericGuildChannelEvent: genericGuildChannelEvent, Category: disgo.EntityBuilder().CreateCategory(channel, api.CacheStrategyNo), @@ -95,7 +95,7 @@ func (h *ChannelDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManager case api.ChannelTypeVoice: disgo.Cache().UncacheVoiceChannel(*channel.GuildID, channel.ID) - eventManager.Dispatch(events.VoiceChannelCreateEvent{ + eventManager.Dispatch(&events.VoiceChannelCreateEvent{ GenericVoiceChannelEvent: &events.GenericVoiceChannelEvent{ GenericGuildChannelEvent: genericGuildChannelEvent, VoiceChannel: disgo.EntityBuilder().CreateVoiceChannel(channel, api.CacheStrategyNo), diff --git a/internal/handlers/guild_member_add_handler.go b/internal/handlers/guild_member_add_handler.go index 0060740a..44e37581 100644 --- a/internal/handlers/guild_member_add_handler.go +++ b/internal/handlers/guild_member_add_handler.go @@ -32,7 +32,7 @@ func (h *GuildMemberAddHandler) HandleGatewayEvent(disgo api.Disgo, eventManager } member = disgo.EntityBuilder().CreateMember(member.GuildID, member, api.CacheStrategyYes) - eventManager.Dispatch(events.GuildMemberJoinEvent{ + eventManager.Dispatch(&events.GuildMemberJoinEvent{ GenericGuildMemberEvent: &events.GenericGuildMemberEvent{ GenericGuildEvent: &events.GenericGuildEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), diff --git a/internal/handlers/guild_member_remove_handler.go b/internal/handlers/guild_member_remove_handler.go index 680d5d47..43a2609b 100644 --- a/internal/handlers/guild_member_remove_handler.go +++ b/internal/handlers/guild_member_remove_handler.go @@ -40,7 +40,7 @@ func (h *GuildMemberRemoveHandler) HandleGatewayEvent(disgo api.Disgo, eventMana member := disgo.Cache().Member(memberData.GuildID, memberData.User.ID) disgo.Cache().UncacheMember(memberData.GuildID, memberData.User.ID) - eventManager.Dispatch(events.GuildMemberLeaveEvent{ + eventManager.Dispatch(&events.GuildMemberLeaveEvent{ GenericGuildMemberEvent: &events.GenericGuildMemberEvent{ GenericGuildEvent: &events.GenericGuildEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), diff --git a/internal/handlers/guild_member_update_handler.go b/internal/handlers/guild_member_update_handler.go index d493b04d..9ca2c47d 100644 --- a/internal/handlers/guild_member_update_handler.go +++ b/internal/handlers/guild_member_update_handler.go @@ -37,7 +37,7 @@ func (h *GuildMemberUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventMana } member = disgo.EntityBuilder().CreateMember(member.GuildID, member, api.CacheStrategyYes) - eventManager.Dispatch(events.GuildMemberUpdateEvent{ + eventManager.Dispatch(&events.GuildMemberUpdateEvent{ GenericGuildMemberEvent: &events.GenericGuildMemberEvent{ GenericGuildEvent: &events.GenericGuildEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), diff --git a/internal/handlers/guild_role_delete_handler.go b/internal/handlers/guild_role_delete_handler.go index a067db3b..c5b7f75e 100644 --- a/internal/handlers/guild_role_delete_handler.go +++ b/internal/handlers/guild_role_delete_handler.go @@ -41,7 +41,7 @@ func (h *GuildRoleDeleteHandler) HandleGatewayEvent(disgo api.Disgo, eventManage disgo.Cache().UncacheRole(roleDeleteData.GuildID, roleDeleteData.RoleID) } - eventManager.Dispatch(events.RoleDeleteEvent{ + eventManager.Dispatch(&events.RoleDeleteEvent{ GenericRoleEvent: &events.GenericRoleEvent{ GenericGuildEvent: &events.GenericGuildEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), diff --git a/internal/handlers/guild_role_update_handler.go b/internal/handlers/guild_role_update_handler.go index 3cf8c3ed..4a952d9b 100644 --- a/internal/handlers/guild_role_update_handler.go +++ b/internal/handlers/guild_role_update_handler.go @@ -42,7 +42,7 @@ func (h *GuildRoleUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManage } role := disgo.EntityBuilder().CreateRole(roleUpdateData.GuildID, roleUpdateData.Role, api.CacheStrategyYes) - eventManager.Dispatch(events.RoleUpdateEvent{ + eventManager.Dispatch(&events.RoleUpdateEvent{ GenericRoleEvent: &events.GenericRoleEvent{ GenericGuildEvent: &events.GenericGuildEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), diff --git a/internal/handlers/guild_update_handler.go b/internal/handlers/guild_update_handler.go index b1db2927..27ce214a 100644 --- a/internal/handlers/guild_update_handler.go +++ b/internal/handlers/guild_update_handler.go @@ -31,7 +31,7 @@ func (h *GuildUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager ap } guild := disgo.EntityBuilder().CreateGuild(fullGuild, api.CacheStrategyYes) - eventManager.Dispatch(events.GuildUpdateEvent{ + eventManager.Dispatch(&events.GuildUpdateEvent{ GenericGuildEvent: &events.GenericGuildEvent{ GenericEvent: events.NewGenericEvent(disgo, sequenceNumber), Guild: guild, diff --git a/internal/handlers/interaction_create_handler.go b/internal/handlers/interaction_create_handler.go index 5724824a..ad925a8f 100644 --- a/internal/handlers/interaction_create_handler.go +++ b/internal/handlers/interaction_create_handler.go @@ -83,13 +83,13 @@ func handleInteraction(disgo api.Disgo, eventManager api.EventManager, sequenceN switch componentInteraction.Data.ComponentType { case api.ComponentTypeButton: - eventManager.Dispatch(events.ButtonClickEvent{ + eventManager.Dispatch(&events.ButtonClickEvent{ GenericComponentEvent: genericComponentEvent, ButtonInteraction: disgo.EntityBuilder().CreateButtonInteraction(fullInteraction, componentInteraction), }) case api.ComponentTypeSelectMenu: - eventManager.Dispatch(events.SelectMenuSubmitEvent{ + eventManager.Dispatch(&events.SelectMenuSubmitEvent{ GenericComponentEvent: genericComponentEvent, SelectMenuInteraction: disgo.EntityBuilder().CreateSelectMenuInteraction(fullInteraction, componentInteraction), }) diff --git a/internal/handlers/message_create_handler.go b/internal/handlers/message_create_handler.go index aad8328a..647b8d0f 100644 --- a/internal/handlers/message_create_handler.go +++ b/internal/handlers/message_create_handler.go @@ -34,18 +34,18 @@ func (h *MessageCreateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager ChannelID: message.ChannelID, } - eventManager.Dispatch(events.MessageCreateEvent{ + eventManager.Dispatch(&events.MessageCreateEvent{ GenericMessageEvent: genericMessageEvent, }) if message.GuildID == nil { - eventManager.Dispatch(events.DMMessageCreateEvent{ + eventManager.Dispatch(&events.DMMessageCreateEvent{ GenericDMMessageEvent: &events.GenericDMMessageEvent{ GenericMessageEvent: genericMessageEvent, }, }) } else { - eventManager.Dispatch(events.GuildMessageCreateEvent{ + eventManager.Dispatch(&events.GuildMessageCreateEvent{ GenericGuildMessageEvent: &events.GenericGuildMessageEvent{ GenericMessageEvent: genericMessageEvent, GuildID: *message.GuildID, diff --git a/internal/handlers/message_update_handler.go b/internal/handlers/message_update_handler.go index c5dd4e5d..2dbff7a8 100644 --- a/internal/handlers/message_update_handler.go +++ b/internal/handlers/message_update_handler.go @@ -37,13 +37,13 @@ func (h *MessageUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager Message: message, } - eventManager.Dispatch(events.MessageUpdateEvent{ + eventManager.Dispatch(&events.MessageUpdateEvent{ GenericMessageEvent: genericMessageEvent, OldMessage: oldMessage, }) if message.GuildID == nil { - eventManager.Dispatch(events.DMMessageUpdateEvent{ + eventManager.Dispatch(&events.DMMessageUpdateEvent{ GenericDMMessageEvent: &events.GenericDMMessageEvent{ GenericMessageEvent: genericMessageEvent, }, @@ -51,7 +51,7 @@ func (h *MessageUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager }) } else { - eventManager.Dispatch(events.GuildMessageUpdateEvent{ + eventManager.Dispatch(&events.GuildMessageUpdateEvent{ GenericGuildMessageEvent: &events.GenericGuildMessageEvent{ GenericMessageEvent: genericMessageEvent, GuildID: *message.GuildID, diff --git a/internal/handlers/voice_state_update_handler.go b/internal/handlers/voice_state_update_handler.go index c115cdab..d548814e 100644 --- a/internal/handlers/voice_state_update_handler.go +++ b/internal/handlers/voice_state_update_handler.go @@ -56,14 +56,13 @@ func (h *VoiceStateUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManag }, VoiceState: voiceState, } - disgo.EventManager().Dispatch(genericGuildVoiceEvent) if (oldVoiceState == nil || oldVoiceState.ChannelID == nil) && voiceStateUpdate.VoiceState.ChannelID != nil { - disgo.EventManager().Dispatch(events.GuildVoiceJoinEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent}) + disgo.EventManager().Dispatch(&events.GuildVoiceJoinEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent}) } else if oldVoiceState != nil && oldVoiceState.ChannelID != nil && voiceStateUpdate.VoiceState.ChannelID == nil { - disgo.EventManager().Dispatch(events.GuildVoiceLeaveEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent}) + disgo.EventManager().Dispatch(&events.GuildVoiceLeaveEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent}) } else if oldVoiceState != nil && oldVoiceState.ChannelID != nil && voiceStateUpdate.VoiceState.ChannelID != nil { - disgo.EventManager().Dispatch(events.GuildVoiceUpdateEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent, OldVoiceState: oldVoiceState}) + disgo.EventManager().Dispatch(&events.GuildVoiceUpdateEvent{GenericGuildVoiceEvent: genericGuildVoiceEvent, OldVoiceState: oldVoiceState}) } else { disgo.Logger().Warnf("could not decide which GuildVoiceEvent to fire") } diff --git a/internal/handlers/webhooks_update_handler.go b/internal/handlers/webhooks_update_handler.go index 6421b30d..4abdd991 100644 --- a/internal/handlers/webhooks_update_handler.go +++ b/internal/handlers/webhooks_update_handler.go @@ -30,7 +30,7 @@ func (h *WebhooksUpdateHandler) HandleGatewayEvent(disgo api.Disgo, eventManager return } - eventManager.Dispatch(events.WebhooksUpdateEvent{ + eventManager.Dispatch(&events.WebhooksUpdateEvent{ GenericTextChannelEvent: &events.GenericTextChannelEvent{ GenericGuildChannelEvent: &events.GenericGuildChannelEvent{ GenericChannelEvent: &events.GenericChannelEvent{ diff --git a/internal/restclient_impl.go b/internal/restclient_impl.go index e53fbe37..8c94e262 100644 --- a/internal/restclient_impl.go +++ b/internal/restclient_impl.go @@ -39,7 +39,7 @@ func (r *restClientImpl) DoWithHeaders(route *restclient.CompiledAPIRoute, rqBod err := r.RestClient.DoWithHeaders(route, rqBody, rsBody, customHeader) rErr = restclient.NewError(nil, err) // TODO reimplement events.HTTPRequestEvent - /*r.Disgo().EventManager().Dispatch(events.HTTPRequestEvent{ + /*r.Disgo().EventManager().Dispatch(&events.HTTPRequestEvent{ GenericEvent: events.NewEvent(r.Disgo(), 0), Request: rq, Response: rs, From 9d620dbcd7b72fbba33f62610135956ff1a7d547 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Tue, 6 Jul 2021 19:12:32 +0200 Subject: [PATCH 60/64] fixed docs --- api/command_interaction.go | 17 +++++++++++++++++ api/events/interaction_events.go | 14 ++++++-------- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/api/command_interaction.go b/api/command_interaction.go index f8290a12..93c505fa 100644 --- a/api/command_interaction.go +++ b/api/command_interaction.go @@ -6,22 +6,39 @@ type CommandInteraction struct { Data *CommandInteractionData `json:"data,omitempty"` } +// CommandID returns the ID of the api.Command which got used func (i *CommandInteraction) CommandID() Snowflake { return i.Data.ID } +// CommandName the name of the api.Command which got used func (i *CommandInteraction) CommandName() string { return i.Data.CommandName } +// SubCommandName the subcommand name of the api.Command which got used. May be nil func (i *CommandInteraction) SubCommandName() *string { return i.Data.SubCommandName } +// SubCommandGroupName the subcommand group name of the api.Command which got used. May be nil func (i *CommandInteraction) SubCommandGroupName() *string { return i.Data.SubCommandGroupName } +// CommandPath returns the api.Command path +func (i *CommandInteraction) CommandPath() string { + path := i.CommandName() + if name := i.SubCommandName(); name != nil { + path += "/" + *name + } + if name := i.SubCommandGroupName(); name != nil { + path += "/" + *name + } + return path +} + +// Options returns the parsed Option which the Command got used with func (i *CommandInteraction) Options() []*Option { return i.Data.Options } diff --git a/api/events/interaction_events.go b/api/events/interaction_events.go index a2b1ece9..34d54105 100644 --- a/api/events/interaction_events.go +++ b/api/events/interaction_events.go @@ -56,34 +56,32 @@ type CommandEvent struct { CommandInteraction *api.CommandInteraction } +// CommandID returns the ID of the api.Command which got used func (e *CommandEvent) CommandID() api.Snowflake { return e.CommandInteraction.CommandID() } +// CommandName the name of the api.Command which got used func (e *CommandEvent) CommandName() string { return e.CommandInteraction.CommandName() } +// SubCommandName the subcommand name of the api.Command which got used. May be nil func (e *CommandEvent) SubCommandName() *string { return e.CommandInteraction.SubCommandName() } +// SubCommandGroupName the subcommand group name of the api.Command which got used. May be nil func (e *CommandEvent) SubCommandGroupName() *string { return e.CommandInteraction.SubCommandGroupName() } // CommandPath returns the api.Command path func (e *CommandEvent) CommandPath() string { - path := e.CommandName() - if name := e.SubCommandName(); name != nil { - path += "/" + *name - } - if name := e.SubCommandGroupName(); name != nil { - path += "/" + *name - } - return path + return e.CommandInteraction.CommandPath() } +// Options returns the parsed api.Option which the api.Command got used with func (e *CommandEvent) Options() []*api.Option { return e.CommandInteraction.Options() } From eec9e0b150d3d5cad970af78720ac80d2d732b21 Mon Sep 17 00:00:00 2001 From: Eve <46286597+EveCodes31@users.noreply.github.com> Date: Wed, 7 Jul 2021 09:42:01 +0100 Subject: [PATCH 61/64] Remove bool pointer on template.IsDirty MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ToπSenpai <15636011+TopiSenpai@users.noreply.github.com> --- api/guild_template.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/guild_template.go b/api/guild_template.go index 80be9b0b..9f7ef14f 100644 --- a/api/guild_template.go +++ b/api/guild_template.go @@ -19,7 +19,7 @@ type GuildTemplate struct { UpdatedAt time.Time `json:"updated_at"` GuildID Snowflake `json:"source_guild_id"` PartialGuild PartialGuild `json:"serialized_source_guild"` - IsDirty *bool `json:"is_dirty,omitempty"` + IsDirty bool `json:"is_dirty,omitempty"` } // Guild returns the full Guild of the GuildTemplate if in cache From 40ab7ff8bca15ab4b0f5fdbc0060c667868d0e57 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Thu, 8 Jul 2021 16:59:02 +0200 Subject: [PATCH 62/64] renamed MessageCreate/UpdateBuilder methods --- api/guild.go | 13 ++----- api/message_create.go | 87 ++++++++++++++++++++++++++++++------------- api/message_update.go | 76 +++++++++++++++++++++++++------------ api/self_member.go | 6 --- api/self_user.go | 6 +++ api/user.go | 79 +++++++++++++++++++++++++++++++++++---- example/examplebot.go | 28 +++++++------- example/go.sum | 1 - 8 files changed, 210 insertions(+), 86 deletions(-) delete mode 100644 api/self_member.go diff --git a/api/guild.go b/api/guild.go index fc75018c..882ade81 100644 --- a/api/guild.go +++ b/api/guild.go @@ -181,11 +181,9 @@ func (g *Guild) Roles() []*Role { return g.Disgo.Cache().Roles(g.ID) } -// SelfMember returns the Member for the current logged in User for this Guild -func (g *Guild) SelfMember() *SelfMember { - return &SelfMember{ - Member: g.Disgo.Cache().Member(g.ID, g.Disgo.ClientID()), - } +// SelfMember returns the Member for the current logged-in User for this Guild +func (g *Guild) SelfMember() *Member { + return g.Disgo.Cache().Member(g.ID, g.Disgo.ClientID()) } // Disconnect sends a api.GatewayCommand to disconnect from this Guild @@ -218,11 +216,6 @@ func (g *Guild) DeleteRole(roleID Snowflake) restclient.RestError { return g.Disgo.RestClient().DeleteRole(g.ID, roleID) } -// GetSelfMember returns the SelfMember for this Guild -func (g *Guild) GetSelfMember() *SelfMember { - return &SelfMember{Member: g.GetMember(g.Disgo.ClientID())} -} - // Leave leaves the Guild func (g *Guild) Leave() restclient.RestError { return g.Disgo.RestClient().LeaveGuild(g.ID) diff --git a/api/message_create.go b/api/message_create.go index 0e7dd4c9..fc65be4a 100644 --- a/api/message_create.go +++ b/api/message_create.go @@ -42,8 +42,8 @@ func NewMessageCreateBuilder() *MessageCreateBuilder { } } -// NewMessageBuilderByMessage returns a new MessageCreateBuilder and takes an existing Message -func NewMessageBuilderByMessage(message *Message) *MessageCreateBuilder { +// NewMessageCreateBuilderByMessage returns a new MessageCreateBuilder and takes an existing Message +func NewMessageCreateBuilderByMessage(message *Message) *MessageCreateBuilder { msg := MessageCreate{ TTS: message.TTS, Components: message.Components, @@ -66,8 +66,7 @@ func (b *MessageCreateBuilder) SetContent(content string) *MessageCreateBuilder // SetContentf sets content of the Message func (b *MessageCreateBuilder) SetContentf(content string, a ...interface{}) *MessageCreateBuilder { - b.Content = fmt.Sprintf(content, a...) - return b + return b.SetContent(fmt.Sprintf(content, a...)) } // ClearContent removes content of the Message @@ -81,12 +80,20 @@ func (b *MessageCreateBuilder) SetTTS(tts bool) *MessageCreateBuilder { return b } -// SetEmbeds sets the embeds of the Message +// SetEmbeds sets the Embed(s) of the Message func (b *MessageCreateBuilder) SetEmbeds(embeds ...Embed) *MessageCreateBuilder { b.Embeds = embeds return b } +// SetEmbed sets the provided Embed at the index of the Message +func (b *MessageCreateBuilder) SetEmbed(i int, embed Embed) *MessageCreateBuilder { + if len(b.Embeds) > i { + b.Embeds[i] = embed + } + return b +} + // AddEmbeds adds multiple embeds to the Message func (b *MessageCreateBuilder) AddEmbeds(embeds ...Embed) *MessageCreateBuilder { b.Embeds = append(b.Embeds, embeds...) @@ -100,52 +107,74 @@ func (b *MessageCreateBuilder) ClearEmbeds() *MessageCreateBuilder { } // 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:]...) +func (b *MessageCreateBuilder) RemoveEmbed(i int) *MessageCreateBuilder { + if len(b.Embeds) > i { + b.Embeds = append(b.Embeds[:i], b.Embeds[i+1:]...) } return b } -// SetComponents sets the Component(s) of the Message -func (b *MessageCreateBuilder) SetComponents(components ...Component) *MessageCreateBuilder { - b.Components = components +// SetActionRows sets the ActionRow(s) of the Message +func (b *MessageCreateBuilder) SetActionRows(actionRows ...ActionRow) *MessageCreateBuilder { + b.Components = actionRowsToComponents(actionRows) return b } -// AddComponents adds the Component(s) to the Message -func (b *MessageCreateBuilder) AddComponents(components ...Component) *MessageCreateBuilder { - b.Components = append(b.Components, components...) +// SetActionRow sets the provided ActionRow at the index of Component(s) +func (b *MessageCreateBuilder) SetActionRow(i int, actionRow ActionRow) *MessageCreateBuilder { + if len(b.Components) > i { + b.Components[i] = actionRow + } return b } -// ClearComponents removes all of the Component(s) of the Message -func (b *MessageCreateBuilder) ClearComponents() *MessageCreateBuilder { - b.Components = []Component{} +// AddActionRow adds a new ActionRow with the provided Component(s) to the Message +func (b *MessageCreateBuilder) AddActionRow(components ...Component) *MessageCreateBuilder { + b.Components = append(b.Components, NewActionRow(components...)) return b } -// RemoveComponent removes a Component from the Message -func (b *MessageCreateBuilder) RemoveComponent(i int) *MessageCreateBuilder { - if b != nil && len(b.Components) > i { +// AddActionRows adds the ActionRow(s) to the Message +func (b *MessageCreateBuilder) AddActionRows(actionRows ...ActionRow) *MessageCreateBuilder { + b.Components = append(b.Components, actionRowsToComponents(actionRows)...) + return b +} + +// RemoveActionRow removes a ActionRow from the Message +func (b *MessageCreateBuilder) RemoveActionRow(i int) *MessageCreateBuilder { + if len(b.Components) > i { b.Components = append(b.Components[:i], b.Components[i+1:]...) } return b } -// SetFiles sets the files for this WebhookMessageCreate +// ClearActionRows removes all of the ActionRow(s) of the Message +func (b *MessageCreateBuilder) ClearActionRows() *MessageCreateBuilder { + b.Components = []Component{} + return b +} + +// SetFiles sets the restclient.File(s) for this MessageCreate func (b *MessageCreateBuilder) SetFiles(files ...restclient.File) *MessageCreateBuilder { b.Files = files return b } -// AddFiles adds the files to the WebhookMessageCreate +// SetFile sets the restclient.File at the index for this MessageCreate +func (b *MessageCreateBuilder) SetFile(i int, file restclient.File) *MessageCreateBuilder { + if len(b.Files) > i { + b.Files[i] = file + } + return b +} + +// AddFiles adds the restclient.File(s) to the MessageCreate func (b *MessageCreateBuilder) AddFiles(files ...restclient.File) *MessageCreateBuilder { b.Files = append(b.Files, files...) return b } -// AddFile adds a file to the WebhookMessageCreate +// AddFile adds a restclient.File to the MessageCreate func (b *MessageCreateBuilder) AddFile(name string, reader io.Reader, flags ...restclient.FileFlags) *MessageCreateBuilder { b.Files = append(b.Files, restclient.File{ Name: name, @@ -155,7 +184,7 @@ func (b *MessageCreateBuilder) AddFile(name string, reader io.Reader, flags ...r return b } -// ClearFiles removes all files of this WebhookMessageCreate +// ClearFiles removes all files of this MessageCreate func (b *MessageCreateBuilder) ClearFiles() *MessageCreateBuilder { b.Files = []restclient.File{} return b @@ -163,7 +192,7 @@ func (b *MessageCreateBuilder) ClearFiles() *MessageCreateBuilder { // RemoveFiles removes the file at this index func (b *MessageCreateBuilder) RemoveFiles(i int) *MessageCreateBuilder { - if b != nil && len(b.Files) > i { + if len(b.Files) > i { b.Files = append(b.Files[:i], b.Files[i+1:]...) } return b @@ -232,3 +261,11 @@ func (b *MessageCreateBuilder) SetEphemeral(ephemeral bool) *MessageCreateBuilde func (b *MessageCreateBuilder) Build() MessageCreate { return b.MessageCreate } + +func actionRowsToComponents(actionRows []ActionRow) []Component { + components := make([]Component, len(actionRows)) + for i := range actionRows { + components[i] = components[i] + } + return components +} diff --git a/api/message_update.go b/api/message_update.go index fc4d88bb..1f51326a 100644 --- a/api/message_update.go +++ b/api/message_update.go @@ -56,12 +56,20 @@ func (b *MessageUpdateBuilder) ClearContent() *MessageUpdateBuilder { return b.SetContent("") } -// SetEmbeds sets the embeds of the Message +// SetEmbeds sets the Embed(s) of the Message func (b *MessageUpdateBuilder) SetEmbeds(embeds ...Embed) *MessageUpdateBuilder { b.Embeds = embeds return b } +// SetEmbed sets the provided Embed at the index of the Message +func (b *MessageUpdateBuilder) SetEmbed(i int, embed Embed) *MessageUpdateBuilder { + if len(b.Embeds) > i { + b.Embeds[i] = embed + } + return b +} + // AddEmbeds adds multiple embeds to the Message func (b *MessageUpdateBuilder) AddEmbeds(embeds ...Embed) *MessageUpdateBuilder { b.Embeds = append(b.Embeds, embeds...) @@ -75,52 +83,74 @@ func (b *MessageUpdateBuilder) ClearEmbeds() *MessageUpdateBuilder { } // 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:]...) +func (b *MessageUpdateBuilder) RemoveEmbed(i int) *MessageUpdateBuilder { + if len(b.Embeds) > i { + b.Embeds = append(b.Embeds[:i], b.Embeds[i+1:]...) } return b } -// SetComponents sets the Component(s) of the Message -func (b *MessageUpdateBuilder) SetComponents(components ...Component) *MessageUpdateBuilder { - b.Components = components +// SetActionRows sets the ActionRow(s) of the Message +func (b *MessageUpdateBuilder) SetActionRows(actionRows ...ActionRow) *MessageUpdateBuilder { + b.Components = actionRowsToComponents(actionRows) + return b +} + +// SetActionRow sets the provided ActionRow at the index of Component(s) +func (b *MessageUpdateBuilder) SetActionRow(i int, actionRow ActionRow) *MessageUpdateBuilder { + if len(b.Components) > i { + b.Components[i] = actionRow + } return b } -// AddComponents adds the Component(s) to the Message -func (b *MessageUpdateBuilder) AddComponents(components ...Component) *MessageUpdateBuilder { - b.Components = append(b.Components, components...) +// AddActionRow adds a new ActionRow with the provided Component(s) to the Message +func (b *MessageUpdateBuilder) AddActionRow(components ...Component) *MessageUpdateBuilder { + b.Components = append(b.Components, NewActionRow(components...)) return b } -// ClearComponents removes all of the Component(s) of the Message -func (b *MessageUpdateBuilder) ClearComponents() *MessageUpdateBuilder { - b.Components = []Component{} +// AddActionRows adds the ActionRow(s) to the Message +func (b *MessageUpdateBuilder) AddActionRows(actionRows ...ActionRow) *MessageUpdateBuilder { + b.Components = append(b.Components, actionRowsToComponents(actionRows)...) return b } -// RemoveComponent removes a Component from the Message -func (b *MessageUpdateBuilder) RemoveComponent(i int) *MessageUpdateBuilder { +// RemoveActionRow removes a ActionRow from the Message +func (b *MessageUpdateBuilder) RemoveActionRow(i int) *MessageUpdateBuilder { if len(b.Components) > i { b.Components = append(b.Components[:i], b.Components[i+1:]...) } return b } -// SetFiles sets the files for this Message +// ClearActionRows removes all of the ActionRow(s) of the Message +func (b *MessageUpdateBuilder) ClearActionRows() *MessageUpdateBuilder { + b.Components = []Component{} + return b +} + +// SetFiles sets the restclient.File(s) for this MessageCreate func (b *MessageUpdateBuilder) SetFiles(files ...restclient.File) *MessageUpdateBuilder { b.Files = files return b } -// AddFiles adds the files to the Message +// SetFile sets the restclient.File at the index for this MessageCreate +func (b *MessageUpdateBuilder) SetFile(i int, file restclient.File) *MessageUpdateBuilder { + if len(b.Files) > i { + b.Files[i] = file + } + return b +} + +// AddFiles adds the restclient.File(s) to the MessageCreate func (b *MessageUpdateBuilder) AddFiles(files ...restclient.File) *MessageUpdateBuilder { b.Files = append(b.Files, files...) return b } -// AddFile adds a file to the Message +// AddFile adds a restclient.File to the MessageCreate func (b *MessageUpdateBuilder) AddFile(name string, reader io.Reader, flags ...restclient.FileFlags) *MessageUpdateBuilder { b.Files = append(b.Files, restclient.File{ Name: name, @@ -130,7 +160,7 @@ func (b *MessageUpdateBuilder) AddFile(name string, reader io.Reader, flags ...r return b } -// ClearFiles removes all files of this Message +// ClearFiles removes all files of this MessageCreate func (b *MessageUpdateBuilder) ClearFiles() *MessageUpdateBuilder { b.Files = []restclient.File{} return b @@ -168,12 +198,12 @@ func (b *MessageUpdateBuilder) SetAllowedMentions(allowedMentions *AllowedMentio // ClearAllowedMentions clears the allowed mentions of the Message func (b *MessageUpdateBuilder) ClearAllowedMentions() *MessageUpdateBuilder { - return b.SetAllowedMentions(&AllowedMentions{}) + return b.SetAllowedMentions(nil) } -// SetFlags sets the MessageFlags of the Message -func (b *MessageUpdateBuilder) SetFlags(flags ...MessageFlags) *MessageUpdateBuilder { - *b.Flags = MessageFlagNone.Add(flags...) +// SetFlags sets the message flags of the Message +func (b *MessageUpdateBuilder) SetFlags(flags MessageFlags) *MessageUpdateBuilder { + *b.Flags = flags return b } diff --git a/api/self_member.go b/api/self_member.go deleted file mode 100644 index 5aa9a7b8..00000000 --- a/api/self_member.go +++ /dev/null @@ -1,6 +0,0 @@ -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 69a3185a..d7e32eca 100644 --- a/api/self_user.go +++ b/api/self_user.go @@ -12,6 +12,12 @@ var ErrDMChannelToYourself = restclient.NewError(nil, errors.New("can't open a d // SelfUser represents the current logged in User type SelfUser struct { *User + MfaEnabled *bool `json:"mfa_enabled"` + Locale *string `json:"locale"` + Verified *bool `json:"verified"` + Email *string `json:"email"` + Flags *int `json:"flags"` + PremiumType *int `json:"premium_type"` } // Update updates the SelfUser with the given payload diff --git a/api/user.go b/api/user.go index 78c9bc9c..d29cb5da 100644 --- a/api/user.go +++ b/api/user.go @@ -16,14 +16,8 @@ type User struct { Discriminator string `json:"discriminator"` Avatar *string `json:"avatar"` IsBot bool `json:"bot"` - System *bool `json:"system"` - MfaEnabled *bool `json:"mfa_enabled"` - Locale *string `json:"locale"` - Verified *bool `json:"verified"` - Email *string `json:"email"` - Flags *int `json:"flags"` - PremiumType *int `json:"premium_type"` - PublicFlags *int `json:"public_flags"` + System bool `json:"system"` + PublicFlags UserFlags `json:"public_flags"` } // AvatarURL returns the Avatar URL of the User @@ -65,3 +59,72 @@ func (u *User) String() string { func (u *User) OpenDMChannel() (*DMChannel, restclient.RestError) { return u.Disgo.RestClient().CreateDMChannel(u.ID) } + +type UserFlags int + +const ( + UserFlagDiscordEmployee UserFlags = 1 << iota + UserFlagPartneredServerOwner + UserFlagHypeSquadEvents + UserFlagBugHunterLevel1 + UserFlagHouseBravery + UserFlagHouseBrilliance + UserFlagHouseBalance + UserFlagEarlySupporter + UserFlagTeamUser + UserFlagBugHunterLevel2 + UserFlagVerifiedBot + UserFlagEarlyVerifiedBotDeveloper + UserFlagDiscordCertifiedModerator + UserFlagNone UserFlags = 0 +) + +// Add allows you to add multiple bits together, producing a new bit +func (f UserFlags) Add(bits ...UserFlags) UserFlags { + total := UserFlags(0) + for _, bit := range bits { + total |= bit + } + f |= total + return f +} + +// Remove allows you to subtract multiple bits from the first, producing a new bit +func (f UserFlags) Remove(bits ...UserFlags) UserFlags { + total := UserFlags(0) + for _, bit := range bits { + total |= bit + } + f &^= total + return f +} + +// HasAll will ensure that the bit includes all of the bits entered +func (f UserFlags) HasAll(bits ...UserFlags) bool { + for _, bit := range bits { + if !f.Has(bit) { + return false + } + } + return true +} + +// Has will check whether the Bit contains another bit +func (f UserFlags) Has(bit UserFlags) bool { + return (f & bit) == bit +} + +// MissingAny will check whether the bit is missing any one of the bits +func (f UserFlags) MissingAny(bits ...UserFlags) bool { + for _, bit := range bits { + if !f.Has(bit) { + return true + } + } + return false +} + +// Missing will do the inverse of UserFlags.Has +func (f UserFlags) Missing(bit UserFlags) bool { + return !f.Has(bit) +} \ No newline at end of file diff --git a/example/examplebot.go b/example/examplebot.go index 54be677e..2158ccc8 100644 --- a/example/examplebot.go +++ b/example/examplebot.go @@ -287,15 +287,17 @@ func commandListener(event *events.CommandEvent) { if err := event.Reply(api.NewMessageCreateBuilder(). SetContent("test message"). AddFile("gopher.png", reader). - SetComponents( - api.NewActionRow( - api.NewPrimaryButton("test1", "test1", nil), - api.NewPrimaryButton("test2", "test2", nil), - api.NewPrimaryButton("test3", "test3", nil), - api.NewPrimaryButton("test4", "test4", nil), - ), - api.NewActionRow( - api.NewSelectMenu("test3", "test", 0, 1, api.NewSelectOption("test1", "1"), api.NewSelectOption("test2", "2"), api.NewSelectOption("test3", "3")), + AddActionRow( + api.NewPrimaryButton("test1", "test1", nil), + api.NewPrimaryButton("test2", "test2", nil), + api.NewPrimaryButton("test3", "test3", nil), + api.NewPrimaryButton("test4", "test4", nil), + ). + AddActionRow( + api.NewSelectMenu("test3", "test", 1, 1, + api.NewSelectOption("test1", "1"), + api.NewSelectOption("test2", "2"), + api.NewSelectOption("test3", "3"), ), ). Build(), @@ -306,8 +308,8 @@ func commandListener(event *events.CommandEvent) { 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 { + + if err := event.Disgo().RestClient().AddMemberRole(*event.Interaction.GuildID, user.ID, role.ID); err == nil { _ = event.Reply(api.NewMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(green).SetDescriptionf("Added %s to %s", role, user).Build(), ).Build()) @@ -320,8 +322,8 @@ func commandListener(event *events.CommandEvent) { case "removerole": user := event.Option("member").User() role := event.Option("role").Role() - err := event.Disgo().RestClient().RemoveMemberRole(*event.Interaction.GuildID, user.ID, role.ID) - if err == nil { + + if err := event.Disgo().RestClient().RemoveMemberRole(*event.Interaction.GuildID, user.ID, role.ID); err == nil { _ = event.Reply(api.NewMessageCreateBuilder().AddEmbeds( api.NewEmbedBuilder().SetColor(65280).SetDescriptionf("Removed %s from %s", role, user).Build(), ).Build()) diff --git a/example/go.sum b/example/go.sum index 148f1c7e..daa590e9 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 eedf505cbbce8d342016cdfa711ad5e88c3e5a84 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 9 Jul 2021 02:35:49 +0200 Subject: [PATCH 63/64] added docu for user flags --- api/user.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/api/user.go b/api/user.go index d29cb5da..025abcd2 100644 --- a/api/user.go +++ b/api/user.go @@ -60,8 +60,10 @@ func (u *User) OpenDMChannel() (*DMChannel, restclient.RestError) { return u.Disgo.RestClient().CreateDMChannel(u.ID) } +// UserFlags defines certain flags/badges a user can have (https://discord.com/developers/docs/resources/user#user-object-user-flags) type UserFlags int +// All UserFlags const ( UserFlagDiscordEmployee UserFlags = 1 << iota UserFlagPartneredServerOwner From e10263b31a87e18548c3a358274625717f82eb19 Mon Sep 17 00:00:00 2001 From: TopiSenpai Date: Fri, 9 Jul 2021 19:10:28 +0200 Subject: [PATCH 64/64] modified permission getter for interaction perms --- api/member.go | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/api/member.go b/api/member.go index 0254e592..6470af9c 100644 --- a/api/member.go +++ b/api/member.go @@ -8,21 +8,24 @@ import ( // Member is a discord GuildMember type Member struct { - Disgo Disgo - GuildID Snowflake `json:"guild_id"` - User *User `json:"user"` - Nick *string `json:"nick"` - RoleIDs []Snowflake `json:"roles,omitempty"` - JoinedAt time.Time `json:"joined_at"` - PremiumSince *time.Time `json:"premium_since,omitempty"` - Deaf *bool `json:"deaf,omitempty"` - Mute *bool `json:"mute,omitempty"` - Pending bool `json:"pending"` - ChannelPermissions *Permissions `json:"permissions,omitempty"` + Disgo Disgo + GuildID Snowflake `json:"guild_id"` + User *User `json:"user"` + Nick *string `json:"nick"` + RoleIDs []Snowflake `json:"roles,omitempty"` + JoinedAt time.Time `json:"joined_at"` + PremiumSince *time.Time `json:"premium_since,omitempty"` + Deaf bool `json:"deaf,omitempty"` + Mute bool `json:"mute,omitempty"` + Pending bool `json:"pending"` + InteractionPermissions *Permissions `json:"permissions,omitempty"` } // Permissions returns the Permissions the Member has in the Guild func (m *Member) Permissions() Permissions { + if m.InteractionPermissions != nil { + return *m.InteractionPermissions + } return GetMemberPermissions(m) }