2022-12-22 14:57:34 +00:00
|
|
|
import { ChatGPTAPIBrowser } from "chatgpt";
|
2022-12-09 09:41:17 +00:00
|
|
|
import { MatrixClient } from "matrix-bot-sdk";
|
2022-12-28 23:16:21 +00:00
|
|
|
import { matrixBotUsername, matrixPrefix } from "./config.js";
|
2022-12-09 09:41:17 +00:00
|
|
|
import { isEventAMessage } from "./utils.js";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Run when *any* room event is received. The bot only sends a message if needed.
|
|
|
|
* @param client
|
|
|
|
* @returns Room event handler, which itself returnings nothing
|
|
|
|
*/
|
2022-12-22 14:57:34 +00:00
|
|
|
export async function handleRoomEvent(client: MatrixClient, chatGPT: ChatGPTAPIBrowser): Promise<(roomId: string, event: any) => Promise<void>> {
|
2022-12-09 09:41:17 +00:00
|
|
|
return async (roomId: string, event: any) => {
|
|
|
|
if (event.sender === matrixBotUsername) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (Date.now() - event.origin_server_ts > 10000) {
|
|
|
|
// Don't send notifications for old events if the bot shuts down for some reason.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isEventAMessage(event)) {
|
2022-12-28 23:16:21 +00:00
|
|
|
let question: string;
|
|
|
|
if (matrixPrefix){
|
|
|
|
if (!event.content.body.startsWith(matrixPrefix)){
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
question = event.content.body.slice(matrixPrefix.length).trimStart();
|
|
|
|
} else {
|
|
|
|
question = event.content.body;
|
|
|
|
}
|
2022-12-09 09:41:17 +00:00
|
|
|
if (question === undefined) {
|
|
|
|
await client.sendReadReceipt(roomId, event.event_id);
|
|
|
|
await client.sendText(roomId,
|
|
|
|
`Question is undefined. I don't currently support encrypted chats, maybe that's the issue?
|
|
|
|
Please add me to an unencrypted chat.`);
|
|
|
|
await client.sendReadReceipt(roomId, event.event_id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
await client.sendReadReceipt(roomId, event.event_id);
|
|
|
|
await client.setTyping(roomId, true, 10000)
|
|
|
|
try {
|
2022-12-22 14:57:34 +00:00
|
|
|
// timeout after 2 minutes (which will also abort the underlying HTTP request)
|
|
|
|
const result = await chatGPT.sendMessage(question, {
|
|
|
|
timeoutMs: 2 * 60 * 1000
|
|
|
|
})
|
2022-12-09 09:41:17 +00:00
|
|
|
await client.setTyping(roomId, false, 500)
|
2022-12-22 14:57:34 +00:00
|
|
|
|
|
|
|
await client.sendText(roomId, `${result.response}`);
|
2022-12-09 09:41:17 +00:00
|
|
|
await client.sendReadReceipt(roomId, event.event_id);
|
|
|
|
} catch (e) {
|
|
|
|
await client.setTyping(roomId, false, 500)
|
|
|
|
await client.sendText(roomId, `ChatGPT returned an error :(`);
|
|
|
|
await client.sendReadReceipt(roomId, event.event_id);
|
|
|
|
console.error("ChatGPS returned an error:");
|
|
|
|
console.error(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-12-22 14:57:34 +00:00
|
|
|
}
|