main.go 1.6 KB

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