This guide provides developers with detailed instructions for integrating and customizing the Talkk.ai
Web Chatbot. Learn how to apply advanced theming options for UI components like buttons, message
bubbles, and headers using CSS variables and API configurations. step-by-step integration steps, this
document ensures a seamless setup process.
Replace variables like {GROUPID}, {API_CHAT_BASE_URL},
{ENCRYPTION_KEY} accordingly in implementation and store them in a
.env file for global access.
Get Bot Information
The API called to get bot information like themeing.
Base Configuration
Base URL: https://[chat_domain]/ Endpoint:/api/1.0.0/getBotInfoEnc Method: POST
Retrieves configuration data for your chatbot, including theming, company info, bot details, and
form specifications.
Authentication & Security
The API uses AES encryption for request/response data. All data must be encrypted before sending
and decrypted upon receipt using the provided encryption key.
Implement the encryption/decryption functions as shown above
Make the API call to retrieve bot configuration
Apply theming and configuration from the response to your chatbot implementation
Implement the lead and feedback forms according to the response specifications
Error Handling
The decryption function returns an empty array [] if decryption fails. Implement
proper error handling to manage API failures or decryption errors.
Notes for Developers
Always store encryption keys securely
The API returns all necessary information to render and configure the chatbot in a single
call
Use the theming information from appInfo to maintain brand consistency
Lead and feedback forms should be implemented exactly as specified in the response
Chat Theming
This section outlines the theming capabilities and customization options available for the Talkk
Chat Application. The application supports comprehensive theming for all major UI components,
including buttons, message bubbles, header, background, and action buttons.
Button Styling
Buttons throughout the application can be themed using the following variables:
const data = response.data.appInfo //will get this in getBotInfo api
Description
Source Property
Primary button background color
data.actionColorsTest.btnBg
Primary button text color
data.actionColorsTest.btnColor
Primary button background color on hover
data.actionColorsTest.btnHoverBg
Primary button text color on hover
data.actionColorsTest.btnHoverColor
Outline button background color
data.actionColorsTest.outlineBtnBg
Outline button text color
data.actionColorsTest.outlineBtnColor
Message Bubble Styling
Message bubbles for both user and bot messages can be themed separately:
const data = response.data.appInfo //will get this in getBotInfo api
Description
Source Property
User message bubble background color
data.userBBg
User message text color
data.userBColor
Bot message bubble background color
data.botBBg
Bot message text color
data.botBColor
Header Styling
The header can be customized with background and text colors:
const data = response.data.appInfo //will get this in getBotInfo api
Description
Source Property
Header background color (supports linear gradients)
data.cHeaderBg
Header text color
data.cHeaderText
Chat Background
The chat window background can be customized:
Description
Source Property
Chat window background color
data.cWindowBg
Action Button Styling
Send and voice input buttons can be customized:
Description
Source Property
Send button background color
data.csendBtnBg
Voice input button background color
data.cvoiceBtnBg
Widget Style Components
The application supports multiple pre-defined style variants for different UI components. These
styles are applied as CSS classes based on the configuration received from the server.
const styleData = botInfo.data.appInfo //will get this form getBotInfo
Chat Header StylestyleData.headerStyle
Header Style 1Header Style 2Header Style 3
Chat Body StylestyleData.chatWindowStyle
Chat Body Style 1Chat Body Style 2Chat Body Style 3
The bot icon is selected based on the following priority:
If botInfo.data.appInfo.botIcon.url exists, use this URL
Otherwise, use botInfo.data.bot.profileImagePath
If neither exists, fall back to a static bot image
Overall Theming Key
You will get this key in botInfo.data.appInfo from API
For further testing and implementation, use the tabled variables as reference placeholders in
your code. Reach out to support@talkk.ai for credentials
and integration access.
Socket Integration
Overview
This document provides detailed instructions for integrating socket communication with the Talkk
webchatbot platform. The socket connection enables real-time messaging between users and the
chatbot, maintains conversation history, and handles various events like typing indicators and
message reactions.
Socket Package: socket.io-client@2.2.0
Socket URL: https://[chat_domain]/
Environment Variable: API_CHAT_BASE_URL (Socket URL store in env file)
Environment Variable: GROUPID (group id store in env file)
Socket Connection Setup
const socketvar = io(API_CHAT_BASE_URL, {
transports: ['websocket', 'polling'],
path: '/talkk', // for web
path: '/mobile', // for mobile application
multiplex: true,
query: {
q: encryptData({
type: 'user',
page: 'chat',
locale: "en",
group: GROUPID,
session_id: newSessionId // in case of mobile app pass device id
})
},
});
In web applications, session IDs should be generated randomly and uniquely each time, then
stored in cookies to preserve chat history across page refreshes.
Socket Events
Emitting Events (Client to Server)
All events sent to the server must be encrypted using the encryptData function.
1. Initialize Chat History
Retrieve chat history upon connection:
//for web
socket.emit(encryptData(["user-option", {}]));
//for mobile app
socket.emit(["user-option", encryptData({})])
Important: Note the different encryption patterns between web and mobile
implementations. For web, the entire event array is encrypted. For mobile, only the data payload
is encrypted, while the event name remains unencrypted.
2. Send User Message
function sendMessage(message, payload = '') {
const sendData = {
text: message,
payload: payload
};
//for web
socket.emit(encryptData(["user-send", sendData]));
//for mobile application
socket.emit(["user-send ", encryptData(sendData)])
}
3. Close Chat Session
function closeChat() {
//for web
socket.emit(encryptData(["close-chat", {}]));
//for mobile application
socket.emit(["close-chat", encryptData({})]);
}
Listening to Events (Server to Client)
Set up a main event listener and handle different event types:
user-send - to receive user message
agent-message - to receive bot message
agent-typing - to show bot typing
close-chat - to receive close chat event
stream-message - to receive bot streaming message
if (socket) {
socket.on("*", (event, data) => {
if (typeof event !== "string") {
event = bufferToString(event);
var message = decryptData(event);
if (message[0] == "user-send") {
//do action for user send message
} else if (message[0] == "agent-message") {
//do action for bot send message
}
//write same for all events
}
});
}
Buffer to String Conversion
This is only applicable for web.
For handling binary data from socket events:
function bufferToString(arrayBuffer) {
var result = "";
var i = 0;
var c = 0;
var c1 = 0;
var c2 = 0;
var c3 = 0;
var data = new Int8Array(arrayBuffer);
if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
i = 3;
}
while (i < data.length) {
c = data[i];
if (c < 128) {
result += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
if (i+1 >= data.length) {
throw "UTF-8 Decode failed. Two byte character was truncated.";
}
c2 = data[i+1];
result += String.fromCharCode(((c&31)<<6) | (c2&63));
i += 2;
} else {
if (i+2 >= data.length) {
throw "UTF-8 Decode failed. Multi byte character was truncated.";
}
c2 = data[i+1];
c3 = data[i+2];
result += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
i += 3;
}
}
return result;
}
Error Handling
Implement error handling for socket connection issues and data processing errors:
If the messageType is "N", the message should be excluded from display in chat.
In the Mobile App, the session_id should be set as the device ID of the mobile
device.
This integration is built on Socket.IO version 2. Ensure your client uses the compatible
version.
Refer to the Template Message Formats section for guidance on how to render various types of
chatbot responses.
Display messages follow WhatsApp-style formatting — e.g., bold,
italic, etc.
Some responses may include raw HTML tags; these should be safely parsed and rendered by the
front-end.
In the case of Web, we use a wildcard emit listener; hence, the entire request and response
payload is encrypted.
In the case of the Mobile App, the emit name is not encrypted, but the entire payload of the
response is encrypted.
For example: ["user-message", "encrypted-response"]
API Integration
Overview
This section provides details on how to integrate the Talkk Chat Application with your backend
services using API calls. The API allows you to retrieve bot configuration, theming, and
conversation history.
API Endpoint
Get Conversation History Endpoint:/api/apiai
Get Answer Endpoint:/<-bot-identifier->/<-company-id->
Note :- This details will be shared by Talkk team.
Get Conversation History API
To retrieve the conversation history, make a POST request to /api/apiai with the
following request body:
Note: The session_id should be set as the device ID or any unique
device identifier to ensure conversation history is correctly associated with each user/device.
Each item in the data array is a message object as described in the Chat Message
Structure section.
Get Response from AI Assistant
To get a response from the AI assistant, make a POST request to the API endpoint with the
following headers and body:
session_id: The user's phone number or unique identifier for tracking the
session. In the Mobile App, should be set as the device ID of the mobile
device.
message: The user's query or input to the AI assistant.
Sample Success Response
{
"success": 1,
"message": "Hello! i'm an ai assistant",
"data": {
//message object
}
}
success: Indicates the success status of the request (1 for success).
message: The AI assistant's reply (may contain SSML tags for speech
synthesis).
data: The message object (see Chat Message Structure section).
Sample Error Response
{
"success": 0,
"message": "Invalid session_id or token."
}
success: Indicates the failure status of the request (0 for failure).
message: A descriptive error message.
Notes
Ensure the x-access-token is passed correctly in the headers for
authentication.
The session_id should be the user's phone number or unique identifier.
The message field should contain the user's query or input.
Chat Message Socket Integration
Message Object Structure
The main message object contains critical information about the conversation, user details, and
message content:
{
"title": "Talk to Agent",
"type": "postback",
"mode": "talkktoagent"
}
Leave a Message
Allows leaving a message when agents are unavailable:
{
"title": "Leave Message",
"type": "postback",
"mode": "leavemessage",
"team": [] //this will contain agents list which we can show to user to select agent from different department
}
Used for displaying menu options to the user if the element type is “List” which show menu as
button array and replace footer input element with button. On click of that button it will show
menu on drawer.
Sample List MenuSample Menu Option
Message Ratings
When a bot message includes step: 99, a rating interface (thumbs up/down) is
displayed below the message. Will show message rating on hover of the message like thumbs
down/up and onclick of thumbs will call below emit.
The pre-chat form is used to collect user information before starting a conversation. The system
checks for the presence of leadForm.en in the getBotInfo response. The
leadForm.en object contains form field definitions, error messages, and validation
rules.
In submit form should hit below code:
sendData = {
text: "/st_greetings",
notification: 'N',
locale: prefLang,
info: data //this should contain formdata which is collected from prechat form.
}
Postchat Form
The post-chat form is used to collect feedback after a conversation ends. The system checks for
the presence of postForm.en in the getBotInfo response. The
postForm.en object contains form field definitions, error messages, validation
rules, and rating options.
Postchat API
Endpoint:${API_CHAT_BASE_URL}api/1.0.0/survey-details/add Method: POST
Body:
let object = {
group_id: GroupID,
survey_details: obj, //form data which is collected from postform data
conversation_id: msg.conversationId.Id,
customer_id: msg.customerId.Id,
type: 'POST'
}
Sample Prechat FormSample Postchat Form
SSML Format
[{ "ssml": "Hi! Welcome back. How can I help you today?" }]
This will come with every message that we have readout using voice library in voice mode. SSML
will come in message template.
Time Display
Message timestamps are displayed using the updatedAt field from the message object.
Close Chat
In header click on menu icon to click on close chat menu to close current conversation and
display feedback form if it is there in postForm.
Chat Message API Integration
Base Response Format
{
"success": 1,
"message": < speak >< s >Have a Good Day
!< / s >< / speak >",
"display": [ ...
]
}
1 = success, 0 =
error
``: Text (with optional SSML tags for voice)
``: Array of display templates, each using the template key with type
and elements
Error Response
{
"success": 0,
"error": "Please try Again Later."
}
This guide provides step-by-step instructions to integrate the chatbot into your mobile
application using an in-app browser. It also covers the necessary permissions required for
Microphone, Voice, and Storage to enable voice interactions and store cookies.
By following this guide, you will ensure a seamless and fully functional chatbot
experience for users.
Integration Process
Step 1: Determine How You Will Open the Chatbot
There are two common methods to integrate the chatbot into your app:
Using WebView (Embedded Browser in Your App) – This keeps users within your app.
Using In-App Browser (Chrome Custom Tabs for Android / Safari View Controller for iOS) – This provides a more native browser-like experience.
Choose the method that best fits your app’s UX needs.
Step 2: Implement WebView or In-App Browser
For WebView Integration:
-Ensure JavaScript is enabled.
-Allow microphone and storage access in the WebView settings.
-Handle WebViewClient for a smooth experience without redirecting to an external browser.
For In-App Browser Integration:
-Use Chrome Custom Tabs (Android) for a lightweight, optimized experience.
-Use Safari View Controller (iOS) to open the chatbot in an in-app browser.
Step 3: Handle User Permissions for Microphone & Storage
If a user denies permissions, show a prompt explaining why they are needed.
Ensure the chatbot can access cookies and microphone input without restrictions.
Passing User Data to the Chatbot
To personalize the chatbot experience, user information is passed via query parameters in the chatbot URL.
To securely and cleanly pass a user object to the chatbot via a URL, you can encode the object using btoa() (Base64 encoding). This allows you to include structured data as a single query parameter.
const user = {
name: "John",
email: "john@gmail.com"
};
const encodedData = btoa(JSON.stringify(user)); //use base64 encryption to pass data
const url = `[bot_url]?userdata=${encodedData}`;
These parameters are extracted by the chatbot SDK or iframe loader and used to personalize conversations.
Security Tip:
Avoid passing sensitive data (like passwords or tokens) in query strings. Use encryption or token-based methods if needed.