Readme

A example Serverless Bot for Matrix chat. See https://vlad.roam.garden/How-to-create-a-serverless-Matrix-Chat-bot for a more detailed write-up on how to set one up!

To test this bot:

  • invite serverless-echo@matrix.org to your unencrypted room
  • Send a message starting with !echo and the bot will repeat content after.

Use https://matrix-serverless.netlify.app/ to configure Matrix to call the endpoint on newly received messages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { sendMatrixChatRoomTextMessage } from "https://esm.town/v/vlad/sendMatrixChatRoomTextMessage";
import { joinMatrixRoom } from "https://esm.town/v/vlad/joinMatrixRoom";
import process from "node:process";
export async function serverlessMatrixEchoBot(
req: express.Request,
res: express.Response,
) {
// Todo: explicitly ignore encrypted messages, or matrix will keep try sending them
// as rn this will just error out
const event = req.body.notification;
const matrixToken = process.env.matrixEchoBot;
/**
* Accept all invites sent to the bot, generally this is optional
* (e.g. I have a personal bot that I only talk to in a specific room and so I just joined that room from bot account)
* but you'd want this if you want to make a bot anyone can interact with
*/
if (event.membership === "invite") {
await joinMatrixRoom(matrixToken, event.room_id);
return res.json({ rejected: [] });
}
//
const text = event.content.body;
const roomId = event.room_id;
//
const echoText = "!echo ";
if (text.startsWith(echoText)) {
await sendMatrixChatRoomTextMessage(
matrixToken,
roomId,
text.slice(echoText.length),
);
}
//
// This is important - if you don't return this JSON -
// Matrix won't consider notification as processed and will keep sending you the same one
return res.json({ rejected: [] });
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
vlad-serverlessmatrixechobot.express.val.run
v35
October 23, 2023