matrix-js-bot-sdk
A lightweight version of the matrix-js-sdk intended for bots. For help and support, visit #matrix-bot-sdk:t2bot.io
Installing
This package can be found on npm:
npm install matrix-bot-sdk
Quickstart Bot
Here's an example of a very simple bot written using this library. It will auto-join rooms and respond to !hello
as a command.
import {
MatrixClient,
SimpleFsStorageProvider,
AutojoinRoomsMixin,
RichReply,
} from "matrix-bot-sdk";
const homeserverUrl = "https://matrix.org";
const accessToken = "YourSecretAccessToken";
const storage = new SimpleFsStorageProvider("hello-bot.json");
const client = new MatrixClient(homeserverUrl, accessToken, storage);
AutojoinRoomsMixin.setupOnClient(client);
client.on("room.message", handleCommand);
client.start().then(() => console.log("Client started!"));
async function handleCommand(roomId, event, client) {
if (!event["content"]) return;
if (event["content"]["msgtype"] !== "m.text") return;
if (event["sender"] === await client.getUserId()) return;
const body = event["content"]["body"];
if (!body || !body.startsWith("!hello")) return;
const replyBody = "Hello World!";
const reply = RichReply.createFor(roomId, event, replyBody, replyBody);
reply["msgtype"] = "m.notice";
client.sendMessage(roomId, reply);
}
Usage
const MatrixClient = require("matrix-bot-sdk").MatrixClient;
const AutojoinRoomsMixin = require("matrix-bot-sdk").AutojoinRoomsMixin;
const client = new MatrixClient("https://matrix.org", "your_access_token_here");
AutojoinRoomsMixin.setupOnClient(client);
client.on("room.message", (roomId, event) => {
if (!event["content"]) return;
console.log(event["sender"] + " says " + event["content"]["body"]);
client.sendMessage(roomId, {
"msgtype": "m.notice",
"body": "hello!",
});
client.sendNotice(roomId, "hello!");
});
client.on("room.event", (roomId, event) => {
if (!event["content"]) return;
console.log(event["sender"] + " sent " + event["type"]);
});
client.start().then(() => console.log("Client started!"));
Rich replies
To automatically process rich replies coming into the client:
const MatrixClient = require("matrix-bot-sdk").MatrixClient;
const RichRepliesPreprocessor = require("matrix-bot-sdk").RichRepliesPreprocessor;
const IRichReplyMetadata = require("matrix-bot-sdk").IRichReplyMetadata;
const client = new MatrixClient("https://matrix.org", "your_access_token_here");
client.addPreprocessor(new RichRepliesPreprocessor(fetchRealEventContents: false));
const event = {};
if (event["mx_richreply"]) {
const reply = <IRichReplyMetadata>event["mx_richreply"];
console.log("The original event was " + reply.parentEventId + " and the text was " + reply.fallbackPlainBody);
}
To send a rich reply to an event:
const MatrixClient = require("matrix-bot-sdk").MatrixClient;
const AutojoinRoomsMixin = require("matrix-bot-sdk").AutojoinRoomsMixin;
const RichReply = require("matrix-bot-sdk").RichReply;
const client = new MatrixClient("https://matrix.org", "your_access_token_here");
AutojoinRoomsMixin.setupOnClient(client);
client.on("room.message", (roomId, event) => {
if (!event["content"]) return;
const newEvent = RichReply.createFor(event, "Hello!", "<b>Hello!</b>");
newEvent["msgtype"] = "m.notice";
client.sendMessage(roomId, newEvent);
});
client.start().then(() => console.log("Client started!"));
Application Services
Application service support is an experimental feature of the SDK. This does things like Intent management, impersonation, and transaction handling on behalf of the application.
You'll need to load your registration file from somewhere, however the fastest path is:
const Appservice = require("matrix-bot-sdk").Appservice;
const registration = {
as_token: "YourTokenHere",
hs_token: "YourTokenHere",
sender_localpart: "_some_bridge",
namespaces: {
users: [
{
exclusive: true,
regex: "@_some_bridge_.*",
},
],
rooms: [],
aliases: [],
},
};
const options = {
port: 9000,
bindAddress: "0.0.0.0",
homeserverName: "matrix.org",
homeserverUrl: "https://matrix.org",
};
const appservice = new Appservice(options, registration);
appservice.getIntent("_some_bridge_user").sendText("!somewhere:domain.com", "Hello world!");
appservice.getIntentForSuffix("user").sendText("!somewhere:domain.com", "Hello world!");
Room upgrades
When a room is upgraded, bots and bridges might have to relocate data to the new room. This SDK can handle the easier part of ensuring the bot/bridge is in the new room, and emits events to make the remainder of the process a little easier.
An upgrade happens in two phases: a room.archived
phase where the old room is flagged as being replaced by another room and a room.upgraded
phase once the bot/bridge is aware of the new room. Bots and appservices can be told to automatically try and join the new room by attaching a AutojoinUpgradedRoomsMixin
to the client/appservice, much like the AutojoinRoomsMixin
.
Bots and appservices should listen for room.upgraded
to perform a data transfer as this is when there is referential integrity between the two rooms. Prior to an upgrade, there is no guarantee that the replacement room advertised is actually valid.
To get the full chain of rooms, use getRoomUpgradeHistory(roomId)
on a MatrixClient
(ie: the botIntent.underlyingClient
or your own).