Skip to content

Instantly share code, notes, and snippets.

@sudojunior
Created November 22, 2021 20:05
Show Gist options
  • Save sudojunior/e720cc1083c08d1258e9835d692b49b1 to your computer and use it in GitHub Desktop.
Save sudojunior/e720cc1083c08d1258e9835d692b49b1 to your computer and use it in GitHub Desktop.
The initial idea for wildcard components, contained within a class and with self-removal (made specifically for ephemeral components at the time, https://github.com/TinkerStorm/story-engine/commit/eda121e934d8aaeb3dbec96235cd5134b32b1368#diff-c5149d754d0b17617d7ea33dad86ed50b7fd50924ef1e86be57c143f4073aa0b).
import { ComponentContext, SlashCreator } from "slash-create";
export default class ComponentWildcard {
cache: Map<string, {
eventKeys: string[],
id: string,
callback: WildcardCallback
}> = new Map();
constructor(public creator: SlashCreator) {
this.creator.on('componentInteraction', this.listen.bind(this));
}
private async listen(ctx: ComponentContext) {
const { id } = ctx.message;
const cache = this.cache.get(id);
if (!cache) return;
const { eventKeys, callback } = cache;
if (!eventKeys.includes(ctx.customID)) return;
this.unregister(id);
await callback(ctx, ctx.customID);
}
public register(id: string, eventKeys: string[], callback: WildcardCallback) {
this.cache.set(id, { eventKeys, id, callback });
}
public unregister(id: string) {
this.cache.delete(id);
}
}
export type WildcardCallback = (ctx: ComponentContext, eventKey: string) => void | Promise<void>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment