Add custom payload to Converse API JSON

Hi there, I use the Bot as a backend API for my website, and send/receive message using the Converse API provided with the bot. Everything is working well but I want my bot to be able to send some more payload than “text”, for example some custom variables to trigger styling changes.

current payload

{"responses":[
{"type":"typing","value":true},
{"type":"text","text":Blabla"}
]}

what I would like to receive

{"responses":[
{"type":"typing","value":true},
{"type":"text","text":Blabla"},
{"type":"styling","blue"}
]}

Hey @gregoire_d !

To modify the outgoing message, you can create a “Before Outgoing” hook. You can create this hook from the Code Editor.

This hook will send a new event in the outgoing direction, like so:

async function action(bp: typeof sdk, event: sdk.IO.IncomingEvent) {
  /** Your code starts below */

  async function hook() {
    if (event.channel === 'api' && event.payload.type === 'text' && event.payload.text === 'Blabla') {
      const newEvent = bp.IO.Event({
        channel: 'api',
        botId: event.botId,
        direction: 'outgoing',
        target: event.target,
        payload: { type: 'styling', color: 'blue' },
        type: 'styling'
      })

      bp.events.sendEvent(newEvent)
    }
  }

  return hook()

  /** Your code ends here */
}

Let me know if you need more help!

Thank your for your quick reply ! It helps me a lot.

It’s also possible to create an action so i can edit it using the flow editor !

async function action(bp: typeof sdk, event: sdk.IO.IncomingEvent, args: any, { user, temp, session } = event.state) {
  /** Your code starts below */
/**
   * Crée une variable custom
   * @title Custom Payload
   * @category Custom
   * @author Gregoire
   * @param {string} name - Name of the custom payload variable
   * @param {any} value - Value of the custom payload variable
   */
  const myAction = async (name, value) => {
    const newEvent = bp.IO.Event({
      channel: 'api',
      botId: event.botId,
      direction: 'outgoing',
      target: event.target,
      payload: { type: name, value: value },
      type: value
    })
    bp.events.sendEvent(newEvent)
  }

  return myAction(args.name, args.value)
  /** Your code ends here */
}