Variables
Botpress uses variables to store information from one place and use it in other parts of a flow. Variables help make conversations more personalized and help track information about users. They can also help connect with third-party APIs and data sources.
Variable Scopes
Botpress also includes different types of variables. These Variable types differ in scope or where they can be accessed in your bot's flows.
Creating Variables in Botpress
- Open up the Variables tab from the sidebar and click the + icon in the Variables section.
- A new window will appear, allowing you to formulate a new Variable.
- Assign a suitable scope (Workflow, Bot or User) to your Variable, select the Data Type (see below table), give it a name, and click Add to create the Variable.
- (Optional) From the Additional Settings, you can also initialize your Variable with a default value.
Using Variables in Botpress
Once the Variable is established, employ {{workflow.variablename}}
or @workflow.variablename
to render it in a send message card.
Data Types for Variables
Botpress variables are typed, meaning they are limited in what data they can hold. Not only are these data types important to ensure the code behind Botpress runs smoothly, but these types also help AI tasks generate better results. Here are the different data types available for Botpress variables:
Type | Description |
---|---|
String | Values that are treated as text. Strings can contain any amount of letters, numbers, or special characters. Example uses: Storing a user's name, storing an AI task's generated message. |
Boolean | Variables can be true or false, with a lowercase 't' or 'f'. Example uses: Storing if a user is a returning customer, storing whether the bot has greeted the user or not |
Number | Variables that are numeric, either with or without decimal places. Example uses: Storing a user's phone number, storing an address's area code |
Date | Variables that are a single date or date and time. Botpress uses ISO 8601 date/time format, such as 20220921T10:34:14 for 21 September 2023 at 10:34 AM (with 14 seconds). Example uses: Storing when the user starts a chat, storing a user's appointment date |
Object | Variable that is a collection of key-value pairs. Useful when dealing with code and written like {key: value} . Example uses: Storing a user's profile, storing the results of an API call |
Array | Variable that is a collection of other, similar variables. Arrays can contain strings, like [“a”, “b”, “c”] , or Objects like [{key:value},{key:value}] . Example uses: Storing a user's past messages, storing options for the user to choose from |
Enum | Variable that can be one of a set number of choices. Example uses: Storing days of the week, storing items available from a food menu |
Pattern | Variable that uses Regular Expressions/Regex to store a special pattern. This pattern can match certain words or numbers. Example uses: Storing account numbers, storing flight numbers |
Workflow Variables
Workflow Variables are created and used only within a single workflow. These variables are great for single-use or in standalone flows, such as:
- Storing an AI Task's output
- Saving the user's answer to a question
- Organizing data returned from an API call
- Saving flags or tags that track the conversation
Info
Workflow variables are not accessible in any workflow other than the one they were created in. For example, a workflow Variable created in a separate workflow will not be accessible in Main.
Creating a Workflow Variable
To create a Variable in your bot's workflow, you can follow these steps:
- Select the appropriate workflow from the Flows section in the Side Panel.
- Click on the + icon in the Variables section, at the bottom of the Side Panel.
- Give your Variable a name, pick a type and click Add to create the Variable. (Default scope is Workflow)
- Once the Variable is created, you can use
{{workflow.variablename}}
or@workflow.variablename
to display it in a send message card.
Input and Output Workflow Variables
Workflows can have inputs and outputs to help pass information throughout the bot. This can be useful if your workflow returns information like a verified phone number, or requires information like a user id.
To mark an Input Variable
- Go into your new workflow(not Main) and create a Variable and Click it's Entry node.
- In the inspector panel, click on the Variable you want to make an input. It should get a blue border and appear in the Entry node.
- When you call this workflow from another flow, there should be an input box for that Variable in the workflow's card. This will let you pass information or another Variable into that workflow.
To mark an Output Variable
- Go into your new workflow(not Main) and create a Variable and click on the Exit node.
- In the inspector panel, click on the Variable you want to make an output. It should get a blue border and appear in the Exit node.
- When you call this workflow from another flow, the output Variable will be accessible by typing
{{workflow.<workflow-cardName>.<variablename>}}
, replacing<workflow-cardName>
and<variablename>
with the name of the card that represents your workflow and Variable respectively.
User Variables
User Variables are variables that follow a user between conversations. For example, if a user speaks with your bot on Monday and Wednesday, any user variables set on Monday will still be accessible on Wednesday. User variables are great for storing data that doesn't change very often, such as:
Storing users' personal details or id numbers
- Collecting tags or notes from past conversations
- Storing extra flags like VIP customer
- Saving language preferences
Creating a User Variable
- Open up the Variables tab and navigate to the + icon in the Variables section.
- Change the scope to User, select the Data Type, give it a name, and click Add to create the Variable.
Using User Variables
Once the User Variable is established, employ {{user.variablename}}
or @user.variablename
to render it in a send message card.
Bot Variables
Bot Variables can be accessed by all users of the chatbot across all conversations. They are typically used for configuration and developer information, such as:
- Storing the endpoint for the bot's API calls
- Saving bot's version number
- Storing the bot's name
- Metadata about the bot/services
Bot variables are not encrypted or stored securely. Do not save secrets like API keys or passwords in bot variables - use configuration variables instead!
Creating a Bot Variable
- Open up the Variables tab and navigate to the + icon in the Variables section.
- Change the scope to Bot, select the Data Type, give it a name, and click Add to create the Variable.
Using Bot Variables
Bot variables can be used in text and other cards just like user variables - with either @bot.variablename
or {{bot.variablename}}
.
Session Variables
Session variables are available in all flows, but only for one conversation. These variables are great for data used throughout a conversation, such as:
- Collecting items in a virtual shopping cart for the user to order
- Saving raw data from an API call for further processing
- Storing chat history for that conversation
- Saving an order number or policy number
Creating a Session Variable
Session variables can only be created inside of an Execute Code card.
To create one, simply write: event.state.session.variablename = "Hello World"
or for short session.variablename = "Hello World"
To use a Session Variable in a text or other card, enclose it in double curly brackets like {{event.state.session.variablename}}
or for short {{session.variablename}}
Configuration Variables
Configuration variables are a special kind of secure bot Variable. They can also be managed from the Cloud Dashboard without opening the bot. Configuration variables can store secrets like:
- API Tokens
- Private IP Addresses
- Database usernames and passwords
Creating a Configuration Variable (or Environment Variable)
- Click the Botpress icon in the upper-left corner and select Chatbot Settings
- Scroll down and click on the button to add a Configuration Variable. Fill in the Variable's name and value and click Done.
You can use env.key in your code to get the value of the Configuration Variable. To use it in an Execute Code Card, you can write env.key to access its value.
Once a configuration Variable is created, you can access and manage it from the cloud admin dashboard. Just select your bot and then click on the tab for Configuration Variables.
Passing Variables between Flows
- In your target workflow, define an input Variable from the workflow properties window.
- Toggle it
ON
on theEntry node
of the target workflow. - Now, on the
exit
node of the parent workflow, the one that brings the user to the target workflow, match the parent workflow Variable with the target workflow input Variable. - Now, when you call the target workflow from the parent workflow, you will see the input Variable in the card. You can pass a value or a Variable to it.
Using Variables in Code Card
Variables in code follow the pattern variabletype.variablename
. Here's a breakdown and examples of how to use these:
1. Assigning a Value to a Variable
This is typically how you'd initialize a variable or change its value.
workflow.orderNumber = 12345
session.cartTotal = 59.99
user.lastName = 'Smith'
bot.version = '1.2.3'
env.databaseURL = 'https://example.com/db'
2. Using Variables in Conditional Statements
This checks the value of a variable and executes code accordingly.
if (user.firstName === 'John') {
console.log('Hello John!')
} else {
console.log('Welcome, user!')
}
3. Using Variables in Functions
Here, you might pass a variable as a function argument or use it inside a function.
function greetUser(firstName) {
console.log('Hello, ' + firstName + '!')
}
greetUser(user.firstName)
4. Combining Variables
You might want to combine or concatenate variables.
var fullName = user.firstName + ' ' + user.lastName
//or
var welcomeMessage = 'Hello, ' + user.firstName + ' ' + user.lastName + '!'
5. Checking Variable Type
Botpress might throw an error if types don't match, you can use type checking before assigning values.
if (typeof workflow.userAcctId === 'number') {
workflow.userAcctId = 67890 // This is okay.
} else {
console.error('Invalid type for userAcctId!')
}
6. Using Variables with External APIs
If your bot interacts with external services, you might use an environment variable like env.apiKey.
const apiKey = env.API_KEY
const apiUrl = env.API_URL
const config = {
headers: {
Authorization: `Bearer ${apiKey}`,
},
}
const response = await axios.get(apiUrl, config)
const data = response.data
// Process the data as needed
// ...
// Example: Log the response data
console.log(data)
Special Variables
Botpress makes available several different variables that can be used in your bot's code. These variables are useful for debugging and for accessing information about the user and conversation.
Path | Type | Description |
---|---|---|
event.preview | Event | The last message sent by the user. It will be replaced every time there is a new message. |
conversation.SummaryAgent.summary | Agent | Summary of the conversation created by the Summary Agent. It's an explanation of what happened. |
conversation.SummaryAgent.transcript | Agent | Transcript of the conversation going back a certain amount of turns. |
turn.KnowledgeAgent.answer | Agent | The answer provided by the Knowledge Agent |
turn.KnowledgeAgent.responded | Agent | Wether the Knowledge Agent has responded automatically to a user question. Its value will be true or false |
turn.KnowledgeAgent?.answer?.length | Agent | The amount of characters in the Knowledge answer. Use this in an Expression to check if there is an answer in the KB. Optionally add ! to start of the code in order to check if there was NOT an answer. |
turn.KnowledgeAgent.citations | Agent | A list of citations for the Knowledge answer. |
user.TranslatorAgent.language | Agent | The current user language code in ISO 639-1 format. More about the Translator Agent |
user.TranslatorAgent.language = 'en' | Agent | This code snippet set's the user language to English. Replace with any language code in the ISO 639-1 format |
event.kb.results.map((a) => a.dsFriendlyName + '\n' + a.content).join('\n\n') | Event | This code snippet returns the raw content that generated the final Knowledge answer. |
event.tags.conversation['whatsapp:userPhone'] | Integration | The user's phone number on WhatsApp. Includes the international code. |
event.tags.conversation['whatsapp:phoneNumberId'] | Integration | The phone number Id of the bot on WhatsApp. |
Updated 3 months ago