On This Page

Events and Collectors

55 symbols from @neontechspace/fluxerly/effect

Interfaces#

Collector#

A running message collector registered in a Scope

Use close to end collection and result to receive its result after cleanup

interface Collector<M extends MessageCore = Message>interface Collector<
  M extends MessageCore = Message
>

close#

Stop accepting messages now, keeping accepted messages for a successful partial result

Repeated calls preserve whichever terminal outcome was recorded first. Use result to await callback cleanup and read the collection

close(): Effect<void>
Returns
Effect<void>

Stops collection when the Effect executes

result#

Wait for the final frozen collection result after timer, queue, filter, listener and callback cleanup

Idle, timeout or stop can succeed with no messages or a partial collection. Collection cancellation, filter or callback failure, overflow, gateway loss and client closure fail without partial messages. Multiple or later waiters receive the same collection outcome. Cancelling this wait affects only the waiter, not collection. Keeping the handle or successful result keeps its message snapshots in memory

result(): Effect<CollectorResult<M>, CollectorFailure>result(): Effect<
  CollectorResult<M>,
  CollectorFailure
>

Defects keep their Cause

CollectorOptions#

Choose which new messages to collect in one channel and when to stop

Connect the client before registering. Collection does not read history or connect automatically. Only messageCreate observations are collected, using this client's selected message fields. Each accepted message ID is counted once. Later edits and deletions do not revise the result. Reaching the count or a listening deadline can finish successfully. Filter, handler, budget and connection failures return no partial result. For sharded clients, a shard is one gateway connection assigned to a group of communities

interface CollectorOptions<
    E = never,
    R = never,
    M extends MessageCore = Message
>
    extends EventBufferOptionsinterface CollectorOptions<
  E = never,
  R = never,
  M extends MessageCore = Message
>
  extends EventBufferOptions

The onMessage callback executes with the services available when collection is registered

filter optional#

Return true to accept a message, or false to skip it

Omit to accept all messages in the channel, including bots. Runs synchronously in receive order, after channel selection. Do not return a Promise or perform blocking work. Throwing or returning anything except a boolean fails this collector with reason filter. A thrown value is the CollectorError cause. The failure is also reported to the client-level onError with kind filter and the message IDs, or logged at Error. Asynchronous work returned by mistake is neither awaited nor cancelled, and its rejection is discarded. A slow filter blocks other JavaScript work. The collector checks its deadlines again after the filter returns

(message: M) => boolean
guildId optional#

Community that owns this channel, as a positive decimal ID within the unsigned 64-bit range

The caller must supply the correct community, because the SDK does not fetch the channel to verify membership. Its assigned gateway shard must be connected. Recovery of that shard ends collection, while unrelated shards do not. Events with a different supplied guildId are discarded. Missing community context does not prove the channel is private. Omit this option for unknown or private scope. Then the whole gateway must be connected and any shard recovery ends collection

string
idleMs optional#

Stop successfully after this many milliseconds without an accepted message

Omit to disable this deadline. Integer 1 through 2,147,483,647. The interval starts at registration and resets before each accepted message's callback. Rejected messages, duplicate IDs and messages still queued do not reset it. Callback time counts as idle time. The earlier idle or total deadline wins. Equal deadlines produce reason timeout

number
maxBytes optional#

Maximum UTF-8 JSON bytes kept for accepted messages

Positive safe integer, default 4,194,304, not a total memory limit

number
maxMessages optional#

Stop successfully after this many accepted messages and their callbacks

Positive safe integer, default 1

number
onMessage optional#

Run once per accepted message ID, sequentially, after filtering and stored-byte limit checks

Failures and defects while active fail collection with CollectorError handler, whose cause is the original failure or defect. The failure is also reported to the client-level onError with kind collector, the message IDs and the full Cause, or logged at Error. Stop, timeout, idle completion, scope closure, recovery and shutdown interrupt active work and await its finalizers. Uninterruptible work can delay closure. Do not await this collector's completion or client shutdown inside its handler. Already-dispatched effects are not rolled back. Callbacks are never retried

(message: M) => Effect<unknown, E, R>
timeoutMs optional#

Stop successfully after this many milliseconds from registration, regardless of activity

Integer 1 through 2,147,483,647, default 30,000

number

Inherited from EventBufferOptions: maxPendingBytes, maxPendingMessages

EventHandlerOptions#

Set event-handler queue limits, concurrency, ordering, overflow policy, an optional failure hook and an optional partition readiness hook

Reporting and the readiness hook use the services available when the handler is registered. The type parameter T is the event payload that a partition function receives

interface EventHandlerOptions<E = never, R = never, T = unknown>
    extends HandlerOptions<T>interface EventHandlerOptions<
  E = never, R = never, T = unknown
>
  extends HandlerOptions<T>
onError optional#

Receive this subscription's failures instead of the client-level onError, with the original error and its full Cause

(report: FailureReport) => Effect<unknown, E, R>(report: FailureReport)
  => Effect<unknown, E, R>

A failure only queues its report, so the hook never holds a handler slot. One worker with the services available at registration delivers reports one at a time in order, with up to 64 waiting while the hook is busy. Later ones are logged instead, with fields.reportOutcome "queueFull", and counted in diagnostics().counters.reportsDropped. A failed or defective hook is logged together with the original failure and is never retried. Reports already queued when the subscription closes are still delivered. Client shutdown interrupts a running hook and waits at most one second for its cleanup, then logs the interrupted and queued reports at Error with fields.reportOutcome "interrupted" or "subscriptionClosed". A hook that interrupts itself also logs its report with "interrupted", and later reports still reach the hook

partitionReady optional#

Hold the events of a partition key until that key is ready, without using a handler slot

Valid only together with partition, otherwise registration dies with ConfigurationError. Before the first waiting event of a key starts, the SDK calls this hook with the key. The key's events stay in the queue until the hook's Effect completes, while events of other keys keep starting. A held event does not use one of the concurrency slots, but it counts toward maxPendingMessages and maxPendingBytes, so a bot that waits for many keys at once needs a larger maxPendingMessages than the default 256. Held events also count as waiting work for a draining shutdown, so a hook that never completes makes the drain wait until its limit. The hook returns an Effect, which the SDK runs with the services available when the handler is registered. An Effect that completes without waiting marks the key ready at once, and one that waits holds the key until it completes. The SDK remembers that a key is ready only while it has waiting or running events. After the key went idle, its next event calls the hook again, so memory stays bounded by the keys with queued work. Hooks for different keys run at the same time, and every burst of events after an idle period calls the hook again. Keep it a cheap, idempotent check that answers at once when the key is already ready, such as an Effect that succeeds at once. Events without a key share the key "", and the hook receives "". With partition "guild", a direct message has no community, so its key is its channel ID. A hook should treat keys it does not know as ready. A hook that fails or dies reports every waiting event of that key as a failure of that event's handler, as a throwing partition function does, and those handlers do not run. The key is then forgotten, so a later event calls the hook again. The hook is interrupted when the subscription stops, which includes closing it, client shutdown and a draining shutdown that reaches its drain limit

(key: string) => Effect<unknown, E, R>
TypeScript
import { Effect } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function afterServerSetup(client: Client, setups: Map<string, Effect.Effect<void>>) {
    // A server whose setup is unknown, such as a direct message channel, is ready at once
    return client.on("messageCreate", (message) => Effect.sync(() => void message.content), {
        partition: "guild",
        partitionReady: (key) => setups.get(key) ?? Effect.void,
    })
}

Inherited from HandlerOptions: concurrency, maxPendingBytes, maxPendingMessages, overflow, partition

EventWaitOptions#

Settings for waitFor to receive one future event that passes an optional filter

Waiting does not connect the gateway, read cached history or reconstruct missed events. The queue budgets apply to events received before the wait can take them. Completion, timeout, cancellation and shutdown release the wait's subscription

interface EventWaitOptions<
    K extends EventName,
    M extends MessageCore = Message
>
    extends EventBufferOptionsinterface EventWaitOptions<
  K extends EventName,
  M extends MessageCore = Message
>
  extends EventBufferOptions
filter optional#

Return true to complete with this event, false to keep waiting

Omit to accept the first event. Runs synchronously and can run while the gateway receives events. Keep it short, since deadlines cannot preempt blocking JavaScript. A throw or non-boolean return fails with EventWaitError reason filter. A thrown value is the error's cause. Do not return a Promise. Mistaken asynchronous work is neither awaited nor cancelled, and its rejection is discarded

(event: EventMap<M>[K]) => boolean
timeoutMs optional#

Total milliseconds to wait from registration, an integer from 1 through 2,147,483,647, default 30,000

Expiry fails with EventWaitError reason timeout, rather than returning an empty event

number

Inherited from EventBufferOptions: maxPendingBytes, maxPendingMessages

MiddlewareRegistration#

Remove event middleware registered with client.use before its registration Scope closes

interface MiddlewareRegistration

close#

Stop applying the middleware to invocations that start later

Invocations already running keep their chain. Repeated calls do nothing

close(): Effect<void>
Returns
Effect<void>

ReactionCollector#

A running reaction collector registered in a Scope

Use close to end collection and result to receive its result after cleanup

interface ReactionCollector

close#

Stop accepting additions now and keep accepted observations for a successful partial result

Repeated calls preserve the first recorded outcome. Use result to await callback cleanup and read the observations

close(): Effect<void>
Returns
Effect<void>

Stops collection when the Effect executes

result#

Wait for the final frozen reaction result after queue, timer, filter, listener and callback cleanup

Idle, timeout or stop can succeed with empty or partial observations. Collection cancellation, filter or callback failure, overflow, gateway loss and client shutdown fail without partial observations. Multiple or later waiters receive the same outcome. Cancelling this wait affects only the waiter, not collection. Keeping the handle or successful result retains its snapshots in memory

result(): Effect<ReactionCollectorResult, CollectorFailure>result(): Effect<
  ReactionCollectorResult,
  CollectorFailure
>

Defects keep their Cause

ReactionCollectorOptions#

Choose which new reaction additions to collect on one message and when to stop

This listens to single additions and server batches, not existing reactions, removals or current vote totals. Repeated user and emoji pairs count as separate additions. No unique-user count is maintained. Connect before registering. Registration does not fetch the message, check existing reactors or connect automatically. A shard is one gateway connection assigned to a group of communities, and guildId can restrict collection to its owning shard

interface ReactionCollectorOptions<E = never, R = never>
    extends EventBufferOptionsinterface ReactionCollectorOptions<
  E = never, R = never
>
  extends EventBufferOptions

The onReaction callback executes with the services available when collection is registered

emoji optional#

Collect only this emoji, or omit to accept any emoji

Use any ReactionEmojiInput, including Unicode, custom markup and parsed or received emoji. The SDK normalizes and copies it at registration. Unicode text must match exactly, including skin tone and variation selectors. Custom emoji match by ID even after renaming. A custom input still needs a valid name. Invalid input fails registration with ConfigurationError field emoji, without a request. Matching runs before filter and onReaction, but after the event enters the queue, so other emoji can still fill the pending queue

ReactionEmojiInput
filter optional#

Return true to accept an addition, or false to skip it

Runs after target and optional emoji matching. With both emoji and filter supplied, both must match. Omission accepts every addition passing the emoji selector. Runs synchronously in receive order, then batch order. A throw or non-boolean return fails only this collector with reason filter, and is reported to the client-level onError with kind filter and the message IDs, or logged at Error. Do not return a Promise. Mistaken asynchronous work is not awaited or cancelled, and its rejection is discarded. Slow code blocks JavaScript. Deadlines are checked after the filter returns

(reaction: MessageReaction) => boolean
guildId optional#

Community that owns the target channel, as a positive decimal ID within the unsigned 64-bit range

The caller must supply the correct community, because no channel lookup verifies it. Its assigned gateway shard must be connected. Recovery of that shard ends collection, while unrelated shard recovery does not. Events with a different supplied guildId are discarded. Missing community context does not prove private scope. Omit for private or unknown scope, requiring a connected whole gateway and ending collection on any shard recovery

string
idleMs optional#

Stop successfully after this many milliseconds without an accepted addition

Omit to disable. Integer 1 through 2,147,483,647. Starts at registration and resets before each accepted addition's callback. Excluded emoji, rejected additions and unprocessed queue or batch entries do not reset it. Callback time counts as idle time. Repeated pairs reset the interval when accepted. The earlier idle or total deadline wins, with timeout winning ties

number
maxBytes optional#

Maximum UTF-8 JSON bytes kept for accepted MessageReaction values

Positive safe integer, default 4,194,304, not a total memory limit

number
maxReactions optional#

Stop successfully after this many accepted additions and their callbacks

Repeated pairs count, positive safe integer, default 1

number
onReaction optional#

Run once per accepted addition, sequentially, before continuing collection

Failures and defects while active fail collection with CollectorError handler, whose cause is the original failure or defect. The failure is also reported to the client-level onError with kind collector, the message IDs and the full Cause, or logged at Error. Stop, timeout, idle completion, scope closure, recovery and shutdown interrupt active work and await its finalizers. Uninterruptible work can delay closure. Do not await this collector's completion inside its handler. Already-dispatched effects are not rolled back. Callbacks are never retried

(reaction: MessageReaction) => Effect<unknown, E, R>(reaction: MessageReaction)
  => Effect<unknown, E, R>
timeoutMs optional#

Stop successfully after this many milliseconds from registration

Activity does not extend it, integer 1 through 2,147,483,647, default 30,000

number

Inherited from EventBufferOptions: maxPendingBytes, maxPendingMessages

Subscription#

An event subscription registered in a Scope, independent of the client's connection

Use close to request a stop and waitForClose to wait for handler cleanup

interface Subscription
id#

Identifier of this subscription, such as messageCreate#3, used in failure reports and log records

string

close#

Stop new deliveries, drop queued events and stop running handlers, without waiting for the handler that called close

When queued events are dropped, one events.discarded Debug record reports how many, and diagnostics().counters.eventsDropped.closed counts them

close(): Effect<void>
Returns
Effect<void>

Stops the subscription when the Effect executes and interrupts its handlers

waitForClose#

Wait until this subscription has closed and the SDK has released its queue and listeners

Normal closure succeeds with no value, and overflow fails with EventOverflowError, even for a later waiter. Cancelling this wait affects only the waiter, not the subscription or other waiters. Later waits see the same subscription outcome. Do not await this subscription's own closure from inside its handler

waitForClose(): Effect<void, EventOverflowError>waitForClose(): Effect<
  void, EventOverflowError
>

Handlers or finalizers that disable interruption can delay completion. Unexpected faults remain in the Cause

Type Aliases#

EventMiddleware#

Event middleware for the Effect API, run around each client.on handler invocation that starts after registration

It receives the invocation and a next Effect that runs the rest of the chain and the handler. The next Effect completes when the rest of the chain has finished, whether or not it failed, and never fails. Failures after next are reported by the SDK where they occur, so middleware can time or trace a handler but cannot hide its failure. A failed or defective middleware Effect is reported like a handler failure, with its full Cause

type EventMiddleware<
    M extends MessageCore = Message,
    E = never,
    R = never
> = (invocation: EventInvocation<M>, next: Effect.Effect<void>)
    => Effect.Effect<unknown, E, R>type EventMiddleware<
  M extends MessageCore = Message,
  E = never,
  R = never
> = (
  invocation: EventInvocation<M>,
  next: Effect.Effect<void>
) => Effect.Effect<unknown, E, R>

Re-Exports#

Declared in JavaScript & TypeScript and documented there. Import them from @neontechspace/fluxerly/effect as well

CallCreate#
A private-channel call began or became visible, including initial call state delivered shortly after READY and state recovered after a lost call connection
CallDelete#
A private-channel call ended or became temporarily unavailable
CallUpdate#
Current state of an active private-channel call: Its ringing set, participants and voice region
CallVoiceState#
One participant's connection in a private call, as observed when the call was created or updated
ChannelPinsUpdate#
Notice that a channel's pins changed, without identifying the pinned or unpinned message
CollectorResult#
Messages collected before the count, total deadline, idle deadline or explicit stop ended collection
DirectMessageRecipientChange#
IDs accompanying a private-channel recipient change
EntranceSoundPlay#
A participant's entrance sound started playing in a voice channel or private call they were already connected to
EventBufferOptions#
Limit the waiting queue for one event subscription or collector
EventContext#
Delivery details for one event, passed to on handlers, runBot handlers and event middleware
EventInvocationOf#
One on handler invocation of a specific event type, as seen by event middleware
EventMap#
Event names and payload types accepted by on, events and waitFor
GuildAuditLogEntryCreate#
Audit entry newly written in a community, using the same field names as audit-log requests
GuildChannelUpdateBulk#
Visible channel updates delivered together, not a complete community channel list
GuildCreate#
Frozen community data received with an availability event, plus information about whether this is a new join
GuildDeletion#
Gateway notification that a community is no longer visible to this client
GuildEmojisUpdate#
Custom emoji collection supplied in one community update, frozen in received order
GuildHealthUpdate#
Frozen community-server health notice, without a cache write or automatic reconnect
GuildLifecycleEvents#
Payload types for community availability, configuration and visibility events
GuildStickersUpdate#
Custom sticker collection supplied in one community update, frozen in received order
HandlerOptions#
Queue limits, parallelism, ordering and overflow behavior for one on callback registration
InviteDeleteEvent#
Notice that an invite was deleted, without its former settings
MessageBulkDeletion#
Message IDs deleted together in one channel
MessageDeletion#
Notice identifying one deleted message, not its full contents or a recoverable copy
MessageReaction#
One reaction addition or removal delivered by Fluxer
MessageReactionBatch#
Reaction additions grouped by Fluxer into one messageReactionAddMany event
MessageReactionEmojiRemoval#
Notice that every reaction using one emoji was cleared from a message
ObservedCustomStatus#
A custom status observed in a presence event, kept as Fluxer sent it
ObservedCustomStatusEmoji#
The emoji of an observed custom status
PresenceUpdate#
Account presence reported by Fluxer at one point in time, not a cached or continuously updated status
PresenceUpdateBulk#
Visible online presences grouped into one event after a community becomes available again
PreviousSnapshots#
The cached snapshot that EventContext.previous holds for each event that changes or removes one cached entity, keyed by event name
RawDispatch#
One gateway dispatch as Fluxer sent it, before the SDK decodes or validates its body
ReactionCollectorResult#
Successful observations of reaction additions, not a final vote count
ThreadDeletion#
Identity of a deleted thread, without its former settings or messages, which EventContext.previous can hold from the channel cache
ThreadListSync#
The bot's complete set of active threads in a community, or in some of its channels, as Fluxer replaced it
ThreadMembersUpdate#
Accounts that joined or left one thread, including the bot itself
TypingStart#
Notice that an account began typing, not a lasting indication that it is still typing
VoiceState#
One account's voice connection as observed in a community, without audio or video access
VoiceStateSnapshot#
Visible voice connections supplied when a community becomes available
WebhooksUpdate#
Notice that the webhooks in a channel changed
EventInvocation#
One on handler invocation passed to event middleware
EventName#
Event-name strings accepted by on, events and waitFor in both entry points
ObservedPresenceStatus#
An account status observed in a presence event
PreviousSnapshot#
The type of EventContext.previous for event K: The PreviousSnapshots entry or undefined, and only undefined for an event without one
ThreadCreateEvent#
A thread that was created or that the bot was added to, with whether it was just created