package main import ( "fmt" "os" "os/signal" "syscall" "github.com/bwmarrin/discordgo" "github.com/joho/godotenv" ) func main() { err := godotenv.Load() if err != nil { fmt.Println("Error loading .env file") return } botToken := os.Getenv("DISCORD_BOT_TOKEN") if botToken == "" { fmt.Println("Missing variable in .env") return } // initialize bot session dg, err := discordgo.New("Bot " + botToken) if err != nil { fmt.Println("Error creating Discord session,", err) return } // open WebSocket connection dg.AddHandler(readyHandler) dg.AddHandler(messageCreate) err = dg.Open() if err != nil { fmt.Println("Error opening connection,", err) return } // wait here until CTRL-C or other term signal is received. fmt.Println("Bot is now running. Press CTRL-C to exit.") sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc // cleanly close down the Discord session dg.Close() } func readyHandler(s *discordgo.Session, r *discordgo.Ready) { fmt.Println("Ready to rumble!") } // This function will be called (due to AddHandler above) every time a new // message is created on any channel that the authenticated bot has access to. func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { // Ignore all messages created by the bot itself // This isn't required in this specific example but it's a good practice. if m.Author.ID == s.State.User.ID { return } // Ugh message is blank, must be some weird intents thing? fmt.Println(m.Author.Username + " sent: " + m.Content) // If the message is "ping" reply with "Pong!" if m.Content == "ping" { s.ChannelMessageSend(m.ChannelID, "Pong!") } // If the message is "pong" reply with "Ping!" if m.Content == "pong" { s.ChannelMessageSend(m.ChannelID, "Ping!") } }