Skip to content

Instantly share code, notes, and snippets.

@oogali
Created October 17, 2022 21:31
Show Gist options
  • Save oogali/6460a7404fe505405711c0133a321a00 to your computer and use it in GitHub Desktop.
Save oogali/6460a7404fe505405711c0133a321a00 to your computer and use it in GitHub Desktop.
discord bot hello world
package main
import (
"os"
"os/signal"
"github.com/bwmarrin/discordgo"
"github.com/rs/zerolog/log"
)
func main() {
bot, err := discordgo.New("Bot " + os.Getenv("DISCORD_BOT_TOKEN"))
if err != nil {
log.Fatal().Err(err).Msg("could not instantiate discord instance")
}
commands := []*discordgo.ApplicationCommand{
{
Name: "testing",
Description: "a test command",
},
}
handlers := map[string]func(session *discordgo.Session, interaction *discordgo.InteractionCreate){
"testing": func(session *discordgo.Session, interaction *discordgo.InteractionCreate) {
session.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "a programmatic response!",
},
})
},
}
bot.AddHandler(func(session *discordgo.Session, ready *discordgo.Ready) {
log.Info().Str("username", session.State.User.Username).Str("discriminator", session.State.User.Discriminator).Msg("logged in")
})
bot.AddHandler(func(session *discordgo.Session, interaction *discordgo.InteractionCreate) {
if handler, ok := handlers[interaction.ApplicationCommandData().Name]; ok {
handler(session, interaction)
}
})
if err := bot.Open(); err != nil {
log.Fatal().Err(err).Msg("could not establish session with discord")
}
var registeredCommands []*discordgo.ApplicationCommand
for _, c := range commands {
cmd, err := bot.ApplicationCommandCreate(bot.State.User.ID, "", c)
if err != nil {
log.Fatal().Err(err).Msg("could not create application command")
}
registeredCommands = append(registeredCommands, cmd)
}
defer bot.Close()
log.Debug().Str("token", bot.Token).Msg("discord initialized")
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
<-stop
for _, cmd := range registeredCommands {
if err := bot.ApplicationCommandDelete(bot.State.User.ID, "", cmd.ID); err != nil {
log.Fatal().Err(err).Str("command", cmd.Name).Msg("cannot delete application command")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment