github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/examples/slash_commands/main.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"flag"
     6  	"fmt"
     7  	"log"
     8  	"os"
     9  	"os/signal"
    10  	"strings"
    11  	"time"
    12  
    13  	"github.com/bwmarrin/discordgo"
    14  )
    15  
    16  // Bot parameters
    17  var (
    18  	GuildID        = flag.String("guild", "", "Test guild ID. If not passed - bot registers commands globally")
    19  	BotToken       = flag.String("token", "", "Bot access token")
    20  	RemoveCommands = flag.Bool("rmcmd", true, "Remove all commands after shutdowning or not")
    21  )
    22  
    23  var s *discordgo.Session
    24  
    25  func init() { flag.Parse() }
    26  
    27  func init() {
    28  	var err error
    29  	s, err = discordgo.New("Bot " + *BotToken)
    30  	if err != nil {
    31  		log.Fatalf("Invalid bot parameters: %v", err)
    32  	}
    33  }
    34  
    35  var (
    36  	integerOptionMinValue          = 1.0
    37  	dmPermission                   = false
    38  	defaultMemberPermissions int64 = discordgo.PermissionManageGuild
    39  
    40  	commands = []*discordgo.ApplicationCommand{
    41  		{
    42  			Name: "basic-command",
    43  			// All commands and options must have a description
    44  			// Commands/options without description will fail the registration
    45  			// of the command.
    46  			Description: "Basic command",
    47  		},
    48  		{
    49  			Name:                     "permission-overview",
    50  			Description:              "Command for demonstration of default command permissions",
    51  			DefaultMemberPermissions: &defaultMemberPermissions,
    52  			DMPermission:             &dmPermission,
    53  		},
    54  		{
    55  			Name:        "basic-command-with-files",
    56  			Description: "Basic command with files",
    57  		},
    58  		{
    59  			Name:        "localized-command",
    60  			Description: "Localized command. Description and name may vary depending on the Language setting",
    61  			NameLocalizations: &map[discordgo.Locale]string{
    62  				discordgo.ChineseCN: "本地化的命令",
    63  			},
    64  			DescriptionLocalizations: &map[discordgo.Locale]string{
    65  				discordgo.ChineseCN: "这是一个本地化的命令",
    66  			},
    67  			Options: []*discordgo.ApplicationCommandOption{
    68  				{
    69  					Name:        "localized-option",
    70  					Description: "Localized option. Description and name may vary depending on the Language setting",
    71  					NameLocalizations: map[discordgo.Locale]string{
    72  						discordgo.ChineseCN: "一个本地化的选项",
    73  					},
    74  					DescriptionLocalizations: map[discordgo.Locale]string{
    75  						discordgo.ChineseCN: "这是一个本地化的选项",
    76  					},
    77  					Type: discordgo.ApplicationCommandOptionInteger,
    78  					Choices: []*discordgo.ApplicationCommandOptionChoice{
    79  						{
    80  							Name: "First",
    81  							NameLocalizations: map[discordgo.Locale]string{
    82  								discordgo.ChineseCN: "一的",
    83  							},
    84  							Value: 1,
    85  						},
    86  						{
    87  							Name: "Second",
    88  							NameLocalizations: map[discordgo.Locale]string{
    89  								discordgo.ChineseCN: "二的",
    90  							},
    91  							Value: 2,
    92  						},
    93  					},
    94  				},
    95  			},
    96  		},
    97  		{
    98  			Name:        "options",
    99  			Description: "Command for demonstrating options",
   100  			Options: []*discordgo.ApplicationCommandOption{
   101  
   102  				{
   103  					Type:        discordgo.ApplicationCommandOptionString,
   104  					Name:        "string-option",
   105  					Description: "String option",
   106  					Required:    true,
   107  				},
   108  				{
   109  					Type:        discordgo.ApplicationCommandOptionInteger,
   110  					Name:        "integer-option",
   111  					Description: "Integer option",
   112  					MinValue:    &integerOptionMinValue,
   113  					MaxValue:    10,
   114  					Required:    true,
   115  				},
   116  				{
   117  					Type:        discordgo.ApplicationCommandOptionNumber,
   118  					Name:        "number-option",
   119  					Description: "Float option",
   120  					MaxValue:    10.1,
   121  					Required:    true,
   122  				},
   123  				{
   124  					Type:        discordgo.ApplicationCommandOptionBoolean,
   125  					Name:        "bool-option",
   126  					Description: "Boolean option",
   127  					Required:    true,
   128  				},
   129  
   130  				// Required options must be listed first since optional parameters
   131  				// always come after when they're used.
   132  				// The same concept applies to Discord's Slash-commands API
   133  
   134  				{
   135  					Type:        discordgo.ApplicationCommandOptionChannel,
   136  					Name:        "channel-option",
   137  					Description: "Channel option",
   138  					// Channel type mask
   139  					ChannelTypes: []discordgo.ChannelType{
   140  						discordgo.ChannelTypeGuildText,
   141  						discordgo.ChannelTypeGuildVoice,
   142  					},
   143  					Required: false,
   144  				},
   145  				{
   146  					Type:        discordgo.ApplicationCommandOptionUser,
   147  					Name:        "user-option",
   148  					Description: "User option",
   149  					Required:    false,
   150  				},
   151  				{
   152  					Type:        discordgo.ApplicationCommandOptionRole,
   153  					Name:        "role-option",
   154  					Description: "Role option",
   155  					Required:    false,
   156  				},
   157  			},
   158  		},
   159  		{
   160  			Name:        "subcommands",
   161  			Description: "Subcommands and command groups example",
   162  			Options: []*discordgo.ApplicationCommandOption{
   163  				// When a command has subcommands/subcommand groups
   164  				// It must not have top-level options, they aren't accesible in the UI
   165  				// in this case (at least not yet), so if a command has
   166  				// subcommands/subcommand any groups registering top-level options
   167  				// will cause the registration of the command to fail
   168  
   169  				{
   170  					Name:        "subcommand-group",
   171  					Description: "Subcommands group",
   172  					Options: []*discordgo.ApplicationCommandOption{
   173  						// Also, subcommand groups aren't capable of
   174  						// containing options, by the name of them, you can see
   175  						// they can only contain subcommands
   176  						{
   177  							Name:        "nested-subcommand",
   178  							Description: "Nested subcommand",
   179  							Type:        discordgo.ApplicationCommandOptionSubCommand,
   180  						},
   181  					},
   182  					Type: discordgo.ApplicationCommandOptionSubCommandGroup,
   183  				},
   184  				// Also, you can create both subcommand groups and subcommands
   185  				// in the command at the same time. But, there's some limits to
   186  				// nesting, count of subcommands (top level and nested) and options.
   187  				// Read the intro of slash-commands docs on Discord dev portal
   188  				// to get more information
   189  				{
   190  					Name:        "subcommand",
   191  					Description: "Top-level subcommand",
   192  					Type:        discordgo.ApplicationCommandOptionSubCommand,
   193  				},
   194  			},
   195  		},
   196  		{
   197  			Name:        "responses",
   198  			Description: "Interaction responses testing initiative",
   199  			Options: []*discordgo.ApplicationCommandOption{
   200  				{
   201  					Name:        "resp-type",
   202  					Description: "Response type",
   203  					Type:        discordgo.ApplicationCommandOptionInteger,
   204  					Choices: []*discordgo.ApplicationCommandOptionChoice{
   205  						{
   206  							Name:  "Channel message with source",
   207  							Value: 4,
   208  						},
   209  						{
   210  							Name:  "Deferred response With Source",
   211  							Value: 5,
   212  						},
   213  					},
   214  					Required: true,
   215  				},
   216  			},
   217  		},
   218  		{
   219  			Name:        "followups",
   220  			Description: "Followup messages",
   221  		},
   222  	}
   223  
   224  	commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
   225  		"basic-command": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   226  			s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   227  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   228  				Data: &discordgo.InteractionResponseData{
   229  					Content: "Hey there! Congratulations, you just executed your first slash command",
   230  				},
   231  			})
   232  		},
   233  		"basic-command-with-files": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   234  			s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   235  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   236  				Data: &discordgo.InteractionResponseData{
   237  					Content: "Hey there! Congratulations, you just executed your first slash command with a file in the response",
   238  					Files: []*discordgo.File{
   239  						{
   240  							ContentType: "text/plain",
   241  							Name:        "test.txt",
   242  							Reader:      strings.NewReader("Hello Discord!!"),
   243  						},
   244  					},
   245  				},
   246  			})
   247  		},
   248  		"localized-command": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   249  			responses := map[discordgo.Locale]string{
   250  				discordgo.ChineseCN: "你好! 这是一个本地化的命令",
   251  			}
   252  			response := "Hi! This is a localized message"
   253  			if r, ok := responses[i.Locale]; ok {
   254  				response = r
   255  			}
   256  			err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   257  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   258  				Data: &discordgo.InteractionResponseData{
   259  					Content: response,
   260  				},
   261  			})
   262  			if err != nil {
   263  				panic(err)
   264  			}
   265  		},
   266  		"options": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   267  			// Access options in the order provided by the user.
   268  			options := i.ApplicationCommandData().Options
   269  
   270  			// Or convert the slice into a map
   271  			optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
   272  			for _, opt := range options {
   273  				optionMap[opt.Name] = opt
   274  			}
   275  
   276  			// This example stores the provided arguments in an []interface{}
   277  			// which will be used to format the bot's response
   278  			margs := make([]interface{}, 0, len(options))
   279  			msgformat := "You learned how to use command options! " +
   280  				"Take a look at the value(s) you entered:\n"
   281  
   282  			// Get the value from the option map.
   283  			// When the option exists, ok = true
   284  			if option, ok := optionMap["string-option"]; ok {
   285  				// Option values must be type asserted from interface{}.
   286  				// Discordgo provides utility functions to make this simple.
   287  				margs = append(margs, option.StringValue())
   288  				msgformat += "> string-option: %s\n"
   289  			}
   290  
   291  			if opt, ok := optionMap["integer-option"]; ok {
   292  				margs = append(margs, opt.IntValue())
   293  				msgformat += "> integer-option: %d\n"
   294  			}
   295  
   296  			if opt, ok := optionMap["number-option"]; ok {
   297  				margs = append(margs, opt.FloatValue())
   298  				msgformat += "> number-option: %f\n"
   299  			}
   300  
   301  			if opt, ok := optionMap["bool-option"]; ok {
   302  				margs = append(margs, opt.BoolValue())
   303  				msgformat += "> bool-option: %v\n"
   304  			}
   305  
   306  			if opt, ok := optionMap["channel-option"]; ok {
   307  				margs = append(margs, opt.ChannelValue(nil).ID)
   308  				msgformat += "> channel-option: <#%s>\n"
   309  			}
   310  
   311  			if opt, ok := optionMap["user-option"]; ok {
   312  				margs = append(margs, opt.UserValue(nil).ID)
   313  				msgformat += "> user-option: <@%s>\n"
   314  			}
   315  
   316  			if opt, ok := optionMap["role-option"]; ok {
   317  				margs = append(margs, opt.RoleValue(nil, "").ID)
   318  				msgformat += "> role-option: <@&%s>\n"
   319  			}
   320  
   321  			s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   322  				// Ignore type for now, they will be discussed in "responses"
   323  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   324  				Data: &discordgo.InteractionResponseData{
   325  					Content: fmt.Sprintf(
   326  						msgformat,
   327  						margs...,
   328  					),
   329  				},
   330  			})
   331  		},
   332  		"permission-overview": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   333  			perms, err := s.ApplicationCommandPermissions(s.State.User.ID, i.GuildID, i.ApplicationCommandData().ID)
   334  
   335  			var restError *discordgo.RESTError
   336  			if errors.As(err, &restError) && restError.Message != nil && restError.Message.Code == discordgo.ErrCodeUnknownApplicationCommandPermissions {
   337  				s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   338  					Type: discordgo.InteractionResponseChannelMessageWithSource,
   339  					Data: &discordgo.InteractionResponseData{
   340  						Content: ":x: No permission overwrites",
   341  					},
   342  				})
   343  				return
   344  			} else if err != nil {
   345  				panic(err)
   346  			}
   347  
   348  			if err != nil {
   349  				panic(err)
   350  			}
   351  			format := "- %s %s\n"
   352  
   353  			channels := ""
   354  			users := ""
   355  			roles := ""
   356  
   357  			for _, o := range perms.Permissions {
   358  				emoji := "❌"
   359  				if o.Permission {
   360  					emoji = "☑"
   361  				}
   362  
   363  				switch o.Type {
   364  				case discordgo.ApplicationCommandPermissionTypeUser:
   365  					users += fmt.Sprintf(format, emoji, "<@!"+o.ID+">")
   366  				case discordgo.ApplicationCommandPermissionTypeChannel:
   367  					allChannels, _ := discordgo.GuildAllChannelsID(i.GuildID)
   368  
   369  					if o.ID == allChannels {
   370  						channels += fmt.Sprintf(format, emoji, "All channels")
   371  					} else {
   372  						channels += fmt.Sprintf(format, emoji, "<#"+o.ID+">")
   373  					}
   374  				case discordgo.ApplicationCommandPermissionTypeRole:
   375  					if o.ID == i.GuildID {
   376  						roles += fmt.Sprintf(format, emoji, "@everyone")
   377  					} else {
   378  						roles += fmt.Sprintf(format, emoji, "<@&"+o.ID+">")
   379  					}
   380  				}
   381  			}
   382  
   383  			s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   384  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   385  				Data: &discordgo.InteractionResponseData{
   386  					Embeds: []*discordgo.MessageEmbed{
   387  						{
   388  							Title:       "Permissions overview",
   389  							Description: "Overview of permissions for this command",
   390  							Fields: []*discordgo.MessageEmbedField{
   391  								{
   392  									Name:  "Users",
   393  									Value: users,
   394  								},
   395  								{
   396  									Name:  "Channels",
   397  									Value: channels,
   398  								},
   399  								{
   400  									Name:  "Roles",
   401  									Value: roles,
   402  								},
   403  							},
   404  						},
   405  					},
   406  					AllowedMentions: &discordgo.MessageAllowedMentions{},
   407  				},
   408  			})
   409  		},
   410  		"subcommands": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   411  			options := i.ApplicationCommandData().Options
   412  			content := ""
   413  
   414  			// As you can see, names of subcommands (nested, top-level)
   415  			// and subcommand groups are provided through the arguments.
   416  			switch options[0].Name {
   417  			case "subcommand":
   418  				content = "The top-level subcommand is executed. Now try to execute the nested one."
   419  			case "subcommand-group":
   420  				options = options[0].Options
   421  				switch options[0].Name {
   422  				case "nested-subcommand":
   423  					content = "Nice, now you know how to execute nested commands too"
   424  				default:
   425  					content = "Oops, something went wrong.\n" +
   426  						"Hol' up, you aren't supposed to see this message."
   427  				}
   428  			}
   429  
   430  			s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   431  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   432  				Data: &discordgo.InteractionResponseData{
   433  					Content: content,
   434  				},
   435  			})
   436  		},
   437  		"responses": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   438  			// Responses to a command are very important.
   439  			// First of all, because you need to react to the interaction
   440  			// by sending the response in 3 seconds after receiving, otherwise
   441  			// interaction will be considered invalid and you can no longer
   442  			// use the interaction token and ID for responding to the user's request
   443  
   444  			content := ""
   445  			// As you can see, the response type names used here are pretty self-explanatory,
   446  			// but for those who want more information see the official documentation
   447  			switch i.ApplicationCommandData().Options[0].IntValue() {
   448  			case int64(discordgo.InteractionResponseChannelMessageWithSource):
   449  				content =
   450  					"You just responded to an interaction, sent a message and showed the original one. " +
   451  						"Congratulations!"
   452  				content +=
   453  					"\nAlso... you can edit your response, wait 5 seconds and this message will be changed"
   454  			default:
   455  				err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   456  					Type: discordgo.InteractionResponseType(i.ApplicationCommandData().Options[0].IntValue()),
   457  				})
   458  				if err != nil {
   459  					s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   460  						Content: "Something went wrong",
   461  					})
   462  				}
   463  				return
   464  			}
   465  
   466  			err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   467  				Type: discordgo.InteractionResponseType(i.ApplicationCommandData().Options[0].IntValue()),
   468  				Data: &discordgo.InteractionResponseData{
   469  					Content: content,
   470  				},
   471  			})
   472  			if err != nil {
   473  				s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   474  					Content: "Something went wrong",
   475  				})
   476  				return
   477  			}
   478  			time.AfterFunc(time.Second*5, func() {
   479  				content := content + "\n\nWell, now you know how to create and edit responses. " +
   480  					"But you still don't know how to delete them... so... wait 10 seconds and this " +
   481  					"message will be deleted."
   482  				_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
   483  					Content: &content,
   484  				})
   485  				if err != nil {
   486  					s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   487  						Content: "Something went wrong",
   488  					})
   489  					return
   490  				}
   491  				time.Sleep(time.Second * 10)
   492  				s.InteractionResponseDelete(i.Interaction)
   493  			})
   494  		},
   495  		"followups": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   496  			// Followup messages are basically regular messages (you can create as many of them as you wish)
   497  			// but work as they are created by webhooks and their functionality
   498  			// is for handling additional messages after sending a response.
   499  
   500  			s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   501  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   502  				Data: &discordgo.InteractionResponseData{
   503  					// Note: this isn't documented, but you can use that if you want to.
   504  					// This flag just allows you to create messages visible only for the caller of the command
   505  					// (user who triggered the command)
   506  					Flags:   discordgo.MessageFlagsEphemeral,
   507  					Content: "Surprise!",
   508  				},
   509  			})
   510  			msg, err := s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   511  				Content: "Followup message has been created, after 5 seconds it will be edited",
   512  			})
   513  			if err != nil {
   514  				s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   515  					Content: "Something went wrong",
   516  				})
   517  				return
   518  			}
   519  			time.Sleep(time.Second * 5)
   520  
   521  			content := "Now the original message is gone and after 10 seconds this message will ~~self-destruct~~ be deleted."
   522  			s.FollowupMessageEdit(i.Interaction, msg.ID, &discordgo.WebhookEdit{
   523  				Content: &content,
   524  			})
   525  
   526  			time.Sleep(time.Second * 10)
   527  
   528  			s.FollowupMessageDelete(i.Interaction, msg.ID)
   529  
   530  			s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   531  				Content: "For those, who didn't skip anything and followed tutorial along fairly, " +
   532  					"take a unicorn :unicorn: as reward!\n" +
   533  					"Also, as bonus... look at the original interaction response :D",
   534  			})
   535  		},
   536  	}
   537  )
   538  
   539  func init() {
   540  	s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   541  		if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
   542  			h(s, i)
   543  		}
   544  	})
   545  }
   546  
   547  func main() {
   548  	s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
   549  		log.Printf("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator)
   550  	})
   551  	err := s.Open()
   552  	if err != nil {
   553  		log.Fatalf("Cannot open the session: %v", err)
   554  	}
   555  
   556  	log.Println("Adding commands...")
   557  	registeredCommands := make([]*discordgo.ApplicationCommand, len(commands))
   558  	for i, v := range commands {
   559  		cmd, err := s.ApplicationCommandCreate(s.State.User.ID, *GuildID, v)
   560  		if err != nil {
   561  			log.Panicf("Cannot create '%v' command: %v", v.Name, err)
   562  		}
   563  		registeredCommands[i] = cmd
   564  	}
   565  
   566  	defer s.Close()
   567  
   568  	stop := make(chan os.Signal, 1)
   569  	signal.Notify(stop, os.Interrupt)
   570  	log.Println("Press Ctrl+C to exit")
   571  	<-stop
   572  
   573  	if *RemoveCommands {
   574  		log.Println("Removing commands...")
   575  		// // We need to fetch the commands, since deleting requires the command ID.
   576  		// // We are doing this from the returned commands on line 375, because using
   577  		// // this will delete all the commands, which might not be desirable, so we
   578  		// // are deleting only the commands that we added.
   579  		// registeredCommands, err := s.ApplicationCommands(s.State.User.ID, *GuildID)
   580  		// if err != nil {
   581  		// 	log.Fatalf("Could not fetch registered commands: %v", err)
   582  		// }
   583  
   584  		for _, v := range registeredCommands {
   585  			err := s.ApplicationCommandDelete(s.State.User.ID, *GuildID, v.ID)
   586  			if err != nil {
   587  				log.Panicf("Cannot delete '%v' command: %v", v.Name, err)
   588  			}
   589  		}
   590  	}
   591  
   592  	log.Println("Gracefully shutting down.")
   593  }