# EventHandler

`class` in `gateway` · v0.9.0

<https://seedcord.org/docs/packages/gateway/0.9.0/classes/event-handler>

Base class for a Discord client event handler.

Pass the event name(s) as the generic, the same one(s) as `@RegisterEvent`. On a single-event handler, read
`this.event` (the payload tuple) directly. On a handler registered for several events, branch with `this.match`,
keyed by event name, since the union of payload tuples is not directly readable.

```ts
abstract class EventHandler<
    Names extends ValidNonInteractionKeys
> extends BaseHandler<ClientEvents[Names]>
```

## Examples

```ts
\@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
class PingPong extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
    async execute() {
        await this.match({
            [Events.MessageCreate]: (message) => message.reply('pong'),
            [Events.MessageUpdate]: (_oldMessage, edited) => edited.reply('pong')
        });
    }
}
```

## Constructors

### constructor

```ts
EventHandler(
    event: ClientEvents[Names],
    core: Core,
    dispatch: DispatchContext
)
```

Constructs a new instance of the `EventHandler` class

## Properties

### core

```ts
readonly core: TCore
```

### dispatch

```ts
protected readonly dispatch: DispatchContext
```

The bag for this dispatch. Each interaction gets its own. Every handler for one event shares a single bag.

### event

```ts
protected readonly event: SingleEventPayload<Names>
```

### logger

```ts
protected readonly logger: Logger
```

### route

```ts
protected readonly route: Names
```

The event that started this dispatch, one of the names in the generic.

## Methods

### execute

```ts
abstract execute(): Promisable<void>
```

Holds the main logic of your handler. The dispatcher calls it after the handler's gates pass, so a
gate that refuses stops `execute()` from running.

### getEvent

```ts
getEvent(): ValidEvent
```

### match

```ts
protected async match<Ret, Cases>(
    cases: OnlyCases<Cases, EventMatchCases<Names, Ret>>
): Promise<MatchResult<Ret, Cases>>
```

Run the case for the current event. Use this only when the handler is registered for several
events. On a single-event handler, read `this.event` directly. On a multi-event handler `this.event` is
`never`, so match is the only way to read the payload.

Provide one case per registered event, keyed by its name, and each case receives that event's own
payload tuple. The cases must cover every event in the generic. A missing event or an unknown key is a
compile error.
