botpress / v12

Botpress OSS – v12
https://v12.botpress.com
GNU Affero General Public License v3.0
78 stars 87 forks source link

[BUG] No access to variables from hook #1582

Closed kusmira closed 2 years ago

kusmira commented 2 years ago

Bug description

Event object in before_outgoing_middleware hook doesn't contain variables.

event.state contains only empty __stacktrace element

console.log(event.state)

results with

{ __stacktrace: [] }

To Reproduce

  1. Create simple node with two actions on enter setVariable _type: temp, name: username, value: bob sendMessage(Text) Hi

Zrzut ekranu 2021-12-29 134445

  1. Create before_outgoing_middleware hook with simple logging code

    console.log(event.state)

    image

  2. Go to emulator, start conversation and check result in logs

    { __stacktrace: [] }

    image

Expected behavior event.state object should contain variable structures like temp, user, ...

Environment

allardy commented 2 years ago

@kusmira Currently the state is not accessible in outgoing events. Since you are creating an "before_outgoing_middleware", the event typings should actually be event: sdk.IO.OutgoingEvent , which doesn't include the state

coatesap commented 2 years ago

This is a problem I've run into today. When modifying outgoing payloads, you often need to do it conditionally, based on the current state.

coatesap commented 2 years ago

@Raid55 - botpress/botpress#11566 doesn't provide state to an outgoing hook, it just corrects the type signature, so I think this should be reopened?

allardy commented 2 years ago

Hello @coatesap , the incoming and outgoing event are unrelated behind the scene. The outgoing event does include the incoming event id however, which could be loaded this way:

   const incomingEvents = await bp.events.findEvents({ direction: 'incoming', id: event.incomingEventId })
    const incomingEvent = incomingEvents[0].event

The state is a different story, it's stored in the dialog session. You might load it with the code snippet below, but i'm not sure it will be really up-to-date, because I think the session is stored after everything is completed (incoming/outgoing).

  const session = await bp
      .database('dialog_sessions')
      .select('*')
      .where({ id: bp.dialog.createId(event) })

If you only need one specific info from the state, maybe you could use the kvs instead ?

coatesap commented 2 years ago

Thanks for the reply @allardy. For my own purposes, I did consider using the KVS instead, but it means you lose convenient access to that data in other areas. As a made-up example, being able to say something like I understand you are {{user.age}} years old in the flow editor is very useful (and works fine currently). But then I'd expect to be able to do something like filter or change the response in an outgoing hook along the lines of if (event.state.user.age < 18) ....

github-actions[bot] commented 2 years ago

Available on v12.26.11