discord.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.14.0-dev"
  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. // IF THE TOKEN IS FOR A BOT, IT MUST BE PREFIXED WITH `BOT `
  25. // eg: `"Bot <token>"`
  26. // With an email and password - Discord will sign in with the provided
  27. // credentials.
  28. // With an email, password and auth token - Discord will verify the auth
  29. // token, if it is invalid it will sign in with the provided
  30. // credentials. This is the Discord recommended way to sign in.
  31. func New(args ...interface{}) (s *Session, err error) {
  32. // Create an empty Session interface.
  33. s = &Session{
  34. State: NewState(),
  35. ratelimiter: NewRatelimiter(),
  36. StateEnabled: true,
  37. Compress: true,
  38. ShouldReconnectOnError: true,
  39. ShardID: 0,
  40. ShardCount: 1,
  41. MaxRestRetries: 3,
  42. }
  43. // If no arguments are passed return the empty Session interface.
  44. if args == nil {
  45. return
  46. }
  47. // Variables used below when parsing func arguments
  48. var auth, pass string
  49. // Parse passed arguments
  50. for _, arg := range args {
  51. switch v := arg.(type) {
  52. case []string:
  53. if len(v) > 3 {
  54. err = fmt.Errorf("Too many string parameters provided.")
  55. return
  56. }
  57. // First string is either token or username
  58. if len(v) > 0 {
  59. auth = v[0]
  60. }
  61. // If second string exists, it must be a password.
  62. if len(v) > 1 {
  63. pass = v[1]
  64. }
  65. // If third string exists, it must be an auth token.
  66. if len(v) > 2 {
  67. s.Token = v[2]
  68. }
  69. case string:
  70. // First string must be either auth token or username.
  71. // Second string must be a password.
  72. // Only 2 input strings are supported.
  73. if auth == "" {
  74. auth = v
  75. } else if pass == "" {
  76. pass = v
  77. } else if s.Token == "" {
  78. s.Token = v
  79. } else {
  80. err = fmt.Errorf("Too many string parameters provided.")
  81. return
  82. }
  83. // case Config:
  84. // TODO: Parse configuration struct
  85. default:
  86. err = fmt.Errorf("Unsupported parameter type provided.")
  87. return
  88. }
  89. }
  90. // If only one string was provided, assume it is an auth token.
  91. // Otherwise get auth token from Discord, if a token was specified
  92. // Discord will verify it for free, or log the user in if it is
  93. // invalid.
  94. if pass == "" {
  95. s.Token = auth
  96. } else {
  97. err = s.Login(auth, pass)
  98. if err != nil || s.Token == "" {
  99. err = fmt.Errorf("Unable to fetch discord authentication token. %v", err)
  100. return
  101. }
  102. }
  103. // The Session is now able to have RestAPI methods called on it.
  104. // It is recommended that you now call Open() so that events will trigger.
  105. return
  106. }
  107. // validateHandler takes an event handler func, and returns the type of event.
  108. // eg.
  109. // Session.validateHandler(func (s *discordgo.Session, m *discordgo.MessageCreate))
  110. // will return the reflect.Type of *discordgo.MessageCreate
  111. func (s *Session) validateHandler(handler interface{}) reflect.Type {
  112. handlerType := reflect.TypeOf(handler)
  113. if handlerType.NumIn() != 2 {
  114. panic("Unable to add event handler, handler must be of the type func(*discordgo.Session, *discordgo.EventType).")
  115. }
  116. if handlerType.In(0) != reflect.TypeOf(s) {
  117. panic("Unable to add event handler, first argument must be of type *discordgo.Session.")
  118. }
  119. eventType := handlerType.In(1)
  120. // Support handlers of type interface{}, this is a special handler, which is triggered on every event.
  121. if eventType.Kind() == reflect.Interface {
  122. eventType = nil
  123. }
  124. return eventType
  125. }
  126. // AddHandler allows you to add an event handler that will be fired anytime
  127. // the Discord WSAPI event that matches the interface fires.
  128. // eventToInterface in events.go has a list of all the Discord WSAPI events
  129. // and their respective interface.
  130. // eg:
  131. // Session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
  132. // })
  133. //
  134. // or:
  135. // Session.AddHandler(func(s *discordgo.Session, m *discordgo.PresenceUpdate) {
  136. // })
  137. // The return value of this method is a function, that when called will remove the
  138. // event handler.
  139. func (s *Session) AddHandler(handler interface{}) func() {
  140. s.initialize()
  141. eventType := s.validateHandler(handler)
  142. s.handlersMu.Lock()
  143. defer s.handlersMu.Unlock()
  144. h := reflect.ValueOf(handler)
  145. s.handlers[eventType] = append(s.handlers[eventType], h)
  146. // This must be done as we need a consistent reference to the
  147. // reflected value, otherwise a RemoveHandler method would have
  148. // been nice.
  149. return func() {
  150. s.handlersMu.Lock()
  151. defer s.handlersMu.Unlock()
  152. handlers := s.handlers[eventType]
  153. for i, v := range handlers {
  154. if h == v {
  155. s.handlers[eventType] = append(handlers[:i], handlers[i+1:]...)
  156. return
  157. }
  158. }
  159. }
  160. }
  161. // handle calls any handlers that match the event type and any handlers of
  162. // interface{}.
  163. func (s *Session) handle(event interface{}) {
  164. s.handlersMu.RLock()
  165. defer s.handlersMu.RUnlock()
  166. if s.handlers == nil {
  167. return
  168. }
  169. handlerParameters := []reflect.Value{reflect.ValueOf(s), reflect.ValueOf(event)}
  170. s.onInterface(event)
  171. if handlers, ok := s.handlers[nil]; ok {
  172. for _, handler := range handlers {
  173. go handler.Call(handlerParameters)
  174. }
  175. }
  176. if handlers, ok := s.handlers[reflect.TypeOf(event)]; ok {
  177. for _, handler := range handlers {
  178. go handler.Call(handlerParameters)
  179. }
  180. }
  181. }
  182. // initialize adds all internal handlers and state tracking handlers.
  183. func (s *Session) initialize() {
  184. s.log(LogInformational, "called")
  185. s.handlersMu.Lock()
  186. defer s.handlersMu.Unlock()
  187. if s.handlers != nil {
  188. return
  189. }
  190. s.handlers = map[interface{}][]reflect.Value{}
  191. }
  192. // onInterface handles all internal events and routes them to the appropriate internal handler.
  193. func (s *Session) onInterface(i interface{}) {
  194. switch t := i.(type) {
  195. case *Ready:
  196. s.onReady(t)
  197. case *Resumed:
  198. s.onResumed(t)
  199. case *VoiceServerUpdate:
  200. go s.onVoiceServerUpdate(t)
  201. case *VoiceStateUpdate:
  202. go s.onVoiceStateUpdate(t)
  203. }
  204. s.State.onInterface(s, i)
  205. }
  206. // onReady handles the ready event.
  207. func (s *Session) onReady(r *Ready) {
  208. // Store the SessionID within the Session struct.
  209. s.sessionID = r.SessionID
  210. // Start the heartbeat to keep the connection alive.
  211. go s.heartbeat(s.wsConn, s.listening, r.HeartbeatInterval)
  212. }
  213. // onResumed handles the resumed event.
  214. func (s *Session) onResumed(r *Resumed) {
  215. // Start the heartbeat to keep the connection alive.
  216. go s.heartbeat(s.wsConn, s.listening, r.HeartbeatInterval)
  217. }