discord.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains high level helper functions and easy entry points for the
  7. // entire discordgo package. These functions are beling developed and are very
  8. // experimental at this point. They will most likley change so please use the
  9. // low level functions if that's a problem.
  10. // Package discordgo provides Discord binding for Go
  11. package discordgo
  12. import (
  13. "fmt"
  14. "reflect"
  15. )
  16. // VERSION of Discordgo, follows Symantic Versioning. (http://semver.org/)
  17. const VERSION = "0.11.0-alpha"
  18. // New creates a new Discord session and will automate some startup
  19. // tasks if given enough information to do so. Currently you can pass zero
  20. // arguments and it will return an empty Discord session.
  21. // There are 3 ways to call New:
  22. // With a single auth token - All requests will use the token blindly,
  23. // no verification of the token will be done and requests may fail.
  24. // With an email and password - Discord will sign in with the provided
  25. // credentials.
  26. // With an email, password and auth token - Discord will verify the auth
  27. // token, if it is invalid it will sign in with the provided
  28. // credentials. This is the Discord recommended way to sign in.
  29. func New(args ...interface{}) (s *Session, err error) {
  30. // Create an empty Session interface.
  31. s = &Session{
  32. State: NewState(),
  33. StateEnabled: true,
  34. Compress: true,
  35. ShouldReconnectOnError: true,
  36. }
  37. // If no arguments are passed return the empty Session interface.
  38. // Later I will add default values, if appropriate.
  39. if args == nil {
  40. return
  41. }
  42. // Variables used below when parsing func arguments
  43. var auth, pass string
  44. // Parse passed arguments
  45. for _, arg := range args {
  46. switch v := arg.(type) {
  47. case []string:
  48. if len(v) > 3 {
  49. err = fmt.Errorf("Too many string parameters provided.")
  50. return
  51. }
  52. // First string is either token or username
  53. if len(v) > 0 {
  54. auth = v[0]
  55. }
  56. // If second string exists, it must be a password.
  57. if len(v) > 1 {
  58. pass = v[1]
  59. }
  60. // If third string exists, it must be an auth token.
  61. if len(v) > 2 {
  62. s.Token = v[2]
  63. }
  64. case string:
  65. // First string must be either auth token or username.
  66. // Second string must be a password.
  67. // Only 2 input strings are supported.
  68. if auth == "" {
  69. auth = v
  70. } else if pass == "" {
  71. pass = v
  72. } else if s.Token == "" {
  73. s.Token = v
  74. } else {
  75. err = fmt.Errorf("Too many string parameters provided.")
  76. return
  77. }
  78. // case Config:
  79. // TODO: Parse configuration
  80. default:
  81. err = fmt.Errorf("Unsupported parameter type provided.")
  82. return
  83. }
  84. }
  85. // If only one string was provided, assume it is an auth token.
  86. // Otherwise get auth token from Discord, if a token was specified
  87. // Discord will verify it for free, or log the user in if it is
  88. // invalid.
  89. if pass == "" {
  90. s.Token = auth
  91. } else {
  92. err = s.Login(auth, pass)
  93. if err != nil || s.Token == "" {
  94. err = fmt.Errorf("Unable to fetch discord authentication token. %v", err)
  95. return
  96. }
  97. }
  98. // The Session is now able to have RestAPI methods called on it.
  99. // It is recommended that you now call Open() so that events will trigger.
  100. return
  101. }
  102. // AddHandler allows you to add an event handler that will be fired anytime
  103. // the given event is triggered.
  104. func (s *Session) AddHandler(handler interface{}) {
  105. s.initialize()
  106. handlerType := reflect.TypeOf(handler)
  107. if handlerType.NumIn() != 2 {
  108. panic("Unable to add event handler, handler must be of the type func(*discordgo.Session, *discordgo.EventType).")
  109. }
  110. if handlerType.In(0) != reflect.TypeOf(s) {
  111. panic("Unable to add event handler, first argument must be of type *discordgo.Session.")
  112. }
  113. s.Lock()
  114. defer s.Unlock()
  115. eventType := handlerType.In(1)
  116. // Support handlers of type interface{}, this is a special handler, which is triggered on every event.
  117. if eventType.Kind() == reflect.Interface {
  118. eventType = nil
  119. }
  120. handlers := s.handlers[eventType]
  121. if handlers == nil {
  122. handlers = []reflect.Value{}
  123. }
  124. s.handlers[eventType] = append(handlers, reflect.ValueOf(handler))
  125. }
  126. func (s *Session) handle(event interface{}) {
  127. s.initialize()
  128. s.RLock()
  129. defer s.RUnlock()
  130. handlerParameters := []reflect.Value{reflect.ValueOf(s), reflect.ValueOf(event)}
  131. if handlers, ok := s.handlers[reflect.TypeOf(event)]; ok {
  132. for _, handler := range handlers {
  133. handler.Call(handlerParameters)
  134. }
  135. }
  136. if handlers, ok := s.handlers[nil]; ok {
  137. for _, handler := range handlers {
  138. handler.Call(handlerParameters)
  139. }
  140. }
  141. }
  142. // initialize adds all internal handlers and state tracking handlers.
  143. func (s *Session) initialize() {
  144. s.Lock()
  145. if s.handlers != nil {
  146. s.Unlock()
  147. return
  148. }
  149. s.handlers = map[interface{}][]reflect.Value{}
  150. s.Unlock()
  151. s.AddHandler(s.onEvent)
  152. s.AddHandler(s.onReady)
  153. s.AddHandler(s.onVoiceServerUpdate)
  154. s.AddHandler(s.onVoiceStateUpdate)
  155. s.AddHandler(s.State.onInterface)
  156. }
  157. // onEvent handles events that are unhandled or errored while unmarshalling
  158. func (s *Session) onEvent(se *Session, e *Event) {
  159. printEvent(e)
  160. }
  161. // onReady handles the ready event.
  162. func (s *Session) onReady(se *Session, r *Ready) {
  163. go s.heartbeat(s.wsConn, s.listening, r.HeartbeatInterval)
  164. }