Skip to content

Commit

Permalink
Merge pull request #112 from DisgoOrg/interaction-refactor
Browse files Browse the repository at this point in the history
refactor discord interactions
  • Loading branch information
topi314 authored Jan 10, 2022
2 parents 3b19c25 + 0d88c3b commit 07549dd
Show file tree
Hide file tree
Showing 32 changed files with 985 additions and 1,670 deletions.
12 changes: 6 additions & 6 deletions _examples/application_commands/gateway/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func main() {
bot.WithGatewayOpts(gateway.WithGatewayIntents(discord.GatewayIntentsNone)),
bot.WithCacheOpts(core.WithCacheFlags(core.CacheFlagsDefault)),
bot.WithEventListeners(&events.ListenerAdapter{
OnSlashCommand: commandListener,
OnApplicationCommandInteraction: commandListener,
}),
)
if err != nil {
Expand All @@ -55,8 +55,7 @@ func main() {

defer disgo.Close(context.TODO())

_, err = disgo.SetGuildCommands(guildID, commands)
if err != nil {
if _, err = disgo.SetGuildCommands(guildID, commands); err != nil {
log.Fatal("error while registering commands: ", err)
}

Expand All @@ -70,10 +69,11 @@ func main() {
<-s
}

func commandListener(event *events.SlashCommandEvent) {
if event.Data.CommandName == "say" {
func commandListener(event *events.ApplicationCommandInteractionEvent) {
data := event.SlashCommandInteractionData()
if data.CommandName == "say" {
err := event.Create(discord.NewMessageCreateBuilder().
SetContent(*event.Data.Options.String("message")).
SetContent(*data.Options.String("message")).
Build(),
)
if err != nil {
Expand Down
22 changes: 11 additions & 11 deletions _examples/application_commands/http/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func main() {
httpserver.WithPublicKey(publicKey),
),
bot.WithEventListeners(&events.ListenerAdapter{
OnSlashCommand: commandListener,
OnApplicationCommandInteraction: commandListener,
}),
)
if err != nil {
Expand All @@ -58,13 +58,11 @@ func main() {

defer disgo.Close(context.TODO())

_, err = disgo.SetGuildCommands(guildID, commands)
if err != nil {
if _, err = disgo.SetGuildCommands(guildID, commands); err != nil {
log.Fatal("error while registering commands: ", err)
}

err = disgo.StartHTTPServer()
if err != nil {
if err = disgo.StartHTTPServer(); err != nil {
log.Fatal("error while starting http server: ", err)
}

Expand All @@ -74,13 +72,15 @@ func main() {
<-s
}

func commandListener(event *events.SlashCommandEvent) {
if event.Data.CommandName == "say" {
if err := event.Create(discord.NewMessageCreateBuilder().
SetContent(*event.Data.Options.String("message")).
func commandListener(event *events.ApplicationCommandInteractionEvent) {
data := event.SlashCommandInteractionData()
if data.CommandName == "say" {
err := event.Create(discord.NewMessageCreateBuilder().
SetContent(*data.Options.String("message")).
Build(),
); err != nil {
log.Error("error sending interaction response: ", err)
)
if err != nil {
event.Bot().Logger.Error("error on sending response: ", err)
}
}
}
4 changes: 2 additions & 2 deletions _examples/components/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ func main() {
)
}
},
OnButtonClick: func(event *events.ButtonClickEvent) {
if event.Data.CustomID == "danger" {
OnComponentInteraction: func(event *events.ComponentInteractionEvent) {
if event.ButtonInteractionData().CustomID == "danger" {
_ = event.Create(discord.NewMessageCreateBuilder().SetEphemeral(true).SetContent("Ey that was danger").Build())
}
},
Expand Down
2 changes: 1 addition & 1 deletion _examples/oauth2/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func handleRoot(w http.ResponseWriter, r *http.Request) {
}

func handleLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, client.GenerateAuthorizationURL(baseURL+"/trylogin", discord.ApplicationScopeIdentify, discord.ApplicationScopeGuilds, discord.ApplicationScopeEmail, discord.ApplicationScopeConnections, discord.ApplicationScopeWebhookIncoming), http.StatusMovedPermanently)
http.Redirect(w, r, client.GenerateAuthorizationURL(baseURL+"/trylogin", discord.PermissionsNone, "", false, discord.ApplicationScopeIdentify, discord.ApplicationScopeGuilds, discord.ApplicationScopeEmail, discord.ApplicationScopeConnections, discord.ApplicationScopeWebhookIncoming), http.StatusMovedPermanently)
}

func handleTryLogin(w http.ResponseWriter, r *http.Request) {
Expand Down
92 changes: 47 additions & 45 deletions _examples/test/listeners.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,53 +15,55 @@ import (
)

var listener = &events.ListenerAdapter{
OnGuildMessageCreate: messageListener,
OnSlashCommand: slashCommandListener,
OnButtonClick: buttonClickListener,
OnSelectMenuSubmit: selectMenuSubmitListener,
OnGuildMessageCreate: messageListener,
OnApplicationCommandInteraction: applicationCommandListener,
OnComponentInteraction: componentListener,
}

func buttonClickListener(event *events.ButtonClickEvent) {
switch event.Data.CustomID {
case "test1":
_ = event.Create(discord.NewMessageCreateBuilder().
SetContent(event.Data.CustomID.String()).
Build(),
)
func componentListener(event *events.ComponentInteractionEvent) {
switch data := event.Data.(type) {
case *core.ButtonInteractionData:
switch data.CustomID {
case "test1":
_ = event.Create(discord.NewMessageCreateBuilder().
SetContent(data.CustomID.String()).
Build(),
)

case "test2":
_ = event.DeferCreate(false)
case "test2":
_ = event.DeferCreate(false)

case "test3":
_ = event.DeferUpdate()
case "test3":
_ = event.DeferUpdate()

case "test4":
_ = event.Update(discord.NewMessageUpdateBuilder().
SetContent(event.Data.CustomID.String()).
Build(),
)
}
}
case "test4":
_ = event.Update(discord.NewMessageUpdateBuilder().
SetContent(data.CustomID.String()).
Build(),
)
}

func selectMenuSubmitListener(event *events.SelectMenuSubmitEvent) {
switch event.Data.CustomID {
case "test3":
if err := event.DeferUpdate(); err != nil {
log.Errorf("error sending interaction response: %s", err)
case *core.SelectMenuInteractionData:
switch data.CustomID {
case "test3":
if err := event.DeferUpdate(); err != nil {
log.Errorf("error sending interaction response: %s", err)
}
_, _ = event.CreateFollowupMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContentf("selected options: %s", data.Values).
Build(),
)
}
_, _ = event.CreateFollowup(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContentf("selected options: %s", event.Data.Values).
Build(),
)
}
}

func slashCommandListener(event *events.SlashCommandEvent) {
switch event.Data.CommandName {
func applicationCommandListener(event *events.ApplicationCommandInteractionEvent) {
data := event.SlashCommandInteractionData()
switch data.CommandName {
case "eval":
go func() {
code := *event.Data.Options.String("code")
code := *data.Options.String("code")
embed := discord.NewEmbedBuilder().
SetColor(orange).
AddField("Status", "...", true).
Expand All @@ -80,7 +82,7 @@ func slashCommandListener(event *events.SlashCommandEvent) {
embed.SetField(1, "Time", strconv.Itoa(int(elapsed.Milliseconds()))+"ms", true)

if err != nil {
_, err = event.UpdateOriginal(discord.NewMessageUpdateBuilder().
_, err = event.UpdateResponse(discord.NewMessageUpdateBuilder().
SetEmbeds(embed.
SetColor(red).
SetField(0, "Status", "Failed", true).
Expand All @@ -94,7 +96,7 @@ func slashCommandListener(event *events.SlashCommandEvent) {
}
return
}
_, err = event.UpdateOriginal(discord.NewMessageUpdateBuilder().
_, err = event.UpdateResponse(discord.NewMessageUpdateBuilder().
SetEmbeds(embed.
SetColor(green).
SetField(0, "Status", "Success", true).
Expand All @@ -110,8 +112,8 @@ func slashCommandListener(event *events.SlashCommandEvent) {

case "say":
_ = event.Create(discord.NewMessageCreateBuilder().
SetContent(*event.Data.Options.String("message")).
SetEphemeral(*event.Data.Options.Bool("ephemeral")).
SetContent(*data.Options.String("message")).
SetEphemeral(*data.Options.Bool("ephemeral")).
ClearAllowedMentions().
Build(),
)
Expand All @@ -121,18 +123,18 @@ func slashCommandListener(event *events.SlashCommandEvent) {
_ = event.DeferCreate(true)
members, err := event.Guild().RequestMembersWithQuery("", 0)
if err != nil {
_, _ = event.UpdateOriginal(discord.NewMessageUpdateBuilder().SetContentf("failed to load members. error: %s", err).Build())
_, _ = event.UpdateResponse(discord.NewMessageUpdateBuilder().SetContentf("failed to load members. error: %s", err).Build())
return
}
_, _ = event.UpdateOriginal(discord.NewMessageUpdateBuilder().
_, _ = event.UpdateResponse(discord.NewMessageUpdateBuilder().
SetContentf("loaded %d members", len(members)).
Build(),
)
}()

case "addrole":
user := event.Data.Options.User("member")
role := event.Data.Options.Role("role")
user := data.Options.User("member")
role := data.Options.Role("role")

if err := event.Bot().RestServices.GuildService().AddMemberRole(*event.GuildID, user.ID, role.ID); err == nil {
_ = event.Create(discord.NewMessageCreateBuilder().AddEmbeds(
Expand All @@ -145,8 +147,8 @@ func slashCommandListener(event *events.SlashCommandEvent) {
}

case "removerole":
user := event.Data.Options.User("member")
role := event.Data.Options.Role("role")
user := data.Options.User("member")
role := data.Options.Role("role")

if err := event.Bot().RestServices.GuildService().RemoveMemberRole(*event.GuildID, user.ID, role.ID); err == nil {
_ = event.Create(discord.NewMessageCreateBuilder().AddEmbeds(
Expand Down
87 changes: 87 additions & 0 deletions core/application_command_interaction.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package core

import "github.com/DisgoOrg/disgo/discord"

type ApplicationCommandInteractionFilter func(interaction *ApplicationCommandInteraction) bool

// ApplicationCommandInteraction represents a generic ApplicationCommandInteraction received from discord
type ApplicationCommandInteraction struct {
discord.ApplicationCommandInteraction
*ReplyInteraction
Data ApplicationCommandInteractionData
}

func (i ApplicationCommandInteraction) SlashCommandInteractionData() *SlashCommandInteractionData {
return i.Data.(*SlashCommandInteractionData)
}

func (i ApplicationCommandInteraction) UserCommandInteractionData() *UserCommandInteractionData {
return i.Data.(*UserCommandInteractionData)
}

func (i ApplicationCommandInteraction) MessageCommandInteractionData() *MessageCommandInteractionData {
return i.Data.(*MessageCommandInteractionData)
}

type ApplicationCommandInteractionData interface {
discord.ApplicationCommandInteractionData
}

type SlashCommandInteractionData struct {
discord.SlashCommandInteractionData
SubCommandName *string
SubCommandGroupName *string
Resolved *SlashCommandResolved
Options SlashCommandOptionsMap
}

// CommandPath returns the ApplicationCommand path
func (i SlashCommandInteractionData) CommandPath() string {
path := i.CommandName
if name := i.SubCommandName; name != nil {
path += "/" + *name
}
if name := i.SubCommandGroupName; name != nil {
path += "/" + *name
}
return path
}

// SlashCommandResolved contains resolved mention data for SlashCommand(s)
type SlashCommandResolved struct {
Users map[discord.Snowflake]*User
Members map[discord.Snowflake]*Member
Roles map[discord.Snowflake]*Role
Channels map[discord.Snowflake]Channel
}

type UserCommandInteractionData struct {
discord.UserCommandInteractionData
Resolved *UserCommandResolved
}

func (i *UserCommandInteractionData) TargetUser() *User {
return i.Resolved.Users[i.TargetID]
}

func (i *UserCommandInteractionData) TargetMember() *Member {
return i.Resolved.Members[i.TargetID]
}

type UserCommandResolved struct {
Users map[discord.Snowflake]*User
Members map[discord.Snowflake]*Member
}

type MessageCommandInteractionData struct {
discord.MessageCommandInteractionData
Resolved *MessageCommandResolved
}

func (i *MessageCommandInteractionData) TargetMessage() *Message {
return i.Resolved.Messages[i.TargetID]
}

type MessageCommandResolved struct {
Messages map[discord.Snowflake]*Message
}
Loading

0 comments on commit 07549dd

Please sign in to comment.