| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "os/signal" |
| 8 | "syscall" |
| 9 | |
| 10 | "github.com/bwmarrin/discordgo" |
| 11 | ) |
| 12 | |
| 13 | // Variables used for command line parameters |
| 14 | var ( |
| 15 | Token string |
| 16 | ) |
| 17 | |
| 18 | func init() { |
| 19 | |
| 20 | flag.StringVar(&Token, "t", "", "Bot Token") |
| 21 | flag.Parse() |
| 22 | } |
| 23 | |
| 24 | func main() { |
| 25 | |
| 26 | // Create a new Discord session using the provided bot token. |
| 27 | dg, err := discordgo.New("Bot " + Token) |
| 28 | if err != nil { |
| 29 | fmt.Println("error creating Discord session,", err) |
| 30 | return |
| 31 | } |
| 32 | |
| 33 | // Register the messageCreate func as a callback for MessageCreate events. |
| 34 | dg.AddHandler(messageCreate) |
| 35 | |
| 36 | // Open a websocket connection to Discord and begin listening. |
| 37 | err = dg.Open() |
| 38 | if err != nil { |
| 39 | fmt.Println("error opening connection,", err) |
| 40 | return |
| 41 | } |
| 42 | |
| 43 | // Wait here until CTRL-C or other term signal is received. |
| 44 | fmt.Println("Bot is now running. Press CTRL-C to exit.") |
| 45 | sc := make(chan os.Signal, 1) |
| 46 | signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill) |
| 47 | <-sc |
| 48 | |
| 49 | // Cleanly close down the Discord session. |
| 50 | dg.Close() |
| 51 | } |
| 52 | |
| 53 | // This function will be called (due to AddHandler above) every time a new |
| 54 | // message is created on any channel that the autenticated bot has access to. |
| 55 | func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { |
| 56 | |
| 57 | // Ignore all messages created by the bot itself |
| 58 | // This isn't required in this specific example but it's a good practice. |
| 59 | if m.Author.ID == s.State.User.ID { |
| 60 | return |
| 61 | } |
| 62 | // If the message is "ping" reply with "Pong!" |
| 63 | if m.Content == "bad bot" { |
| 64 | s.ChannelMessageSend(m.ChannelID, "the worst bot") |
| 65 | } |
| 66 | |
| 67 | // If the message is "pong" reply with "Ping!" |
| 68 | if m.Content == "pong" { |
| 69 | s.ChannelMessageSend(m.ChannelID, "Ping!") |
| 70 | } |
| 71 | } |