botpress / v12

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

[BUG] How to Access bot memory from actions #679

Closed JijeshP closed 5 years ago

JijeshP commented 5 years ago

Getting bot is not defined error when trying to store some value to bot. user and temp storage working fine.

slvnperron commented 5 years ago

Can you copy/paste some code snippet?

JijeshP commented 5 years ago

@slvnperron

const doSomeAction = async () => {
 try {

user.somevalue = "test"  // works fine
temp.somevalue = "test"  // works fine
bot.somevalue = "test"  // not working

} catch (error) {
  }
}

return doSomeAction();

https://botpress.io/docs/build/memory/

slvnperron commented 5 years ago

@JijeshP thanks, on it

JijeshP commented 5 years ago

@slvnperron Just wanted to store some variable across all users.

slvnperron commented 5 years ago

@JijeshP bug confirmed, in the meantime for a patch you can use the bp.kvs to store stuff globally

JijeshP commented 5 years ago

Thank you @slvnperron

slvnperron commented 5 years ago

Issue locations

https://github.com/botpress/botpress/blob/1d7e50d9f0dbe2d3b83b9bd0ba121e1be10deb92/src/bp/core/services/action/action-service.ts#L171

https://github.com/botpress/botpress/blob/1d858920d8c056256dcddb46f55737ae6f427621/src/bp/core/services/middleware/state-manager.ts#L42

https://github.com/botpress/botpress/blob/1d858920d8c056256dcddb46f55737ae6f427621/src/bp/core/services/middleware/state-manager.ts#L68

Workaround

Use the KVS (bp.kvs) inside the actions directly: https://botpress.io/reference/modules/_botpress_sdk_.kvs.html

crixx commented 5 years ago

@arnaldobadin What the key-value-store does is saving your object in the database. Consequently, JS objects are serialized to valid JSON and stored into the database. As such, functions of any kind are cleared during the serialization (as it happens when you try to serialize a JS function with JSON.stringify) and thus the output of your await bp.kvs.get(botId, "engine"); looks reasonable to me.

What you want to do is to implement a registry for your functions. In BP 10, one could have attached the functions in a map to the bp object itself, something a long the lines of:

bp.engineStore[botId].engine = new Engine(); But no clue if that still works in BP 11...

But tell us more generally what exactly you want to achieve? It looks like you just want to reuse the "engine" instance right? To reuse the engine, you can make use of nodejs's modules, which <in general> are singletons. Since your Engine is already a node module, it's code is run on the first require and the cached object is returned on subsequenct requires to the exact same file.

/Crixx