package main import ( "fmt" "log" "os" "os/signal" "syscall" "strings" "github.com/bwmarrin/discordgo" "github.com/spf13/viper" ) func main() { vpr := viper.GetViper() vpr.SetConfigFile(".env") var token string = "" if err := vpr.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { log.Fatalln("Config file (.env) not found!") } else { log.Println("Failed to parse config!") } } if vpr.GetString("DISCORD_BOT_TOKEN") == "" { token = os.Getenv("DISCORD_BOT_TOKEN") if token == "" { log.Fatalln("Couldn't fetch bot token!") } } else { token = vpr.GetString("DISCORD_BOT_TOKEN") } dg, err := discordgo.New("Bot " + token) if err != nil { log.Fatalf("Error creating Discord session: %s\n", err) } dg.AddHandler(messageCreate) dg.Identify.Intents = discordgo.IntentsGuildMessages // connect to discord err = dg.Open() if err != nil { log.Fatalf("Couldn't connect to DIscord: %s\n", err) } // wait until ctrl+c or other term signal is received fmt.Println("The Farting Whale is online!") sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc // graceful shutdown dg.Close() } // incoming message handler func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { // ignore messages sent by the bot. if m.Author.ID == s.State.User.ID { return } if strings.HasPrefix(m.Content, "!fart") { c := strings.Fields(m.Content) if len(c) == 1 { s.ChannelMessageSend(m.ChannelID, ":whale2: :dash:") } else if len(c) == 2 { s.ChannelMessageSend(m.ChannelID, fmt.Sprintf(":whale2: :dash: %s", c[1])) } return } }