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: [] });
}