From 8579328ee4164bfc8d092c63264563fc1df51c5f Mon Sep 17 00:00:00 2001 From: vaporvee Date: Thu, 4 Apr 2024 01:27:59 +0200 Subject: [PATCH 01/12] started porting to disgo --- cmd_tag.go | 54 +++++------ go.mod | 11 ++- go.sum | 18 ++++ handlers.go | 256 ++++++++++++++++++++++++++-------------------------- main.go | 55 +++++++---- tool.go | 118 ++++++++---------------- 6 files changed, 254 insertions(+), 258 deletions(-) diff --git a/cmd_tag.go b/cmd_tag.go index 1ea9db3..6daafc8 100644 --- a/cmd_tag.go +++ b/cmd_tag.go @@ -2,22 +2,23 @@ package main import ( "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" + "github.com/disgoorg/json" "github.com/sirupsen/logrus" ) var cmd_tag Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "tag", - DefaultMemberPermissions: int64Ptr(discordgo.PermissionManageServer), + DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageGuild), Description: "A command to show and edit saved presaved messages.", - Options: []*discordgo.ApplicationCommandOption{ - { + Options: []discord.ApplicationCommandOption{ + discord.ApplicationCommandOptionSubCommand{ Name: "get", Description: "A command to get messages saved to the bot.", - Type: discordgo.ApplicationCommandOptionSubCommand, - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionString, + Options: []discord.ApplicationCommandOption{ + discord.ApplicationCommandOptionString{ Name: "tag", Description: "Your predefined tag for the saved message", Required: true, @@ -25,18 +26,15 @@ var cmd_tag Command = Command{ }, }, }, - { + discord.ApplicationCommandOptionSubCommand{ Name: "add", Description: "A command to add messages saved to the bot.", - Type: discordgo.ApplicationCommandOptionSubCommand, }, - { + discord.ApplicationCommandOptionSubCommand{ Name: "remove", Description: "A command to remove messages saved to the bot.", - Type: discordgo.ApplicationCommandOptionSubCommand, - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionString, + Options: []discord.ApplicationCommandOption{ + discord.ApplicationCommandOptionString{ Name: "tag", Description: "The tag you want to remove", Required: true, @@ -46,10 +44,10 @@ var cmd_tag Command = Command{ }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - switch i.ApplicationCommandData().Options[0].Name { + Interact: func(e *events.ApplicationCommandInteractionCreate) { + switch *e.SlashCommandInteractionData().SubCommandName { case "get": - GetTagCommand(i, i.ApplicationCommandData().Options[0].Options[0]) + GetTagCommand(e) case "add": AddTagCommand(i, "") case "remove": @@ -61,17 +59,19 @@ var cmd_tag Command = Command{ } }, ModalIDs: []string{"tag_add_modal"}, - ModalSubmit: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - tagName := i.ModalSubmitData().Components[0].(*discordgo.ActionsRow).Components[0].(*discordgo.TextInput).Value - tagContent := i.ModalSubmitData().Components[1].(*discordgo.ActionsRow).Components[0].(*discordgo.TextInput).Value - addTag(i.GuildID, tagName, tagContent) - err := respond(i.Interaction, "Tag \""+tagName+"\" added!", true) + ModalSubmit: func(e *events.ModalSubmitInteractionCreate) { + tagName := e.Data.Text("tag_add_modal_name") + tagContent := e.Data.Text("tag_add_modal_content") + addTag(e.GuildID().String(), tagName, tagContent) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Tag \"" + tagName + "\" added!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } }, - Autocomplete: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - AutocompleteTag(i) + Autocomplete: func(e *events.AutocompleteInteractionCreate) { + AutocompleteTag(e) }, } @@ -108,8 +108,8 @@ var context_tag Command = Command{ }, } -func GetTagCommand(i *discordgo.InteractionCreate, option *discordgo.ApplicationCommandInteractionDataOption) { - err := respond(i.Interaction, getTagContent(i.GuildID, option.Value.(string)), false) +func GetTagCommand(e *events.ApplicationCommandInteractionCreate) { + err := e.CreateMessage(discord.NewMessageCreateBuilder().SetContent(getTagContent(guildID, option)).SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } diff --git a/go.mod b/go.mod index 222e87f..5dce953 100644 --- a/go.mod +++ b/go.mod @@ -11,9 +11,14 @@ require ( ) require ( - github.com/gorilla/websocket v1.4.2 // indirect - golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b // indirect - golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect + github.com/disgoorg/disgo v0.17.2 // indirect + github.com/disgoorg/json v1.1.0 // indirect + github.com/disgoorg/snowflake/v2 v2.0.1 // indirect + github.com/gorilla/websocket v1.5.1 // indirect + github.com/sasha-s/go-csync v0.0.0-20240107134140-fcbab37b09ad // indirect + golang.org/x/crypto v0.18.0 // indirect + golang.org/x/net v0.20.0 // indirect + golang.org/x/sys v0.16.0 // indirect ) replace github.com/vaporvee/acecore/custom => ./custom diff --git a/go.sum b/go.sum index a7b0048..78e5ddd 100644 --- a/go.sum +++ b/go.sum @@ -3,30 +3,48 @@ github.com/bwmarrin/discordgo v0.27.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/disgoorg/disgo v0.17.2 h1:RxiLq8guMtk+9tArFwve02iya2APQ9yZVtV30ySKNtw= +github.com/disgoorg/disgo v0.17.2/go.mod h1:8r3h9fXSz7BbACxLPsPbtB6LX8gaQFUETgPKV/0gAKQ= +github.com/disgoorg/json v1.1.0 h1:7xigHvomlVA9PQw9bMGO02PHGJJPqvX5AnwlYg/Tnys= +github.com/disgoorg/json v1.1.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA= +github.com/disgoorg/snowflake/v2 v2.0.1 h1:CuUxGLwggUxEswZOmZ+mZ5i0xSumQdXW9tXW7uGqe+0= +github.com/disgoorg/snowflake/v2 v2.0.1/go.mod h1:SPU9c2CNn5DSyb86QcKtdZgix9osEtKrHLW4rMhfLCs= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sasha-s/go-csync v0.0.0-20240107134140-fcbab37b09ad h1:qIQkSlF5vAUHxEmTbaqt1hkJ/t6skqEGYiMag343ucI= +github.com/sasha-s/go-csync v0.0.0-20240107134140-fcbab37b09ad/go.mod h1:/pA7k3zsXKdjjAiUhB5CjuKib9KJGCaLvZwtxGC8U0s= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= +golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 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= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/handlers.go b/handlers.go index 5027b1b..6f917c3 100644 --- a/handlers.go +++ b/handlers.go @@ -5,54 +5,43 @@ import ( "slices" "strings" - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" + "github.com/disgoorg/snowflake/v2" "github.com/sirupsen/logrus" ) type Command struct { - Definition discordgo.ApplicationCommand - Interact func(s *discordgo.Session, i *discordgo.InteractionCreate) - ComponentInteract func(s *discordgo.Session, i *discordgo.InteractionCreate) - Autocomplete func(s *discordgo.Session, i *discordgo.InteractionCreate) - ModalSubmit func(s *discordgo.Session, i *discordgo.InteractionCreate) + Definition discord.SlashCommandCreate + Interact func(e *events.ApplicationCommandInteractionCreate) + Autocomplete func(e *events.AutocompleteInteractionCreate) + ComponentInteract func(e *events.ComponentInteractionCreate) + ModalSubmit func(e *events.ModalSubmitInteractionCreate) ComponentIDs []string ModalIDs []string - DynamicComponentIDs func() []string DynamicModalIDs func() []string + DynamicComponentIDs func() []string AllowDM bool } var commands []Command = []Command{cmd_form, cmd_ticket_form, cmd_tag, cmd_tag_short, cmd_dadjoke, cmd_ping, cmd_ask, cmd_sticky, cmd_cat, cmd_autojoinroles, cmd_autopublish, context_sticky, context_tag, cmd_userinfo} -func ready(s *discordgo.Session, event *discordgo.Ready) { +func ready(e *events.Ready) { logrus.Info("Starting up...") findAndDeleteUnusedMessages() - removeOldCommandFromAllGuilds(s) + removeOldCommandFromAllGuilds() var existingCommandNames []string - existingCommands, err := s.ApplicationCommands(s.State.User.ID, "") + existingCommands, err := client.Rest().GetGlobalCommands(app.Bot.ID, false) if err != nil { logrus.Errorf("error fetching existing global commands: %v", err) } else { for _, existingCommand := range existingCommands { - existingCommandNames = append(existingCommandNames, existingCommand.Name) - } - } - if slices.Contains(os.Args, "--clean") { - guilds := s.State.Guilds - if err != nil { - logrus.Errorf("error retrieving guilds: %v", err) - } - - for _, guild := range guilds { - _, err := s.ApplicationCommandBulkOverwrite(s.State.User.ID, guild.ID, []*discordgo.ApplicationCommand{}) - if err != nil { - logrus.Errorf("error deleting guild commands: %v", err) - } + existingCommandNames = append(existingCommandNames, existingCommand.Name()) } } for _, command := range commands { if !slices.Contains(existingCommandNames, command.Definition.Name) || slices.Contains(os.Args, "--update="+command.Definition.Name) || slices.Contains(os.Args, "--update=all") || slices.Contains(os.Args, "--clean") { - cmd, err := s.ApplicationCommandCreate(s.State.User.ID, "", &command.Definition) + cmd, err := client.Rest().CreateGlobalCommand(app.Bot.ID, command.Definition) if err != nil { logrus.Errorf("error creating global command '%s': %v", cmd.Name, err) } else { @@ -63,123 +52,138 @@ func ready(s *discordgo.Session, event *discordgo.Ready) { logrus.Info("Successfully started the Bot!") } -func interactionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) { +func applicationCommandInteractionCreate(e *events.ApplicationCommandInteractionCreate) { for _, command := range commands { - switch i.Type { - case discordgo.InteractionApplicationCommand: - if command.Interact != nil && i.ApplicationCommandData().Name == command.Definition.Name { - if !command.AllowDM && i.Interaction.GuildID == "" { - respond(i.Interaction, "This command is not available in DMs.", true) - } else { - command.Interact(s, i) - } - } - case discordgo.InteractionApplicationCommandAutocomplete: - if command.Autocomplete != nil && i.ApplicationCommandData().Name == command.Definition.Name { - if !command.AllowDM && i.Interaction.GuildID == "" { - err := bot.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionApplicationCommandAutocompleteResult, - Data: &discordgo.InteractionResponseData{ - Choices: nil, - }, - }) - if err != nil { - logrus.Error(err) - } - } else { - command.Autocomplete(s, i) - } - } - case discordgo.InteractionModalSubmit: - if !command.AllowDM && i.Interaction.GuildID == "" { - respond(i.Interaction, "This modal is not available in DMs.", true) + if command.Interact != nil && e.SlashCommandInteractionData().CommandName() == command.Definition.Name { + if !command.AllowDM && e.SlashCommandInteractionData().GuildID().String() == "" { + e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("This command is not available in DMs.").SetEphemeral(true). + Build()) } else { - if command.ModalSubmit != nil { - var hasID bool = false - var modalIDs []string - if command.ModalIDs != nil { - modalIDs = command.ModalIDs - } - if command.DynamicModalIDs != nil { - modalIDs = append(command.ModalIDs, command.DynamicModalIDs()...) - } - for _, modalID := range modalIDs { - if strings.HasPrefix(i.ModalSubmitData().CustomID, modalID) { - hasID = true - break - } - } - if hasID { - command.ModalSubmit(s, i) - return // I have no idea why it crashes without that return - } - } - } - case discordgo.InteractionMessageComponent: - if !command.AllowDM && i.Interaction.GuildID == "" { - respond(i.Interaction, "This component is not available in DMs.", true) - } else { - if command.ComponentInteract != nil { - if slices.Contains(command.ComponentIDs, i.MessageComponentData().CustomID) || slices.ContainsFunc(command.DynamicComponentIDs(), func(id string) bool { - var customID string - if strings.ContainsAny(i.MessageComponentData().CustomID, ";") { - customID = strings.TrimSuffix(i.MessageComponentData().CustomID, ";"+strings.Split(i.MessageComponentData().CustomID, ";")[1]) - } else { - customID = i.MessageComponentData().CustomID - } - return id == customID - }) { - command.ComponentInteract(s, i) - } - } + command.Interact(e) } } } } -func removeOldCommandFromAllGuilds(s *discordgo.Session) { - existingCommands, err := s.ApplicationCommands(s.State.User.ID, "") - if err != nil { - logrus.Errorf("error fetching existing commands: %v\n", err) - var commandIDs []string - for _, command := range commands { - commandIDs = append(commandIDs, command.Definition.Name) - } - for _, existingCommand := range existingCommands { - if !slices.Contains(commandIDs, existingCommand.Name) { - logrus.Infof("Deleting command '%s'", existingCommand.Name) - err := s.ApplicationCommandDelete(s.State.User.ID, "", existingCommand.ID) +func autocompleteInteractionCreate(e *events.AutocompleteInteractionCreate) { + for _, command := range commands { + if command.Autocomplete != nil && e.Data.CommandName == command.Definition.Name { + if !command.AllowDM && e.GuildID().String() == "" { + err := e.AutocompleteResult(nil) if err != nil { - logrus.Errorf("error deleting command %s: %v", existingCommand.Name, err) + logrus.Error(err) + } + } else { + command.Autocomplete(e) + } + } + } +} + +func componentInteractionCreate(e *events.ComponentInteractionCreate) { + for _, command := range commands { + if !command.AllowDM && e.GuildID().String() == "" { + e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("This component is not available in DMs.").SetEphemeral(true). + Build()) + } else { + if command.ComponentInteract != nil { + if slices.Contains(command.ComponentIDs, e.Data.CustomID()) || slices.ContainsFunc(command.DynamicComponentIDs(), func(id string) bool { + var customID string + if strings.ContainsAny(e.Data.CustomID(), ";") { + customID = strings.TrimSuffix(e.Data.CustomID(), ";"+strings.Split(e.Data.CustomID(), ";")[1]) + } else { + customID = e.Data.CustomID() + } + return id == customID + }) { + command.ComponentInteract(e) } } } } } -func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { - if len(m.Embeds) == 0 || m.Embeds[0].Footer == nil || m.Embeds[0].Footer.Text != "📌 Sticky message" { - if hasSticky(m.GuildID, m.ChannelID) { - stickymessageID := getStickyMessageID(m.GuildID, m.ChannelID) - err := s.ChannelMessageDelete(m.ChannelID, stickymessageID) - stickyMessage, _ := s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{ - Type: discordgo.EmbedTypeArticle, - Footer: &discordgo.MessageEmbedFooter{ - Text: "📌 Sticky message", +func modalSubmitInteractionCreate(e *events.ModalSubmitInteractionCreate) { + for _, command := range commands { + if !command.AllowDM && e.GuildID().String() == "" { + e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("This modal is not available in DMs.").SetEphemeral(true). + Build()) + } else { + if command.ModalSubmit != nil { + var hasID bool = false + var modalIDs []string + if command.ModalIDs != nil { + modalIDs = command.ModalIDs + } + if command.DynamicModalIDs != nil { + modalIDs = append(command.ModalIDs, command.DynamicModalIDs()...) + } + for _, modalID := range modalIDs { + if strings.HasPrefix(e.Data.CustomID, modalID) { + hasID = true + break + } + } + if hasID { + command.ModalSubmit(e) + return // I have no idea why it crashes without that return + } + } + } + } +} + +func removeOldCommandFromAllGuilds() { + globalCommands, err := client.Rest().GetGlobalCommands(app.Bot.ID, false) + if err != nil { + logrus.Error("error fetching existing global commands: %v", err) + return + } + var commandNames []string + for _, command := range commands { + commandNames = append(commandNames, command.Definition.Name) + } + + for _, existingCommand := range globalCommands { + if slices.Contains(commandNames, existingCommand.Name()) { + logrus.Info("Deleting command '%s'", existingCommand.Name) + err := client.Rest().DeleteGlobalCommand(app.Bot.ID, existingCommand.ID()) + if err != nil { + logrus.Error("error deleting command %s: %v", existingCommand.Name, err) + } + } + } +} + +func messageCreate(e *events.MessageCreate) { + if len(e.Message.Embeds) == 0 || e.Message.Embeds[0].Footer == nil || e.Message.Embeds[0].Footer.Text != "📌 Sticky message" { + if hasSticky(e.Message.GuildID.String(), e.Message.ChannelID.String()) { + stickymessageID := getStickyMessageID(e.Message.GuildID.String(), e.Message.ChannelID.String()) + err := e.Client().Rest().DeleteMessage(e.ChannelID, snowflake.MustParse(stickymessageID)) + stickyMessage, _ := e.Client().Rest().CreateMessage(e.ChannelID, discord.MessageCreate{ + Embeds: []discord.Embed{ + { + Footer: &discord.EmbedFooter{ + Text: "📌 Sticky message", + }, + Color: hexToDecimal(color["primary"]), + Description: getStickyMessageContent(e.Message.GuildID.String(), e.Message.ChannelID.String()), + }, }, - Color: hexToDecimal(color["primary"]), - Description: getStickyMessageContent(m.GuildID, m.ChannelID), }) if err != nil { logrus.Error(err) } - updateStickyMessageID(m.GuildID, m.ChannelID, stickyMessage.ID) + updateStickyMessageID(e.Message.GuildID.String(), e.Message.ChannelID.String(), stickyMessage.ID.String()) } } - channel, _ := s.Channel(m.ChannelID) - if channel.Type == discordgo.ChannelTypeGuildNews { - if isAutopublishEnabled(m.GuildID, m.ChannelID) { - _, err := s.ChannelMessageCrosspost(m.ChannelID, m.ID) + channel, _ := e.Channel() + if channel.Type() == discord.ChannelTypeGuildNews { + if isAutopublishEnabled(e.GuildID.String(), e.ChannelID.String()) { + _, err := e.Client().Rest().CrosspostMessage(e.ChannelID, e.MessageID) if err != nil { logrus.Error(err) } @@ -187,14 +191,14 @@ func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { } } -func messageDelete(s *discordgo.Session, m *discordgo.MessageDelete) { //TODO: also clear on bot start when message doesn't exist - tryDeleteUnusedMessage(m.ID) +func messageDelete(e *events.MessageDelete) { //TODO: also clear on bot start when message doesn't exist + tryDeleteUnusedMessage(e.MessageID.String()) } -func guildMemberJoin(s *discordgo.Session, m *discordgo.GuildMemberAdd) { - role := getAutoJoinRole(m.GuildID, m.User.Bot) +func guildMemberJoin(e *events.GuildMemberJoin) { + role := getAutoJoinRole(e.GuildID.String(), e.Member.User.Bot) if role != "" { - err := s.GuildMemberRoleAdd(m.GuildID, m.User.ID, role) + err := e.Client().Rest().AddMemberRole(e.GuildID, e.Member.User.ID, snowflake.MustParse(role)) if err != nil { logrus.Error(err) } diff --git a/main.go b/main.go index 46f3537..08e45e5 100644 --- a/main.go +++ b/main.go @@ -1,27 +1,30 @@ package main import ( + "context" + "database/sql" "io" + "net/url" "os" "os/signal" "strconv" "syscall" "time" - "database/sql" - "net/url" - - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo" + "github.com/disgoorg/disgo/bot" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/gateway" "github.com/joho/godotenv" - _ "github.com/lib/pq" "github.com/sirupsen/logrus" "github.com/vaporvee/acecore/log2webhook" ) -//TODO: add more error handlings - -var db *sql.DB -var bot *discordgo.Session +var ( + app *discord.Application + client bot.Client + db *sql.DB +) func main() { logrusInitFile() @@ -33,30 +36,42 @@ func main() { logrus.Fatal(err) } initTables() - bot, err = discordgo.New("Bot " + os.Getenv("BOT_TOKEN")) + client, err := disgo.New("Bot "+os.Getenv("BOT_TOKEN"), + bot.WithGatewayConfigOpts( + gateway.WithIntents( + gateway.IntentGuilds, + gateway.IntentGuildMessages, + gateway.IntentDirectMessages, + ), + ), + bot.WithEventListenerFunc(ready), + bot.WithEventListenerFunc(applicationCommandInteractionCreate), + bot.WithEventListenerFunc(autocompleteInteractionCreate), + bot.WithEventListenerFunc(messageCreate), + bot.WithEventListenerFunc(messageDelete), + bot.WithEventListenerFunc(guildMemberJoin), + ) if err != nil { logrus.Fatal("error creating Discord session,", err) return } else { logrus.Info("Discord session created") } - bot.Identify.Intents = discordgo.IntentsGuildMessages | discordgo.IntentsGuilds | discordgo.IntentMessageContent | discordgo.IntentGuildMembers - bot.AddHandler(ready) - bot.AddHandler(interactionCreate) - bot.AddHandler(messageCreate) - bot.AddHandler(messageDelete) - bot.AddHandler(guildMemberJoin) - err = bot.Open() - if err != nil { + + if err = client.OpenGateway(context.TODO()); err != nil { logrus.Error("error opening connection,", err) return } - logrus.Infof("Bot is now running as '%s'!", bot.State.User.Username) + app, err := client.Rest().GetCurrentApplication() + if err != nil { + logrus.Error(err) + } + logrus.Infof("Bot is now running as '%s'!", app.Bot.Username) + sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc logrus.Info("Shutting down...") - bot.Close() } func logrusInitFile() { diff --git a/tool.go b/tool.go index 1069c7d..e40efcb 100644 --- a/tool.go +++ b/tool.go @@ -9,7 +9,8 @@ import ( "strconv" "strings" - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/snowflake/v2" "github.com/sirupsen/logrus" ) @@ -34,46 +35,40 @@ type MessageIDs struct { ChannelID string } -func jsonStringShowModal(interaction *discordgo.Interaction, manageID string, formID string, overwrite ...string) { +func jsonStringShowModal(userID string, manageID string, formID string, overwrite ...string) discord.InteractionResponse { var modal ModalJson = getModalByFormID(formID) - var components []discordgo.MessageComponent + var components []discord.ContainerComponent for index, component := range modal.Form { - var style discordgo.TextInputStyle = discordgo.TextInputShort + var style discord.TextInputStyle = discord.TextInputStyleShort if component.IsParagraph { - style = discordgo.TextInputParagraph + style = discord.TextInputStyleParagraph } - components = append(components, discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.TextInput{ - CustomID: fmt.Sprint(index), - Label: component.Label, - Style: style, - Placeholder: component.Placeholder, - Required: component.Required, - MaxLength: component.MaxLength, - MinLength: component.MinLength, - Value: component.Value, - }, + components = append(components, discord.ActionRowComponent{ + discord.TextInputComponent{ + CustomID: fmt.Sprint(index), + Label: component.Label, + Style: style, + Placeholder: component.Placeholder, + Required: component.Required, + MaxLength: component.MaxLength, + MinLength: &component.MinLength, + Value: component.Value, }, }) } if overwrite != nil && overwrite[0] != "" { modal.Title = overwrite[0] } - var err error - if modal.Title != "" && components != nil { - err = bot.InteractionRespond(interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionResponseModal, - Data: &discordgo.InteractionResponseData{ - CustomID: manageID + ":" + interaction.Member.User.ID, - Title: modal.Title, - Components: components, - }, - }) - } - if err != nil { - logrus.Error(err) + + return discord.InteractionResponse{ + Type: discord.InteractionResponseTypeModal, + Data: &discord.ModalCreate{ + CustomID: manageID + ":" + userID, + Title: modal.Title, + Components: components, + }, } + } // Why does the golang compiler care about commands?? @@ -106,22 +101,21 @@ func getModalByFormID(formID string) ModalJson { return modal } -func getHighestRole(guildID string) (*discordgo.Role, error) { - botMember, err := bot.GuildMember(guildID, bot.State.User.ID) +func getHighestRole(guildID string) (*discord.Role, error) { + botmember, err := client.Rest().GetMember(snowflake.MustParse(guildID), app.Bot.ID) if err != nil { return nil, err } - roles, err := bot.GuildRoles(guildID) + roles, err := client.Rest().GetRoles(snowflake.MustParse(guildID)) if err != nil { return nil, err } - - var highestRole *discordgo.Role - for _, roleID := range botMember.Roles { + var highestRole *discord.Role + for _, roleID := range botmember.RoleIDs { for _, role := range roles { if role.ID == roleID { if highestRole == nil || role.Position > highestRole.Position { - highestRole = role + highestRole = &role } break } @@ -130,9 +124,7 @@ func getHighestRole(guildID string) (*discordgo.Role, error) { return highestRole, nil } -func int64Ptr(i int64) *int64 { - return &i -} +func ptr(s string) *string { return &s } func hexToDecimal(hexColor string) int { hexColor = strings.TrimPrefix(hexColor, "#") @@ -173,59 +165,21 @@ func simpleGetFromAPI(key string, url string) interface{} { return result[key] } -func respond(interaction *discordgo.Interaction, content string, ephemeral bool) error { - var flag discordgo.MessageFlags - if ephemeral { - flag = discordgo.MessageFlagsEphemeral - } - err := bot.InteractionRespond(interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionResponseChannelMessageWithSource, - Data: &discordgo.InteractionResponseData{ - Content: content, - Flags: flag, - }, - }) - if err != nil { - return err - } - return nil -} - -func respondEmbed(interaction *discordgo.Interaction, embed discordgo.MessageEmbed, ephemeral bool) error { - var flag discordgo.MessageFlags - if ephemeral { - flag = discordgo.MessageFlagsEphemeral - } - err := bot.InteractionRespond(interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionResponseChannelMessageWithSource, - Data: &discordgo.InteractionResponseData{ - Flags: flag, - Embeds: []*discordgo.MessageEmbed{ - &embed, - }, - }, - }) - if err != nil { - return err - } - return nil -} - func findAndDeleteUnusedMessages() { for _, message := range getAllSavedMessages() { - _, err := bot.ChannelMessage(message.ChannelID, message.ID) + _, err := client.Rest().GetMessage(snowflake.MustParse(message.ChannelID), snowflake.MustParse(message.ID)) if err != nil { tryDeleteUnusedMessage(message.ID) } } } -func isIDRole(guildID, id string) bool { - _, err1 := bot.GuildMember(guildID, id) +func isIDRole(guildID snowflake.ID, id snowflake.ID) bool { + _, err1 := client.Rest().GetMember(guildID, id) if err1 == nil { return false } - roles, err2 := bot.GuildRoles(guildID) + roles, err2 := client.Rest().GetRoles(guildID) if err2 == nil { for _, role := range roles { if role.ID == id { From 9738ab390172e93f6e098970977df6b3a1a08fca Mon Sep 17 00:00:00 2001 From: vaporvee Date: Thu, 4 Apr 2024 02:18:33 +0200 Subject: [PATCH 02/12] continued porting to disgo --- cmd_ask.go | 2 + cmd_autojoinroles.go | 7 +-- cmd_autopublish.go | 2 + cmd_cat.go | 11 +--- cmd_dadjoke.go | 2 + cmd_form.go | 12 +--- cmd_info.go | 2 + cmd_ping.go | 2 + cmd_sticky.go | 2 + cmd_tag.go | 135 +++++++++++++++++++++++-------------------- handlers.go | 12 ++-- main.go | 6 +- 12 files changed, 101 insertions(+), 94 deletions(-) diff --git a/cmd_ask.go b/cmd_ask.go index fefadbd..402cf6f 100644 --- a/cmd_ask.go +++ b/cmd_ask.go @@ -1,5 +1,6 @@ package main +/* import ( "github.com/bwmarrin/discordgo" "github.com/sirupsen/logrus" @@ -31,3 +32,4 @@ var cmd_ask Command = Command{ }, AllowDM: true, } +*/ diff --git a/cmd_autojoinroles.go b/cmd_autojoinroles.go index 9b47539..118074c 100644 --- a/cmd_autojoinroles.go +++ b/cmd_autojoinroles.go @@ -1,10 +1,6 @@ package main -import ( - "github.com/bwmarrin/discordgo" - "github.com/sirupsen/logrus" -) - +/* var cmd_autojoinroles Command = Command{ Definition: discordgo.ApplicationCommand{ Name: "autojoinroles", @@ -66,3 +62,4 @@ var cmd_autojoinroles Command = Command{ purgeUnusedAutoJoinRoles(i.GuildID) }, } +*/ diff --git a/cmd_autopublish.go b/cmd_autopublish.go index bd643ea..a69b0b6 100644 --- a/cmd_autopublish.go +++ b/cmd_autopublish.go @@ -1,5 +1,6 @@ package main +/* import ( "github.com/bwmarrin/discordgo" "github.com/sirupsen/logrus" @@ -32,3 +33,4 @@ var cmd_autopublish Command = Command{ } }, } +*/ diff --git a/cmd_cat.go b/cmd_cat.go index 54c2674..7e14008 100644 --- a/cmd_cat.go +++ b/cmd_cat.go @@ -1,14 +1,6 @@ package main -import ( - "encoding/json" - "io" - "net/http" - - "github.com/bwmarrin/discordgo" - "github.com/sirupsen/logrus" -) - +/* var cmd_cat Command = Command{ Definition: discordgo.ApplicationCommand{ Name: "cat", @@ -52,3 +44,4 @@ func GetCatImageURL() (string, error) { return "https://cataas.com/cat/" + images.ID, err } +*/ diff --git a/cmd_dadjoke.go b/cmd_dadjoke.go index 9cee282..1a976b0 100644 --- a/cmd_dadjoke.go +++ b/cmd_dadjoke.go @@ -1,5 +1,6 @@ package main +/* import ( "github.com/bwmarrin/discordgo" "github.com/sirupsen/logrus" @@ -18,3 +19,4 @@ var cmd_dadjoke Command = Command{ }, AllowDM: true, } +*/ diff --git a/cmd_form.go b/cmd_form.go index 62ebdcd..13a1d98 100644 --- a/cmd_form.go +++ b/cmd_form.go @@ -1,15 +1,6 @@ package main -import ( - "bytes" - "fmt" - "strings" - - "github.com/bwmarrin/discordgo" - "github.com/google/uuid" - "github.com/sirupsen/logrus" -) - +/* var cmd_form Command = Command{ Definition: discordgo.ApplicationCommand{ Name: "form", @@ -572,3 +563,4 @@ func getFormButtonIDs() []string { } return IDs } +*/ diff --git a/cmd_info.go b/cmd_info.go index d84f2cf..4ebdeac 100644 --- a/cmd_info.go +++ b/cmd_info.go @@ -1,5 +1,6 @@ package main +/* import ( "encoding/json" "fmt" @@ -232,3 +233,4 @@ func parseRetryAfterHeader(headers http.Header) time.Duration { return time.Duration(retryAfter) * time.Millisecond } +*/ diff --git a/cmd_ping.go b/cmd_ping.go index 9341bb9..9068e90 100644 --- a/cmd_ping.go +++ b/cmd_ping.go @@ -1,5 +1,6 @@ package main +/* import ( "fmt" "net/http" @@ -48,3 +49,4 @@ var cmd_ping Command = Command{ }, AllowDM: true, } +*/ diff --git a/cmd_sticky.go b/cmd_sticky.go index cdbedfb..8d9901f 100644 --- a/cmd_sticky.go +++ b/cmd_sticky.go @@ -1,5 +1,6 @@ package main +/* import ( "github.com/bwmarrin/discordgo" "github.com/sirupsen/logrus" @@ -99,3 +100,4 @@ func inputStickyMessage(i *discordgo.InteractionCreate) { } } } +*/ diff --git a/cmd_tag.go b/cmd_tag.go index 6daafc8..ef6dc0e 100644 --- a/cmd_tag.go +++ b/cmd_tag.go @@ -1,7 +1,6 @@ package main import ( - "github.com/bwmarrin/discordgo" "github.com/disgoorg/disgo/discord" "github.com/disgoorg/disgo/events" "github.com/disgoorg/json" @@ -49,10 +48,12 @@ var cmd_tag Command = Command{ case "get": GetTagCommand(e) case "add": - AddTagCommand(i, "") + AddTagCommand(e, "") case "remove": - removeTag(i.GuildID, i.ApplicationCommandData().Options[0].Options[0].StringValue()) - err := respond(i.Interaction, "Tag removed!", true) + removeTag(e.GuildID().String(), e.SlashCommandInteractionData().String("tag")) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Tag removed!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } @@ -76,12 +77,11 @@ var cmd_tag Command = Command{ } var cmd_tag_short Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "g", Description: "A short command to get presaved messages.", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionString, + Options: []discord.ApplicationCommandOption{ + discord.ApplicationCommandOptionString{ Name: "tag", Description: "Your predefined tag for the saved message", Required: true, @@ -89,86 +89,95 @@ var cmd_tag_short Command = Command{ }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - GetTagCommand(i, i.ApplicationCommandData().Options[0]) + Interact: func(e *events.ApplicationCommandInteractionCreate) { + GetTagCommand(e) }, - Autocomplete: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - AutocompleteTag(i) + Autocomplete: func(e *events.AutocompleteInteractionCreate) { + AutocompleteTag(e) }, } var context_tag Command = Command{ - Definition: discordgo.ApplicationCommand{ - Type: discordgo.MessageApplicationCommand, + Definition: discord.SlashCommandCreate{ Name: "Save as tag", - DefaultMemberPermissions: int64Ptr(discordgo.PermissionManageServer), + DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageGuild), }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - AddTagCommand(i, i.ApplicationCommandData().Resolved.Messages[i.ApplicationCommandData().TargetID].Content) + Interact: func(e *events.ApplicationCommandInteractionCreate) { + AddTagCommand(e, e.SlashCommandInteractionData().String("")) }, } func GetTagCommand(e *events.ApplicationCommandInteractionCreate) { - err := e.CreateMessage(discord.NewMessageCreateBuilder().SetContent(getTagContent(guildID, option)).SetEphemeral(true).Build()) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent(getTagContent(e.GuildID().String(), e.SlashCommandInteractionData().String("tag"))). + Build()) if err != nil { logrus.Error(err) } } -func AddTagCommand(i *discordgo.InteractionCreate, prevalue string) { - err := bot.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionResponseModal, - Data: &discordgo.InteractionResponseData{ - CustomID: "tag_add_modal" + i.Interaction.Member.User.ID, - Title: "Add a custom tag command", - Components: []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.TextInput{ - CustomID: "tag_add_modal_name", - Label: "Name", - Style: discordgo.TextInputShort, - Required: true, - MaxLength: 20, - Value: "", - }, - }, - }, - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.TextInput{ - CustomID: "tag_add_modal_content", - Label: "Content", - Placeholder: "Content that gets returned when the tag will be run", - Style: discordgo.TextInputParagraph, - Required: true, - MaxLength: 2000, - Value: prevalue, - }, - }, +func AddTagCommand(e *events.ApplicationCommandInteractionCreate, prevalue string) { + err := e.Modal(discord.ModalCreate{ + CustomID: "tag_add_modal" + e.User().ID.String(), + Title: "Add a custom tag command", + Components: []discord.ContainerComponent{ + discord.ActionRowComponent{ + discord.TextInputComponent{ + CustomID: "tag_add_modal_name", + Label: "Name", + Style: discord.TextInputStyleShort, + Required: true, + MaxLength: 20, + Value: "", }, }, }, }) - if err != nil { - logrus.Error(err) - } -} - -func AutocompleteTag(i *discordgo.InteractionCreate) { - err := bot.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionApplicationCommandAutocompleteResult, - Data: &discordgo.InteractionResponseData{ - Choices: generateTagChoices(i.GuildID), + /*Data: &discordgo.InteractionResponseData{ + CustomID: "tag_add_modal" + i.Interaction.Member.User.ID, + Title: "Add a custom tag command", + Components: []discordgo.MessageComponent{ + discordgo.ActionsRow{ + Components: []discordgo.MessageComponent{ + discordgo.TextInput{ + CustomID: "tag_add_modal_name", + Label: "Name", + Style: discordgo.TextInputShort, + Required: true, + MaxLength: 20, + Value: "", + }, + }, + }, + discordgo.ActionsRow{ + Components: []discordgo.MessageComponent{ + discordgo.TextInput{ + CustomID: "tag_add_modal_content", + Label: "Content", + Placeholder: "Content that gets returned when the tag will be run", + Style: discordgo.TextInputParagraph, + Required: true, + MaxLength: 2000, + Value: prevalue, + }, + }, + }, }, - }) + },*/ if err != nil { logrus.Error(err) } } -func generateTagChoices(guildID string) []*discordgo.ApplicationCommandOptionChoice { - choices := []*discordgo.ApplicationCommandOptionChoice{} +func AutocompleteTag(e *events.AutocompleteInteractionCreate) { + err := e.AutocompleteResult(generateTagChoices(e.GuildID().String())) + if err != nil { + logrus.Error(err) + } +} + +func generateTagChoices(guildID string) []discord.AutocompleteChoice { + choices := []discord.AutocompleteChoice{} IDs, err := getTagIDs(guildID) if err != nil { logrus.Error(err) @@ -176,7 +185,7 @@ func generateTagChoices(guildID string) []*discordgo.ApplicationCommandOptionCho } for _, id := range IDs { id_name := getTagName(guildID, id) - choices = append(choices, &discordgo.ApplicationCommandOptionChoice{ + choices = append(choices, &discord.AutocompleteChoiceString{ Name: id_name, Value: id, }) diff --git a/handlers.go b/handlers.go index 6f917c3..5723d1f 100644 --- a/handlers.go +++ b/handlers.go @@ -24,7 +24,7 @@ type Command struct { AllowDM bool } -var commands []Command = []Command{cmd_form, cmd_ticket_form, cmd_tag, cmd_tag_short, cmd_dadjoke, cmd_ping, cmd_ask, cmd_sticky, cmd_cat, cmd_autojoinroles, cmd_autopublish, context_sticky, context_tag, cmd_userinfo} +var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag /*, cmd_form, cmd_ticket_form, cmd_dadjoke, cmd_ping, cmd_ask, cmd_sticky, cmd_cat, cmd_autojoinroles, cmd_autopublish, context_sticky, cmd_userinfo*/} func ready(e *events.Ready) { logrus.Info("Starting up...") @@ -43,9 +43,9 @@ func ready(e *events.Ready) { if !slices.Contains(existingCommandNames, command.Definition.Name) || slices.Contains(os.Args, "--update="+command.Definition.Name) || slices.Contains(os.Args, "--update=all") || slices.Contains(os.Args, "--clean") { cmd, err := client.Rest().CreateGlobalCommand(app.Bot.ID, command.Definition) if err != nil { - logrus.Errorf("error creating global command '%s': %v", cmd.Name, err) + logrus.Errorf("error creating global command '%s': %v", cmd.Name(), err) } else { - logrus.Infof("Added global command '%s'", cmd.Name) + logrus.Infof("Added global command '%s'", cmd.Name()) } } } @@ -139,7 +139,7 @@ func modalSubmitInteractionCreate(e *events.ModalSubmitInteractionCreate) { func removeOldCommandFromAllGuilds() { globalCommands, err := client.Rest().GetGlobalCommands(app.Bot.ID, false) if err != nil { - logrus.Error("error fetching existing global commands: %v", err) + logrus.Errorf("error fetching existing global commands: %v", err) return } var commandNames []string @@ -149,10 +149,10 @@ func removeOldCommandFromAllGuilds() { for _, existingCommand := range globalCommands { if slices.Contains(commandNames, existingCommand.Name()) { - logrus.Info("Deleting command '%s'", existingCommand.Name) + logrus.Infof("Deleting command '%s'", existingCommand.Name()) err := client.Rest().DeleteGlobalCommand(app.Bot.ID, existingCommand.ID()) if err != nil { - logrus.Error("error deleting command %s: %v", existingCommand.Name, err) + logrus.Errorf("error deleting command %s: %v", existingCommand.Name(), err) } } } diff --git a/main.go b/main.go index 08e45e5..b33c067 100644 --- a/main.go +++ b/main.go @@ -11,6 +11,8 @@ import ( "syscall" "time" + _ "github.com/lib/pq" + "github.com/disgoorg/disgo" "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/discord" @@ -36,7 +38,7 @@ func main() { logrus.Fatal(err) } initTables() - client, err := disgo.New("Bot "+os.Getenv("BOT_TOKEN"), + client, err := disgo.New(os.Getenv("BOT_TOKEN"), bot.WithGatewayConfigOpts( gateway.WithIntents( gateway.IntentGuilds, @@ -47,6 +49,8 @@ func main() { bot.WithEventListenerFunc(ready), bot.WithEventListenerFunc(applicationCommandInteractionCreate), bot.WithEventListenerFunc(autocompleteInteractionCreate), + bot.WithEventListenerFunc(componentInteractionCreate), + bot.WithEventListenerFunc(modalSubmitInteractionCreate), bot.WithEventListenerFunc(messageCreate), bot.WithEventListenerFunc(messageDelete), bot.WithEventListenerFunc(guildMemberJoin), From b85d9d5294b21b76eaf60c18b47f739c3c1b9b89 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Thu, 4 Apr 2024 16:35:35 +0200 Subject: [PATCH 03/12] continued porting to disgo --- handlers.go | 46 ++++++++++++++++++++++++---------------------- main.go | 18 +++++++++--------- tool.go | 2 +- 3 files changed, 34 insertions(+), 32 deletions(-) diff --git a/handlers.go b/handlers.go index 5723d1f..e0c2823 100644 --- a/handlers.go +++ b/handlers.go @@ -1,7 +1,6 @@ package main import ( - "os" "slices" "strings" @@ -28,28 +27,30 @@ var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag /*, cmd_f func ready(e *events.Ready) { logrus.Info("Starting up...") - findAndDeleteUnusedMessages() + //findAndDeleteUnusedMessages() removeOldCommandFromAllGuilds() - var existingCommandNames []string - existingCommands, err := client.Rest().GetGlobalCommands(app.Bot.ID, false) - if err != nil { - logrus.Errorf("error fetching existing global commands: %v", err) - } else { - for _, existingCommand := range existingCommands { - existingCommandNames = append(existingCommandNames, existingCommand.Name()) - } - } - for _, command := range commands { - if !slices.Contains(existingCommandNames, command.Definition.Name) || slices.Contains(os.Args, "--update="+command.Definition.Name) || slices.Contains(os.Args, "--update=all") || slices.Contains(os.Args, "--clean") { - cmd, err := client.Rest().CreateGlobalCommand(app.Bot.ID, command.Definition) - if err != nil { - logrus.Errorf("error creating global command '%s': %v", cmd.Name(), err) - } else { - logrus.Infof("Added global command '%s'", cmd.Name()) + /* + var existingCommandNames []string + existingCommands, err := client.Rest().GetGlobalCommands(client.ApplicationID(), false) + if err != nil { + logrus.Errorf("error fetching existing global commands: %v", err) + } else { + for _, existingCommand := range existingCommands { + existingCommandNames = append(existingCommandNames, existingCommand.Name()) } } - } - logrus.Info("Successfully started the Bot!") + for _, command := range commands { + if !slices.Contains(existingCommandNames, command.Definition.Name) || slices.Contains(os.Args, "--update="+command.Definition.Name) || slices.Contains(os.Args, "--update=all") || slices.Contains(os.Args, "--clean") { + cmd, err := client.Rest().CreateGlobalCommand(client.ApplicationID(), command.Definition) + if err != nil { + logrus.Errorf("error creating global command '%s': %v", cmd.Name(), err) + } else { + logrus.Infof("Added global command '%s'", cmd.Name()) + } + } + } + logrus.Info("Successfully started the Bot!") + */ } func applicationCommandInteractionCreate(e *events.ApplicationCommandInteractionCreate) { @@ -137,7 +138,9 @@ func modalSubmitInteractionCreate(e *events.ModalSubmitInteractionCreate) { } func removeOldCommandFromAllGuilds() { + logrus.Debug(app.Bot.ID.String()) globalCommands, err := client.Rest().GetGlobalCommands(app.Bot.ID, false) + logrus.Debug("HERE") //doesnt get called if err != nil { logrus.Errorf("error fetching existing global commands: %v", err) return @@ -146,11 +149,10 @@ func removeOldCommandFromAllGuilds() { for _, command := range commands { commandNames = append(commandNames, command.Definition.Name) } - for _, existingCommand := range globalCommands { if slices.Contains(commandNames, existingCommand.Name()) { logrus.Infof("Deleting command '%s'", existingCommand.Name()) - err := client.Rest().DeleteGlobalCommand(app.Bot.ID, existingCommand.ID()) + err := client.Rest().DeleteGlobalCommand(client.ApplicationID(), existingCommand.ID()) if err != nil { logrus.Errorf("error deleting command %s: %v", existingCommand.Name(), err) } diff --git a/main.go b/main.go index b33c067..0dd620b 100644 --- a/main.go +++ b/main.go @@ -23,8 +23,8 @@ import ( ) var ( - app *discord.Application client bot.Client + app *discord.Application db *sql.DB ) @@ -47,13 +47,13 @@ func main() { ), ), bot.WithEventListenerFunc(ready), - bot.WithEventListenerFunc(applicationCommandInteractionCreate), - bot.WithEventListenerFunc(autocompleteInteractionCreate), - bot.WithEventListenerFunc(componentInteractionCreate), - bot.WithEventListenerFunc(modalSubmitInteractionCreate), - bot.WithEventListenerFunc(messageCreate), - bot.WithEventListenerFunc(messageDelete), - bot.WithEventListenerFunc(guildMemberJoin), + //bot.WithEventListenerFunc(applicationCommandInteractionCreate), + //bot.WithEventListenerFunc(autocompleteInteractionCreate), + //bot.WithEventListenerFunc(componentInteractionCreate), + //bot.WithEventListenerFunc(modalSubmitInteractionCreate), + //bot.WithEventListenerFunc(messageCreate), + //bot.WithEventListenerFunc(messageDelete), + //bot.WithEventListenerFunc(guildMemberJoin), ) if err != nil { logrus.Fatal("error creating Discord session,", err) @@ -66,7 +66,7 @@ func main() { logrus.Error("error opening connection,", err) return } - app, err := client.Rest().GetCurrentApplication() + app, err = client.Rest().GetCurrentApplication() if err != nil { logrus.Error(err) } diff --git a/tool.go b/tool.go index e40efcb..13ec791 100644 --- a/tool.go +++ b/tool.go @@ -102,7 +102,7 @@ func getModalByFormID(formID string) ModalJson { } func getHighestRole(guildID string) (*discord.Role, error) { - botmember, err := client.Rest().GetMember(snowflake.MustParse(guildID), app.Bot.ID) + botmember, err := client.Rest().GetMember(snowflake.MustParse(guildID), client.ApplicationID()) if err != nil { return nil, err } From 68a99fbb1005a3404023e93d6e10b54817cca449 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Thu, 4 Apr 2024 20:14:47 +0200 Subject: [PATCH 04/12] made getting tags working --- cmd_tag.go | 10 ++++++- handlers.go | 79 +++++++++++++++++++++++++++++++---------------------- main.go | 23 ++++++++-------- tool.go | 17 ++++++------ 4 files changed, 75 insertions(+), 54 deletions(-) diff --git a/cmd_tag.go b/cmd_tag.go index ef6dc0e..85c50c4 100644 --- a/cmd_tag.go +++ b/cmd_tag.go @@ -98,7 +98,7 @@ var cmd_tag_short Command = Command{ } var context_tag Command = Command{ - Definition: discord.SlashCommandCreate{ + Definition: discord.MessageCommandCreate{ Name: "Save as tag", DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageGuild), }, @@ -130,6 +130,14 @@ func AddTagCommand(e *events.ApplicationCommandInteractionCreate, prevalue strin MaxLength: 20, Value: "", }, + discord.TextInputComponent{ + CustomID: "tag_add_modal_content", + Label: "Content", + Style: discord.TextInputStyleParagraph, + Required: true, + MaxLength: 2000, + Value: prevalue, + }, }, }, }) diff --git a/handlers.go b/handlers.go index e0c2823..dce8aa8 100644 --- a/handlers.go +++ b/handlers.go @@ -1,9 +1,12 @@ package main import ( + "fmt" + "os" "slices" "strings" + "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/discord" "github.com/disgoorg/disgo/events" "github.com/disgoorg/snowflake/v2" @@ -11,7 +14,7 @@ import ( ) type Command struct { - Definition discord.SlashCommandCreate + Definition discord.ApplicationCommandCreate Interact func(e *events.ApplicationCommandInteractionCreate) Autocomplete func(e *events.AutocompleteInteractionCreate) ComponentInteract func(e *events.ComponentInteractionCreate) @@ -27,49 +30,57 @@ var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag /*, cmd_f func ready(e *events.Ready) { logrus.Info("Starting up...") - //findAndDeleteUnusedMessages() - removeOldCommandFromAllGuilds() - /* - var existingCommandNames []string - existingCommands, err := client.Rest().GetGlobalCommands(client.ApplicationID(), false) - if err != nil { - logrus.Errorf("error fetching existing global commands: %v", err) - } else { - for _, existingCommand := range existingCommands { - existingCommandNames = append(existingCommandNames, existingCommand.Name()) - } + findAndDeleteUnusedMessages(e.Client()) + removeOldCommandFromAllGuilds(e.Client()) + var existingCommandNames []string + existingCommands, err := e.Client().Rest().GetGlobalCommands(e.Client().ApplicationID(), false) + if err != nil { + logrus.Errorf("error fetching existing global commands: %v", err) + } else { + for _, existingCommand := range existingCommands { + existingCommandNames = append(existingCommandNames, existingCommand.Name()) } - for _, command := range commands { - if !slices.Contains(existingCommandNames, command.Definition.Name) || slices.Contains(os.Args, "--update="+command.Definition.Name) || slices.Contains(os.Args, "--update=all") || slices.Contains(os.Args, "--clean") { - cmd, err := client.Rest().CreateGlobalCommand(client.ApplicationID(), command.Definition) - if err != nil { - logrus.Errorf("error creating global command '%s': %v", cmd.Name(), err) - } else { - logrus.Infof("Added global command '%s'", cmd.Name()) - } - } + } + globalCommands := []discord.ApplicationCommandCreate{} + for _, command := range commands { + if !slices.Contains(existingCommandNames, command.Definition.CommandName()) || slices.Contains(os.Args, "--update="+command.Definition.CommandName()) || slices.Contains(os.Args, "--update=all") || slices.Contains(os.Args, "--clean") { + globalCommands = append(globalCommands, command.Definition) + logrus.Infof("Appending command \"%s\"", command.Definition.CommandName()) } - logrus.Info("Successfully started the Bot!") - */ + } + logrus.Infof("Attempting to add global commands %s", fmt.Sprint(globalCommands)) + _, err = e.Client().Rest().SetGlobalCommands(e.Client().ApplicationID(), globalCommands) + if err != nil { + logrus.Errorf("error creating global commands '%s'", err) + } else { + logrus.Infof("Added global commands sucessfully!") + } + logrus.Info("Successfully started the Bot!") } func applicationCommandInteractionCreate(e *events.ApplicationCommandInteractionCreate) { + app, err := e.Client().Rest().GetCurrentApplication() + if err != nil { + logrus.Error(err) + } for _, command := range commands { - if command.Interact != nil && e.SlashCommandInteractionData().CommandName() == command.Definition.Name { - if !command.AllowDM && e.SlashCommandInteractionData().GuildID().String() == "" { + if command.Interact != nil && e.SlashCommandInteractionData().CommandName() == command.Definition.CommandName() { + if !command.AllowDM && app.GuildID.String() == "" { e.CreateMessage(discord.NewMessageCreateBuilder(). SetContent("This command is not available in DMs.").SetEphemeral(true). Build()) } else { command.Interact(e) } + } + } } func autocompleteInteractionCreate(e *events.AutocompleteInteractionCreate) { for _, command := range commands { - if command.Autocomplete != nil && e.Data.CommandName == command.Definition.Name { + if command.Autocomplete != nil && e.Data.CommandName == command.Definition.CommandName() { if !command.AllowDM && e.GuildID().String() == "" { err := e.AutocompleteResult(nil) if err != nil { @@ -137,22 +148,24 @@ func modalSubmitInteractionCreate(e *events.ModalSubmitInteractionCreate) { } } -func removeOldCommandFromAllGuilds() { - logrus.Debug(app.Bot.ID.String()) - globalCommands, err := client.Rest().GetGlobalCommands(app.Bot.ID, false) - logrus.Debug("HERE") //doesnt get called +func removeOldCommandFromAllGuilds(c bot.Client) { + app, err := c.Rest().GetCurrentApplication() + if err != nil { + logrus.Error(err) + } + globalCommands, err := c.Rest().GetGlobalCommands(app.Bot.ID, false) if err != nil { logrus.Errorf("error fetching existing global commands: %v", err) return } var commandNames []string for _, command := range commands { - commandNames = append(commandNames, command.Definition.Name) + commandNames = append(commandNames, command.Definition.CommandName()) } for _, existingCommand := range globalCommands { - if slices.Contains(commandNames, existingCommand.Name()) { + if !slices.Contains(commandNames, existingCommand.Name()) { logrus.Infof("Deleting command '%s'", existingCommand.Name()) - err := client.Rest().DeleteGlobalCommand(client.ApplicationID(), existingCommand.ID()) + err := c.Rest().DeleteGlobalCommand(c.ApplicationID(), existingCommand.ID()) if err != nil { logrus.Errorf("error deleting command %s: %v", existingCommand.Name(), err) } diff --git a/main.go b/main.go index 0dd620b..205a56b 100644 --- a/main.go +++ b/main.go @@ -15,7 +15,6 @@ import ( "github.com/disgoorg/disgo" "github.com/disgoorg/disgo/bot" - "github.com/disgoorg/disgo/discord" "github.com/disgoorg/disgo/gateway" "github.com/joho/godotenv" "github.com/sirupsen/logrus" @@ -23,9 +22,7 @@ import ( ) var ( - client bot.Client - app *discord.Application - db *sql.DB + db *sql.DB ) func main() { @@ -47,13 +44,15 @@ func main() { ), ), bot.WithEventListenerFunc(ready), - //bot.WithEventListenerFunc(applicationCommandInteractionCreate), - //bot.WithEventListenerFunc(autocompleteInteractionCreate), - //bot.WithEventListenerFunc(componentInteractionCreate), - //bot.WithEventListenerFunc(modalSubmitInteractionCreate), - //bot.WithEventListenerFunc(messageCreate), - //bot.WithEventListenerFunc(messageDelete), - //bot.WithEventListenerFunc(guildMemberJoin), + bot.WithEventListenerFunc(applicationCommandInteractionCreate), + bot.WithEventListenerFunc(autocompleteInteractionCreate), + bot.WithEventListenerFunc(componentInteractionCreate), + bot.WithEventListenerFunc(modalSubmitInteractionCreate), + /* + bot.WithEventListenerFunc(messageCreate), + bot.WithEventListenerFunc(messageDelete), + bot.WithEventListenerFunc(guildMemberJoin), + */ ) if err != nil { logrus.Fatal("error creating Discord session,", err) @@ -66,7 +65,7 @@ func main() { logrus.Error("error opening connection,", err) return } - app, err = client.Rest().GetCurrentApplication() + app, err := client.Rest().GetCurrentApplication() if err != nil { logrus.Error(err) } diff --git a/tool.go b/tool.go index 13ec791..bf9f9d8 100644 --- a/tool.go +++ b/tool.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" + "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/discord" "github.com/disgoorg/snowflake/v2" "github.com/sirupsen/logrus" @@ -101,12 +102,12 @@ func getModalByFormID(formID string) ModalJson { return modal } -func getHighestRole(guildID string) (*discord.Role, error) { - botmember, err := client.Rest().GetMember(snowflake.MustParse(guildID), client.ApplicationID()) +func getHighestRole(guildID string, c bot.Client) (*discord.Role, error) { + botmember, err := c.Rest().GetMember(snowflake.MustParse(guildID), c.ApplicationID()) if err != nil { return nil, err } - roles, err := client.Rest().GetRoles(snowflake.MustParse(guildID)) + roles, err := c.Rest().GetRoles(snowflake.MustParse(guildID)) if err != nil { return nil, err } @@ -165,21 +166,21 @@ func simpleGetFromAPI(key string, url string) interface{} { return result[key] } -func findAndDeleteUnusedMessages() { +func findAndDeleteUnusedMessages(c bot.Client) { for _, message := range getAllSavedMessages() { - _, err := client.Rest().GetMessage(snowflake.MustParse(message.ChannelID), snowflake.MustParse(message.ID)) + _, err := c.Rest().GetMessage(snowflake.MustParse(message.ChannelID), snowflake.MustParse(message.ID)) if err != nil { tryDeleteUnusedMessage(message.ID) } } } -func isIDRole(guildID snowflake.ID, id snowflake.ID) bool { - _, err1 := client.Rest().GetMember(guildID, id) +func isIDRole(c bot.Client, guildID snowflake.ID, id snowflake.ID) bool { + _, err1 := c.Rest().GetMember(guildID, id) if err1 == nil { return false } - roles, err2 := client.Rest().GetRoles(guildID) + roles, err2 := c.Rest().GetRoles(guildID) if err2 == nil { for _, role := range roles { if role.ID == id { From 5f2fc7cbf16725c7988526ee00ed48022c2d498a Mon Sep 17 00:00:00 2001 From: vaporvee Date: Sun, 7 Apr 2024 14:22:18 +0200 Subject: [PATCH 05/12] reimplemented tag comment with disgo --- cmd_tag.go | 33 ++------------------------------- go.mod | 7 +++---- go.sum | 16 ++-------------- handlers.go | 28 +++++++++++++--------------- 4 files changed, 20 insertions(+), 64 deletions(-) diff --git a/cmd_tag.go b/cmd_tag.go index 85c50c4..e0bc64a 100644 --- a/cmd_tag.go +++ b/cmd_tag.go @@ -130,6 +130,8 @@ func AddTagCommand(e *events.ApplicationCommandInteractionCreate, prevalue strin MaxLength: 20, Value: "", }, + }, + discord.ActionRowComponent{ discord.TextInputComponent{ CustomID: "tag_add_modal_content", Label: "Content", @@ -141,37 +143,6 @@ func AddTagCommand(e *events.ApplicationCommandInteractionCreate, prevalue strin }, }, }) - /*Data: &discordgo.InteractionResponseData{ - CustomID: "tag_add_modal" + i.Interaction.Member.User.ID, - Title: "Add a custom tag command", - Components: []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.TextInput{ - CustomID: "tag_add_modal_name", - Label: "Name", - Style: discordgo.TextInputShort, - Required: true, - MaxLength: 20, - Value: "", - }, - }, - }, - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.TextInput{ - CustomID: "tag_add_modal_content", - Label: "Content", - Placeholder: "Content that gets returned when the tag will be run", - Style: discordgo.TextInputParagraph, - Required: true, - MaxLength: 2000, - Value: prevalue, - }, - }, - }, - }, - },*/ if err != nil { logrus.Error(err) } diff --git a/go.mod b/go.mod index 5dce953..aa60d05 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,9 @@ module github.com/vaporvee/acecore go 1.21.6 require ( - github.com/bwmarrin/discordgo v0.27.1 + github.com/disgoorg/disgo v0.17.2 + github.com/disgoorg/json v1.1.0 + github.com/disgoorg/snowflake/v2 v2.0.1 github.com/google/uuid v1.6.0 github.com/joho/godotenv v1.5.1 github.com/lib/pq v1.10.9 @@ -11,9 +13,6 @@ require ( ) require ( - github.com/disgoorg/disgo v0.17.2 // indirect - github.com/disgoorg/json v1.1.0 // indirect - github.com/disgoorg/snowflake/v2 v2.0.1 // indirect github.com/gorilla/websocket v1.5.1 // indirect github.com/sasha-s/go-csync v0.0.0-20240107134140-fcbab37b09ad // indirect golang.org/x/crypto v0.18.0 // indirect diff --git a/go.sum b/go.sum index 78e5ddd..ca69a43 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,3 @@ -github.com/bwmarrin/discordgo v0.27.1 h1:ib9AIc/dom1E/fSIulrBwnez0CToJE113ZGt4HoliGY= -github.com/bwmarrin/discordgo v0.27.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -11,8 +9,6 @@ github.com/disgoorg/snowflake/v2 v2.0.1 h1:CuUxGLwggUxEswZOmZ+mZ5i0xSumQdXW9tXW7 github.com/disgoorg/snowflake/v2 v2.0.1/go.mod h1:SPU9c2CNn5DSyb86QcKtdZgix9osEtKrHLW4rMhfLCs= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= @@ -26,25 +22,17 @@ github.com/sasha-s/go-csync v0.0.0-20240107134140-fcbab37b09ad/go.mod h1:/pA7k3z github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg= -golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 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= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/handlers.go b/handlers.go index dce8aa8..70aca38 100644 --- a/handlers.go +++ b/handlers.go @@ -43,29 +43,27 @@ func ready(e *events.Ready) { } globalCommands := []discord.ApplicationCommandCreate{} for _, command := range commands { - if !slices.Contains(existingCommandNames, command.Definition.CommandName()) || slices.Contains(os.Args, "--update="+command.Definition.CommandName()) || slices.Contains(os.Args, "--update=all") || slices.Contains(os.Args, "--clean") { + if !slices.Contains(existingCommandNames, command.Definition.CommandName()) || slices.Contains(os.Args, "--update-all") || slices.Contains(os.Args, "--clean") { globalCommands = append(globalCommands, command.Definition) logrus.Infof("Appending command \"%s\"", command.Definition.CommandName()) } } - logrus.Infof("Attempting to add global commands %s", fmt.Sprint(globalCommands)) - _, err = e.Client().Rest().SetGlobalCommands(e.Client().ApplicationID(), globalCommands) - if err != nil { - logrus.Errorf("error creating global commands '%s'", err) - } else { - logrus.Infof("Added global commands sucessfully!") + if len(globalCommands) > 0 { + logrus.Infof("Attempting to add global commands %s", fmt.Sprint(globalCommands)) + _, err = e.Client().Rest().SetGlobalCommands(e.Client().ApplicationID(), globalCommands) + if err != nil { + logrus.Errorf("error creating global commands '%s'", err) + } else { + logrus.Infof("Added global commands sucessfully!") + } } logrus.Info("Successfully started the Bot!") } func applicationCommandInteractionCreate(e *events.ApplicationCommandInteractionCreate) { - app, err := e.Client().Rest().GetCurrentApplication() - if err != nil { - logrus.Error(err) - } for _, command := range commands { if command.Interact != nil && e.SlashCommandInteractionData().CommandName() == command.Definition.CommandName() { - if !command.AllowDM && app.GuildID.String() == "" { + if !command.AllowDM && e.ApplicationCommandInteraction.GuildID().String() == "" { e.CreateMessage(discord.NewMessageCreateBuilder(). SetContent("This command is not available in DMs.").SetEphemeral(true). Build()) @@ -81,7 +79,7 @@ func applicationCommandInteractionCreate(e *events.ApplicationCommandInteraction func autocompleteInteractionCreate(e *events.AutocompleteInteractionCreate) { for _, command := range commands { if command.Autocomplete != nil && e.Data.CommandName == command.Definition.CommandName() { - if !command.AllowDM && e.GuildID().String() == "" { + if !command.AllowDM && e.AutocompleteInteraction.GuildID().String() == "" { err := e.AutocompleteResult(nil) if err != nil { logrus.Error(err) @@ -95,7 +93,7 @@ func autocompleteInteractionCreate(e *events.AutocompleteInteractionCreate) { func componentInteractionCreate(e *events.ComponentInteractionCreate) { for _, command := range commands { - if !command.AllowDM && e.GuildID().String() == "" { + if !command.AllowDM && e.ComponentInteraction.GuildID().String() == "" { e.CreateMessage(discord.NewMessageCreateBuilder(). SetContent("This component is not available in DMs.").SetEphemeral(true). Build()) @@ -119,7 +117,7 @@ func componentInteractionCreate(e *events.ComponentInteractionCreate) { func modalSubmitInteractionCreate(e *events.ModalSubmitInteractionCreate) { for _, command := range commands { - if !command.AllowDM && e.GuildID().String() == "" { + if !command.AllowDM && e.ModalSubmitInteraction.GuildID().String() == "" { e.CreateMessage(discord.NewMessageCreateBuilder(). SetContent("This modal is not available in DMs.").SetEphemeral(true). Build()) From 9e613d5adc8c217de319b166701e5dcc4c3dbca0 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Sun, 7 Apr 2024 16:02:30 +0200 Subject: [PATCH 06/12] fixed message context interaction --- cmd_tag.go | 10 +++++++--- handlers.go | 7 +++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/cmd_tag.go b/cmd_tag.go index e0bc64a..634926f 100644 --- a/cmd_tag.go +++ b/cmd_tag.go @@ -48,7 +48,7 @@ var cmd_tag Command = Command{ case "get": GetTagCommand(e) case "add": - AddTagCommand(e, "") + AddTagCommand(e) case "remove": removeTag(e.GuildID().String(), e.SlashCommandInteractionData().String("tag")) err := e.CreateMessage(discord.NewMessageCreateBuilder(). @@ -103,7 +103,7 @@ var context_tag Command = Command{ DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageGuild), }, Interact: func(e *events.ApplicationCommandInteractionCreate) { - AddTagCommand(e, e.SlashCommandInteractionData().String("")) + AddTagCommand(e) }, } @@ -116,7 +116,11 @@ func GetTagCommand(e *events.ApplicationCommandInteractionCreate) { } } -func AddTagCommand(e *events.ApplicationCommandInteractionCreate, prevalue string) { +func AddTagCommand(e *events.ApplicationCommandInteractionCreate) { + var prevalue string + if e.ApplicationCommandInteraction.Data.Type() == discord.ApplicationCommandTypeMessage { + prevalue = e.MessageCommandInteractionData().TargetMessage().Content + } err := e.Modal(discord.ModalCreate{ CustomID: "tag_add_modal" + e.User().ID.String(), Title: "Add a custom tag command", diff --git a/handlers.go b/handlers.go index 70aca38..b481a0a 100644 --- a/handlers.go +++ b/handlers.go @@ -62,11 +62,14 @@ func ready(e *events.Ready) { func applicationCommandInteractionCreate(e *events.ApplicationCommandInteractionCreate) { for _, command := range commands { - if command.Interact != nil && e.SlashCommandInteractionData().CommandName() == command.Definition.CommandName() { + if command.Interact != nil && e.Data.CommandName() == command.Definition.CommandName() { if !command.AllowDM && e.ApplicationCommandInteraction.GuildID().String() == "" { - e.CreateMessage(discord.NewMessageCreateBuilder(). + err := e.CreateMessage(discord.NewMessageCreateBuilder(). SetContent("This command is not available in DMs.").SetEphemeral(true). Build()) + if err != nil { + logrus.Error(err) + } } else { command.Interact(e) } From 01ac1ec36386d81161989a8f979189084657d987 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Sun, 7 Apr 2024 18:00:08 +0200 Subject: [PATCH 07/12] added sticky command back with disgo --- cmd_sticky.go | 87 ++++++++++++++++++++++++++------------------------- handlers.go | 23 ++++++++------ main.go | 2 +- 3 files changed, 59 insertions(+), 53 deletions(-) diff --git a/cmd_sticky.go b/cmd_sticky.go index 8d9901f..f1aa818 100644 --- a/cmd_sticky.go +++ b/cmd_sticky.go @@ -1,103 +1,106 @@ package main -/* import ( - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" + "github.com/disgoorg/json" + "github.com/disgoorg/snowflake/v2" "github.com/sirupsen/logrus" ) var cmd_sticky Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "sticky", Description: "Stick or unstick messages to the bottom of the current channel", - DefaultMemberPermissions: int64Ptr(discordgo.PermissionManageMessages), - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionString, + DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageMessages), + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionString{ Name: "message", Description: "The message you want to stick to the bottom of this channel", Required: false, }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - if len(i.ApplicationCommandData().Options) == 0 { - if hasSticky(i.GuildID, i.ChannelID) { - err := s.ChannelMessageDelete(i.ChannelID, getStickyMessageID(i.GuildID, i.ChannelID)) + Interact: func(e *events.ApplicationCommandInteractionCreate) { + if len(e.SlashCommandInteractionData().Options) == 0 { + if hasSticky(e.GuildID().String(), e.Channel().ID().String()) { + err := e.Client().Rest().DeleteMessage(e.Channel().ID(), snowflake.MustParse(getStickyMessageID(e.GuildID().String(), e.Channel().ID().String()))) if err != nil { logrus.Error(err) } - removeSticky(i.GuildID, i.ChannelID) - err = respond(i.Interaction, "The sticky message was removed from this channel!", true) + removeSticky(e.GuildID().String(), e.Channel().ID().String()) + err = e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("The sticky message was removed from this channel!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } else { - err := respond(i.Interaction, "This channel has no sticky message!", true) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("This channel has no sticky message!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } } else { - inputStickyMessage(i) + inputStickyMessage(e) } }, } var context_sticky Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.MessageCommandCreate{ Name: "Stick to channel", - Type: discordgo.MessageApplicationCommand, - DefaultMemberPermissions: int64Ptr(discordgo.PermissionManageMessages), + DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageMessages), }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - inputStickyMessage(i) + Interact: func(e *events.ApplicationCommandInteractionCreate) { + inputStickyMessage(e) }, } -func inputStickyMessage(i *discordgo.InteractionCreate) { +func inputStickyMessage(e *events.ApplicationCommandInteractionCreate) { var messageText string - if len(i.ApplicationCommandData().Options) == 0 { - messageText = i.ApplicationCommandData().Resolved.Messages[i.ApplicationCommandData().TargetID].Content //TODO add more data then just content + if e.ApplicationCommandInteraction.Data.Type() == discord.ApplicationCommandTypeMessage { + messageText = e.MessageCommandInteractionData().TargetMessage().Content //TODO add more data then just content } else { - messageText = i.ApplicationCommandData().Options[0].StringValue() + messageText = e.SlashCommandInteractionData().String("message") } if messageText == "" { - err := respond(i.Interaction, "Can't add empty sticky messages!", true) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Can't add empty sticky messages!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } else { - message, err := bot.ChannelMessageSendEmbed(i.ChannelID, &discordgo.MessageEmbed{ - Type: discordgo.EmbedTypeArticle, - Footer: &discordgo.MessageEmbedFooter{ - Text: "📌 Sticky message", - }, - Color: hexToDecimal(color["primary"]), - Description: messageText, - }) + message, err := e.Client().Rest().CreateMessage(e.Channel().ID(), discord.MessageCreate{Embeds: []discord.Embed{ + {Description: messageText, Footer: &discord.EmbedFooter{Text: "📌 Sticky message"}, Color: hexToDecimal(color["primary"])}}}) if err != nil { logrus.Error(err) } - if hasSticky(i.GuildID, i.ChannelID) { - err = bot.ChannelMessageDelete(i.ChannelID, getStickyMessageID(i.GuildID, i.ChannelID)) + if hasSticky(e.GuildID().String(), e.Channel().ID().String()) { + err = e.Client().Rest().DeleteMessage(e.Channel().ID(), snowflake.MustParse(getStickyMessageID(e.GuildID().String(), e.Channel().ID().String()))) if err != nil { - logrus.Error(err, getStickyMessageID(i.GuildID, i.ChannelID)) + logrus.Error(err, getStickyMessageID(e.GuildID().String(), e.Channel().ID().String())) } - removeSticky(i.GuildID, i.ChannelID) - addSticky(i.GuildID, i.ChannelID, messageText, message.ID) - err = respond(i.Interaction, "Sticky message in this channel was updated!", true) + removeSticky(e.GuildID().String(), e.Channel().ID().String()) + addSticky(e.GuildID().String(), e.Channel().ID().String(), messageText, message.ID.String()) + err = e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Sticky message in this channel was updated!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } else { - addSticky(i.GuildID, i.ChannelID, messageText, message.ID) - err := respond(i.Interaction, "Message sticked to the channel!", true) + addSticky(e.GuildID().String(), e.Channel().ID().String(), messageText, message.ID.String()) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Message sticked to the channel!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } } } -*/ diff --git a/handlers.go b/handlers.go index b481a0a..066213d 100644 --- a/handlers.go +++ b/handlers.go @@ -26,7 +26,7 @@ type Command struct { AllowDM bool } -var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag /*, cmd_form, cmd_ticket_form, cmd_dadjoke, cmd_ping, cmd_ask, cmd_sticky, cmd_cat, cmd_autojoinroles, cmd_autopublish, context_sticky, cmd_userinfo*/} +var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag, cmd_sticky, context_sticky /*, cmd_form, cmd_ticket_form, cmd_dadjoke, cmd_ping, cmd_ask, cmd_cat, cmd_autojoinroles, cmd_autopublish, cmd_userinfo*/} func ready(e *events.Ready) { logrus.Info("Starting up...") @@ -196,15 +196,18 @@ func messageCreate(e *events.MessageCreate) { updateStickyMessageID(e.Message.GuildID.String(), e.Message.ChannelID.String(), stickyMessage.ID.String()) } } - channel, _ := e.Channel() - if channel.Type() == discord.ChannelTypeGuildNews { - if isAutopublishEnabled(e.GuildID.String(), e.ChannelID.String()) { - _, err := e.Client().Rest().CrosspostMessage(e.ChannelID, e.MessageID) - if err != nil { - logrus.Error(err) - } - } - } + /* + channel, _ := e.Channel() + + if channel.Type() == discord.ChannelTypeGuildNews { + if isAutopublishEnabled(e.GuildID.String(), e.ChannelID.String()) { + _, err := e.Client().Rest().CrosspostMessage(e.ChannelID, e.MessageID) + if err != nil { + logrus.Error(err) + } + } + } + */ } func messageDelete(e *events.MessageDelete) { //TODO: also clear on bot start when message doesn't exist diff --git a/main.go b/main.go index 205a56b..4f2430f 100644 --- a/main.go +++ b/main.go @@ -48,8 +48,8 @@ func main() { bot.WithEventListenerFunc(autocompleteInteractionCreate), bot.WithEventListenerFunc(componentInteractionCreate), bot.WithEventListenerFunc(modalSubmitInteractionCreate), + bot.WithEventListenerFunc(messageCreate), /* - bot.WithEventListenerFunc(messageCreate), bot.WithEventListenerFunc(messageDelete), bot.WithEventListenerFunc(guildMemberJoin), */ From b7f126efba3abe285fbadbeb06a979afe8468da8 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Tue, 9 Apr 2024 23:21:08 +0200 Subject: [PATCH 08/12] continued porting to disgo... --- cmd_ask.go | 27 ++--- cmd_cat.go | 29 +++--- cmd_dadjoke.go | 16 +-- cmd_form.go | 269 +++++++++++++++++++++---------------------------- cmd_info.go | 256 ++++++++++++++++------------------------------ cmd_ping.go | 33 +++--- go.mod | 8 +- go.sum | 8 ++ handlers.go | 2 +- tool.go | 15 +++ 10 files changed, 284 insertions(+), 379 deletions(-) diff --git a/cmd_ask.go b/cmd_ask.go index 402cf6f..cfef599 100644 --- a/cmd_ask.go +++ b/cmd_ask.go @@ -1,35 +1,30 @@ package main -/* import ( - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" "github.com/sirupsen/logrus" ) -var cmd_ask Command = Command{ - Definition: discordgo.ApplicationCommand{ +var cmd_ask = Command{ + Definition: discord.SlashCommandCreate{ Name: "ask", Description: "Ask anything and get a gif as response!", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionString, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionString{ Name: "question", Description: "The question you want to ask", Required: true, }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - err := respondEmbed(i.Interaction, discordgo.MessageEmbed{ - Type: discordgo.EmbedTypeImage, - Color: hexToDecimal(color["primary"]), - Image: &discordgo.MessageEmbedImage{ - URL: simpleGetFromAPI("image", "https://yesno.wtf/api").(string), - }}, false) + Interact: func(e *events.ApplicationCommandInteractionCreate) { + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + AddEmbeds(discord.NewEmbedBuilder().SetImage(simpleGetFromAPI("image", "https://yesno.wtf/api").(string)).SetColor(hexToDecimal(color["primary"])).Build()). + Build()) if err != nil { - logrus.Error("Failed to respond with embed: ", err) + logrus.Error(err) } }, AllowDM: true, } -*/ diff --git a/cmd_cat.go b/cmd_cat.go index 7e14008..a125f57 100644 --- a/cmd_cat.go +++ b/cmd_cat.go @@ -1,25 +1,29 @@ package main -/* -var cmd_cat Command = Command{ - Definition: discordgo.ApplicationCommand{ +import ( + "encoding/json" + "io" + "net/http" + + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" + "github.com/sirupsen/logrus" +) + +var cmd_cat = Command{ + Definition: discord.SlashCommandCreate{ Name: "cat", Description: "Random cat pictures", }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { + Interact: func(e *events.ApplicationCommandInteractionCreate) { cat, err := GetCatImageURL() if err == nil { - err := respondEmbed(i.Interaction, discordgo.MessageEmbed{ - Type: discordgo.EmbedTypeImage, - Color: hexToDecimal(color["primary"]), - Image: &discordgo.MessageEmbedImage{ - URL: cat, - }}, false) + err = e.CreateMessage(discord.NewMessageCreateBuilder(). + AddEmbeds(discord.NewEmbedBuilder().SetImage(cat).SetColor(hexToDecimal(color["primary"])).Build()). + Build()) if err != nil { logrus.Error(err) } - } else { - logrus.Error(err) } }, AllowDM: true, @@ -44,4 +48,3 @@ func GetCatImageURL() (string, error) { return "https://cataas.com/cat/" + images.ID, err } -*/ diff --git a/cmd_dadjoke.go b/cmd_dadjoke.go index 1a976b0..4dd67de 100644 --- a/cmd_dadjoke.go +++ b/cmd_dadjoke.go @@ -1,22 +1,24 @@ package main -/* import ( - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" "github.com/sirupsen/logrus" ) -var cmd_dadjoke Command = Command{ - Definition: discordgo.ApplicationCommand{ +var cmd_dadjoke = Command{ + Definition: discord.SlashCommandCreate{ Name: "dadjoke", Description: "Gives you a random joke that is as bad as your dad would tell them", }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - err := respond(i.Interaction, simpleGetFromAPI("joke", "https://icanhazdadjoke.com/").(string), false) + Interact: func(e *events.ApplicationCommandInteractionCreate) { + joke := simpleGetFromAPI("joke", "https://icanhazdadjoke.com/").(string) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent(joke). + Build()) if err != nil { logrus.Error(err) } }, AllowDM: true, } -*/ diff --git a/cmd_form.go b/cmd_form.go index 13a1d98..6ad58ff 100644 --- a/cmd_form.go +++ b/cmd_form.go @@ -1,65 +1,68 @@ package main -/* +import ( + "bytes" + "fmt" + "strings" + + "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" + "github.com/disgoorg/json" + "github.com/disgoorg/snowflake/v2" + "github.com/google/uuid" + "github.com/sirupsen/logrus" +) + var cmd_form Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "form", - DefaultMemberPermissions: int64Ptr(discordgo.PermissionManageChannels), + DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageChannels), Description: "Create custom forms right inside Discord", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionSubCommand{ Name: "help", - Description: "Gives you a example file and demo for creating custom forms", + Description: "Gives you an example file and demo for creating custom forms", }, - { - Type: discordgo.ApplicationCommandOptionSubCommand, + &discord.ApplicationCommandOptionSubCommand{ Name: "custom", Description: "Create a new custom form right inside Discord", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionAttachment, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionAttachment{ Name: "json", Description: "Your edited form file", Required: true, }, }, }, - { - Type: discordgo.ApplicationCommandOptionSubCommand, + &discord.ApplicationCommandOptionSubCommand{ Name: "add", Description: "Adds existing forms to this channel", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionChannel, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionChannel{ Name: "result_channel", Description: "Where the form results should appear", - ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText}, + ChannelTypes: []discord.ChannelType{discord.ChannelTypeGuildText}, }, - { - Type: discordgo.ApplicationCommandOptionMentionable, + &discord.ApplicationCommandOptionMentionable{ Name: "moderator", Description: "Who can interact with moderating buttons.", }, - { - Type: discordgo.ApplicationCommandOptionString, + &discord.ApplicationCommandOptionString{ Name: "type", Description: "Which type of form you want to add", Autocomplete: true, }, - { - Type: discordgo.ApplicationCommandOptionString, + &discord.ApplicationCommandOptionString{ Name: "title", Description: "The title the form should have", }, - { - Type: discordgo.ApplicationCommandOptionChannel, + &discord.ApplicationCommandOptionChannel{ Name: "approve_channel", Description: "Channel for results that need to be accepted by a moderator before sending it to the result channel", - ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText}, + ChannelTypes: []discord.ChannelType{discord.ChannelTypeGuildText}, }, - { - Type: discordgo.ApplicationCommandOptionBoolean, + &discord.ApplicationCommandOptionBool{ Name: "mods_can_answer", Description: "Moderators can open a new channel on the form result, which then pings the user who submitted it", }, @@ -67,8 +70,8 @@ var cmd_form Command = Command{ }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - switch i.ApplicationCommandData().Options[0].Name { + Interact: func(e *events.ApplicationCommandInteractionCreate) { + switch *e.SlashCommandInteractionData().SubCommandName { case "help": fileData, err := formTemplates.ReadFile("form_templates/form_demo.json") if err != nil { @@ -76,39 +79,18 @@ var cmd_form Command = Command{ return } fileReader := bytes.NewReader(fileData) - err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionResponseChannelMessageWithSource, - Data: &discordgo.InteractionResponseData{ - Content: "NOT SUPPORTED YET!(use `/form add` instead)\n\nGet the example file edit it (make sure to have a unique \"form_type\") and submit it via `/form create`.\nOr use the demo button to get an idea of how the example would look like.", - Flags: discordgo.MessageFlagsEphemeral, - Files: []*discordgo.File{ - { - Name: "example.json", - ContentType: "json", - Reader: fileReader, - }, - }, - Components: []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.Button{ - Emoji: discordgo.ComponentEmoji{ - Name: "📑", - }, - CustomID: "form_demo", - Label: "Demo", - Style: discordgo.PrimaryButton, - }, - }, - }, - }, - }, - }) + err = e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("NOT SUPPORTED YET!(use `/form add` instead)\n\nGet the example file edit it (make sure to have a unique \"form_type\") and submit it via `/form create`.\nOr use the demo button to get an idea of how the example would look like."). + SetFiles(discord.NewFile("example.json", "json", fileReader)). + SetContainerComponents(discord.ActionRowComponent{discord.NewPrimaryButton("Demo", "form_demo").WithEmoji(discord.ComponentEmoji{Name: "📑"})}).SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } case "custom": - err := respond(i.Interaction, "Feature not available yet use `/form add` instead", true) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Feature not available yet use `/form add` instead").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } @@ -116,30 +98,21 @@ var cmd_form Command = Command{ var title, formID, overwriteTitle, acceptChannelID string var modsCanAnswer bool var resultChannelID string - moderator := i.Member.User.ID - if i.ApplicationCommandData().Options != nil { - options := i.ApplicationCommandData().Options[0] - for _, opt := range options.Options { - switch opt.Name { - case "result_channel": - resultChannelID = opt.ChannelValue(s).ID - case "type": - formID = opt.StringValue() - case "title": - overwriteTitle = opt.StringValue() - title = overwriteTitle - case "approve_channel": - acceptChannelID = opt.ChannelValue(s).ID - case "mods_can_answer": - modsCanAnswer = opt.BoolValue() - case "moderator": - moderator = opt.RoleValue(s, i.GuildID).ID - if moderator == "" { - moderator = opt.UserValue(s).ID - } - } - } + moderator := e.Member().User.ID.String() + data := e.SlashCommandInteractionData() + resultChannelID = data.Channel("result_channel").ID.String() + moderator = data.Role("moderator").ID.String() + if moderator == "" { + moderator = data.User("moderator").ID.String() } + formID = data.String("type") + overwriteTitle = data.String("title") + if overwriteTitle != "" { + title = overwriteTitle + } + acceptChannelID = data.Channel("accept_channel").ID.String() + modsCanAnswer = data.Bool("mods_can_answer") + if formID == "" { formID = "template_general" } @@ -159,44 +132,29 @@ var cmd_form Command = Command{ formManageID = uuid.New() exists = getFormManageIdExists(formManageID) } - - message, err := s.ChannelMessageSendComplex(i.ChannelID, &discordgo.MessageSend{ - Embed: &discordgo.MessageEmbed{ - Color: hexToDecimal(color["primary"]), - Title: title, - Description: "Press the bottom button to open a form popup.", - }, - Components: []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.Button{ - CustomID: "form:" + formManageID.String(), - Style: discordgo.SuccessButton, - Label: "Submit", - Emoji: discordgo.ComponentEmoji{ - Name: "anim_rocket", - ID: "1215740398706757743", - Animated: true, - }, - }, - }, - }, - }, - }) + messagebuild := discord.NewMessageCreateBuilder().SetEmbeds(discord.NewEmbedBuilder(). + SetTitle(title).SetDescription("Press the bottom button to open a form popup.").SetColor(hexToDecimal(color["primary"])). + Build()).SetContainerComponents(discord.ActionRowComponent{ + discord.NewSuccessButton("Submit", "form:"+formManageID.String()).WithEmoji(discord.ComponentEmoji{ + Name: "anim_rocket", + ID: snowflake.MustParse("1215740398706757743"), + Animated: true, + })}). + Build() + message, err := e.Client().Rest().CreateMessage(e.Channel().ID(), messagebuild) if err != nil { logrus.Error(err) - return } var category string if modsCanAnswer { - c, err := s.GuildChannelCreate(i.GuildID, title+" mod answers", discordgo.ChannelTypeGuildCategory) + c, err := e.Client().Rest().CreateGuildChannel(*e.GuildID(), discord.GuildCategoryChannelCreate{Name: title + " mod answers"}) if err != nil { logrus.Error(err) } - category = c.ID + category = c.ID().String() } - addFormButton(i.GuildID, i.ChannelID, message.ID, formManageID.String(), formID, resultChannelID, overwriteTitle, acceptChannelID, category, moderator) - err = respond(i.Interaction, "Successfully added form button!", true) + addFormButton(e.GuildID().String(), e.Channel().ID().String(), message.ID.String(), formManageID.String(), formID, resultChannelID, overwriteTitle, acceptChannelID, category, moderator) + err = e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Successfully added form button!").SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } @@ -204,43 +162,44 @@ var cmd_form Command = Command{ }, DynamicComponentIDs: func() []string { return getFormButtonIDs() }, DynamicModalIDs: func() []string { return getFormButtonIDs() }, - ComponentInteract: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - if strings.ContainsAny(i.MessageComponentData().CustomID, ";") { - var form_manage_id string = strings.TrimPrefix(strings.Split(i.MessageComponentData().CustomID, ";")[0], "form:") - switch strings.Split(i.MessageComponentData().CustomID, ";")[1] { - case "decline": - err := s.ChannelMessageDelete(i.ChannelID, i.Message.ID) - if err != nil { - logrus.Error(err) + ComponentInteract: func(e *events.ComponentInteractionCreate) { + if e.Data.Type() == discord.ComponentTypeButton { + if strings.ContainsAny(e.ButtonInteractionData().CustomID(), ";") { + var form_manage_id string = strings.TrimPrefix(strings.Split(e.ButtonInteractionData().CustomID(), ";")[0], "form:") + switch strings.Split(e.ButtonInteractionData().CustomID(), ";")[1] { + case "decline": + err := e.Client().Rest().DeleteMessage(e.Channel().ID(), e.Message.ID) + if err != nil { + logrus.Error(err) + } + e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Submission declined!").SetEphemeral(true).Build()) + case "approve": + embed := e.Message.Embeds[0] + embed.Description = fmt.Sprintf("This submission was approved by <@%s>.", e.Member().User.ID) + _, err := e.Client().Rest().CreateMessage(snowflake.MustParse(getFormResultValues(form_manage_id).ResultChannelID), discord.NewMessageCreateBuilder(). + SetEmbeds(embed). + Build()) + if err != nil { + logrus.Error(err) + } + e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Submission accepted!").SetEphemeral(true).Build()) + err = e.Client().Rest().DeleteMessage(e.Channel().ID(), e.Message.ID) + if err != nil { + logrus.Error(err) + } + case "comment": + author := strings.TrimSuffix(strings.Split(e.Message.Embeds[0].Fields[len(e.Message.Embeds[0].Fields)-1].Value, "<@")[1], ">") + embed := e.Message.Embeds[0] + moderator := e.Member().User.ID + createFormComment(form_manage_id, author, moderator, "answer", embed, e) } - respond(i.Interaction, "Submission declined!", true) - case "approve": - embed := i.Message.Embeds[0] - embed.Description = fmt.Sprintf("This submission was approved by <@%s>.", i.Member.User.ID) - _, err := s.ChannelMessageSendComplex(getFormResultValues(form_manage_id).ResultChannelID, &discordgo.MessageSend{ - Embed: embed, - }) - if err != nil { - logrus.Error(err) + } else { + if strings.HasPrefix(i.Interaction.MessageComponentData().CustomID, "form:") { + var formManageID string = strings.TrimPrefix(i.Interaction.MessageComponentData().CustomID, "form:") + jsonStringShowModal(i.Interaction, i.Interaction.MessageComponentData().CustomID, getFormType(formManageID), getFormOverwriteTitle(formManageID)) + } else if i.Interaction.MessageComponentData().CustomID == "form_demo" { + jsonStringShowModal(i.Interaction, "form_demo", "form_demo") } - respond(i.Interaction, "Submission accepted!", true) - err = s.ChannelMessageDelete(i.ChannelID, i.Message.ID) - if err != nil { - logrus.Error(err) - } - - case "comment": - author := strings.TrimSuffix(strings.Split(i.Message.Embeds[0].Fields[len(i.Message.Embeds[0].Fields)-1].Value, "<@")[1], ">") - embed := i.Message.Embeds[0] - moderator := i.Member.User.ID - createFormComment(form_manage_id, author, moderator, "answer", embed, i) - } - } else { - if strings.HasPrefix(i.Interaction.MessageComponentData().CustomID, "form:") { - var formManageID string = strings.TrimPrefix(i.Interaction.MessageComponentData().CustomID, "form:") - jsonStringShowModal(i.Interaction, i.Interaction.MessageComponentData().CustomID, getFormType(formManageID), getFormOverwriteTitle(formManageID)) - } else if i.Interaction.MessageComponentData().CustomID == "form_demo" { - jsonStringShowModal(i.Interaction, "form_demo", "form_demo") } } }, @@ -507,18 +466,18 @@ var cmd_ticket_form Command = Command{ } // moderator can be userID as well as roleID -func createFormComment(form_manage_id string, author string, moderator string, commentName string, embed *discordgo.MessageEmbed, i *discordgo.InteractionCreate) { - category := getFormResultValues(form_manage_id).CommentCategoryID - _, err := bot.Channel(category) +func createFormComment(form_manage_id string, author string, moderator snowflake.ID, commentName string, embed discord.Embed, e *events.ComponentInteractionCreate) { + var category snowflake.ID + _, err := e.Client().Rest().GetChannel(snowflake.MustParse(getFormResultValues(form_manage_id).CommentCategoryID)) if err != nil { - c, err := bot.GuildChannelCreate(i.GuildID, strings.Trim(embed.Title, "\"")+" mod "+commentName+"s", discordgo.ChannelTypeGuildCategory) + c, err := e.Client().Rest().CreateGuildChannel(*e.GuildID(), discord.GuildCategoryChannelCreate{Name: strings.Trim(embed.Title, "\"") + " mod " + commentName + "s"}) if err != nil { logrus.Error(err) } - category = c.ID - updateFormCommentCategory(form_manage_id, c.ID) + category = c.ID() + updateFormCommentCategory(form_manage_id, category.String()) } - ch, err := bot.GuildChannelCreateComplex(i.GuildID, discordgo.GuildChannelCreateData{ + ch, err := e.Client().Rest().CreateGuildChannel(*e.GuildID(), discord.GuildTextChannelCreate{ ParentID: category, Name: strings.ToLower(embed.Author.Name) + "-" + commentName, }) @@ -526,6 +485,7 @@ func createFormComment(form_manage_id string, author string, moderator string, c logrus.Error(err) } err = bot.ChannelPermissionSet(ch.ID, i.GuildID, discordgo.PermissionOverwriteTypeRole, 0, discordgo.PermissionViewChannel) + _, err = e.Client().Rest().UpdateChannel(ch.ID(), discord.GuildTextChannelUpdate{PermissionOverwrites: &[]discord.PermissionOverwrite{}}) if err != nil { logrus.Error(err) } @@ -563,4 +523,3 @@ func getFormButtonIDs() []string { } return IDs } -*/ diff --git a/cmd_info.go b/cmd_info.go index 4ebdeac..e2e44a6 100644 --- a/cmd_info.go +++ b/cmd_info.go @@ -1,17 +1,12 @@ package main -/* import ( - "encoding/json" "fmt" - "io" - "net/http" - "os" "strconv" "strings" - "time" - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" "github.com/sirupsen/logrus" ) @@ -25,128 +20,98 @@ type AvatarDecoration struct { URL string } -var userFlagsString map[discordgo.UserFlags]string = map[discordgo.UserFlags]string{ - discordgo.UserFlagDiscordEmployee: "<:Discord_Employee:1224708831419043942>[`Discord Employee`](https://discord.com/company)", - discordgo.UserFlagDiscordPartner: "<:Discord_Partner:1224708689190060092>[`Discord Partner`](https://discord.com/partners)", - discordgo.UserFlagHypeSquadEvents: "<:Hypesquad_Events:1224708685494747237>[`HypeSquad Events`](https://discord.com/hypesquad)", - discordgo.UserFlagBugHunterLevel1: "<:Bug_Hunter_Level_1:1224708828415918231>[`Bug Hunter Level 1`](https://support.discord.com/hc/en-us/articles/360046057772-Discord-Bugs)", - discordgo.UserFlagHouseBravery: "<:Hypesquad_Bravery:1224708678905630801>[`HypeSquad Bravery`](https://discord.com/settings/hypesquad-online)", - discordgo.UserFlagHouseBrilliance: "<:Hypesquad_Brilliance:1224708677584424961>[`HypeSquad Brilliance`](https://discord.com/settings/hypesquad-online)", - discordgo.UserFlagHouseBalance: "<:Hypequad_Balance:1224708826901516309>[`HypeSquad Balance`](https://discord.com/settings/hypesquad-online)", - discordgo.UserFlagEarlySupporter: "<:Early_Supporter:1224708674065272873>[`Early Supporter`](https://discord.com/settings/premium)", - discordgo.UserFlagTeamUser: "`TeamUser`", - discordgo.UserFlagSystem: "", - discordgo.UserFlagBugHunterLevel2: "<:Bug_Hunter_Level_2:1224708682378383461>[`Bug Hunter Level 2`](https://support.discord.com/hc/en-us/articles/360046057772-Discord-Bugs)", - discordgo.UserFlagVerifiedBot: "", - discordgo.UserFlagVerifiedBotDeveloper: "<:Early_Verified_Bot_Developer:1224708675294203934>`Early Verified Bot Developer`", - discordgo.UserFlagDiscordCertifiedModerator: "<:Discord_Certified_Moderator:1224708830223532124>[`Discord Certified Moderator`](https://discord.com/safety)", - 1 << 19: "`BotHTTPInteractions`", - 1 << 22: "<:Active_Developer:1224708676611215380>[`Active Developer`](https://support-dev.discord.com/hc/en-us/articles/10113997751447?ref=badge)", +var userFlagsString map[discord.UserFlags]string = map[discord.UserFlags]string{ + discord.UserFlagDiscordEmployee: "<:Discord_Employee:1224708831419043942>[`Discord Employee`](https://discord.com/company)", + discord.UserFlagPartneredServerOwner: "<:Discord_Partner:1224708689190060092>[`Discord Partner`](https://discord.com/partners)", + discord.UserFlagHypeSquadEvents: "<:Hypesquad_Events:1224708685494747237>[`HypeSquad Events`](https://discord.com/hypesquad)", + discord.UserFlagBugHunterLevel1: "<:Bug_Hunter_Level_1:1224708828415918231>[`Bug Hunter Level 1`](https://support.discord.com/hc/en-us/articles/360046057772-Discord-Bugs)", + discord.UserFlagHouseBravery: "<:Hypesquad_Bravery:1224708678905630801>[`HypeSquad Bravery`](https://discord.com/settings/hypesquad-online)", + discord.UserFlagHouseBrilliance: "<:Hypesquad_Brilliance:1224708677584424961>[`HypeSquad Brilliance`](https://discord.com/settings/hypesquad-online)", + discord.UserFlagHouseBalance: "<:Hypequad_Balance:1224708826901516309>[`HypeSquad Balance`](https://discord.com/settings/hypesquad-online)", + discord.UserFlagEarlySupporter: "<:Early_Supporter:1224708674065272873>[`Early Supporter`](https://discord.com/settings/premium)", + discord.UserFlagTeamUser: "`TeamUser`", + discord.UserFlagBugHunterLevel2: "<:Bug_Hunter_Level_2:1224708682378383461>[`Bug Hunter Level 2`](https://support.discord.com/hc/en-us/articles/360046057772-Discord-Bugs)", + discord.UserFlagVerifiedBot: "", + discord.UserFlagEarlyVerifiedBotDeveloper: "<:Early_Verified_Bot_Developer:1224708675294203934>`Early Verified Bot Developer`", + discord.UserFlagDiscordCertifiedModerator: "<:Discord_Certified_Moderator:1224708830223532124>[`Discord Certified Moderator`](https://discord.com/safety)", + discord.UserFlagBotHTTPInteractions: "`BotHTTPInteractions`", + discord.UserFlagActiveDeveloper: "<:Active_Developer:1224708676611215380>[`Active Developer`](https://support-dev.discord.com/hc/en-us/articles/10113997751447?ref=badge)", } var cmd_userinfo Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "info", Description: "Gives you information about a user or this bot.", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionSubCommand{ Name: "user", Description: "Gives you information about a user and its profile images.", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionUser, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionUser{ Name: "user", Description: "The user you need information about.", Required: true, }, }, }, - { - Type: discordgo.ApplicationCommandOptionSubCommand, + &discord.ApplicationCommandOptionSubCommand{ Name: "bot-service", Description: "Gives you information about this bot's server service.", }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - switch i.ApplicationCommandData().Options[0].Name { + Interact: func(e *events.ApplicationCommandInteractionCreate) { + switch *e.SlashCommandInteractionData().SubCommandName { case "user": - var user *discordgo.User = i.ApplicationCommandData().Options[0].Options[0].UserValue(s) - var extendedUser UserExtend = extendedUserFromAPI(user.ID) - var userHasFlags string = fetchFlagStrings(user, extendedUser.AvatarDecorationData.Asset) + var user discord.User = e.SlashCommandInteractionData().User("user") + var userHasFlags string = fetchFlagStrings(user) var userType string = "User" if user.Bot { userType = "Unverified Bot" - if user.PublicFlags&discordgo.UserFlagVerifiedBot != 0 { + if user.PublicFlags&discord.UserFlagVerifiedBot != 0 { userType = "Verified Bot" } } else if user.System { userType = "System" } - createdate, err := discordgo.SnowflakeTimestamp(user.ID) - if err != nil { - logrus.Error(err) - } - err = respondEmbed(i.Interaction, discordgo.MessageEmbed{ - Title: extendedUser.GlobalName + " user info", - Thumbnail: &discordgo.MessageEmbedThumbnail{URL: user.AvatarURL("512")}, - Description: user.Mention(), - Type: discordgo.EmbedTypeArticle, - Fields: []*discordgo.MessageEmbedField{ - { - Name: "test", - Value: fmt.Sprint(s.State.Application.BotPublic), - }, - { - Name: "ID", - Value: user.ID, - }, - { - Name: "Type", - Value: userType, - Inline: true, - }, - { - Name: "Global name", - Value: extendedUser.GlobalName, - Inline: true, - }, - { - Name: "Username", - Value: user.Username, - Inline: true, - }, - { - Name: "Badges", - Value: userHasFlags, - }, - { - Name: "Discriminator", - Value: user.Discriminator, - Inline: true, - }, - { - Name: "Accent color", - Value: "#" + decimalToHex(user.AccentColor), - Inline: true, - }, - { - Name: "Avatar Decoration", - Value: "[PNG (animated)](" + extendedUser.AvatarDecorationData.URL + ")\n[PNG](" + extendedUser.AvatarDecorationData.URL + "?size=4096&passthrough=false)\nSKU ID: `" + extendedUser.AvatarDecorationData.SkuID + "`", - Inline: true, - }, - { - Name: "Created at", - Value: "<:discord_member:1224717530078253166> - ", - }, - }, - Color: hexToDecimal(color["primary"]), - Image: &discordgo.MessageEmbedImage{URL: user.BannerURL("512")}, - }, false) + embedBuilder := discord.NewEmbedBuilder() + embedBuilder.SetThumbnail(checkDefaultPb(user)) + embedBuilder.AddField("ID", user.ID.String(), false) + embedBuilder.AddField("Type", userType, true) + if user.GlobalName != nil { + embedBuilder.AddField("Global name", *user.GlobalName, true) + } + embedBuilder.AddField("Username", user.Username, true) + if userHasFlags != "" { + embedBuilder.AddField("Badges", userHasFlags, false) + } + if user.Discriminator != "0" { + embedBuilder.AddField("Discriminator", user.Discriminator, false) + } + if user.AccentColor != nil { + embedBuilder.AddField("Accent color", strconv.Itoa(*user.AccentColor), true) + } + if user.AvatarDecorationURL() != nil { + decoration := strings.TrimSuffix(*user.AvatarDecorationURL(), ".gif") + value := fmt.Sprintf("[PNG (animated)](%s)\n[PNG](%s)", decoration, decoration+"?passthrough=false") + embedBuilder.AddField("Avatar decoration", value, true) + } + creation := "<:discord_member:1224717530078253166> " + discord.TimestampStyleLongDateTime.FormatTime(user.CreatedAt()) + "-" + discord.TimestampStyleRelative.FormatTime(user.CreatedAt()) + embedBuilder.AddField("Created at", creation, false) + if user.BannerURL() != nil { + embedBuilder.SetImage(*user.BannerURL()) + } + embedBuilder.SetTitle("User info") + embedBuilder.SetDescription(user.Mention()) + embedBuilder.SetColor(hexToDecimal(color["primary"])) + embedBuilder.SetFooterText("Currently a bit broken because of Discord's constant user API changes") + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetEmbeds(embedBuilder.Build()). + Build()) if err != nil { logrus.Error(err) } + case "bot-service": } @@ -155,82 +120,37 @@ var cmd_userinfo Command = Command{ AllowDM: true, } -func fetchFlagStrings(user *discordgo.User, decorationAsset string) string { +func checkDefaultPb(user discord.User) string { + if user.AvatarURL() == nil { + return "https://discord.com/assets/ac6f8cf36394c66e7651.png" + } + return *user.AvatarURL() +} + +func fetchFlagStrings(user discord.User) string { var userHasFlagsString string for flag, flagName := range userFlagsString { - if user.PublicFlags&flag != 0 { + if flag&user.PublicFlags != 0 { userHasFlagsString += flagName + ", " } } - if user.PremiumType > 0 { - userHasFlagsString += "<:Nitro:1224708672492666943>[`Nitro`](https://discord.com/settings/premium), " - } - if decorationAsset == "a_5e1210779d99ece1c0b4f438a5bc6e72" { + if noNullString(user.AvatarDecorationData.Asset) == "a_5e1210779d99ece1c0b4f438a5bc6e72" { userHasFlagsString += "<:Limited_Lootbox_Clown:1224714172705804300>[`Lootbox Clown`](https://discord.com/settings/Lootboxes)" } - if user.Bot { - appuser := bot.State.Application - if appuser.Flags&1<<23 != 0 { - userHasFlagsString += "<:Supports_Commands:1224848976201646100>[`Supports Commands`](https://discord.com/blog/welcome-to-the-new-era-of-discord-apps?ref=badge)" - } - if appuser.Flags&1<<6 != 0 { - userHasFlagsString += "<:Uses_Automod:1224862880982106202>`Uses Automod`" - } - } - + /* + if user.PremiumType > 0 { + userHasFlagsString += "<:Nitro:1224708672492666943>[`Nitro`](https://discord.com/settings/premium), " + } + if user.Bot { + appuser := bot.State.Application + if appuser.Flags&1<<23 != 0 { + userHasFlagsString += "<:Supports_Commands:1224848976201646100>[`Supports Commands`](https://discord.com/blog/welcome-to-the-new-era-of-discord-apps?ref=badge)" + } + if appuser.Flags&1<<6 != 0 { + userHasFlagsString += "<:Uses_Automod:1224862880982106202>`Uses Automod`" + } + } + */ returnString := strings.TrimSuffix(userHasFlagsString, ", ") return returnString } - -func extendedUserFromAPI(userID string) UserExtend { - client := &http.Client{} - var userExtend UserExtend - req, err := http.NewRequest("GET", "https://discord.com/api/v10/users/"+userID, nil) - if err != nil { - logrus.Error(err) - return userExtend - } - req.Header.Add("Authorization", "Bot "+os.Getenv("BOT_TOKEN")) - req.Header.Add("Content-Type", "application/json") - - res, err := client.Do(req) - if err != nil { - logrus.Error(err) - return userExtend - } - defer res.Body.Close() - - if res.StatusCode == http.StatusTooManyRequests { - retryAfter := parseRetryAfterHeader(res.Header) - if retryAfter > 0 { - time.Sleep(retryAfter) - } - } - - body, err := io.ReadAll(res.Body) - if err != nil { - logrus.Error(err) - return userExtend - } - - json.Unmarshal(body, &userExtend) - if userExtend.AvatarDecorationData.Asset != "" { - userExtend.AvatarDecorationData.URL = "https://cdn.discordapp.com/avatar-decoration-presets/" + userExtend.AvatarDecorationData.Asset + ".png" - } - return userExtend -} - -func parseRetryAfterHeader(headers http.Header) time.Duration { - retryAfterStr := headers.Get("Retry-After") - if retryAfterStr == "" { - return 0 - } - - retryAfter, err := strconv.Atoi(retryAfterStr) - if err != nil { - return 0 - } - - return time.Duration(retryAfter) * time.Millisecond -} -*/ diff --git a/cmd_ping.go b/cmd_ping.go index 9068e90..233adf8 100644 --- a/cmd_ping.go +++ b/cmd_ping.go @@ -1,28 +1,28 @@ package main -/* import ( "fmt" "net/http" "time" - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" "github.com/sirupsen/logrus" ) var cmd_ping Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "ping", Description: "Returns the ping of the bot", }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { + Interact: func(e *events.ApplicationCommandInteractionCreate) { start := time.Now() client := http.Client{ Timeout: 5 * time.Second, } - resp, err := client.Get("https://discord.com/api/" + discordgo.APIVersion + "/gateway/bot") + resp, err := client.Get("https://discord.com/api/v9/gateway/bot") if err != nil { logrus.Error(err) return @@ -30,23 +30,26 @@ var cmd_ping Command = Command{ defer resp.Body.Close() ping := time.Since(start) - var ping_color string + var pingColor string if ping.Milliseconds() < 200 { - ping_color = "green" + pingColor = "green" } else if ping.Milliseconds() < 400 { - ping_color = "yellow" + pingColor = "yellow" } else { - ping_color = "red" + pingColor = "red" } - err = respondEmbed(i.Interaction, discordgo.MessageEmbed{ - Title: s.State.User.Username + " ping", - Description: fmt.Sprintf("# %.2fms", ping.Seconds()*1000), - Type: discordgo.EmbedTypeArticle, - Color: hexToDecimal(color[ping_color])}, true) + app, err := e.Client().Rest().GetCurrentApplication() + if err != nil { + logrus.Error(err) + } + err = e.CreateMessage(discord.NewMessageCreateBuilder(). + SetEmbeds(discord.NewEmbedBuilder(). + SetTitle(app.Bot.Username + " ping"). + SetDescription(fmt.Sprintf("# %.2fms", ping.Seconds()*1000)). + SetColor(hexToDecimal(color[pingColor])).Build()).SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } }, AllowDM: true, } -*/ diff --git a/go.mod b/go.mod index aa60d05..db9aef6 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/vaporvee/acecore go 1.21.6 require ( - github.com/disgoorg/disgo v0.17.2 + github.com/disgoorg/disgo v0.18.0 github.com/disgoorg/json v1.1.0 github.com/disgoorg/snowflake/v2 v2.0.1 github.com/google/uuid v1.6.0 @@ -15,9 +15,9 @@ require ( require ( github.com/gorilla/websocket v1.5.1 // indirect github.com/sasha-s/go-csync v0.0.0-20240107134140-fcbab37b09ad // indirect - golang.org/x/crypto v0.18.0 // indirect - golang.org/x/net v0.20.0 // indirect - golang.org/x/sys v0.16.0 // indirect + golang.org/x/crypto v0.19.0 // indirect + golang.org/x/net v0.21.0 // indirect + golang.org/x/sys v0.17.0 // indirect ) replace github.com/vaporvee/acecore/custom => ./custom diff --git a/go.sum b/go.sum index ca69a43..33ab55a 100644 --- a/go.sum +++ b/go.sum @@ -3,6 +3,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/disgoorg/disgo v0.17.2 h1:RxiLq8guMtk+9tArFwve02iya2APQ9yZVtV30ySKNtw= github.com/disgoorg/disgo v0.17.2/go.mod h1:8r3h9fXSz7BbACxLPsPbtB6LX8gaQFUETgPKV/0gAKQ= +github.com/disgoorg/disgo v0.18.0 h1:EviKy/OiGofYW2X4kLjgxAUYrqjmBEMpVp/MMXHP1pY= +github.com/disgoorg/disgo v0.18.0/go.mod h1:gkl6DBdbKUvmOOJayWPSvS52KPN/8uJGJ2f13gCEB1o= github.com/disgoorg/json v1.1.0 h1:7xigHvomlVA9PQw9bMGO02PHGJJPqvX5AnwlYg/Tnys= github.com/disgoorg/json v1.1.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA= github.com/disgoorg/snowflake/v2 v2.0.1 h1:CuUxGLwggUxEswZOmZ+mZ5i0xSumQdXW9tXW7uGqe+0= @@ -27,11 +29,17 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= +golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/handlers.go b/handlers.go index 066213d..0eef560 100644 --- a/handlers.go +++ b/handlers.go @@ -26,7 +26,7 @@ type Command struct { AllowDM bool } -var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag, cmd_sticky, context_sticky /*, cmd_form, cmd_ticket_form, cmd_dadjoke, cmd_ping, cmd_ask, cmd_cat, cmd_autojoinroles, cmd_autopublish, cmd_userinfo*/} +var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag, cmd_sticky, context_sticky, cmd_ping, cmd_userinfo, cmd_form, cmd_ask, cmd_cat, cmd_dadjoke /*, cmd_ticket_form, cmd_autojoinroles, cmd_autopublish*/} func ready(e *events.Ready) { logrus.Info("Starting up...") diff --git a/tool.go b/tool.go index bf9f9d8..2024bb8 100644 --- a/tool.go +++ b/tool.go @@ -36,6 +36,21 @@ type MessageIDs struct { ChannelID string } +func noNullString(in interface{}) string { + var s string = "" + var is_str bool + switch in.(type) { + case string: + is_str = true + case *string: + is_str = true + } + if in != nil && is_str { + s = fmt.Sprint(in) + } + return s +} + func jsonStringShowModal(userID string, manageID string, formID string, overwrite ...string) discord.InteractionResponse { var modal ModalJson = getModalByFormID(formID) var components []discord.ContainerComponent From 09454c7aea74f8c18bd067a0ed083d7e0c99f6d2 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Wed, 10 Apr 2024 13:51:17 +0200 Subject: [PATCH 09/12] got forms half way working with disgo --- cmd_form.go | 348 ++++++++++++++++++++++------------------------------ cmd_info.go | 29 ++--- go.mod | 2 +- go.sum | 2 + handlers.go | 2 +- main.go | 2 +- tool.go | 16 +-- 7 files changed, 177 insertions(+), 224 deletions(-) diff --git a/cmd_form.go b/cmd_form.go index 6ad58ff..8aa150c 100644 --- a/cmd_form.go +++ b/cmd_form.go @@ -5,7 +5,7 @@ import ( "fmt" "strings" - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/discord" "github.com/disgoorg/disgo/events" "github.com/disgoorg/json" @@ -98,19 +98,22 @@ var cmd_form Command = Command{ var title, formID, overwriteTitle, acceptChannelID string var modsCanAnswer bool var resultChannelID string - moderator := e.Member().User.ID.String() data := e.SlashCommandInteractionData() - resultChannelID = data.Channel("result_channel").ID.String() - moderator = data.Role("moderator").ID.String() - if moderator == "" { - moderator = data.User("moderator").ID.String() + if data.Channel("result_channel").ID.String() != "0" { + resultChannelID = data.Channel("result_channel").ID.String() + } + moderator := data.Role("moderator").ID.String() + if moderator == "0" { + moderator = e.User().ID.String() } formID = data.String("type") overwriteTitle = data.String("title") if overwriteTitle != "" { title = overwriteTitle } - acceptChannelID = data.Channel("accept_channel").ID.String() + if data.Channel("accept_channel").ID.String() != "0" { + acceptChannelID = data.Channel("accept_channel").ID.String() + } modsCanAnswer = data.Bool("mods_can_answer") if formID == "" { @@ -153,6 +156,7 @@ var cmd_form Command = Command{ } category = c.ID().String() } + addFormButton(e.GuildID().String(), e.Channel().ID().String(), message.ID.String(), formManageID.String(), formID, resultChannelID, overwriteTitle, acceptChannelID, category, moderator) err = e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Successfully added form button!").SetEphemeral(true).Build()) if err != nil { @@ -175,7 +179,7 @@ var cmd_form Command = Command{ e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Submission declined!").SetEphemeral(true).Build()) case "approve": embed := e.Message.Embeds[0] - embed.Description = fmt.Sprintf("This submission was approved by <@%s>.", e.Member().User.ID) + embed.Description = fmt.Sprintf("This submission was approved by <@%s>.", e.User().ID) _, err := e.Client().Rest().CreateMessage(snowflake.MustParse(getFormResultValues(form_manage_id).ResultChannelID), discord.NewMessageCreateBuilder(). SetEmbeds(embed). Build()) @@ -190,149 +194,117 @@ var cmd_form Command = Command{ case "comment": author := strings.TrimSuffix(strings.Split(e.Message.Embeds[0].Fields[len(e.Message.Embeds[0].Fields)-1].Value, "<@")[1], ">") embed := e.Message.Embeds[0] - moderator := e.Member().User.ID - createFormComment(form_manage_id, author, moderator, "answer", embed, e) + moderator := e.User().ID + channel := createFormComment(form_manage_id, snowflake.MustParse(author), moderator, "answer", embed, *e.GuildID(), e.Client()) + e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Created channel " + discord.ChannelMention(channel.ID())).SetEphemeral(true).Build()) } } else { - if strings.HasPrefix(i.Interaction.MessageComponentData().CustomID, "form:") { - var formManageID string = strings.TrimPrefix(i.Interaction.MessageComponentData().CustomID, "form:") - jsonStringShowModal(i.Interaction, i.Interaction.MessageComponentData().CustomID, getFormType(formManageID), getFormOverwriteTitle(formManageID)) - } else if i.Interaction.MessageComponentData().CustomID == "form_demo" { - jsonStringShowModal(i.Interaction, "form_demo", "form_demo") + if strings.HasPrefix(e.ButtonInteractionData().CustomID(), "form:") { + var formManageID string = strings.TrimPrefix(e.ButtonInteractionData().CustomID(), "form:") + e.Modal(jsonStringBuildModal(e.User().ID.String(), formManageID, getFormType(formManageID), getFormOverwriteTitle(formManageID))) + } else if e.ButtonInteractionData().CustomID() == "form_demo" { + e.Modal(jsonStringBuildModal(e.User().ID.String(), "form_demo", "form_demo")) } } } }, - ModalSubmit: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - if !strings.HasPrefix(i.ModalSubmitData().CustomID, "form_demo") { - var form_manage_id string = strings.Split(i.ModalSubmitData().CustomID, ":")[1] + ModalSubmit: func(e *events.ModalSubmitInteractionCreate) { + if !strings.HasPrefix(e.Data.CustomID, "form_demo") { + var form_manage_id string = strings.Split(e.Data.CustomID, ":")[1] var result FormResult = getFormResultValues(form_manage_id) - var fields []*discordgo.MessageEmbedField + var fields []discord.EmbedField var modal ModalJson = getModalByFormID(getFormType(form_manage_id)) var overwrite_title string = getFormOverwriteTitle(form_manage_id) if overwrite_title != "" { modal.Title = overwrite_title } - for index, component := range i.ModalSubmitData().Components { - var input *discordgo.TextInput = component.(*discordgo.ActionsRow).Components[0].(*discordgo.TextInput) - fields = append(fields, &discordgo.MessageEmbedField{ + var inline bool + var index int = 0 + for _, component := range e.Data.Components { + var input discord.TextInputComponent = component.(discord.TextInputComponent) + inline = input.Style == discord.TextInputStyleShort + fields = append(fields, discord.EmbedField{ Name: modal.Form[index].Label, Value: input.Value, - Inline: input.Style == discordgo.TextInputShort, + Inline: &inline, }) + index++ } - channel, _ := s.Channel(i.ChannelID) - fields = append(fields, &discordgo.MessageEmbedField{ - Value: "From <#" + channel.ID + "> by <@" + i.Member.User.ID + ">", + fields = append(fields, discord.EmbedField{ + Value: "From <#" + e.Channel().ID().String() + "> by " + e.User().Mention(), }) if result.ResultChannelID == "" { if result.CommentCategoryID != "" { - createFormComment(form_manage_id, i.Member.User.ID, result.ModeratorID, "answer", &discordgo.MessageEmbed{ - Author: &discordgo.MessageEmbedAuthor{ - Name: i.Member.User.Username, - IconURL: i.Member.AvatarURL("256"), - }, - Title: "\"" + modal.Title + "\"", - Color: hexToDecimal(color["primary"]), - Description: "This is the submitted result", - Fields: fields, - }, i) + channel := createFormComment(form_manage_id, e.User().ID, snowflake.MustParse(result.ModeratorID), "answer", discord.NewEmbedBuilder(). + SetAuthorName(*e.User().GlobalName).SetAuthorIcon(*e.User().AvatarURL()).SetTitle("\""+modal.Title+"\"").SetDescription("This is the submitted result"). + SetColor(hexToDecimal(color["primary"])).SetFields(fields...). + Build(), *e.GuildID(), e.Client()) + err := e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Created channel " + discord.ChannelMention(channel.ID())).SetEphemeral(true).Build()) + if err != nil { + logrus.Error(err) + } } else { - respond(i.Interaction, "You need to provide either a `result_channel` or enable `mods_can_answer` to create a valid form.", true) + e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("You need to provide either a `result_channel` or enable `mods_can_answer` to create a valid form.").SetEphemeral(true). + Build()) } } else { if result.AcceptChannelID == "" { - var buttons []discordgo.MessageComponent + var buttons []discord.ButtonComponent + var components []discord.ContainerComponent if result.CommentCategoryID != "" { - buttons = []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.Button{ - Style: discordgo.PrimaryButton, - Emoji: discordgo.ComponentEmoji{ - Name: "👥", - }, - Label: "Comment", - CustomID: "form:" + form_manage_id + ";comment", - }, - }, - }, + buttons = []discord.ButtonComponent{discord. + NewButton(discord.ButtonStylePrimary, "Comment", "form:"+form_manage_id+";comment", ""). + WithEmoji(discord.ComponentEmoji{Name: "👥"})} + for _, button := range buttons { + components = append(components, discord.NewActionRow(button)) } } - _, err := s.ChannelMessageSendComplex(result.ResultChannelID, &discordgo.MessageSend{ - Embed: &discordgo.MessageEmbed{ - Author: &discordgo.MessageEmbedAuthor{ - Name: i.Member.User.Username, - IconURL: i.Member.AvatarURL("256"), - }, - Title: "\"" + modal.Title + "\"", - Color: hexToDecimal(color["primary"]), - Description: "This is the submitted result", - Fields: fields, - }, - Components: buttons, - }) + _, err := e.Client().Rest().CreateMessage(snowflake.MustParse(result.ResultChannelID), discord.NewMessageCreateBuilder(). + SetEmbeds(discord.NewEmbedBuilder(). + SetAuthorName(*e.User().GlobalName).SetAuthorIcon(*e.User().AvatarURL()).SetTitle("\""+modal.Title+"\"").SetDescription("This is the submitted result"). + SetColor(hexToDecimal(color["primary"])).SetFields(fields...). + Build()). + SetContainerComponents(components...). + Build()) if err != nil { logrus.Error(err) } else { - err = respond(i.Interaction, "Submited!", true) + err = e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Submitted!").SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } } } else { - var buttons []discordgo.MessageComponent + var buttons []discord.ButtonComponent if result.CommentCategoryID != "" { - buttons = []discordgo.MessageComponent{ - discordgo.Button{ - Style: discordgo.PrimaryButton, - Emoji: discordgo.ComponentEmoji{ - Name: "👥", - }, - Label: "Comment", - CustomID: "form:" + form_manage_id + ";comment", - }, - } + buttons = []discord.ButtonComponent{discord. + NewButton(discord.ButtonStylePrimary, "Comment", "form:"+form_manage_id+";comment", ""). + WithEmoji(discord.ComponentEmoji{Name: "👥"})} } - buttons = append(buttons, - discordgo.Button{ - Style: discordgo.DangerButton, - Emoji: discordgo.ComponentEmoji{ - Name: "🛑", - }, - Label: "Decline", - CustomID: "form:" + form_manage_id + ";decline", - }, - discordgo.Button{ - Style: discordgo.SuccessButton, - Emoji: discordgo.ComponentEmoji{ - Name: "🎉", - }, - Label: "Approve", - CustomID: "form:" + form_manage_id + ";approve", - }) - _, err := s.ChannelMessageSendComplex(result.AcceptChannelID, &discordgo.MessageSend{ - Embed: &discordgo.MessageEmbed{ - Author: &discordgo.MessageEmbedAuthor{ - Name: i.Member.User.Username, - IconURL: i.Member.AvatarURL("256"), - }, - Title: "\"" + modal.Title + "\"", - Color: hexToDecimal(color["primary"]), - Description: "**This submission needs approval.**", - Fields: fields, - }, - Components: []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: buttons, - }, - }}, - ) + buttons = append(buttons, discord. + NewButton(discord.ButtonStylePrimary, "Decline", "form:"+form_manage_id+";decline", ""). + WithEmoji(discord.ComponentEmoji{Name: "🛑"}), + discord. + NewButton(discord.ButtonStylePrimary, "Approve", "form:"+form_manage_id+";approve", ""). + WithEmoji(discord.ComponentEmoji{Name: "🎉"})) + var components []discord.ContainerComponent + for _, button := range buttons { + components = append(components, discord.NewActionRow(button)) + } + _, err := e.Client().Rest().CreateMessage(snowflake.MustParse(result.AcceptChannelID), discord.NewMessageCreateBuilder(). + SetEmbeds(discord.NewEmbedBuilder(). + SetAuthorName(*e.User().GlobalName).SetAuthorIcon(*e.User().AvatarURL()).SetTitle("\""+modal.Title+"\"").SetDescription("**This submission needs approval.**"). + SetColor(hexToDecimal(color["primary"])).SetFields(fields...). + Build()). + SetContainerComponents(components...). + Build()) + if err != nil { logrus.Error(err) } else { - err = respond(i.Interaction, "Submited!", true) + err = e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Submitted!").SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } @@ -340,33 +312,27 @@ var cmd_form Command = Command{ } } } else { - err := respond(i.Interaction, "The results would be submited...", true) + err := e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("The results would be submited...").SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } } }, - Autocomplete: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - choices := []*discordgo.ApplicationCommandOptionChoice{ - { + Autocomplete: func(e *events.AutocompleteInteractionCreate) { + err := e.AutocompleteResult([]discord.AutocompleteChoice{ + &discord.AutocompleteChoiceString{ Name: "Support Ticket", Value: "template_ticket", }, - { + &discord.AutocompleteChoiceString{ Name: "Submit URL", Value: "template_url", }, - { + &discord.AutocompleteChoiceString{ Name: "General", Value: "template_general", }, - } - err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ - Type: discordgo.InteractionApplicationCommandAutocompleteResult, - Data: &discordgo.InteractionResponseData{ - Choices: choices, - }, }) if err != nil { logrus.Error(err) @@ -375,41 +341,31 @@ var cmd_form Command = Command{ } var cmd_ticket_form Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "ticket", - DefaultMemberPermissions: int64Ptr(discordgo.PermissionManageChannels), + DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageChannels), Description: "A quick command to create Ticketpanels. (/form for more)", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionString, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionString{ Name: "title", Description: "The title the ticket should have", }, - { - Type: discordgo.ApplicationCommandOptionMentionable, + &discord.ApplicationCommandOptionMentionable{ Name: "moderator", Description: "Who can interact with moderating buttons.", }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { + Interact: func(e *events.ApplicationCommandInteractionCreate) { var title string = "Ticket" var moderator string - if i.ApplicationCommandData().Options != nil { - for _, opt := range i.ApplicationCommandData().Options { - switch opt.Name { - case "title": - title = opt.StringValue() - case "moderator": - moderator = opt.RoleValue(s, i.GuildID).ID - if moderator == "" { - moderator = opt.UserValue(s).ID - } - } - } + data := e.SlashCommandInteractionData() + if data.String("title") != "" { + title = data.String("title") } + moderator = data.Role("moderator").ID.String() if moderator == "" { - moderator = i.Member.User.ID + moderator = data.User("moderator").ID.String() } var exists bool = true var formManageID uuid.UUID = uuid.New() @@ -417,29 +373,16 @@ var cmd_ticket_form Command = Command{ formManageID = uuid.New() exists = getFormManageIdExists(formManageID) } - message, err := s.ChannelMessageSendComplex(i.ChannelID, &discordgo.MessageSend{ - Embed: &discordgo.MessageEmbed{ - Color: hexToDecimal(color["primary"]), - Title: title, - Description: "Press the bottom button to open a form popup.", - }, - Components: []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.Button{ - CustomID: "form:" + formManageID.String(), - Style: discordgo.SuccessButton, - Label: "Submit", - Emoji: discordgo.ComponentEmoji{ - Name: "anim_rocket", - ID: "1215740398706757743", - Animated: true, - }, - }, - }, - }, - }, - }) + messagebuild := discord.NewMessageCreateBuilder().SetEmbeds(discord.NewEmbedBuilder(). + SetTitle(title).SetDescription("Press the bottom button to open a form popup.").SetColor(hexToDecimal(color["primary"])). + Build()).SetContainerComponents(discord.ActionRowComponent{ + discord.NewSuccessButton("Submit", "form:"+formManageID.String()).WithEmoji(discord.ComponentEmoji{ + Name: "anim_rocket", + ID: snowflake.MustParse("1215740398706757743"), + Animated: true, + })}). + Build() + message, err := e.Client().Rest().CreateMessage(e.Channel().ID(), messagebuild) if err != nil { logrus.Error(err) return @@ -448,17 +391,17 @@ var cmd_ticket_form Command = Command{ title = "Ticket" } var category string - c, err := s.GuildChannelCreate(i.GuildID, title+" mod answers", discordgo.ChannelTypeGuildCategory) + c, err := e.Client().Rest().CreateGuildChannel(*e.GuildID(), discord.GuildCategoryChannelCreate{Name: title + " mod answers"}) if err != nil { logrus.Error(err) } - category = c.ID + category = c.ID().String() if title == "Ticket" { title = "" } - addFormButton(i.GuildID, i.ChannelID, message.ID, formManageID.String(), "template_ticket", "", title, "", category, moderator) - err = respond(i.Interaction, "Successfully added ticket panel!\n(`/form` for more options or custom ticket forms.)", true) + addFormButton(e.GuildID().String(), e.Channel().ID().String(), message.ID.String(), formManageID.String(), "template_ticket", "", title, "", category, moderator) + err = e.CreateMessage(discord.NewMessageCreateBuilder().SetContent("Successfully added ticket panel!\n(`/form` for more options or custom ticket forms.)").SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } @@ -466,53 +409,60 @@ var cmd_ticket_form Command = Command{ } // moderator can be userID as well as roleID -func createFormComment(form_manage_id string, author string, moderator snowflake.ID, commentName string, embed discord.Embed, e *events.ComponentInteractionCreate) { +func createFormComment(form_manage_id string, author snowflake.ID, moderator snowflake.ID, commentName string, embed discord.Embed, guildID snowflake.ID, client bot.Client) discord.Channel { var category snowflake.ID - _, err := e.Client().Rest().GetChannel(snowflake.MustParse(getFormResultValues(form_manage_id).CommentCategoryID)) + _, err := client.Rest().GetChannel(snowflake.MustParse(getFormResultValues(form_manage_id).CommentCategoryID)) if err != nil { - c, err := e.Client().Rest().CreateGuildChannel(*e.GuildID(), discord.GuildCategoryChannelCreate{Name: strings.Trim(embed.Title, "\"") + " mod " + commentName + "s"}) + c, err := client.Rest().CreateGuildChannel(guildID, discord.GuildCategoryChannelCreate{Name: strings.Trim(embed.Title, "\"") + " mod " + commentName + "s"}) if err != nil { logrus.Error(err) } category = c.ID() updateFormCommentCategory(form_manage_id, category.String()) } - ch, err := e.Client().Rest().CreateGuildChannel(*e.GuildID(), discord.GuildTextChannelCreate{ + ch, err := client.Rest().CreateGuildChannel(guildID, discord.GuildTextChannelCreate{ ParentID: category, Name: strings.ToLower(embed.Author.Name) + "-" + commentName, }) if err != nil { logrus.Error(err) } - err = bot.ChannelPermissionSet(ch.ID, i.GuildID, discordgo.PermissionOverwriteTypeRole, 0, discordgo.PermissionViewChannel) - _, err = e.Client().Rest().UpdateChannel(ch.ID(), discord.GuildTextChannelUpdate{PermissionOverwrites: &[]discord.PermissionOverwrite{}}) - if err != nil { - logrus.Error(err) + var permissionOverwrites []discord.PermissionOverwrite = []discord.PermissionOverwrite{ + discord.RolePermissionOverwrite{ + RoleID: guildID, + Deny: discord.PermissionViewChannel, + }} + + if isIDRole(client, guildID, moderator) { + permissionOverwrites = append(permissionOverwrites, discord.RolePermissionOverwrite{ + RoleID: moderator, + Allow: discord.PermissionViewChannel, + }) + } else { + permissionOverwrites = append(permissionOverwrites, discord.MemberPermissionOverwrite{ + UserID: moderator, + Allow: discord.PermissionViewChannel, + }) } - modType := discordgo.PermissionOverwriteTypeMember - if isIDRole(i.GuildID, moderator) { - modType = discordgo.PermissionOverwriteTypeRole - } - err = bot.ChannelPermissionSet(ch.ID, moderator, modType, discordgo.PermissionViewChannel, 0) - if err != nil { - logrus.Error(err) - } - err = bot.ChannelPermissionSet(ch.ID, author, discordgo.PermissionOverwriteTypeMember, discordgo.PermissionViewChannel, 0) - if err != nil { - logrus.Error(err) - } - modTypeChar := "&" - if modType == discordgo.PermissionOverwriteTypeMember { - modTypeChar = "" - } - _, err = bot.ChannelMessageSendComplex(ch.ID, &discordgo.MessageSend{ - Content: "<@" + modTypeChar + moderator + "> <@" + author + ">", - Embed: embed, + permissionOverwrites = append(permissionOverwrites, discord.RolePermissionOverwrite{ + RoleID: author, + Allow: discord.PermissionViewChannel, }) + _, err = client.Rest().UpdateChannel(ch.ID(), discord.GuildTextChannelUpdate{PermissionOverwrites: &permissionOverwrites}) if err != nil { logrus.Error(err) } - respond(i.Interaction, "Created channel <#"+ch.ID+">", true) + modTypeChar := "" + if isIDRole(client, guildID, moderator) { + modTypeChar = "&" + } + _, err = client.Rest().CreateMessage(ch.ID(), discord.NewMessageCreateBuilder(). + SetContent("<@"+modTypeChar+moderator.String()+"> <@"+author.String()+">").SetEmbeds(embed). + Build()) + if err != nil { + logrus.Error(err) + } + return ch } func getFormButtonIDs() []string { diff --git a/cmd_info.go b/cmd_info.go index e2e44a6..d0b455e 100644 --- a/cmd_info.go +++ b/cmd_info.go @@ -92,14 +92,15 @@ var cmd_userinfo Command = Command{ embedBuilder.AddField("Accent color", strconv.Itoa(*user.AccentColor), true) } if user.AvatarDecorationURL() != nil { - decoration := strings.TrimSuffix(*user.AvatarDecorationURL(), ".gif") - value := fmt.Sprintf("[PNG (animated)](%s)\n[PNG](%s)", decoration, decoration+"?passthrough=false") + value := fmt.Sprintf("[PNG (animated)](%s)\n[PNG](%s)", *user.AvatarDecorationURL(), *user.AvatarDecorationURL()+"?passthrough=false") embedBuilder.AddField("Avatar decoration", value, true) } creation := "<:discord_member:1224717530078253166> " + discord.TimestampStyleLongDateTime.FormatTime(user.CreatedAt()) + "-" + discord.TimestampStyleRelative.FormatTime(user.CreatedAt()) embedBuilder.AddField("Created at", creation, false) + if user.BannerURL() != nil { - embedBuilder.SetImage(*user.BannerURL()) + value := fmt.Sprint(*user.BannerURL()) + embedBuilder.SetImage(value) } embedBuilder.SetTitle("User info") embedBuilder.SetDescription(user.Mention()) @@ -134,22 +135,22 @@ func fetchFlagStrings(user discord.User) string { userHasFlagsString += flagName + ", " } } - if noNullString(user.AvatarDecorationData.Asset) == "a_5e1210779d99ece1c0b4f438a5bc6e72" { + if user.AvatarDecorationData != nil && user.AvatarDecorationData.Asset == "a_5e1210779d99ece1c0b4f438a5bc6e72" { userHasFlagsString += "<:Limited_Lootbox_Clown:1224714172705804300>[`Lootbox Clown`](https://discord.com/settings/Lootboxes)" } /* if user.PremiumType > 0 { userHasFlagsString += "<:Nitro:1224708672492666943>[`Nitro`](https://discord.com/settings/premium), " - } - if user.Bot { - appuser := bot.State.Application - if appuser.Flags&1<<23 != 0 { - userHasFlagsString += "<:Supports_Commands:1224848976201646100>[`Supports Commands`](https://discord.com/blog/welcome-to-the-new-era-of-discord-apps?ref=badge)" - } - if appuser.Flags&1<<6 != 0 { - userHasFlagsString += "<:Uses_Automod:1224862880982106202>`Uses Automod`" - } - } + } + if user.Bot { + appuser := bot.State.Application + if appuser.Flags&1<<23 != 0 { + userHasFlagsString += "<:Supports_Commands:1224848976201646100>[`Supports Commands`](https://discord.com/blog/welcome-to-the-new-era-of-discord-apps?ref=badge)" + } + if appuser.Flags&1<<6 != 0 { + userHasFlagsString += "<:Uses_Automod:1224862880982106202>`Uses Automod`" + } + } */ returnString := strings.TrimSuffix(userHasFlagsString, ", ") return returnString diff --git a/go.mod b/go.mod index db9aef6..1c2fd31 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/vaporvee/acecore go 1.21.6 require ( - github.com/disgoorg/disgo v0.18.0 + github.com/disgoorg/disgo v0.18.1-0.20240408224120-2676e29d6e86 github.com/disgoorg/json v1.1.0 github.com/disgoorg/snowflake/v2 v2.0.1 github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum index 33ab55a..e32c6d1 100644 --- a/go.sum +++ b/go.sum @@ -5,6 +5,8 @@ github.com/disgoorg/disgo v0.17.2 h1:RxiLq8guMtk+9tArFwve02iya2APQ9yZVtV30ySKNtw github.com/disgoorg/disgo v0.17.2/go.mod h1:8r3h9fXSz7BbACxLPsPbtB6LX8gaQFUETgPKV/0gAKQ= github.com/disgoorg/disgo v0.18.0 h1:EviKy/OiGofYW2X4kLjgxAUYrqjmBEMpVp/MMXHP1pY= github.com/disgoorg/disgo v0.18.0/go.mod h1:gkl6DBdbKUvmOOJayWPSvS52KPN/8uJGJ2f13gCEB1o= +github.com/disgoorg/disgo v0.18.1-0.20240408224120-2676e29d6e86 h1:hSRIjnKWL07TYxvZRxdSBpS78gJNf+JkAuzXY3O1Kos= +github.com/disgoorg/disgo v0.18.1-0.20240408224120-2676e29d6e86/go.mod h1:gkl6DBdbKUvmOOJayWPSvS52KPN/8uJGJ2f13gCEB1o= github.com/disgoorg/json v1.1.0 h1:7xigHvomlVA9PQw9bMGO02PHGJJPqvX5AnwlYg/Tnys= github.com/disgoorg/json v1.1.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA= github.com/disgoorg/snowflake/v2 v2.0.1 h1:CuUxGLwggUxEswZOmZ+mZ5i0xSumQdXW9tXW7uGqe+0= diff --git a/handlers.go b/handlers.go index 0eef560..9888652 100644 --- a/handlers.go +++ b/handlers.go @@ -26,7 +26,7 @@ type Command struct { AllowDM bool } -var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag, cmd_sticky, context_sticky, cmd_ping, cmd_userinfo, cmd_form, cmd_ask, cmd_cat, cmd_dadjoke /*, cmd_ticket_form, cmd_autojoinroles, cmd_autopublish*/} +var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag, cmd_sticky, context_sticky, cmd_ping, cmd_userinfo, cmd_form, cmd_ask, cmd_cat, cmd_dadjoke, cmd_ticket_form /*, cmd_autojoinroles, cmd_autopublish*/} func ready(e *events.Ready) { logrus.Info("Starting up...") diff --git a/main.go b/main.go index 4f2430f..1c00241 100644 --- a/main.go +++ b/main.go @@ -49,8 +49,8 @@ func main() { bot.WithEventListenerFunc(componentInteractionCreate), bot.WithEventListenerFunc(modalSubmitInteractionCreate), bot.WithEventListenerFunc(messageCreate), + bot.WithEventListenerFunc(messageDelete), /* - bot.WithEventListenerFunc(messageDelete), bot.WithEventListenerFunc(guildMemberJoin), */ ) diff --git a/tool.go b/tool.go index 2024bb8..a664af9 100644 --- a/tool.go +++ b/tool.go @@ -51,7 +51,7 @@ func noNullString(in interface{}) string { return s } -func jsonStringShowModal(userID string, manageID string, formID string, overwrite ...string) discord.InteractionResponse { +func jsonStringBuildModal(userID string, manageID string, formID string, overwrite ...string) discord.ModalCreate { var modal ModalJson = getModalByFormID(formID) var components []discord.ContainerComponent for index, component := range modal.Form { @@ -76,13 +76,10 @@ func jsonStringShowModal(userID string, manageID string, formID string, overwrit modal.Title = overwrite[0] } - return discord.InteractionResponse{ - Type: discord.InteractionResponseTypeModal, - Data: &discord.ModalCreate{ - CustomID: manageID + ":" + userID, - Title: modal.Title, - Components: components, - }, + return discord.ModalCreate{ + CustomID: "form:" + manageID + ":" + userID, + Title: modal.Title, + Components: components, } } @@ -94,6 +91,9 @@ var formTemplates embed.FS func getModalByFormID(formID string) ModalJson { var modal ModalJson + if formID == "" { + return modal + } entries, err := formTemplates.ReadDir("form_templates") if err != nil { logrus.Error(err) From 648839c78b049a16474ae847ff593d3c3588903e Mon Sep 17 00:00:00 2001 From: vaporvee Date: Wed, 10 Apr 2024 15:54:17 +0200 Subject: [PATCH 10/12] added forms fully with disgo --- cmd_form.go | 39 +++++++++++++++------------------------ cmd_info.go | 15 ++++++++------- 2 files changed, 23 insertions(+), 31 deletions(-) diff --git a/cmd_form.go b/cmd_form.go index 8aa150c..d66637c 100644 --- a/cmd_form.go +++ b/cmd_form.go @@ -111,8 +111,8 @@ var cmd_form Command = Command{ if overwriteTitle != "" { title = overwriteTitle } - if data.Channel("accept_channel").ID.String() != "0" { - acceptChannelID = data.Channel("accept_channel").ID.String() + if data.Channel("approve_channel").ID.String() != "0" { + acceptChannelID = data.Channel("approve_channel").ID.String() } modsCanAnswer = data.Bool("mods_can_answer") @@ -250,23 +250,16 @@ var cmd_form Command = Command{ Build()) } } else { + logrus.Debug(result.AcceptChannelID) if result.AcceptChannelID == "" { - var buttons []discord.ButtonComponent - var components []discord.ContainerComponent - if result.CommentCategoryID != "" { - buttons = []discord.ButtonComponent{discord. - NewButton(discord.ButtonStylePrimary, "Comment", "form:"+form_manage_id+";comment", ""). - WithEmoji(discord.ComponentEmoji{Name: "👥"})} - for _, button := range buttons { - components = append(components, discord.NewActionRow(button)) - } - } _, err := e.Client().Rest().CreateMessage(snowflake.MustParse(result.ResultChannelID), discord.NewMessageCreateBuilder(). SetEmbeds(discord.NewEmbedBuilder(). SetAuthorName(*e.User().GlobalName).SetAuthorIcon(*e.User().AvatarURL()).SetTitle("\""+modal.Title+"\"").SetDescription("This is the submitted result"). SetColor(hexToDecimal(color["primary"])).SetFields(fields...). Build()). - SetContainerComponents(components...). + SetContainerComponents(discord.NewActionRow(discord. + NewButton(discord.ButtonStylePrimary, "Comment", "form:"+form_manage_id+";comment", ""). + WithEmoji(discord.ComponentEmoji{Name: "👥"}))). Build()) if err != nil { logrus.Error(err) @@ -277,28 +270,25 @@ var cmd_form Command = Command{ } } } else { - var buttons []discord.ButtonComponent + logrus.Debug("HEERE") + var buttons []discord.InteractiveComponent if result.CommentCategoryID != "" { - buttons = []discord.ButtonComponent{discord. + buttons = []discord.InteractiveComponent{discord. NewButton(discord.ButtonStylePrimary, "Comment", "form:"+form_manage_id+";comment", ""). WithEmoji(discord.ComponentEmoji{Name: "👥"})} } buttons = append(buttons, discord. - NewButton(discord.ButtonStylePrimary, "Decline", "form:"+form_manage_id+";decline", ""). + NewButton(discord.ButtonStyleDanger, "Decline", "form:"+form_manage_id+";decline", ""). WithEmoji(discord.ComponentEmoji{Name: "🛑"}), discord. - NewButton(discord.ButtonStylePrimary, "Approve", "form:"+form_manage_id+";approve", ""). + NewButton(discord.ButtonStyleSuccess, "Approve", "form:"+form_manage_id+";approve", ""). WithEmoji(discord.ComponentEmoji{Name: "🎉"})) - var components []discord.ContainerComponent - for _, button := range buttons { - components = append(components, discord.NewActionRow(button)) - } _, err := e.Client().Rest().CreateMessage(snowflake.MustParse(result.AcceptChannelID), discord.NewMessageCreateBuilder(). SetEmbeds(discord.NewEmbedBuilder(). SetAuthorName(*e.User().GlobalName).SetAuthorIcon(*e.User().AvatarURL()).SetTitle("\""+modal.Title+"\"").SetDescription("**This submission needs approval.**"). SetColor(hexToDecimal(color["primary"])).SetFields(fields...). Build()). - SetContainerComponents(components...). + SetContainerComponents(discord.NewActionRow(buttons...)). Build()) if err != nil { @@ -410,8 +400,8 @@ var cmd_ticket_form Command = Command{ // moderator can be userID as well as roleID func createFormComment(form_manage_id string, author snowflake.ID, moderator snowflake.ID, commentName string, embed discord.Embed, guildID snowflake.ID, client bot.Client) discord.Channel { - var category snowflake.ID - _, err := client.Rest().GetChannel(snowflake.MustParse(getFormResultValues(form_manage_id).CommentCategoryID)) + var category snowflake.ID = snowflake.MustParse(getFormResultValues(form_manage_id).CommentCategoryID) + _, err := client.Rest().GetChannel(category) if err != nil { c, err := client.Rest().CreateGuildChannel(guildID, discord.GuildCategoryChannelCreate{Name: strings.Trim(embed.Title, "\"") + " mod " + commentName + "s"}) if err != nil { @@ -456,6 +446,7 @@ func createFormComment(form_manage_id string, author snowflake.ID, moderator sno if isIDRole(client, guildID, moderator) { modTypeChar = "&" } + embed.Description = "This was submitted" _, err = client.Rest().CreateMessage(ch.ID(), discord.NewMessageCreateBuilder(). SetContent("<@"+modTypeChar+moderator.String()+"> <@"+author.String()+">").SetEmbeds(embed). Build()) diff --git a/cmd_info.go b/cmd_info.go index d0b455e..0c9b2d5 100644 --- a/cmd_info.go +++ b/cmd_info.go @@ -63,8 +63,11 @@ var cmd_userinfo Command = Command{ Interact: func(e *events.ApplicationCommandInteractionCreate) { switch *e.SlashCommandInteractionData().SubCommandName { case "user": - var user discord.User = e.SlashCommandInteractionData().User("user") - var userHasFlags string = fetchFlagStrings(user) + user, err := e.Client().Rest().GetUser(e.SlashCommandInteractionData().User("user").ID) + if err != nil { + logrus.Error(err) + } + var userHasFlags string = fetchFlagStrings(*user) var userType string = "User" if user.Bot { userType = "Unverified Bot" @@ -75,7 +78,7 @@ var cmd_userinfo Command = Command{ userType = "System" } embedBuilder := discord.NewEmbedBuilder() - embedBuilder.SetThumbnail(checkDefaultPb(user)) + embedBuilder.SetThumbnail(checkDefaultPb(*user) + "?size=4096") embedBuilder.AddField("ID", user.ID.String(), false) embedBuilder.AddField("Type", userType, true) if user.GlobalName != nil { @@ -99,14 +102,12 @@ var cmd_userinfo Command = Command{ embedBuilder.AddField("Created at", creation, false) if user.BannerURL() != nil { - value := fmt.Sprint(*user.BannerURL()) - embedBuilder.SetImage(value) + embedBuilder.SetImage(*user.BannerURL() + "?size=4096") } embedBuilder.SetTitle("User info") embedBuilder.SetDescription(user.Mention()) embedBuilder.SetColor(hexToDecimal(color["primary"])) - embedBuilder.SetFooterText("Currently a bit broken because of Discord's constant user API changes") - err := e.CreateMessage(discord.NewMessageCreateBuilder(). + err = e.CreateMessage(discord.NewMessageCreateBuilder(). SetEmbeds(embedBuilder.Build()). Build()) if err != nil { From 5ecbcf93f29e0246f9a32e44226916b323822ac5 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Wed, 10 Apr 2024 17:01:14 +0200 Subject: [PATCH 11/12] finished porting to disgo --- cmd_autojoinroles.go | 54 +++++++++++++++++++++++--------------------- cmd_autopublish.go | 27 +++++++++++++--------- handlers.go | 28 ++++++++++++----------- main.go | 5 ++-- 4 files changed, 61 insertions(+), 53 deletions(-) diff --git a/cmd_autojoinroles.go b/cmd_autojoinroles.go index 118074c..1a69a6d 100644 --- a/cmd_autojoinroles.go +++ b/cmd_autojoinroles.go @@ -1,65 +1,67 @@ package main -/* +import ( + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" + "github.com/sirupsen/logrus" +) + var cmd_autojoinroles Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "autojoinroles", Description: "Give users a role when they join", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionSubCommand{ Name: "bot", Description: "Give bots a role when they join (Leave empty to remove current)", - Options: []*discordgo.ApplicationCommandOption{ - { - - Type: discordgo.ApplicationCommandOptionRole, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionRole{ Name: "role", Description: "The role bots should get when they join the server", }, }, }, - { - Type: discordgo.ApplicationCommandOptionSubCommand, + &discord.ApplicationCommandOptionSubCommand{ Name: "user", Description: "Give users a role when they join (Leave empty to remove current)", - Options: []*discordgo.ApplicationCommandOption{ - { - Type: discordgo.ApplicationCommandOptionRole, + Options: []discord.ApplicationCommandOption{ + &discord.ApplicationCommandOptionRole{ Name: "role", Description: "The role users should get when they join the server", }}, }, }, }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { + Interact: func(e *events.ApplicationCommandInteractionCreate) { var role string - option := i.ApplicationCommandData().Options[0].Name + option := *e.SlashCommandInteractionData().SubCommandName var content string - if len(i.ApplicationCommandData().Options[0].Options) == 1 { - var givenRole *discordgo.Role = i.ApplicationCommandData().Options[0].Options[0].RoleValue(s, i.GuildID) - role = givenRole.ID - botrole, err := getHighestRole(i.GuildID) + if len(e.SlashCommandInteractionData().Options) == 1 { + var givenRole discord.Role = e.SlashCommandInteractionData().Role("role") + role = givenRole.ID.String() + botrole, err := getHighestRole(e.GuildID().String(), e.Client()) if err != nil { logrus.Error(err) } if givenRole.Position >= botrole.Position { - content = "<@&" + role + "> is not below the Bot's current highest role(<@&" + botrole.ID + ">). That makes it unable to manage it." + content = "<@&" + role + "> is not below the Bot's current highest role(<@&" + botrole.ID.String() + ">). That makes it unable to manage it." } else { - if setAutoJoinRole(i.GuildID, option, role) { + if setAutoJoinRole(e.GuildID().String(), option, role) { content = "Updated auto join role for " + option + "s as <@&" + role + ">" } else { content = "Setup auto join role for " + option + "s as <@&" + role + ">" } } - } else if setAutoJoinRole(i.GuildID, option, role) { + } else if setAutoJoinRole(e.GuildID().String(), option, role) { content = "Deleted auto join role for " + option + "s" } - err := respond(i.Interaction, content, true) + if content == "" { + content = "No auto join role set for " + option + "s to delete." + } + err := e.CreateMessage(discord.NewMessageCreateBuilder().SetContent(content).SetEphemeral(true).Build()) if err != nil { logrus.Error(err) } - purgeUnusedAutoJoinRoles(i.GuildID) + purgeUnusedAutoJoinRoles(e.GuildID().String()) }, } -*/ diff --git a/cmd_autopublish.go b/cmd_autopublish.go index a69b0b6..43ae0db 100644 --- a/cmd_autopublish.go +++ b/cmd_autopublish.go @@ -1,36 +1,41 @@ package main -/* import ( - "github.com/bwmarrin/discordgo" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" "github.com/sirupsen/logrus" ) var cmd_autopublish Command = Command{ - Definition: discordgo.ApplicationCommand{ + Definition: discord.SlashCommandCreate{ Name: "autopublish", Description: "Toggle automatically publishing every post in a announcement channel", }, - Interact: func(s *discordgo.Session, i *discordgo.InteractionCreate) { - channel, _ := s.State.Channel(i.ChannelID) - if channel.Type == discordgo.ChannelTypeGuildNews { - if toggleAutoPublish(i.GuildID, i.ChannelID) { - err := respond(i.Interaction, "Autopublishing is now disabled on <#"+i.ChannelID+">", true) + Interact: func(e *events.ApplicationCommandInteractionCreate) { + channel := e.Channel() + if channel.Type() == discord.ChannelTypeGuildNews { + if toggleAutoPublish(e.GuildID().String(), e.Channel().ID().String()) { + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Autopublishing is now disabled on " + discord.ChannelMention(e.Channel().ID())).SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } else { - err := respond(i.Interaction, "Autopublishing is now enabled on <#"+i.ChannelID+">", true) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("Autopublishing is now enabled on " + discord.ChannelMention(e.Channel().ID())).SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } } else { - err := respond(i.Interaction, "This is not an announcement channel!", true) + err := e.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent("This is not an announcement channel!").SetEphemeral(true). + Build()) if err != nil { logrus.Error(err) } } }, } -*/ diff --git a/handlers.go b/handlers.go index 9888652..ed98eaf 100644 --- a/handlers.go +++ b/handlers.go @@ -26,7 +26,7 @@ type Command struct { AllowDM bool } -var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag, cmd_sticky, context_sticky, cmd_ping, cmd_userinfo, cmd_form, cmd_ask, cmd_cat, cmd_dadjoke, cmd_ticket_form /*, cmd_autojoinroles, cmd_autopublish*/} +var commands []Command = []Command{cmd_tag, cmd_tag_short, context_tag, cmd_sticky, context_sticky, cmd_ping, cmd_userinfo, cmd_form, cmd_ask, cmd_cat, cmd_dadjoke, cmd_ticket_form, cmd_autopublish, cmd_autojoinroles} func ready(e *events.Ready) { logrus.Info("Starting up...") @@ -196,18 +196,19 @@ func messageCreate(e *events.MessageCreate) { updateStickyMessageID(e.Message.GuildID.String(), e.Message.ChannelID.String(), stickyMessage.ID.String()) } } - /* - channel, _ := e.Channel() - - if channel.Type() == discord.ChannelTypeGuildNews { - if isAutopublishEnabled(e.GuildID.String(), e.ChannelID.String()) { - _, err := e.Client().Rest().CrosspostMessage(e.ChannelID, e.MessageID) - if err != nil { - logrus.Error(err) - } - } - } - */ + channel, err := e.Client().Rest().GetChannel(e.Message.ChannelID) + if err != nil { + logrus.Error(err) + } + if channel != nil && channel.Type() == discord.ChannelTypeGuildNews { + logrus.Debug("HERE") + if isAutopublishEnabled(e.GuildID.String(), e.ChannelID.String()) { + _, err := e.Client().Rest().CrosspostMessage(e.ChannelID, e.MessageID) + if err != nil { + logrus.Error(err) + } + } + } } func messageDelete(e *events.MessageDelete) { //TODO: also clear on bot start when message doesn't exist @@ -215,6 +216,7 @@ func messageDelete(e *events.MessageDelete) { //TODO: also clear on bot start wh } func guildMemberJoin(e *events.GuildMemberJoin) { + logrus.Debug("TESSST") role := getAutoJoinRole(e.GuildID.String(), e.Member.User.Bot) if role != "" { err := e.Client().Rest().AddMemberRole(e.GuildID, e.Member.User.ID, snowflake.MustParse(role)) diff --git a/main.go b/main.go index 1c00241..d7f314b 100644 --- a/main.go +++ b/main.go @@ -40,6 +40,7 @@ func main() { gateway.WithIntents( gateway.IntentGuilds, gateway.IntentGuildMessages, + gateway.IntentGuildMembers, gateway.IntentDirectMessages, ), ), @@ -50,9 +51,7 @@ func main() { bot.WithEventListenerFunc(modalSubmitInteractionCreate), bot.WithEventListenerFunc(messageCreate), bot.WithEventListenerFunc(messageDelete), - /* - bot.WithEventListenerFunc(guildMemberJoin), - */ + bot.WithEventListenerFunc(guildMemberJoin), ) if err != nil { logrus.Fatal("error creating Discord session,", err) From 63bb68d5828e00a61fcecc6d25b4e5e7b80aef76 Mon Sep 17 00:00:00 2001 From: vaporvee Date: Wed, 10 Apr 2024 17:02:39 +0200 Subject: [PATCH 12/12] removed unused funtions --- tool.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/tool.go b/tool.go index a664af9..242061b 100644 --- a/tool.go +++ b/tool.go @@ -140,8 +140,6 @@ func getHighestRole(guildID string, c bot.Client) (*discord.Role, error) { return highestRole, nil } -func ptr(s string) *string { return &s } - func hexToDecimal(hexColor string) int { hexColor = strings.TrimPrefix(hexColor, "#") decimal, err := strconv.ParseInt(hexColor, 16, 64) @@ -151,11 +149,6 @@ func hexToDecimal(hexColor string) int { return int(decimal) } -func decimalToHex(decimal int) string { - hexString := strconv.FormatInt(int64(decimal), 16) - return hexString -} - func simpleGetFromAPI(key string, url string) interface{} { client := &http.Client{} req, err := http.NewRequest("GET", url, nil)