Develop a Rocket.Chat SDK Bot

Bots integration has been deprecated. We recommend building with Apps-Engine instead.

This bot is a simple example of how you can use Rocket.Chat JS SDK methods directly. It is extremely basic and does not handle errors, different message types, server resets, and other production situations.

Rocket.Chat Bot is a Node.js package that works with Node and NPM. To develop the bot, follow the steps below.

Prerequisites

Before you begin, make sure you have the following:

  • A Rocket.Chat workspace already set up. If you haven’t done this, refer to the deployment guides for assistance

  • A bot user created and ready to use. Refer to the guide for instructions on how to create one

Install Rocket.Chat SDK package

Open the terminal in the directory where you want to develop your bot and run the following command.

npm init -y
npm install @rocket.chat/sdk

Create SDK bot files

To proceed with the simplest setup, you need to create two files: the first one is responsible for the bot's working logic, and the other maps the responses.

  • Create a server.js file with the following content:

const { driver } = require('@rocket.chat/sdk');
const respmap  = require('./reply');

// Environment setup (consider using environment variables)
const HOST = '<ROCKETCHAT_HOST>'; // The server URL of your Rocket.Chat workspace (e.g., https://example.com)
const USER = '<BOT_USERNAME>'; // The username of the bot
const PASS = '<BOT_PASSWORD>'; // The password for the bot user
const BOTNAME = '<BOT_ALIAS>'; // The alias for your Rocket.Chat bot
const SSL = '<USE_SSL>'; // Boolean (e.g., true or false) indicating SSL usage
const ROOMS = ['<ROCKETCHAT_CHANNEL>']; // List of channels (e.g., GENERAL)

let myUserId; // Declare user ID variable

// Bot configuration
const runbot = async () => {
 try {
   const conn = await driver.connect({ host: HOST, useSsl: SSL });
   myUserId = await driver.login({ username: USER, password: PASS });
   const roomsJoined = await driver.joinRooms(ROOMS);
   console.log('joined rooms');

   const subscribed = await driver.subscribeToMessages();
   console.log('subscribed');

   const msgloop = await driver.reactToMessages(processMessages);
   console.log('connected and waiting for messages');

   const sent = await driver.sendToRoom(BOTNAME + ' is listening ...', ROOMS[0]);
   console.log('Greeting message sent');
 } catch (error) {
   console.error("Error:", error);
 }
};

// Process messages
const processMessages = async (err, message, messageOptions) => {
 if (!err) {
   if (message.u._id === myUserId) return;
   const roomname = await driver.getRoomName(message.rid);
   console.log('got message ' + message.msg);


   var response;
   if (message.msg in respmap) {
     response = respmap[message.msg];
   } else {
       response = message.u.username + ', how can I' + ' help you with "' + message.msg + '"';
   }
   try {
     const sentmsg = await driver.sendToRoomId(response, message.rid);
   } catch (error) {
     console.error("Error sending message:", error);
   }
 }
};

runbot()

Create a .env file in your project root folder to add the server and user credentials.

Make sure <BOT USER NAME> has a BOT role on the server. For more information on how to create a bot user please refer to this page.

  • Create a reply.js file with the following content:

const respmap = {
    "hi" : "hey",
    "u da bot" : "no, YOU da bot",
    "no u da bot" : "Come'on - YOU DA BOT!!",
    "I give up" : "ok. silly human :rolleyes:"
};

module.exports = respmap;

Run the SDK bot

node server.js

After executing the last command, Rocket.Chat SDK bot tries to connect to the Rocket.Chat instance and listen to messages in the general room:

$ node server.js
[connect] Connecting { username: 'username',
  password: 'pass',
  ldap: false,
  host: 'rocket.chat.host',
  useSsl: true,
  timeout: 20000,
  rooms: [],
  allPublic: false,
  dm: false,
  livechat: false,
  edited: false,
  integrationId: 'js.SDK',
  roomCacheMaxSize: 10,
  roomCacheMaxAge: 300000,
  dmCacheMaxSize: 10,
  dmCacheMaxAge: 100000 }
[connect] Connected
[login] Logging in botUser
[getRoomIdByNameOrId] Calling (caching): general
[getRoomIdByNameOrId] Success: "GENERAL"
[joinRoom] Calling (async): ["GENERAL"]
[joinRoom] Success
joined rooms
[subscribe] Preparing subscription: stream-room-messages: __my_messages__
[subscribe] Stream ready: 4
subscribed
[reactive] Listening for change events in collection stream-room-messages
connected and waiting for messages
[getRoomIdByNameOrId] Calling (cached): general
[getRoomIdByNameOrId] Success: "GENERAL"
[sendMessage] Calling (async): [{"msg":"Rocket.Chat BOT is listening ...","bot":{"i":"js.SDK"},"rid":"GENERAL"}]
[sendMessage] Success: {"msg":"Rocket.Chat BOT is listening ...","bot":{"i":"js.SDK"},"rid":"GENERAL","ts":{"$date":1573598821912},"u":{"_id":"GDJn6Exf9LpK2Pp5n","username":"botUser"},"mentions":[],"channels":[],"_updatedAt":{"$date":1573598821920},"_id":"6yTcbcNKuMDBdPsFc"}
Greeting message sent
[received] Message in room GENERAL

Talk to your SDK bot

On the server, log in as a regular user (not the BOT user), go to general room, and talk to your newly created bot: