/
SmallBot.ts
207 lines (192 loc) · 7.01 KB
/
SmallBot.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import {
ISmallBotConfig,
MatrixJoinedRoomsResponse,
MatrixRoomEvent,
MatrixRoomStateResponse,
MatrixSyncResponse,
MatrixUserProfileResponse,
MatrixWhoAmIResponse,
} from "./ISmallBot.ts";
/**
* Wrapper to interact with the matrix.org client API
*/
export class SmallBot {
private requestId = 0;
/**
* Create an instance of `SmallBot`
* ```ts
* const client = new SmallBot({
* accessToken: "mysecretaccesstoken",
* homeserverUrl: "https://matrix.org/",
* eventHandler: async (client, roomId, event) => {
* if (event.sender !== client.ownUserId) {
* await client.sendRoomNotice(roomId, "You said: <b>" + event.content.body + "</b>");
* }
* }
*});
* ```
* @param config
*/
constructor(private config: ISmallBotConfig) {
if (!config.syncTimeout) config.syncTimeout = 10000;
if (!config.homeserverUrl) config.homeserverUrl = "https://matrix.org";
if (!config.logger) {
config.logger = {
error: (log) => console.error(log),
info: (log) => console.info(log),
};
}
if (!config.store) {
config.store = {
read: () => {
try {
return Deno.readTextFileSync("small.store");
} catch (err) {
return undefined;
}
},
write: (since) => {
Deno.writeTextFileSync("small.store", since);
},
};
}
if (!config.formatHTMLtoPlain) {
config.formatHTMLtoPlain = (html) => html.replace(/<[^>]+>/g, "");
}
}
private async syncLoop(since?: string) {
const syncResponse = await this.getSync(since);
for (const entry of syncResponse.rooms.join.entries()) {
for (const event of entry[1].timeline.events) {
await this.config.eventHandler(this, entry[0], event);
}
}
this.config.store?.write(syncResponse.next_batch);
this.syncLoop(syncResponse.next_batch);
}
private async doRequest<T>(uri: string, query: string[], method?: string, body?: string) {
const url = this.config.homeserverUrl + (this.config.homeserverUrl?.endsWith("/") ? "" : "/") + "_matrix/client/r0/" + uri;
const q = "?access_token=" + this.config.accessToken + (query.length > 0 ? "&" : "") + query.join("&");
const response = await fetch(url + q, {
method: method ? method : "GET",
body: body
});
this.config.logger?.info("Fetched from '" + url + "'");
return <T>await response.json();
}
private async sendEvent(roomId: string, eventType: string, content: string) {
const txnId = (new Date().getTime()) + "__REQ" + (++this.requestId);
await this.doRequest("rooms/" + escape(roomId) + "/send/" + eventType + "/" + txnId, [], "PUT", content);
}
public get ownUserId(): string | undefined {
return this.config.userId;
}
/**
* Returns `MatrixUserProfileResponse` containing the current display name of the userId
* ```ts
* const profile = await client.getUserProfile(event.sender);
* ```
* @param userId ID of the user to retrieve the profile
*/
async getUserProfile(userId: string) {
return await this.doRequest<MatrixUserProfileResponse>(
"profile/" + userId,
[],
);
}
/**
* Returns `MatrixRoomStateResponse` of the given room id containing the current display name
* @param roomId ID of Room to get the display name
*/
async getRoomStateName(roomId: string) {
return await this.doRequest<MatrixRoomStateResponse>("rooms/" + escape(roomId) + "/state/m.room.name/", []);
}
/**
* Listens for new events on `/sync` with a timeout based on `syncTimeout`
* This method is looped automatically when `start()` is called
* @param since token used to sync events from a specific point in time
*/
async getSync(since?: string) {
const response = await this.doRequest<MatrixSyncResponse>(
"sync",
[
"full_state=false",
"timeout=" + this.config.syncTimeout,
(since ? ("since=" + since) : ""),
]
);
if (response.rooms && response.rooms.join) {
response.rooms.join = new Map<string, MatrixRoomEvent>(Object.entries(response.rooms.join));
} else {
response.rooms = {join: new Map<string, MatrixRoomEvent>()};
}
return response;
}
/**
* Returns the `MatrixWhoAmIResponse` containing the userId of the bot
*/
async whoAmI() {
return await this.doRequest<MatrixWhoAmIResponse>("account/whoami", []);
}
/**
* Returns the `MatrixJoinedRoomsResponse` containing a Map of all joined roomId's
*/
async joinedRooms() {
return await this.doRequest<MatrixJoinedRoomsResponse>("joined_rooms", []);
}
/**
* Alias of `sendMessage` with msgType `m.notice`
* @param roomId ID of the Room
* @param msg the HTML body of the message `formatHTMLtoPlain` will be used to create the plain-text version
*/
async sendRoomNotice(roomId: string, msg: string) {
await this.sendMessage(roomId, "m.notice", msg);
}
/**
* Alias of `sendMessage` with msgType `m.text`
* @param roomId ID of the Room
* @param msg the HTML body of the message `formatHTMLtoPlain` will be used to create the plain-text version
*/
async sendRoomText(roomId: string, msg: string) {
await this.sendMessage(roomId, "m.text", msg);
}
/**
* Send a custom message to a room
* ```ts
* await client.sendMessage(roomId, "m.text", "<b>hello world</b>");
* ```
* @param roomId ID of the Room
* @param msgType type like `m.text` or `m.notice`
* @param formattedBody the HTML body of the message `formatHTMLtoPlain` will be used to create the plain-text version
*/
async sendMessage(
roomId: string,
msgType: string,
formattedBody: string,
) {
const plain = this.config.formatHTMLtoPlain ? this.config.formatHTMLtoPlain(formattedBody) : "";
const payload = {
msgtype: msgType,
format: "org.matrix.custom.html",
body: plain,
formatted_body: formattedBody
};
await this.sendEvent(roomId, "m.room.message", JSON.stringify(payload));
}
/**
* Call this method to start the /sync loop and send all events into your custom handler
* ```ts
* await client.start();
* ```
*/
async start() {
try {
if (!this.config.userId) {
this.config.userId = (await this.whoAmI()).user_id;
}
this.syncLoop(this.config.store?.read());
} catch (err) {
this.config.logger?.error(err);
}
}
}