discord.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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.13.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. if args == nil {
  39. return
  40. }
  41. // Variables used below when parsing func arguments
  42. var auth, pass string
  43. // Parse passed arguments
  44. for _, arg := range args {
  45. switch v := arg.(type) {
  46. case []string:
  47. if len(v) > 3 {
  48. err = fmt.Errorf("Too many string parameters provided.")
  49. return
  50. }
  51. // First string is either token or username
  52. if len(v) > 0 {
  53. auth = v[0]
  54. }
  55. // If second string exists, it must be a password.
  56. if len(v) > 1 {
  57. pass = v[1]
  58. }
  59. // If third string exists, it must be an auth token.
  60. if len(v) > 2 {
  61. s.Token = v[2]
  62. }
  63. case string:
  64. // First string must be either auth token or username.
  65. // Second string must be a password.
  66. // Only 2 input strings are supported.
  67. if auth == "" {
  68. auth = v
  69. } else if pass == "" {
  70. pass = v
  71. } else if s.Token == "" {
  72. s.Token = v
  73. } else {
  74. err = fmt.Errorf("Too many string parameters provided.")
  75. return
  76. }
  77. // case Config:
  78. // TODO: Parse configuration struct
  79. default:
  80. err = fmt.Errorf("Unsupported parameter type provided.")
  81. return
  82. }
  83. }
  84. // If only one string was provided, assume it is an auth token.
  85. // Otherwise get auth token from Discord, if a token was specified
  86. // Discord will verify it for free, or log the user in if it is
  87. // invalid.
  88. if pass == "" {
  89. s.Token = auth
  90. } else {
  91. err = s.Login(auth, pass)
  92. if err != nil || s.Token == "" {
  93. err = fmt.Errorf("Unable to fetch discord authentication token. %v", err)
  94. return
  95. }
  96. }
  97. // The Session is now able to have RestAPI methods called on it.
  98. // It is recommended that you now call Open() so that events will trigger.
  99. return
  100. }
  101. // validateHandler takes an event handler func, and returns the type of event.
  102. // eg.
  103. // Session.validateHandler(func (s *discordgo.Session, m *discordgo.MessageCreate))
  104. // will return the reflect.Type of *discordgo.MessageCreate
  105. func (s *Session) validateHandler(handler interface{}) reflect.Type {
  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. eventType := handlerType.In(1)
  114. // Support handlers of type interface{}, this is a special handler, which is triggered on every event.
  115. if eventType.Kind() == reflect.Interface {
  116. eventType = nil
  117. }
  118. return eventType
  119. }
  120. // AddHandler allows you to add an event handler that will be fired anytime
  121. // the Discord WSAPI event that matches the interface fires.
  122. // eventToInterface in events.go has a list of all the Discord WSAPI events
  123. // and their respective interface.
  124. // eg:
  125. // Session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
  126. // })
  127. //
  128. // or:
  129. // Session.AddHandler(func(s *discordgo.Session, m *discordgo.PresenceUpdate) {
  130. // })
  131. // The return value of this method is a function, that when called will remove the
  132. // event handler.
  133. func (s *Session) AddHandler(handler interface{}) func() {
  134. s.initialize()
  135. eventType := s.validateHandler(handler)
  136. s.handlersMu.Lock()
  137. defer s.handlersMu.Unlock()
  138. h := reflect.ValueOf(handler)
  139. s.handlers[eventType] = append(s.handlers[eventType], h)
  140. // This must be done as we need a consistent reference to the
  141. // reflected value, otherwise a RemoveHandler method would have
  142. // been nice.
  143. return func() {
  144. s.handlersMu.Lock()
  145. defer s.handlersMu.Unlock()
  146. handlers := s.handlers[eventType]
  147. for i, v := range handlers {
  148. if h == v {
  149. s.handlers[eventType] = append(handlers[:i], handlers[i+1:]...)
  150. return
  151. }
  152. }
  153. }
  154. }
  155. // handle calls any handlers that match the event type and any handlers of
  156. // interface{}.
  157. func (s *Session) handle(event interface{}) {
  158. s.handlersMu.RLock()
  159. defer s.handlersMu.RUnlock()
  160. if s.handlers == nil {
  161. return
  162. }
  163. handlerParameters := []reflect.Value{reflect.ValueOf(s), reflect.ValueOf(event)}
  164. if handlers, ok := s.handlers[nil]; ok {
  165. for _, handler := range handlers {
  166. handler.Call(handlerParameters)
  167. }
  168. }
  169. if handlers, ok := s.handlers[reflect.TypeOf(event)]; ok {
  170. for _, handler := range handlers {
  171. handler.Call(handlerParameters)
  172. }
  173. }
  174. }
  175. // initialize adds all internal handlers and state tracking handlers.
  176. func (s *Session) initialize() {
  177. s.handlersMu.Lock()
  178. if s.handlers != nil {
  179. s.handlersMu.Unlock()
  180. return
  181. }
  182. s.handlers = map[interface{}][]reflect.Value{}
  183. s.handlersMu.Unlock()
  184. s.AddHandler(s.onReady)
  185. s.AddHandler(s.onVoiceServerUpdate)
  186. s.AddHandler(s.onVoiceStateUpdate)
  187. s.AddHandler(s.State.onInterface)
  188. }
  189. // onReady handles the ready event.
  190. func (s *Session) onReady(se *Session, r *Ready) {
  191. go s.heartbeat(s.wsConn, s.listening, r.HeartbeatInterval)
  192. }