pingpong.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // This program provides a simple Ping/Pong bot example
  2. // using the DiscordGo API package.
  3. package main
  4. import (
  5. "fmt"
  6. "os"
  7. "github.com/bwmarrin/discordgo"
  8. )
  9. // Will use this to store the Bot's account ID
  10. var BotID string
  11. func main() {
  12. // Check for Token
  13. if len(os.Args) != 2 {
  14. fmt.Println("You must provide the authentication token for your bot account.")
  15. fmt.Println(os.Args[0], " [token]")
  16. return
  17. }
  18. dg, err := discordgo.New(os.Args[1])
  19. if err != nil {
  20. fmt.Println("error creating Discord session: ", err)
  21. return
  22. }
  23. // Get the Bot account information.
  24. u, err := dg.User("@me")
  25. if err != nil {
  26. fmt.Println("error obtaining bot 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. dg.Open()
  34. // Simple way to keep program running until any key press.
  35. var input string
  36. fmt.Scanln(&input)
  37. return
  38. }
  39. // This function will be called (due to AddHandler above) every time a new
  40. // message is created on any channel that the autenticated user has access to.
  41. func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
  42. // Ignore all messages created by the bot itself
  43. if m.Author.ID == BotID {
  44. return
  45. }
  46. // If the message is "ping"
  47. if m.Content == "ping" {
  48. s.ChannelMessageSend(m.ChannelID, "Pong!")
  49. }
  50. if m.Content == "pong" {
  51. s.ChannelMessageSend(m.ChannelID, "Ping!")
  52. }
  53. }