main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // In this example, we only care about receiving message events.
  28. dg.Identify.Intents = discordgo.IntentsGuildMessages
  29. // Open a websocket connection to Discord and begin listening.
  30. err = dg.Open()
  31. if err != nil {
  32. fmt.Println("error opening connection,", err)
  33. return
  34. }
  35. // Wait here until CTRL-C or other term signal is received.
  36. fmt.Println("Bot is now running. Press CTRL-C to exit.")
  37. sc := make(chan os.Signal, 1)
  38. signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
  39. <-sc
  40. // Cleanly close down the Discord session.
  41. dg.Close()
  42. }
  43. // This function will be called (due to AddHandler above) every time a new
  44. // message is created on any channel that the authenticated bot has access to.
  45. func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
  46. // Ignore all messages created by the bot itself
  47. // This isn't required in this specific example but it's a good practice.
  48. if m.Author.ID == s.State.User.ID {
  49. return
  50. }
  51. // If the message is "ping" reply with "Pong!"
  52. if m.Content == "ping" {
  53. s.ChannelMessageSend(m.ChannelID, "Pong!")
  54. }
  55. // If the message is "pong" reply with "Ping!"
  56. if m.Content == "pong" {
  57. s.ChannelMessageSend(m.ChannelID, "Ping!")
  58. }
  59. }