bocoup / chatter

A collection of useful primitives for creating interactive chat bots.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pass arbitrary additional arguments into message handlers

cowboy opened this issue · comments

Right now, if we want to pass per-cached-handler state into message handlers, we need to do something like this:

function getSubCommand(state) {
  return createCommand({name: 'sub'}, message => {
    // do something with message and state
  });
}

const myBot = createBot({
  createMessageHandler() {
    const state = {foo: 1};
    const messageHandler = createCommand({}, [
      getSubCommand(state),
    ]);
    messageHandler.hasState = true;
    return messageHandler;
  },
});

It would be nice if we could do something like this instead:

const subCommand = createCommand({name: 'sub'}, (message, state) => {
  // do something with message and state
});

const myBot = createBot({
  createMessageHandler() {
    const state = {foo: 1};
    const messageHandler = createCommand({
      adjustArgs(message) {
        return [message, state];
      },
    }, [
      subCommand,
    ]);
    messageHandler.hasState = true;
    return messageHandler;
  },
});

I strongly disagree. The language itself provides this functionality (closures), I don't see the value in adding complexity to the API for this.

I'm thinking more about authoring the child message handlers. It might be nice to be able to author a message handler in such a way as to allow it to not know anything about where it's getting its state from. Oh, another argument I can use? Sweet.

okay, good point, you're right!

I'm thinking about creating an args-specific message handler where the code might look like this:

const subCommand = createCommand({name: 'sub'}, (message, state) => {
  // do something with message and state
});

const myBot = createBot({
  createMessageHandler() {
    const state = {foo: 1};
    const messageHandler = createArgsAdjuster({
      adjustArgs(message) {
        return [message, state];
      },
    }, createCommand({}, [
      subCommand,
    ]));
    messageHandler.hasState = true;
    return messageHandler;
  },
});