matrix-org / go-neb

Extensible matrix bot written in Go
Apache License 2.0
284 stars 91 forks source link

Allow services to access Syncer objects #201

Open anoadragon453 opened 7 years ago

anoadragon453 commented 7 years ago

Currently there is no way for services/plugins to react to events in the sync stream. We currently do so in some parts of Go-NEB, but services are not able to access it.

Passing a pointer to the syncer object to the service would allow it to listen and process any event on demand. Is this possible with the current architecture?

alextov commented 6 years ago

@anoadragon453 Here is how I solved this issue:

  1. I forked this repository.
  2. I added EventTypeHandlers(cli *gomatrix.Client) map[string]func(*gomatrix.Event) method to types.Service interface and its default no-op implementation to types.DefaultService struct.
  3. In clients.go file, right after the block you referred to in your comment, I added the following:

    services, err := c.db.LoadServicesForUser(client.UserID)
    if err != nil {
        log.WithFields(log.Fields{
            log.ErrorKey:      err,
            "service_user_id": client.UserID,
        }).Warn("Error loading services")
    }
    
    for _, service := range services {
        for eventType, handler := range service.EventTypeHandlers(client) {
            syncer.OnEventType(eventType, handler)
        }
    }
  4. In my main service file, I added EventTypeHandlers method implementation to my Service struct:
    // EventTypeHandlers returns custom handlers for Matrix event types.
    func (s *Service) EventTypeHandlers(client *gomatrix.Client) map[string]func(*gomatrix.Event) {
    return map[string]func(*gomatrix.Event){
        "m.room.message": func(event *gomatrix.Event) {
            // custom event handling logic goes here
        },
    }
    }

This solution works for my particular use case, but I didn’t look through the code very thoroughly and I can’t guarantee that it doesn’t break anything. Also, I have very little experience with Go. For these reasons, I didn’t want to make a pull request directly, but I hope that my snippets can be useful to someone.

anoadragon453 commented 6 years ago

Great, good to know thanks!