github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/event.go (about)

     1  package discordgo
     2  
     3  // EventHandler is an interface for Discord events.
     4  type EventHandler interface {
     5  	// Type returns the type of event this handler belongs to.
     6  	Type() string
     7  
     8  	// Handle is called whenever an event of Type() happens.
     9  	// It is the receivers responsibility to type assert that the interface
    10  	// is the expected struct.
    11  	Handle(*Session, interface{})
    12  }
    13  
    14  // EventInterfaceProvider is an interface for providing empty interfaces for
    15  // Discord events.
    16  type EventInterfaceProvider interface {
    17  	// Type is the type of event this handler belongs to.
    18  	Type() string
    19  
    20  	// New returns a new instance of the struct this event handler handles.
    21  	// This is called once per event.
    22  	// The struct is provided to all handlers of the same Type().
    23  	New() interface{}
    24  }
    25  
    26  // interfaceEventType is the event handler type for interface{} events.
    27  const interfaceEventType = "__INTERFACE__"
    28  
    29  // interfaceEventHandler is an event handler for interface{} events.
    30  type interfaceEventHandler func(*Session, interface{})
    31  
    32  // Type returns the event type for interface{} events.
    33  func (eh interfaceEventHandler) Type() string {
    34  	return interfaceEventType
    35  }
    36  
    37  // Handle is the handler for an interface{} event.
    38  func (eh interfaceEventHandler) Handle(s *Session, i interface{}) {
    39  	eh(s, i)
    40  }
    41  
    42  var registeredInterfaceProviders = map[string]EventInterfaceProvider{}
    43  
    44  // registerInterfaceProvider registers a provider so that DiscordGo can
    45  // access it's New() method.
    46  func registerInterfaceProvider(eh EventInterfaceProvider) {
    47  	if _, ok := registeredInterfaceProviders[eh.Type()]; ok {
    48  		return
    49  		// XXX:
    50  		// if we should error here, we need to do something with it.
    51  		// fmt.Errorf("event %s already registered", eh.Type())
    52  	}
    53  	registeredInterfaceProviders[eh.Type()] = eh
    54  	return
    55  }
    56  
    57  // eventHandlerInstance is a wrapper around an event handler, as functions
    58  // cannot be compared directly.
    59  type eventHandlerInstance struct {
    60  	eventHandler EventHandler
    61  }
    62  
    63  // addEventHandler adds an event handler that will be fired anytime
    64  // the Discord WSAPI matching eventHandler.Type() fires.
    65  func (s *Session) addEventHandler(eventHandler EventHandler) func() {
    66  	s.handlersMu.Lock()
    67  	defer s.handlersMu.Unlock()
    68  
    69  	if s.handlers == nil {
    70  		s.handlers = map[string][]*eventHandlerInstance{}
    71  	}
    72  
    73  	ehi := &eventHandlerInstance{eventHandler}
    74  	s.handlers[eventHandler.Type()] = append(s.handlers[eventHandler.Type()], ehi)
    75  
    76  	return func() {
    77  		s.removeEventHandlerInstance(eventHandler.Type(), ehi)
    78  	}
    79  }
    80  
    81  // addEventHandler adds an event handler that will be fired the next time
    82  // the Discord WSAPI matching eventHandler.Type() fires.
    83  func (s *Session) addEventHandlerOnce(eventHandler EventHandler) func() {
    84  	s.handlersMu.Lock()
    85  	defer s.handlersMu.Unlock()
    86  
    87  	if s.onceHandlers == nil {
    88  		s.onceHandlers = map[string][]*eventHandlerInstance{}
    89  	}
    90  
    91  	ehi := &eventHandlerInstance{eventHandler}
    92  	s.onceHandlers[eventHandler.Type()] = append(s.onceHandlers[eventHandler.Type()], ehi)
    93  
    94  	return func() {
    95  		s.removeEventHandlerInstance(eventHandler.Type(), ehi)
    96  	}
    97  }
    98  
    99  // AddHandler allows you to add an event handler that will be fired anytime
   100  // the Discord WSAPI event that matches the function fires.
   101  // The first parameter is a *Session, and the second parameter is a pointer
   102  // to a struct corresponding to the event for which you want to listen.
   103  //
   104  // eg:
   105  //     Session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
   106  //     })
   107  //
   108  // or:
   109  //     Session.AddHandler(func(s *discordgo.Session, m *discordgo.PresenceUpdate) {
   110  //     })
   111  //
   112  // List of events can be found at this page, with corresponding names in the
   113  // library for each event: https://discord.com/developers/docs/topics/gateway#event-names
   114  // There are also synthetic events fired by the library internally which are
   115  // available for handling, like Connect, Disconnect, and RateLimit.
   116  // events.go contains all of the Discord WSAPI and synthetic events that can be handled.
   117  //
   118  // The return value of this method is a function, that when called will remove the
   119  // event handler.
   120  func (s *Session) AddHandler(handler interface{}) func() {
   121  	eh := handlerForInterface(handler)
   122  
   123  	if eh == nil {
   124  		s.log(LogError, "Invalid handler type, handler will never be called")
   125  		return func() {}
   126  	}
   127  
   128  	return s.addEventHandler(eh)
   129  }
   130  
   131  // AddHandlerOnce allows you to add an event handler that will be fired the next time
   132  // the Discord WSAPI event that matches the function fires.
   133  // See AddHandler for more details.
   134  func (s *Session) AddHandlerOnce(handler interface{}) func() {
   135  	eh := handlerForInterface(handler)
   136  
   137  	if eh == nil {
   138  		s.log(LogError, "Invalid handler type, handler will never be called")
   139  		return func() {}
   140  	}
   141  
   142  	return s.addEventHandlerOnce(eh)
   143  }
   144  
   145  // removeEventHandler instance removes an event handler instance.
   146  func (s *Session) removeEventHandlerInstance(t string, ehi *eventHandlerInstance) {
   147  	s.handlersMu.Lock()
   148  	defer s.handlersMu.Unlock()
   149  
   150  	handlers := s.handlers[t]
   151  	for i := range handlers {
   152  		if handlers[i] == ehi {
   153  			s.handlers[t] = append(handlers[:i], handlers[i+1:]...)
   154  		}
   155  	}
   156  
   157  	onceHandlers := s.onceHandlers[t]
   158  	for i := range onceHandlers {
   159  		if onceHandlers[i] == ehi {
   160  			s.onceHandlers[t] = append(onceHandlers[:i], onceHandlers[i+1:]...)
   161  		}
   162  	}
   163  }
   164  
   165  // Handles calling permanent and once handlers for an event type.
   166  func (s *Session) handle(t string, i interface{}) {
   167  	for _, eh := range s.handlers[t] {
   168  		if s.SyncEvents {
   169  			eh.eventHandler.Handle(s, i)
   170  		} else {
   171  			go eh.eventHandler.Handle(s, i)
   172  		}
   173  	}
   174  
   175  	if len(s.onceHandlers[t]) > 0 {
   176  		for _, eh := range s.onceHandlers[t] {
   177  			if s.SyncEvents {
   178  				eh.eventHandler.Handle(s, i)
   179  			} else {
   180  				go eh.eventHandler.Handle(s, i)
   181  			}
   182  		}
   183  		s.onceHandlers[t] = nil
   184  	}
   185  }
   186  
   187  // Handles an event type by calling internal methods, firing handlers and firing the
   188  // interface{} event.
   189  func (s *Session) handleEvent(t string, i interface{}) {
   190  	s.handlersMu.RLock()
   191  	defer s.handlersMu.RUnlock()
   192  
   193  	// All events are dispatched internally first.
   194  	s.onInterface(i)
   195  
   196  	// Then they are dispatched to anyone handling interface{} events.
   197  	s.handle(interfaceEventType, i)
   198  
   199  	// Finally they are dispatched to any typed handlers.
   200  	s.handle(t, i)
   201  }
   202  
   203  // setGuildIds will set the GuildID on all the members of a guild.
   204  // This is done as event data does not have it set.
   205  func setGuildIds(g *Guild) {
   206  	for _, c := range g.Channels {
   207  		c.GuildID = g.ID
   208  	}
   209  
   210  	for _, m := range g.Members {
   211  		m.GuildID = g.ID
   212  	}
   213  
   214  	for _, vs := range g.VoiceStates {
   215  		vs.GuildID = g.ID
   216  	}
   217  }
   218  
   219  // onInterface handles all internal events and routes them to the appropriate internal handler.
   220  func (s *Session) onInterface(i interface{}) {
   221  	switch t := i.(type) {
   222  	case *Ready:
   223  		for _, g := range t.Guilds {
   224  			setGuildIds(g)
   225  		}
   226  		s.onReady(t)
   227  	case *GuildCreate:
   228  		setGuildIds(t.Guild)
   229  	case *GuildUpdate:
   230  		setGuildIds(t.Guild)
   231  	case *VoiceServerUpdate:
   232  		go s.onVoiceServerUpdate(t)
   233  	case *VoiceStateUpdate:
   234  		go s.onVoiceStateUpdate(t)
   235  	}
   236  	err := s.State.OnInterface(s, i)
   237  	if err != nil {
   238  		s.log(LogDebug, "error dispatching internal event, %s", err)
   239  	}
   240  }
   241  
   242  // onReady handles the ready event.
   243  func (s *Session) onReady(r *Ready) {
   244  
   245  	// Store the SessionID within the Session struct.
   246  	s.sessionID = r.SessionID
   247  }