counter-bot/index.js
2023-10-25 21:50:21 -04:00

84 lines
2.9 KiB
JavaScript

import config from './config.json' assert {type: "json"};
import { MatrixClient, SimpleFsStorageProvider, AutojoinRoomsMixin } from "matrix-bot-sdk";
import fs from "fs";
const storage = new SimpleFsStorageProvider("storage.json");
const client = new MatrixClient(config.homeserver, config.token, storage);
let lastUpdate, timeoutExists, data;
const error1 = setTimeout(function () {
console.log("\x1b[41m", "ERROR: UNABLE TO CONNECT TO MATRIX SERVER");
}, 10000);
const writeToCache = (data) => {
fs.writeFileSync("count.json", JSON.stringify(data));
};
const readFromCache = () => JSON.parse(fs.readFileSync('count.json').toString());
const lbCommand = async (roomId, message) => {
const unsortedTable = new Map();
for (const row in data.count) {
unsortedTable.set(row, data.count[row]);
}
let leaderboardString = "";
const sortedTable = new Map([...unsortedTable.entries()].sort((a, b) => b[1] - a[1]));
let i = 0;
for (let [id, count] of sortedTable) {
leaderboardString += `${message["sender"]}: ${count}\n`;
if (i++ >= 9) break;
}
client.sendHtmlNotice(roomId, `<h1>Leaderboard</h1><br><p>leaderboardString</p>`);
};
const countCommand = async (roomId, message) => {
client.replyNotice(roomId, message, `You said linux ${message["sender"]} times`)
};
const addCount = async (roomId, message) => {
if (!(message["sender"] in data.count)) {
data.count[message["sender"]] = 0;
}
if (++data.count[message["sender"]] % 10 === 0) {
client.sendNotice(roomId, `${message["sender"]} said linux ${data.count[message["sender"]]} times!`);
}
if (data.count[message["sender"]] > data.max.count) {
data.max.count++;
data.max.username = message["sender"];
if (lastUpdate + 5000 < Date.now()) {
lastUpdate = Date.now();
} else if (!timeoutExists) {
setTimeout(() => {
lastUpdate = Date.now();
timeoutExists = false;
}, lastUpdate + 5000 - Date.now());
timeoutExists = true;
}
}
};
AutojoinRoomsMixin.setupOnClient(client);
client.start().then(() => {
clearTimeout(error1);
// console.log(`Logged into ${client.guilds.cache.size} rooms`); // ? this is possible i think idk how tho
data = readFromCache();
lastUpdate = Date.now();
timeoutExists = false;
});
client.on("room.message", (roomId, event) => {
if (! event["content"] || event["sender"] === config.user) return;
if (event["content"]["body"].toLowerCase().startsWith(config.prefix + "lb")) {
lbCommand(roomId, event);
}
if (event["content"]["body"].toLowerCase().startsWith(config.prefix + "count")) {
countCommand(roomId, event);
}
if (event["content"]["body"].match(/l*.i.*n.*u.*x/mig)){
addCount(roomId, event);
}
})
setInterval(() => writeToCache(data), 60000);