beatsaber-metrics-tracker/src/index.ts

87 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-10-27 11:10:20 +00:00
import { InfluxDB, Point } from "@influxdata/influxdb-client";
import * as dotenv from "dotenv";
2023-10-27 11:52:45 +00:00
import { w3cwebsocket as WebsocketClient } from "websocket";
import { connectMongo } from "./db/mongo";
import { LeaderboardSchema } from "./db/schemas/leaderboard";
2023-10-27 11:15:59 +00:00
const fetch = require("node-fetch");
2023-10-27 11:10:20 +00:00
dotenv.config();
const INFLUXDB_URL = process.env.INFLUXDB_URL;
const INFLUXDB_ORG = process.env.INFLUXDB_ORG;
const INFLUXDB_BUCKET = process.env.INFLUXDB_BUCKET;
const INFLUXDB_TOKEN = process.env.INFLUXDB_TOKEN;
if (!INFLUXDB_URL || !INFLUXDB_ORG || !INFLUXDB_BUCKET || !INFLUXDB_TOKEN) {
throw new Error("Missing InfluxDB environment variables");
}
const writeApi = new InfluxDB({
url: INFLUXDB_URL,
token: INFLUXDB_TOKEN,
}).getWriteApi(INFLUXDB_ORG, INFLUXDB_BUCKET, "ms");
async function update() {
const response = await fetch("https://scoresaber.com/api/players/count");
const count = await response.text();
const point = new Point("scoresaber")
.tag("type", "player_count")
.intField("value", parseInt(count))
.timestamp(new Date());
writeApi.writePoint(point);
console.log(`Updated player count to ${count}`);
}
2023-10-27 11:52:45 +00:00
async function connectWebsocket() {
await connectMongo();
const leaderboard = await LeaderboardSchema.findOne({ _id: "scoresaber" });
if (!leaderboard) {
await LeaderboardSchema.create({ _id: "scoresaber", totalPlays: 0 });
}
let totalScores = leaderboard?.totalPlays || 0;
const socket = new WebsocketClient("wss://scoresaber.com/ws");
socket.onopen = () => {
console.log("Connected to websocket");
};
socket.onclose = () => {
console.log("Disconnected from websocket");
setTimeout(connectWebsocket, 5000);
};
socket.onerror = (error) => {
console.error("Websocket error:", error);
};
socket.onmessage = (message) => {
const data = message.data;
let json;
try {
json = JSON.parse(data.toString());
} catch (e) {
return;
}
const commandName = json.commandName;
const commandData = json.commandData;
if (commandName == "score") {
totalScores++;
LeaderboardSchema.updateOne(
{ _id: "scoresaber" },
{ totalPlays: totalScores }
).exec();
const point = new Point("scoresaber")
2023-10-27 11:53:31 +00:00
.tag("type", "score_count")
2023-10-27 11:52:45 +00:00
.intField("value", totalScores)
.timestamp(new Date());
writeApi.writePoint(point);
}
};
}
2023-10-27 11:10:20 +00:00
update();
2023-10-27 11:52:45 +00:00
connectWebsocket();
2023-10-27 11:10:20 +00:00
setInterval(update, 60_000); // 1 minute