Rocket.Chat.js.SDK
Utility for apps and bots to interact with Rocket.Chat via DDP and/or API
Install / Use
/learn @RocketChat/Rocket.Chat.js.SDKREADME
Rocket.Chat Node.js SDK
Application interface for server methods and message stream subscriptions.
Super Quick Start (30 seconds)
Create your own working BOT for Rocket.Chat, in seconds, at glitch.com.
Quick Start
Add your own Rocket.Chat BOT, running on your favorite Linux, MacOS or Windows system.
First, make sure you have the latest version of nodeJS (nodeJS 8.x or higher).
node -v
v8.9.3
In a project directory, add Rocket.Chat.js.SDK as dependency:
npm install @rocket.chat/sdk --save
Next, create easybot.js with the following:
const { driver } = require('@rocket.chat/sdk');
// customize the following with your server and BOT account information
const HOST = 'myserver.com';
const USER = 'mysuer';
const PASS = 'mypassword';
const BOTNAME = 'easybot'; // name bot response to
const SSL = true; // server uses https ?
const ROOMS = ['GENERAL', 'myroom1'];
var myuserid;
// this simple bot does not handle errors, different message types, server resets
// and other production situations
const runbot = async () => {
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');
// set up subscriptions - rooms we are interested in listening to
const subscribed = await driver.subscribeToMessages();
console.log('subscribed');
// connect the processMessages callback
const msgloop = await driver.reactToMessages( processMessages );
console.log('connected and waiting for messages');
// when a message is created in one of the ROOMS, we
// receive it in the processMesssages callback
// greets from the first room in ROOMS
const sent = await driver.sendToRoom( BOTNAME + ' is listening ...',ROOMS[0]);
console.log('Greeting message sent');
}
// callback for incoming messages filter and processing
const processMessages = async(err, message, messageOptions) => {
if (!err) {
// filter our own message
if (message.u._id === myuserid) return;
// can filter further based on message.rid
const roomname = await driver.getRoomName(message.rid);
if (message.msg.toLowerCase().startsWith(BOTNAME)) {
const response = message.u.username +
', how can ' + BOTNAME + ' help you with ' +
message.msg.substr(BOTNAME.length + 1);
const sentmsg = await driver.sendToRoom(response, roomname);
}
}
}
runbot()
The above code uses async calls to login, join rooms, subscribe to message streams and respond to messages (with a callback) using provided options to filter the types of messages to respond to.
Make sure you customize the constants to your Rocket.Chat server account.
Finally, run the bot:
node easybot.js
TBD: insert screenshot of bot working on a server
Demo
There's a simple listener script provided to demonstrate functionality locally.
See the source here and/or run it with yarn start.
The start script will log to console any message events that appear in its stream. It will respond to a couple specific commands demonstrating usage of the API helpers. Try messaging the bot directly one of the following:
tell everyone <something>- It will send that "something" to everyonewho's online- It will tell you who's online
Overview
Using this package third party apps can control and query a Rocket.Chat server instance, via Asteroid login and method calls as well as DDP for subscribing to stream events.
Designed especially for chat automation, this SDK makes it easy for bot and integration developers to provide the best solutions and experience for their community.
For example, the Hubot Rocketchat adapter uses this package to enable chat-ops workflows and multi-channel, multi-user, public and private interactions. We have more bot features and adapters on the roadmap and encourage the community to implement this SDK to provide adapters for their bot framework or platform of choice.
Docs
Full documentation can be generated locally using yarn docs.
This isn't in a format we can publish yet, but can be useful for development.
Below is just a summary:
The following modules are exported by the SDK:
driver- Handles connection, method calls, room subscriptions (via Asteroid)methodCache- Manages results cache for calls to server (via LRU cache)api- Provides a client for making requests with Rocket.Chat's REST API
Access these modules by importing them from SDK, e.g:
For Node 8 / ES5
const { driver, methodCache, api } = require('@rocket.chat/sdk')
For ES6 supporting platforms
import { driver, methodCache, api } from '@rocket.chat/sdk'
Any Rocket.Chat server method can be called via driver.callMethod,
driver.cacheCall or driver.asyncCall. Server methods are not fully
documented, most require searching the Rocket.Chat codebase.
Driver methods use an Asteroid DDP connection. See its own docs for
more advanced methods that can be called from the driver.asteroid interface.
Rocket.Chat REST API calls can be made via api.get or api.post, with
parameters defining the endpoint, payload and if authorization is required
(respectively). See the REST API docs for details.
Some common requests for user queries are made available as simple helpers under
api.users, such as api.users.onlineIds() which returns the user IDs of all
online users. Run ts-node src/utils/users.ts for a demo of user query outputs.
MESSAGE OBJECTS
The Rocket.Chat message schema can be found here: https://rocket.chat/docs/developer-guides/schema-definition/
The structure for messages in this package matches that schema, with a TypeScript interface defined here: https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/master/src/config/messageInterfaces.ts
The driver.prepareMessage method (documented below) provides a helper for
simple message creation and the message module can also be imported to create
new Message class instances directly if detailed attributes are required.
DRIVER METHODS
driver.connect(options[, cb])
Connects to a Rocket.Chat server
- Options accepts
hostandtimeoutattributes - Can return a promise, or use error-first callback pattern
- Resolves with an Asteroid instance
driver.disconnect()
Unsubscribe, logout, disconnect from Rocket.Chat
- Returns promise
driver.login([credentials])
Login to Rocket.Chat via Asteroid
- Accepts object with
usernameand/oremailandpassword - Uses defaults from env
ROCKETCHAT_USERandROCKETCHAT_PASSWORD - Returns promise
- Resolves with logged in user ID
driver.logout()
Logout current user via Asteroid
- Returns promise
driver.subscribe(topic, roomId)
Subscribe to Meteor subscription
- Accepts parameters for Rocket.Chat streamer
- Returns promise
- Resolves with subscription instance (with ID)
driver.unsubscribe(subscription)
Cancel a subscription
- Accepts a subscription instance
- Returns promise
driver.unsubscribeAll()
Cancel all current subscriptions
- Returns promise
driver.subscribeToMessages()
Shortcut to subscribe to user's message stream
- Uses
.subscribearguments with defaults- topic:
stream-room-messages - roomId:
__my_messages__
- topic:
- Returns a subscription instance
driver.reactToMessages(callback)
Once a subscription is created, using driver.subscribeToMessages() this method
can be used to attach a callback to changes in the message stream.
Fires callback with every change in subscriptions.
- Uses error-first callback pattern
- Second argument is the changed item
- Third argument is additional attributes, such as
roomType
For example usage, see the Rocket.Chat Hubot adapter's receive function, which is bound as a callback to this method: https://github.com/RocketChat/hubot-rocketchat/blob/convert-es6/index.js#L97-L193
driver.respondToMessages(callback, options)
Proxy for reactToMessages with some filtering of messages based on config.
This is a more user-friendly method for bots to subscribe to a message stream.
Fires callback after filters run on subscription events.
- Uses error-first callback pattern
- Second argument is the changed item
- Third argument is additional attributes, such as
roomType
Accepts options object, that parallels respond filter env variables:
- options.rooms : respond to messages in joined rooms
- options.allPublic : respond to messages on all channels
- options.dm : respond to messages in DMs with the SDK user
- options.livechat : respond to messages in Livechat rooms
- options.edited : respond to edited messages
If rooms are given as option or set in the environment with ROCKETCHAT_ROOM
but have not been joined yet this method will join to those rooms automatically.
If allPublic is true, the rooms option will be ignored.
driver.asyncCall(method, params)
Wraps server method calls to always be async
- Accepts a method name and params (array or single param)
- Returns a Promise
driver.cacheCall(method, key)
Call server method with methodCache
- Accepts a method name and single param (used as cache key)
- Returns a promise
- Resolves with server results or cached if still valid
driver.callMethod(method, params)
Implements either asyncCall or cacheCall if cache exists
- Accepts a method name and params (array or single param)
- Outcome depends on if
methodCache.createwas done for the method
driver.useLog(logger)
Replace the default log, e.g. with on
