> ## Documentation Index
> Fetch the complete documentation index at: https://developers.hubspot.es/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Conversaciones | Ejecutar fragmentos de código en bots

export const ScopesList = ({scopes = [], description = "Esta API requiere uno de los siguientes ámbitos:"}) => {
  if (!scopes || scopes.length === 0) {
    return null;
  }
  const sortedScopes = scopes.sort((a, b) => a.localeCompare(b));
  return <div>
      <div className="text-sm mb-2">{description}</div>
      <div>
        {sortedScopes.map((scope, index) => <div key={index}>
            <code>
              <span className="text-xs">{scope}</span>
            </code>
          </div>)}
      </div>
    </div>;
};

<Accordion title="Requisitos de ámbito">
  <ScopesList
    scopes={[
  'content'
]}
  />
</Accordion>

Al [crear o editar un bot](https://knowledge.hubspot.com/es/articles/kcs_article/conversations/create-a-bot), puedes agregar un fragmento de código haciendo clic en «+» para [agregar una acción](https://knowledge.hubspot.com/chatflows/a-guide-to-bot-actions) como normalmente lo harías. En el panel de selección de acción, haz clic en «Ejecutar un fragmento de código»

<Frame>
  <img src="https://developers.hubspot.com/hs-fs/hubfs/KB%20Team/run-a-code-snippet-2.png?width=322&name=run-a-code-snippet-2.png" alt="run-a-code-snippet-2" />
</Frame>

A continuación, asígnale un apodo a tu acción. En el panel de edición de códigos, verás nuestra plantilla predeterminada para Node.js 10. x. Los detalles del objeto «event» y los formatos de objeto de respuesta posibles se detallan a continuación.

<Frame>
  <img src="https://developers.hubspot.com/hs-fs/hubfs/KB%20Team/run-a-code-snippet-editor.png?width=388&name=run-a-code-snippet-editor.png" alt="run-a-code-snippet-editor" />
</Frame>

El código se activará cuando se alcance la acción guardada en una conversación.

Hay tres aspectos principales que debes tener en cuenta al trabajar con fragmentos de código:

* La función `exports.main()` se llama cuando se ejecuta la acción del fragmento de código.
* El argumento `event` es un objeto que contiene detalles para el visitante y la sesión de chat.
* La función `callback()` se utiliza para pasar datos al chatbot y al usuario. Se debe llamar en la función `exports.main`.

El objeto `event` contendrá los siguientes datos:

```json theme={null}
//example payload
{
  "userMessage": {
  // Details for the last message sent to your bot
    "message": "100-500",
    // The last message received by your bot, sent by the visitor
    "quickReply": {
    // If the visitor selected any quick reply options, this will be a list of the selected options.
    // Will be 'null' if no options were selected.
      "quickReplies":[
      // A list of quick reply options selected by the visitor
         {
            "value":"100-500",
            "label":"100-500"
         }
      ],
  },
  "session": {
    "vid": 12345,
    // The contact VID of the visitor, if known.
    "properties": {
    // A list of properties collected by the bot in the current session.
      "CONTACT": {
        "firstname": {
          "value": "John",
          "syncedAt": 1534362540592
        },
        "email": {
          "value": "testing@domain.com",
          "syncedAt": 1534362541764
        },
        "lastname": {
          "value": "Smith",
          "syncedAt": 1534362540592
        }
      }
    },
  "customState":{myCustomCounter: 1, myCustomString:"someString"}
  // Only present if it customState was passed in from a previous callback payload
  }
}
```

La función `callback()` se utiliza para enviar datos al bot. El argumento debe ser un objeto con los siguientes datos:

```json theme={null}
//sample payload
{
  "botMessage": "Thanks for checking out our website!",
  // This is the message your bot will display to the visitor.
  "quickReplies": [{ value:'option',
  // Passed to the bot as the response on click
   label:'Option' // Gets displayed as the button label
    }],
  // the quickReplies object is optional
  "nextModuleNickname": "SuggestAwesomeProduct",
  // The nickname of the next module the bot should execute. If undefined, the bot will follow the default configured behavior
  "responseExpected": false
  // If true, the bot will display the returned botMessage, wait for a response, then execute this code snippet again with that new response.
  "customState":{myCustomCounter: 1, myCustomString:"someString"}
  // Optional field to pass along to the next step.
}
```

## Limitaciones

Los fragmentos de código en los bots deben terminar en un lapso de 20 segundos y solo usar 128 MB de memoria. Exceder estos límites ocasionará un error.

## Bibliotecas disponibles

Varias bibliotecas de Node.js están disponibles para usar dentro del fragmento de código.

* [async](https://www.npmjs.com/package/async)
* [lodash](https://www.npmjs.com/package/lodash)
* [mongoose](https://www.npmjs.com/package/mongoose)
* [mysql](https://www.npmjs.com/package/mysql)
* [redis](https://www.npmjs.com/package/redis)
* [request](https://www.npmjs.com/package/request)
* [aws-sdk](https://www.npmjs.com/package/aws-sdk)

Las bibliotecas se pueden cargar usando la función `require()` normal en la parte superior de tu código.

```js theme={null}
const request = require("request");

exports.main = (event, callback) => {
  request("http://time.jsontest.com/", function (error, response, body) {
    const responseJson = {
      botMessage: "The current time in GMT is " + JSON.parse(body).time,
      responseExpected: false,
    };

    callback(responseJson);
  });
};
```
