main.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/bwmarrin/discordgo"
  6. )
  7. // Variables used for command line parameters
  8. var (
  9. Token string
  10. BotID string
  11. )
  12. func init() {
  13. flag.StringVar(&Token, "t", "", "Bot Token")
  14. flag.Parse()
  15. }
  16. func main() {
  17. // Create a new Discord session using the provided bot token.
  18. dg, err := discordgo.New("Bot " + Token)
  19. if err != nil {
  20. fmt.Println("error creating Discord session,", err)
  21. return
  22. }
  23. // Get the account information.
  24. u, err := dg.User("@me")
  25. if err != nil {
  26. fmt.Println("error obtaining account details,", err)
  27. }
  28. // Store the account ID for later use.
  29. BotID = u.ID
  30. // Register messageCreate as a callback for the messageCreate events.
  31. dg.AddHandler(messageCreate)
  32. // Open the websocket and begin listening.
  33. err = dg.Open()
  34. if err != nil {
  35. fmt.Println("error opening connection,", err)
  36. return
  37. }
  38. fmt.Println("Bot is now running. Press CTRL-C to exit.")
  39. // Simple way to keep program running until CTRL-C is pressed.
  40. <-make(chan struct{})
  41. return
  42. }
  43. // This function will be called (due to AddHandler above) every time a new
  44. // message is created on any channel that the autenticated bot has access to.
  45. func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
  46. // Ignore all messages created by the bot itself
  47. if m.Author.ID == BotID {
  48. return
  49. }
  50. // If the message is "ping" reply with "Pong!"
  51. if m.Content == "ping" {
  52. _, _ = s.ChannelMessageSend(m.ChannelID, "Pong!")
  53. }
  54. // If the message is "pong" reply with "Ping!"
  55. if m.Content == "pong" {
  56. _, _ = s.ChannelMessageSend(m.ChannelID, "Ping!")
  57. }
  58. }