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

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"os/signal"
     9  
    10  	"github.com/bwmarrin/discordgo"
    11  )
    12  
    13  // Bot parameters
    14  var (
    15  	GuildID        = flag.String("guild", "", "Test guild ID. If not passed - bot registers commands globally")
    16  	BotToken       = flag.String("token", "", "Bot access token")
    17  	RemoveCommands = flag.Bool("rmcmd", true, "Remove all commands after shutdowning or not")
    18  )
    19  
    20  var s *discordgo.Session
    21  
    22  func init() { flag.Parse() }
    23  
    24  func init() {
    25  	var err error
    26  	s, err = discordgo.New("Bot " + *BotToken)
    27  	if err != nil {
    28  		log.Fatalf("Invalid bot parameters: %v", err)
    29  	}
    30  }
    31  
    32  var (
    33  	commands = []*discordgo.ApplicationCommand{
    34  		{
    35  			Name:        "single-autocomplete",
    36  			Description: "Showcase of single autocomplete option",
    37  			Type:        discordgo.ChatApplicationCommand,
    38  			Options: []*discordgo.ApplicationCommandOption{
    39  				{
    40  					Name:         "autocomplete-option",
    41  					Description:  "Autocomplete option",
    42  					Type:         discordgo.ApplicationCommandOptionString,
    43  					Required:     true,
    44  					Autocomplete: true,
    45  				},
    46  			},
    47  		},
    48  		{
    49  			Name:        "multi-autocomplete",
    50  			Description: "Showcase of multiple autocomplete option",
    51  			Type:        discordgo.ChatApplicationCommand,
    52  			Options: []*discordgo.ApplicationCommandOption{
    53  				{
    54  					Name:         "autocomplete-option-1",
    55  					Description:  "Autocomplete option 1",
    56  					Type:         discordgo.ApplicationCommandOptionString,
    57  					Required:     true,
    58  					Autocomplete: true,
    59  				},
    60  				{
    61  					Name:         "autocomplete-option-2",
    62  					Description:  "Autocomplete option 2",
    63  					Type:         discordgo.ApplicationCommandOptionString,
    64  					Required:     true,
    65  					Autocomplete: true,
    66  				},
    67  			},
    68  		},
    69  	}
    70  
    71  	commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
    72  		"single-autocomplete": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
    73  			switch i.Type {
    74  			case discordgo.InteractionApplicationCommand:
    75  				data := i.ApplicationCommandData()
    76  				err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
    77  					Type: discordgo.InteractionResponseChannelMessageWithSource,
    78  					Data: &discordgo.InteractionResponseData{
    79  						Content: fmt.Sprintf(
    80  							"You picked %q autocompletion",
    81  							// Autocompleted options do not affect usual flow of handling application command. They are ordinary options at this stage
    82  							data.Options[0].StringValue(),
    83  						),
    84  					},
    85  				})
    86  				if err != nil {
    87  					panic(err)
    88  				}
    89  			// Autocomplete options introduce a new interaction type (8) for returning custom autocomplete results.
    90  			case discordgo.InteractionApplicationCommandAutocomplete:
    91  				data := i.ApplicationCommandData()
    92  				choices := []*discordgo.ApplicationCommandOptionChoice{
    93  					{
    94  						Name:  "Autocomplete",
    95  						Value: "autocomplete",
    96  					},
    97  					{
    98  						Name:  "Autocomplete is best!",
    99  						Value: "autocomplete_is_best",
   100  					},
   101  					{
   102  						Name:  "Choice 3",
   103  						Value: "choice3",
   104  					},
   105  					{
   106  						Name:  "Choice 4",
   107  						Value: "choice4",
   108  					},
   109  					{
   110  						Name:  "Choice 5",
   111  						Value: "choice5",
   112  					},
   113  					// And so on, up to 25 choices
   114  				}
   115  
   116  				if data.Options[0].StringValue() != "" {
   117  					choices = append(choices, &discordgo.ApplicationCommandOptionChoice{
   118  						Name:  data.Options[0].StringValue(), // To get user input you just get value of the autocomplete option.
   119  						Value: "choice_custom",
   120  					})
   121  				}
   122  
   123  				err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   124  					Type: discordgo.InteractionApplicationCommandAutocompleteResult,
   125  					Data: &discordgo.InteractionResponseData{
   126  						Choices: choices, // This is basically the whole purpose of autocomplete interaction - return custom options to the user.
   127  					},
   128  				})
   129  				if err != nil {
   130  					panic(err)
   131  				}
   132  			}
   133  		},
   134  		"multi-autocomplete": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   135  			switch i.Type {
   136  			case discordgo.InteractionApplicationCommand:
   137  				data := i.ApplicationCommandData()
   138  				err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   139  					Type: discordgo.InteractionResponseChannelMessageWithSource,
   140  					Data: &discordgo.InteractionResponseData{
   141  						Content: fmt.Sprintf(
   142  							"Option 1: %s\nOption 2: %s",
   143  							data.Options[0].StringValue(),
   144  							data.Options[1].StringValue(),
   145  						),
   146  					},
   147  				})
   148  				if err != nil {
   149  					panic(err)
   150  				}
   151  			case discordgo.InteractionApplicationCommandAutocomplete:
   152  				data := i.ApplicationCommandData()
   153  				var choices []*discordgo.ApplicationCommandOptionChoice
   154  				switch {
   155  				// In this case there are multiple autocomplete options. The Focused field shows which option user is focused on.
   156  				case data.Options[0].Focused:
   157  					choices = []*discordgo.ApplicationCommandOptionChoice{
   158  						{
   159  							Name:  "Autocomplete 4 first option",
   160  							Value: "autocomplete_default",
   161  						},
   162  						{
   163  							Name:  "Choice 3",
   164  							Value: "choice3",
   165  						},
   166  						{
   167  							Name:  "Choice 4",
   168  							Value: "choice4",
   169  						},
   170  						{
   171  							Name:  "Choice 5",
   172  							Value: "choice5",
   173  						},
   174  					}
   175  					if data.Options[0].StringValue() != "" {
   176  						choices = append(choices, &discordgo.ApplicationCommandOptionChoice{
   177  							Name:  data.Options[0].StringValue(),
   178  							Value: "choice_custom",
   179  						})
   180  					}
   181  
   182  				case data.Options[1].Focused:
   183  					choices = []*discordgo.ApplicationCommandOptionChoice{
   184  						{
   185  							Name:  "Autocomplete 4 second option",
   186  							Value: "autocomplete_1_default",
   187  						},
   188  						{
   189  							Name:  "Choice 3.1",
   190  							Value: "choice3_1",
   191  						},
   192  						{
   193  							Name:  "Choice 4.1",
   194  							Value: "choice4_1",
   195  						},
   196  						{
   197  							Name:  "Choice 5.1",
   198  							Value: "choice5_1",
   199  						},
   200  					}
   201  					if data.Options[1].StringValue() != "" {
   202  						choices = append(choices, &discordgo.ApplicationCommandOptionChoice{
   203  							Name:  data.Options[1].StringValue(),
   204  							Value: "choice_custom_2",
   205  						})
   206  					}
   207  				}
   208  
   209  				err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
   210  					Type: discordgo.InteractionApplicationCommandAutocompleteResult,
   211  					Data: &discordgo.InteractionResponseData{
   212  						Choices: choices,
   213  					},
   214  				})
   215  				if err != nil {
   216  					panic(err)
   217  				}
   218  			}
   219  		},
   220  	}
   221  )
   222  
   223  func main() {
   224  	s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) { log.Println("Bot is up!") })
   225  	s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
   226  		if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
   227  			h(s, i)
   228  		}
   229  	})
   230  	err := s.Open()
   231  	if err != nil {
   232  		log.Fatalf("Cannot open the session: %v", err)
   233  	}
   234  	defer s.Close()
   235  
   236  	createdCommands, err := s.ApplicationCommandBulkOverwrite(s.State.User.ID, *GuildID, commands)
   237  
   238  	if err != nil {
   239  		log.Fatalf("Cannot register commands: %v", err)
   240  	}
   241  
   242  	stop := make(chan os.Signal, 1)
   243  	signal.Notify(stop, os.Interrupt)
   244  	<-stop
   245  	log.Println("Gracefully shutting down")
   246  
   247  	if *RemoveCommands {
   248  		for _, cmd := range createdCommands {
   249  			err := s.ApplicationCommandDelete(s.State.User.ID, *GuildID, cmd.ID)
   250  			if err != nil {
   251  				log.Fatalf("Cannot delete %q command: %v", cmd.Name, err)
   252  			}
   253  		}
   254  	}
   255  }