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

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"os/signal"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/bwmarrin/discordgo"
    13  )
    14  
    15  // Bot parameters
    16  var (
    17  	GuildID  = flag.String("guild", "", "Test guild ID")
    18  	BotToken = flag.String("token", "", "Bot access token")
    19  	AppID    = flag.String("app", "", "Application ID")
    20  )
    21  
    22  var s *discordgo.Session
    23  
    24  func init() { flag.Parse() }
    25  
    26  func init() {
    27  	var err error
    28  	s, err = discordgo.New("Bot " + *BotToken)
    29  	if err != nil {
    30  		log.Fatalf("Invalid bot parameters: %v", err)
    31  	}
    32  }
    33  
    34  // Important note: call every command in order it's placed in the example.
    35  
    36  var (
    37  	componentsHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
    38  		"fd_no": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
    39  			err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
    40  				Type: discordgo.InteractionResponseChannelMessageWithSource,
    41  				Data: &discordgo.InteractionResponseData{
    42  					Content: "Huh. I see, maybe some of these resources might help you?",
    43  					Flags:   discordgo.MessageFlagsEphemeral,
    44  					Components: []discordgo.MessageComponent{
    45  						discordgo.ActionsRow{
    46  							Components: []discordgo.MessageComponent{
    47  								discordgo.Button{
    48  									Emoji: &discordgo.ComponentEmoji{
    49  										Name: "📜",
    50  									},
    51  									Label: "Documentation",
    52  									Style: discordgo.LinkButton,
    53  									URL:   "https://discord.com/developers/docs/interactions/message-components#buttons",
    54  								},
    55  								discordgo.Button{
    56  									Emoji: &discordgo.ComponentEmoji{
    57  										Name: "🔧",
    58  									},
    59  									Label: "Discord developers",
    60  									Style: discordgo.LinkButton,
    61  									URL:   "https://discord.gg/discord-developers",
    62  								},
    63  								discordgo.Button{
    64  									Emoji: &discordgo.ComponentEmoji{
    65  										Name: "đŸĻĢ",
    66  									},
    67  									Label: "Discord Gophers",
    68  									Style: discordgo.LinkButton,
    69  									URL:   "https://discord.gg/7RuRrVHyXF",
    70  								},
    71  							},
    72  						},
    73  					},
    74  				},
    75  			})
    76  			if err != nil {
    77  				panic(err)
    78  			}
    79  		},
    80  		"fd_yes": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
    81  			err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
    82  				Type: discordgo.InteractionResponseChannelMessageWithSource,
    83  				Data: &discordgo.InteractionResponseData{
    84  					Content: "Great! If you wanna know more or just have questions, feel free to visit Discord Devs and Discord Gophers server. " +
    85  						"But now, when you know how buttons work, let's move onto select menus (execute `/selects single`)",
    86  					Flags: discordgo.MessageFlagsEphemeral,
    87  					Components: []discordgo.MessageComponent{
    88  						discordgo.ActionsRow{
    89  							Components: []discordgo.MessageComponent{
    90  								discordgo.Button{
    91  									Emoji: &discordgo.ComponentEmoji{
    92  										Name: "🔧",
    93  									},
    94  									Label: "Discord developers",
    95  									Style: discordgo.LinkButton,
    96  									URL:   "https://discord.gg/discord-developers",
    97  								},
    98  								discordgo.Button{
    99  									Emoji: &discordgo.ComponentEmoji{
   100  										Name: "đŸĻĢ",
   101  									},
   102  									Label: "Discord Gophers",
   103  									Style: discordgo.LinkButton,
   104  									URL:   "https://discord.gg/7RuRrVHyXF",
   105  								},
   106  							},
   107  						},
   108  					},
   109  				},
   110  			})
   111  			if err != nil {
   112  				panic(err)
   113  			}
   114  		},
   115  		"select": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   116  			var response *discordgo.InteractionResponse
   117  
   118  			data := i.MessageComponentData()
   119  			switch data.Values[0] {
   120  			case "go":
   121  				response = &discordgo.InteractionResponse{
   122  					Type: discordgo.InteractionResponseChannelMessageWithSource,
   123  					Data: &discordgo.InteractionResponseData{
   124  						Content: "This is the way.",
   125  						Flags:   discordgo.MessageFlagsEphemeral,
   126  					},
   127  				}
   128  			default:
   129  				response = &discordgo.InteractionResponse{
   130  					Type: discordgo.InteractionResponseChannelMessageWithSource,
   131  					Data: &discordgo.InteractionResponseData{
   132  						Content: "It is not the way to go.",
   133  						Flags:   discordgo.MessageFlagsEphemeral,
   134  					},
   135  				}
   136  			}
   137  			err := s.InteractionRespond(i.Interaction, response)
   138  			if err != nil {
   139  				panic(err)
   140  			}
   141  			time.Sleep(time.Second) // Doing that so user won't see instant response.
   142  			_, err = s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   143  				Content: "Anyways, now when you know how to use single select menus, let's see how multi select menus work. " +
   144  					"Try calling `/selects multi` command.",
   145  				Flags: discordgo.MessageFlagsEphemeral,
   146  			})
   147  			if err != nil {
   148  				panic(err)
   149  			}
   150  		},
   151  		"stackoverflow_tags": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   152  			data := i.MessageComponentData()
   153  
   154  			const stackoverflowFormat = `https://stackoverflow.com/questions/tagged/%s`
   155  
   156  			err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   157  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   158  				Data: &discordgo.InteractionResponseData{
   159  					Content: "Here is your stackoverflow URL: " + fmt.Sprintf(stackoverflowFormat, strings.Join(data.Values, "+")),
   160  					Flags:   discordgo.MessageFlagsEphemeral,
   161  				},
   162  			})
   163  			if err != nil {
   164  				panic(err)
   165  			}
   166  			time.Sleep(time.Second) // Doing that so user won't see instant response.
   167  			_, err = s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
   168  				Content: "But wait, there is more! You can also auto populate the select menu. Try executing `/selects auto-populated`.",
   169  				Flags:   discordgo.MessageFlagsEphemeral,
   170  			})
   171  			if err != nil {
   172  				panic(err)
   173  			}
   174  		},
   175  		"channel_select": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   176  			err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   177  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   178  				Data: &discordgo.InteractionResponseData{
   179  					Content: "This is it. You've reached your destination. Your choice was <#" + i.MessageComponentData().Values[0] + ">\n" +
   180  						"If you want to know more, check out the links below",
   181  					Components: []discordgo.MessageComponent{
   182  						discordgo.ActionsRow{
   183  							Components: []discordgo.MessageComponent{
   184  								discordgo.Button{
   185  									Emoji: &discordgo.ComponentEmoji{
   186  										Name: "📜",
   187  									},
   188  									Label: "Documentation",
   189  									Style: discordgo.LinkButton,
   190  									URL:   "https://discord.com/developers/docs/interactions/message-components#select-menus",
   191  								},
   192  								discordgo.Button{
   193  									Emoji: &discordgo.ComponentEmoji{
   194  										Name: "🔧",
   195  									},
   196  									Label: "Discord developers",
   197  									Style: discordgo.LinkButton,
   198  									URL:   "https://discord.gg/discord-developers",
   199  								},
   200  								discordgo.Button{
   201  									Emoji: &discordgo.ComponentEmoji{
   202  										Name: "đŸĻĢ",
   203  									},
   204  									Label: "Discord Gophers",
   205  									Style: discordgo.LinkButton,
   206  									URL:   "https://discord.gg/7RuRrVHyXF",
   207  								},
   208  							},
   209  						},
   210  					},
   211  
   212  					Flags: discordgo.MessageFlagsEphemeral,
   213  				},
   214  			})
   215  			if err != nil {
   216  				panic(err)
   217  			}
   218  		},
   219  	}
   220  	commandsHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
   221  		"buttons": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   222  			err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   223  				Type: discordgo.InteractionResponseChannelMessageWithSource,
   224  				Data: &discordgo.InteractionResponseData{
   225  					Content: "Are you comfortable with buttons and other message components?",
   226  					Flags:   discordgo.MessageFlagsEphemeral,
   227  					// Buttons and other components are specified in Components field.
   228  					Components: []discordgo.MessageComponent{
   229  						// ActionRow is a container of all buttons within the same row.
   230  						discordgo.ActionsRow{
   231  							Components: []discordgo.MessageComponent{
   232  								discordgo.Button{
   233  									// Label is what the user will see on the button.
   234  									Label: "Yes",
   235  									// Style provides coloring of the button. There are not so many styles tho.
   236  									Style: discordgo.SuccessButton,
   237  									// Disabled allows bot to disable some buttons for users.
   238  									Disabled: false,
   239  									// CustomID is a thing telling Discord which data to send when this button will be pressed.
   240  									CustomID: "fd_yes",
   241  								},
   242  								discordgo.Button{
   243  									Label:    "No",
   244  									Style:    discordgo.DangerButton,
   245  									Disabled: false,
   246  									CustomID: "fd_no",
   247  								},
   248  								discordgo.Button{
   249  									Label:    "I don't know",
   250  									Style:    discordgo.LinkButton,
   251  									Disabled: false,
   252  									// Link buttons don't require CustomID and do not trigger the gateway/HTTP event
   253  									URL: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
   254  									Emoji: &discordgo.ComponentEmoji{
   255  										Name: "🤷",
   256  									},
   257  								},
   258  							},
   259  						},
   260  						// The message may have multiple actions rows.
   261  						discordgo.ActionsRow{
   262  							Components: []discordgo.MessageComponent{
   263  								discordgo.Button{
   264  									Label:    "Discord Developers server",
   265  									Style:    discordgo.LinkButton,
   266  									Disabled: false,
   267  									URL:      "https://discord.gg/discord-developers",
   268  								},
   269  							},
   270  						},
   271  					},
   272  				},
   273  			})
   274  			if err != nil {
   275  				panic(err)
   276  			}
   277  		},
   278  		"selects": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   279  			var response *discordgo.InteractionResponse
   280  			switch i.ApplicationCommandData().Options[0].Name {
   281  			case "single":
   282  				response = &discordgo.InteractionResponse{
   283  					Type: discordgo.InteractionResponseChannelMessageWithSource,
   284  					Data: &discordgo.InteractionResponseData{
   285  						Content: "Now let's take a look on selects. This is single item select menu.",
   286  						Flags:   discordgo.MessageFlagsEphemeral,
   287  						Components: []discordgo.MessageComponent{
   288  							discordgo.ActionsRow{
   289  								Components: []discordgo.MessageComponent{
   290  									discordgo.SelectMenu{
   291  										// Select menu, as other components, must have a customID, so we set it to this value.
   292  										CustomID:    "select",
   293  										Placeholder: "Choose your favorite programming language 👇",
   294  										Options: []discordgo.SelectMenuOption{
   295  											{
   296  												Label: "Go",
   297  												// As with components, this things must have their own unique "id" to identify which is which.
   298  												// In this case such id is Value field.
   299  												Value: "go",
   300  												Emoji: &discordgo.ComponentEmoji{
   301  													Name: "đŸĻĻ",
   302  												},
   303  												// You can also make it a default option, but in this case we won't.
   304  												Default:     false,
   305  												Description: "Go programming language",
   306  											},
   307  											{
   308  												Label: "JS",
   309  												Value: "js",
   310  												Emoji: &discordgo.ComponentEmoji{
   311  													Name: "🟨",
   312  												},
   313  												Description: "JavaScript programming language",
   314  											},
   315  											{
   316  												Label: "Python",
   317  												Value: "py",
   318  												Emoji: &discordgo.ComponentEmoji{
   319  													Name: "🐍",
   320  												},
   321  												Description: "Python programming language",
   322  											},
   323  										},
   324  									},
   325  								},
   326  							},
   327  						},
   328  					},
   329  				}
   330  			case "multi":
   331  				minValues := 1
   332  				response = &discordgo.InteractionResponse{
   333  					Type: discordgo.InteractionResponseChannelMessageWithSource,
   334  					Data: &discordgo.InteractionResponseData{
   335  						Content: "Now let's see how the multi-item select menu works: " +
   336  							"try generating your own stackoverflow search link",
   337  						Flags: discordgo.MessageFlagsEphemeral,
   338  						Components: []discordgo.MessageComponent{
   339  							discordgo.ActionsRow{
   340  								Components: []discordgo.MessageComponent{
   341  									discordgo.SelectMenu{
   342  										CustomID:    "stackoverflow_tags",
   343  										Placeholder: "Select tags to search on StackOverflow",
   344  										// This is where confusion comes from. If you don't specify these things you will get single item select.
   345  										// These fields control the minimum and maximum amount of selected items.
   346  										MinValues: &minValues,
   347  										MaxValues: 3,
   348  										Options: []discordgo.SelectMenuOption{
   349  											{
   350  												Label:       "Go",
   351  												Description: "Simple yet powerful programming language",
   352  												Value:       "go",
   353  												// Default works the same for multi-select menus.
   354  												Default: false,
   355  												Emoji: &discordgo.ComponentEmoji{
   356  													Name: "đŸĻĻ",
   357  												},
   358  											},
   359  											{
   360  												Label:       "JS",
   361  												Description: "Multiparadigm OOP language",
   362  												Value:       "javascript",
   363  												Emoji: &discordgo.ComponentEmoji{
   364  													Name: "🟨",
   365  												},
   366  											},
   367  											{
   368  												Label:       "Python",
   369  												Description: "OOP prototyping programming language",
   370  												Value:       "python",
   371  												Emoji: &discordgo.ComponentEmoji{
   372  													Name: "🐍",
   373  												},
   374  											},
   375  											{
   376  												Label:       "Web",
   377  												Description: "Web related technologies",
   378  												Value:       "web",
   379  												Emoji: &discordgo.ComponentEmoji{
   380  													Name: "🌐",
   381  												},
   382  											},
   383  											{
   384  												Label:       "Desktop",
   385  												Description: "Desktop applications",
   386  												Value:       "desktop",
   387  												Emoji: &discordgo.ComponentEmoji{
   388  													Name: "đŸ’ģ",
   389  												},
   390  											},
   391  										},
   392  									},
   393  								},
   394  							},
   395  						},
   396  					},
   397  				}
   398  			case "auto-populated":
   399  				response = &discordgo.InteractionResponse{
   400  					Type: discordgo.InteractionResponseChannelMessageWithSource,
   401  					Data: &discordgo.InteractionResponseData{
   402  						Content: "The tastiest things are left for the end. Meet auto populated select menus.\n" +
   403  							"By setting `MenuType` on the select menu you can tell Discord to automatically populate the menu with entities of your choice: roles, members, channels. Try one below.",
   404  						Flags: discordgo.MessageFlagsEphemeral,
   405  						Components: []discordgo.MessageComponent{
   406  							discordgo.ActionsRow{
   407  								Components: []discordgo.MessageComponent{
   408  									discordgo.SelectMenu{
   409  										MenuType:     discordgo.ChannelSelectMenu,
   410  										CustomID:     "channel_select",
   411  										Placeholder:  "Pick your favorite channel!",
   412  										ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText},
   413  									},
   414  								},
   415  							},
   416  						},
   417  					},
   418  				}
   419  			}
   420  			err := s.InteractionRespond(i.Interaction, response)
   421  			if err != nil {
   422  				panic(err)
   423  			}
   424  		},
   425  	}
   426  )
   427  
   428  func main() {
   429  	s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
   430  		log.Println("Bot is up!")
   431  	})
   432  	// Components are part of interactions, so we register InteractionCreate handler
   433  	s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   434  		switch i.Type {
   435  		case discordgo.InteractionApplicationCommand:
   436  			if h, ok := commandsHandlers[i.ApplicationCommandData().Name]; ok {
   437  				h(s, i)
   438  			}
   439  		case discordgo.InteractionMessageComponent:
   440  
   441  			if h, ok := componentsHandlers[i.MessageComponentData().CustomID]; ok {
   442  				h(s, i)
   443  			}
   444  		}
   445  	})
   446  	_, err := s.ApplicationCommandCreate(*AppID, *GuildID, &discordgo.ApplicationCommand{
   447  		Name:        "buttons",
   448  		Description: "Test the buttons if you got courage",
   449  	})
   450  
   451  	if err != nil {
   452  		log.Fatalf("Cannot create slash command: %v", err)
   453  	}
   454  	_, err = s.ApplicationCommandCreate(*AppID, *GuildID, &discordgo.ApplicationCommand{
   455  		Name: "selects",
   456  		Options: []*discordgo.ApplicationCommandOption{
   457  			{
   458  				Type:        discordgo.ApplicationCommandOptionSubCommand,
   459  				Name:        "multi",
   460  				Description: "Multi-item select menu",
   461  			},
   462  			{
   463  				Type:        discordgo.ApplicationCommandOptionSubCommand,
   464  				Name:        "single",
   465  				Description: "Single-item select menu",
   466  			},
   467  			{
   468  				Type:        discordgo.ApplicationCommandOptionSubCommand,
   469  				Name:        "auto-populated",
   470  				Description: "Automatically populated select menu, which lets you pick a member, channel or role",
   471  			},
   472  		},
   473  		Description: "Lo and behold: dropdowns are coming",
   474  	})
   475  
   476  	if err != nil {
   477  		log.Fatalf("Cannot create slash command: %v", err)
   478  	}
   479  
   480  	err = s.Open()
   481  	if err != nil {
   482  		log.Fatalf("Cannot open the session: %v", err)
   483  	}
   484  	defer s.Close()
   485  
   486  	stop := make(chan os.Signal, 1)
   487  	signal.Notify(stop, os.Interrupt)
   488  	<-stop
   489  	log.Println("Graceful shutdown")
   490  }