Save the user's progress

If the user has already started the scenario, it would be nice not to have him start the conversation again from scratch.

Take the following scenario:

@Event('start')
start() {
    > Hello, what is your name ?
    Prompt()
    > Ok, { :text }. And your age ?
    Prompt()
    > Thanks !
}

With the help of a middleware, we can recover the progress of the user

const { Newbot } = require('newbot')

const converse = new Newbot()

converse.use({ 
    finished(input, { user, data }) {
       const json = user.toJson()
    } 
})

Here, when the user arrives at the request of a text input (that is, when the user arrives at Prompt() in the scenario), his progress is saved in the constant json

We can save the content in a database like MongoDB, CouchDB, etc.

Load user data

It is good to load a set of users. Suppose each db.users() below is a call to the database to retrieve a collection of data

const retUsers = db.users()
converse.loadUsers(retUsers)

Browser example with localStorage

Assuming that path/dist/browser.js is the path to the generated file after doing newbot build

<script src="https://unpkg.com/newbot@latest/dist/newbot.min.js"></script>
<script src="path/dist/browser.js"></script>

<script>
const converse = new NewBot(mainSkill)

const progress = localStorage.getItem('progress')

if (progress) {
    converse.loadUsers([
        JSON.parse(progress)
    ])
}

converse.use({
    finished(input, { user }) {
       const json = JSON.stringify(user.toJson())
       localStorage.setItem('progress', json)
    }
})

converse.exec('Hey', (output, done) => {
    console.log(output)
    done()
})
</script>

Here we notice: 1. We load the user initially if, of course, we have a record in localStorage 2. We use the finished middleware to register the current user in localStorage

::: tip User ID On the server side, let us indicate the username of the user when using the .exec() method.

converse.exec('input text', 'USER ID', (output, done) => {
    done()
})

Last updated