|
@@ -3,6 +3,9 @@ package main
|
|
|
import (
|
|
|
"flag"
|
|
|
"fmt"
|
|
|
+ "os"
|
|
|
+ "os/signal"
|
|
|
+ "syscall"
|
|
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
|
)
|
|
@@ -10,7 +13,6 @@ import (
|
|
|
// Variables used for command line parameters
|
|
|
var (
|
|
|
Token string
|
|
|
- BotID string
|
|
|
)
|
|
|
|
|
|
func init() {
|
|
@@ -28,29 +30,24 @@ func main() {
|
|
|
return
|
|
|
}
|
|
|
|
|
|
- // Get the account information.
|
|
|
- u, err := dg.User("@me")
|
|
|
- if err != nil {
|
|
|
- fmt.Println("error obtaining account details,", err)
|
|
|
- }
|
|
|
-
|
|
|
- // Store the account ID for later use.
|
|
|
- BotID = u.ID
|
|
|
-
|
|
|
- // Register messageCreate as a callback for the messageCreate events.
|
|
|
+ // Register the messageCreate func as a callback for MessageCreate events.
|
|
|
dg.AddHandler(messageCreate)
|
|
|
|
|
|
- // Open the websocket and begin listening.
|
|
|
+ // Open a websocket connection to Discord and begin listening.
|
|
|
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.")
|
|
|
- // Simple way to keep program running until CTRL-C is pressed.
|
|
|
- <-make(chan struct{})
|
|
|
- return
|
|
|
+ sc := make(chan os.Signal, 1)
|
|
|
+ signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
|
|
|
+ <-sc
|
|
|
+
|
|
|
+ // Cleanly close down the Discord session.
|
|
|
+ dg.Close()
|
|
|
}
|
|
|
|
|
|
// This function will be called (due to AddHandler above) every time a new
|
|
@@ -58,17 +55,17 @@ func main() {
|
|
|
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
|
|
|
|
|
|
// Ignore all messages created by the bot itself
|
|
|
- if m.Author.ID == BotID {
|
|
|
+ // This isn't required in this specific example but it's a good practice.
|
|
|
+ if m.Author.ID == s.State.User.ID {
|
|
|
return
|
|
|
}
|
|
|
-
|
|
|
// If the message is "ping" reply with "Pong!"
|
|
|
if m.Content == "ping" {
|
|
|
- _, _ = s.ChannelMessageSend(m.ChannelID, "Pong!")
|
|
|
+ s.ChannelMessageSend(m.ChannelID, "Pong!")
|
|
|
}
|
|
|
|
|
|
// If the message is "pong" reply with "Ping!"
|
|
|
if m.Content == "pong" {
|
|
|
- _, _ = s.ChannelMessageSend(m.ChannelID, "Ping!")
|
|
|
+ s.ChannelMessageSend(m.ChannelID, "Ping!")
|
|
|
}
|
|
|
}
|