text-gen-bot/index.js
2022-08-22 01:55:10 -04:00

57 lines
1.9 KiB
JavaScript

import config from './config.json' assert {type: "json"};
import { MatrixClient, SimpleFsStorageProvider, AutojoinRoomsMixin } from "matrix-bot-sdk";
import fs from "fs";
import { PythonShell } from 'python-shell';
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(config.file, 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 options = { args: ['generate'] };
PythonShell.run(pyFile, options, (err, message) => {
if (err) throw err;
client.sendText(roomId, message.toString());
console.log("Message sent!");
}); // ? send generated message to room
};
if (trainCounter >= config.retrain || userMessage[0] === "train") {
console.log("Retraining the AI...");
trainCounter = 0;
// TODO: exec training function
console.log("Training finished!");
};
});
function lineCount(text) {
return fs.readFileSync(text).toString().split("\n").length - 1;
};