new_basic.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // This file provides a basic "quick start" example of using the Discordgo
  2. // package to connect to Discord using the New() helper function.
  3. package main
  4. import (
  5. "fmt"
  6. "os"
  7. "time"
  8. "github.com/bwmarrin/discordgo"
  9. )
  10. func main() {
  11. // Check for Username and Password CLI arguments.
  12. if len(os.Args) != 3 {
  13. fmt.Println("You must provide username and password as arguments. See below example.")
  14. fmt.Println(os.Args[0], " [username] [password]")
  15. return
  16. }
  17. // Call the helper function New() passing username and password command
  18. // line arguments. This returns a new Discord session, authenticates,
  19. // connects to the Discord data websocket, and listens for events.
  20. dg, err := discordgo.New(os.Args[1], os.Args[2])
  21. if err != nil {
  22. fmt.Println(err)
  23. return
  24. }
  25. // Register messageCreate as a callback for the messageCreate events.
  26. dg.AddHandler(messageCreate)
  27. // Open the websocket and begin listening.
  28. dg.Open()
  29. // Simple way to keep program running until any key press.
  30. var input string
  31. fmt.Scanln(&input)
  32. return
  33. }
  34. // This function will be called (due to AddHandler above) every time a new
  35. // message is created on any channel that the autenticated user has access to.
  36. func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
  37. // Print message to stdout.
  38. fmt.Printf("%20s %20s %20s > %s\n", m.ChannelID, time.Now().Format(time.Stamp), m.Author.Username, m.Content)
  39. }