api_basic.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // This file provides a basic "quick start" example of using the Discordgo
  2. // package to connect to Discord using the low level API functions.
  3. package main
  4. import (
  5. "fmt"
  6. "os"
  7. "time"
  8. "github.com/bwmarrin/discordgo"
  9. )
  10. func main() {
  11. var err error
  12. // Check for Username and Password CLI arguments.
  13. if len(os.Args) != 3 {
  14. fmt.Println("You must provide username and password as arguments. See below example.")
  15. fmt.Println(os.Args[0], " [username] [password]")
  16. return
  17. }
  18. // Create a new Discord Session interface and set a handler for the
  19. // OnMessageCreate event that happens for every new message on any channel
  20. dg := discordgo.Session{
  21. OnMessageCreate: messageCreate,
  22. }
  23. // Login to the Discord server and store the authentication token
  24. dg.Token, err = dg.Login(os.Args[1], os.Args[2])
  25. if err != nil {
  26. fmt.Println(err)
  27. return
  28. }
  29. // Open websocket connection
  30. err = dg.Open()
  31. if err != nil {
  32. fmt.Println(err)
  33. }
  34. // Do websocket handshake.
  35. err = dg.Handshake()
  36. if err != nil {
  37. fmt.Println(err)
  38. }
  39. // Listen for events.
  40. go dg.Listen()
  41. // Simple way to keep program running until any key press.
  42. var input string
  43. fmt.Scanln(&input)
  44. return
  45. }
  46. // This function will be called (due to above assignment) every time a new
  47. // message is created on any channel that the autenticated user has access to.
  48. func messageCreate(s *discordgo.Session, m discordgo.Message) {
  49. // Print message to stdout.
  50. fmt.Printf("%20s %20s %20s > %s\n", m.ChannelID, time.Now().Format(time.Stamp), m.Author.Username, m.Content)
  51. }