github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/client/event.go (about)

     1  package client
     2  
     3  // from https://github.com/Mrs4s/MiraiGo/blob/master/client/events.go
     4  
     5  import (
     6  	"runtime/debug"
     7  	"sync"
     8  )
     9  
    10  // protected all EventHandle, since write is very rare, use
    11  // only one lock to save memory
    12  var eventMu sync.RWMutex
    13  
    14  type EventHandle[T any] struct {
    15  	// QQClient?
    16  	handlers []func(client *QQClient, event T)
    17  }
    18  
    19  func (handle *EventHandle[T]) Subscribe(handler func(client *QQClient, event T)) {
    20  	eventMu.Lock()
    21  	defer eventMu.Unlock()
    22  	// shrink the slice
    23  	newHandlers := make([]func(client *QQClient, event T), len(handle.handlers)+1)
    24  	copy(newHandlers, handle.handlers)
    25  	newHandlers[len(handle.handlers)] = handler
    26  	handle.handlers = newHandlers
    27  }
    28  
    29  func (handle *EventHandle[T]) dispatch(client *QQClient, event T) {
    30  	eventMu.RLock()
    31  	defer func() {
    32  		eventMu.RUnlock()
    33  		if pan := recover(); pan != nil {
    34  			client.error("event error: %v\n%s", pan, debug.Stack())
    35  		}
    36  	}()
    37  	for _, handler := range handle.handlers {
    38  		handler(client, event)
    39  	}
    40  }
    41  
    42  type eventHandlers struct {
    43  	subscribedEventHandlers     []any
    44  	groupMessageReceiptHandlers sync.Map
    45  }
    46  
    47  func (c *QQClient) SubscribeEventHandler(handler any) {
    48  	c.eventHandlers.subscribedEventHandlers = append(c.eventHandlers.subscribedEventHandlers, handler)
    49  }
    50  
    51  func (c *QQClient) onGroupMessageReceipt(id string, f ...func(*QQClient, *groupMessageReceiptEvent)) {
    52  	if len(f) == 0 {
    53  		c.eventHandlers.groupMessageReceiptHandlers.Delete(id)
    54  		return
    55  	}
    56  	c.eventHandlers.groupMessageReceiptHandlers.LoadOrStore(id, f[0])
    57  }