api_basic.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // Register messageCreate as a callback for the messageCreate events.
  22. dg.AddHandler(messageCreate)
  23. // Login to the Discord server and store the authentication token
  24. 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. // 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. // Print message to stdout.
  43. fmt.Printf("%20s %20s %20s > %s\n", m.ChannelID, time.Now().Format(time.Stamp), m.Author.Username, m.Content)
  44. }