Bots are third-party applications that run inside QuickBlox platform. Chatbots are controlled programmatically via QuickBlox Javascript/Node.js SDK.
QuickBlox application includes everything that brings messaging right into your application - chat, video calling, users, push notifications, etc. To create a QuickBlox application, follow the steps below:
To create a bot user, follow the steps below:
Open terminal and type the following commands:
mkdir my_awesome_bot
cd my_awesome_bot
npm init
This will ask you a bunch of questions, and then write a package.json file for you. More information on npm init. The main thing is that we have now a package.json file and can start to develop our first chatbot.
In terminal type the following command:
npm install quickblox --save
Type the following command in terminal:
touch index.js
It will create the main entry point for your bot. Open this file and let’s write some logic.
Open index.js file and write the following code:
"use strict";
const QB = require("quickblox");
const CONFIG = {
appId: "...",
authKey: "...",
authSecret: "...",
botUser: {
id: "...",
password: "...",
},
};
// Initialise QuickBlox
QB.init(CONFIG.appId, CONFIG.authKey, CONFIG.authSecret);
// Connect to Real-Time Chat
QB.chat.connect(
{
userId: CONFIG.botUser.id,
password: CONFIG.botUser.password,
},
(chatConnectError) => {
if (chatConnectError) {
console.log(
"[QB] chat.connect is failed",
JSON.stringify(chatConnectError)
);
process.exit(1);
}
console.log("[QB] Bot is up and running");
// Add chat messages listener
QB.chat.onMessageListener = onMessageListener;
}
);
function onMessageListener(userId, msg) {
// process 1-1 messages
if (msg.type == "chat") {
if (msg.body) {
let answerMessage = {
type: "chat",
body: msg.body, // echo back original message
extension: {
save_to_history: 1,
},
};
QB.chat.send(userId, answerMessage);
}
}
}
process.on("exit", function () {
console.log("Kill bot");
QB.chat.disconnect();
});
This is a simple bot that simply replies back with origin message.
For CONFIG
variable put the following values:
Bot user ID and password. Get these values following Dashboard => YOUR_APP => Users => Add new user direction. The user ID appears in the table with users once a User is created and the password is taken from the Add user form.
Application ID, Authorization Key, and Authorization Secret. Get these values following Dashboard => YOUR_APP => Overview direction and copy them from here.
In terminal type the following command:
node index.js
Now you can write something to your bot and will receive a reply. See the documentation at https://docs.quickblox.com/docs/js-quick-start.
You can take your simple bot to the next level by adding some intelligence to it. Check out this sample to see a clever bot in action. Follow the guide to learn how to run your clever bot.