62 lines
2.2 KiB
JavaScript
62 lines
2.2 KiB
JavaScript
import config from './config.json' assert {type: "json"};
|
|
import { MatrixClient, SimpleFsStorageProvider, AutojoinRoomsMixin } from "matrix-bot-sdk";
|
|
import { spawn } from 'node:child_process';
|
|
import fs from "fs";
|
|
|
|
const storage = new SimpleFsStorageProvider("storage.json");
|
|
const client = new MatrixClient(config.homeserver, config.token, storage);
|
|
const pyFile = "textgen.py";
|
|
|
|
AutojoinRoomsMixin.setupOnClient(client);
|
|
client.start().then(() => console.log(`Client has started!\n`));
|
|
|
|
let messageCounter = 0;
|
|
let trainCounter = 0;
|
|
|
|
client.on("room.message", (roomId, event) => {
|
|
if (!event["content"] || event["sender"] === config.user) return;
|
|
|
|
++messageCounter;
|
|
++trainCounter;
|
|
let userMessage = event["content"]["body"].split(" ");
|
|
|
|
if (userMessage[0].startsWith(config.prefix)) {
|
|
userMessage[0] = userMessage[0].replace(config.prefix, '').toLowerCase();
|
|
} else {
|
|
fs.appendFile('training-matrix.txt', userMessage.join(' ') + "\n", function (err) {
|
|
if (err) throw err;
|
|
});
|
|
};
|
|
|
|
// ? send message every N messages if big enough dataset is present
|
|
if ((!(messageCounter % config.frequency) && !(lineCount(config.file) < config.size)) || userMessage[0] === "speak") {
|
|
console.log("Generating message...");
|
|
|
|
userMessage.shift()
|
|
const python = spawn('python', [pyFile, "generate", userMessage.join(' ')]);
|
|
|
|
python.stdout.on('data', (message) => {
|
|
message = message.toString();
|
|
client.sendText(roomId, message); // ? send generated message to room
|
|
});
|
|
console.log("Message sent!");
|
|
python.on('close'); // ? close python process when finished
|
|
};
|
|
|
|
if (trainCounter >= config.retrain || userMessage[0] === "train") {
|
|
console.log("Retraining the AI...");
|
|
|
|
trainCounter = 0;
|
|
const python = spawn('python', [pyFile, "train"]);
|
|
|
|
python.stdout.on('data', function (message) {
|
|
console.log(message.toString());
|
|
});
|
|
console.log("Training finished!");
|
|
python.on('close'); // ? close python process when finished
|
|
};
|
|
});
|
|
|
|
function lineCount(text) {
|
|
return fs.readFileSync(text).toString().split("\n").length - 1;
|
|
};
|