2021-10-31 21:33:18 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const config = require('config');
|
2021-11-04 00:51:43 +00:00
|
|
|
const { setTimeout: delay } = require('timers/promises');
|
2021-10-31 21:33:18 +00:00
|
|
|
const bhttp = require('bhttp');
|
|
|
|
const WebSocket = require('ws');
|
2021-11-01 02:45:04 +00:00
|
|
|
const fs = require('fs').promises;
|
2021-11-01 00:12:17 +00:00
|
|
|
const logger = require('simple-node-logger').createSimpleLogger();
|
2021-11-09 12:15:12 +00:00
|
|
|
const { argv } = require('yargs');
|
2021-11-01 00:12:17 +00:00
|
|
|
|
2021-11-09 12:17:53 +00:00
|
|
|
const instance = process.env.NODE_APP_INSTANCE || 'main';
|
2021-11-01 02:45:04 +00:00
|
|
|
const points = {};
|
2021-10-31 21:33:18 +00:00
|
|
|
|
2021-11-09 12:15:12 +00:00
|
|
|
logger.setLevel(argv.level || 'info');
|
2021-11-09 02:11:29 +00:00
|
|
|
|
2021-10-31 21:33:18 +00:00
|
|
|
async function auth() {
|
2021-11-01 15:06:48 +00:00
|
|
|
const httpSession = bhttp.session();
|
2021-11-04 02:53:25 +00:00
|
|
|
const username = config.uniqueUsername ? `${config.user.username}-${new Date().getTime().toString().slice(-5)}` : config.user.username;
|
2021-10-31 21:33:18 +00:00
|
|
|
|
2021-11-04 00:51:43 +00:00
|
|
|
const res = await httpSession.post(`${config.api}/session`, {
|
|
|
|
...config.user,
|
2021-11-04 02:53:25 +00:00
|
|
|
username,
|
2021-11-04 00:51:43 +00:00
|
|
|
}, {
|
2021-11-01 15:06:48 +00:00
|
|
|
encodeJSON: true,
|
|
|
|
});
|
2021-10-31 21:33:18 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
if (res.statusCode !== 200) {
|
|
|
|
throw new Error(`Failed to authenticate: ${res.body.toString()}`);
|
|
|
|
}
|
2021-10-31 21:33:18 +00:00
|
|
|
|
2021-11-04 02:53:25 +00:00
|
|
|
logger.info(`Authenticated as '${username}' with ${config.api}`);
|
2021-11-01 00:12:17 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
return {
|
|
|
|
user: res.body,
|
|
|
|
httpSession,
|
|
|
|
sessionCookie: res.headers['set-cookie'][0],
|
|
|
|
};
|
2021-10-31 21:33:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function getWsId(httpSession) {
|
2021-11-01 15:06:48 +00:00
|
|
|
const res = await httpSession.get(`${config.api}/socket`);
|
2021-10-31 21:33:18 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
if (res.statusCode !== 200) {
|
|
|
|
throw new Error(`Failed to retrieve WebSocket ID: ${res.body.toString()}`);
|
|
|
|
}
|
2021-10-31 21:33:18 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
return res.body;
|
2021-10-31 21:33:18 +00:00
|
|
|
}
|
|
|
|
|
2021-11-12 15:43:20 +00:00
|
|
|
async function setPoints(defaultKey, user, value, { mode = 'add', key }) {
|
|
|
|
const gameKey = key || defaultKey;
|
|
|
|
|
2021-11-06 00:33:52 +00:00
|
|
|
if (!user) {
|
|
|
|
logger.warn(`Failed to set ${gameKey} points for missing user`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
const userKey = `${user.id}:${user.username}`;
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
if (!points[gameKey]) {
|
|
|
|
points[gameKey] = {};
|
|
|
|
}
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
if (mode === 'add') {
|
|
|
|
points[gameKey][userKey] = (points[gameKey][userKey] || 0) + value;
|
|
|
|
}
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
if (mode === 'set') {
|
|
|
|
points[gameKey][userKey] = value;
|
|
|
|
}
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-09 12:17:53 +00:00
|
|
|
await fs.writeFile(`./points-${instance}.json`, JSON.stringify(points, null, 4));
|
2021-11-01 02:45:04 +00:00
|
|
|
}
|
|
|
|
|
2021-11-12 15:43:20 +00:00
|
|
|
function getPoints(game, { user, room, command }) {
|
|
|
|
const userPoints = (points[command] || points[game.key])?.[`${user.id}:${user.username}`];
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
game.sendMessage(`You have scored **${userPoints || 0}** points in ${game.name}, @${user.username}`, room.id);
|
2021-11-01 02:45:04 +00:00
|
|
|
}
|
|
|
|
|
2021-11-12 15:43:20 +00:00
|
|
|
function getLeaderboard(game, { user, room, command }) {
|
|
|
|
const leaderboard = points[command] || points[game.key];
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
if (!leaderboard || Object.keys(leaderboard).length === 0) {
|
|
|
|
game.sendMessage(`No points scored in ${game.name} yet!`, room.id);
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
return;
|
|
|
|
}
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
const curatedLeaderboard = Object.entries(leaderboard)
|
|
|
|
.sort(([, scoreA], [, scoreB]) => scoreB - scoreA)
|
|
|
|
.map(([userKey, score]) => {
|
|
|
|
const username = userKey.split(':')[1];
|
|
|
|
return `**${username === user.username ? '@' : ''}${username}** at **${score}** points`;
|
|
|
|
})
|
|
|
|
.slice(-10)
|
|
|
|
.join(', ');
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-06 00:38:06 +00:00
|
|
|
game.sendMessage(`The top ${Math.min(Object.keys(leaderboard).length, 10)} *${game.name}* players are: ${curatedLeaderboard}`, room.id);
|
2021-11-01 02:45:04 +00:00
|
|
|
}
|
|
|
|
|
2021-11-01 00:12:17 +00:00
|
|
|
function onConnect(data, bot) {
|
2021-11-04 00:51:43 +00:00
|
|
|
bot.socket.transmit('joinRooms', { rooms: config.channels });
|
2021-10-31 21:33:18 +00:00
|
|
|
}
|
|
|
|
|
2021-11-01 00:12:17 +00:00
|
|
|
function onRooms({ rooms, users }, bot) {
|
2021-11-01 15:06:48 +00:00
|
|
|
logger.info(`Joined ${rooms.map((room) => room.name).join(', ')}`);
|
|
|
|
|
|
|
|
/* eslint-disable no-param-reassign */
|
2021-11-09 23:06:28 +00:00
|
|
|
bot.rooms = rooms.reduce((acc, room) => ({ ...acc, [room.id]: room }), {});
|
2021-11-01 15:06:48 +00:00
|
|
|
bot.users = { ...bot.users, ...users };
|
|
|
|
/* eslint-enable no-param-reassign */
|
|
|
|
|
|
|
|
rooms.forEach((room) => {
|
2021-11-04 00:51:43 +00:00
|
|
|
bot.socket.transmit('message', {
|
2021-11-01 15:06:48 +00:00
|
|
|
roomId: room.id,
|
|
|
|
body: `Hi, I am ${config.user.username}, your game host!`,
|
|
|
|
style: config.style,
|
|
|
|
});
|
2021-10-31 21:33:18 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-11-06 00:33:52 +00:00
|
|
|
/* eslint-disable no-param-reassign */
|
|
|
|
function onJoin(data, bot) {
|
2021-11-09 23:06:28 +00:00
|
|
|
if (bot.rooms[data.roomId] && !bot.rooms[data.roomId].userIds?.includes(data.user.id)) {
|
2021-11-06 01:14:33 +00:00
|
|
|
bot.users[data.user.id] = data.user;
|
2021-11-09 23:06:28 +00:00
|
|
|
bot.rooms[data.roomId].userIds.push(data.user.id);
|
2021-11-06 00:33:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function onLeave(data, bot) {
|
2021-11-08 01:48:26 +00:00
|
|
|
if (bot.rooms[data.roomId]) {
|
2021-11-09 23:06:28 +00:00
|
|
|
bot.rooms[data.roomId].userIds = bot.rooms[data.roomId].userIds.filter((userId) => userId !== data.userId);
|
2021-11-08 01:48:26 +00:00
|
|
|
}
|
2021-11-06 00:33:52 +00:00
|
|
|
}
|
|
|
|
|
2021-11-01 02:45:04 +00:00
|
|
|
function onMessage(message, bot, games) {
|
2021-11-01 15:06:48 +00:00
|
|
|
const [, command, subcommand] = message.body?.match(new RegExp(`^${config.prefix}(\\w+)(?:\\:(\\w+))?`)) || [];
|
|
|
|
const user = bot.users[message.userId];
|
2021-11-09 23:06:28 +00:00
|
|
|
const room = bot.rooms[message.roomId];
|
2021-11-01 15:06:48 +00:00
|
|
|
|
|
|
|
if (['leaderboard', 'lead', 'leader', 'leaders', 'scoreboard', 'best'].includes(subcommand) && games[command]) {
|
2021-11-12 15:43:20 +00:00
|
|
|
getLeaderboard(games[command], { user, room, command });
|
2021-11-01 15:06:48 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (['points', 'score'].includes(subcommand) && games[command]) {
|
2021-11-12 15:43:20 +00:00
|
|
|
getPoints(games[command], { user, room, command });
|
2021-11-01 15:06:48 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (command) {
|
|
|
|
const args = message.body.split(/\s+/).slice(1);
|
|
|
|
const game = games[command];
|
|
|
|
|
2021-11-12 15:43:20 +00:00
|
|
|
if (game && game.onCommand) {
|
2021-11-01 15:06:48 +00:00
|
|
|
if (user) {
|
|
|
|
user.points = points[game.key]?.[`${user.id}:${user.username}`] || 0;
|
|
|
|
}
|
|
|
|
|
2021-11-12 15:43:20 +00:00
|
|
|
game.onCommand(args, {
|
2021-11-01 15:06:48 +00:00
|
|
|
...game,
|
2021-11-12 15:43:20 +00:00
|
|
|
command,
|
2021-11-01 15:06:48 +00:00
|
|
|
subcommand,
|
|
|
|
bot,
|
|
|
|
message,
|
|
|
|
user,
|
|
|
|
room,
|
|
|
|
points: points[game.key] || {},
|
|
|
|
logger,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Object.values(games).forEach((game) => game.onMessage?.(message, {
|
2021-11-01 02:45:04 +00:00
|
|
|
...game,
|
|
|
|
bot,
|
|
|
|
message,
|
|
|
|
user,
|
|
|
|
room,
|
|
|
|
logger,
|
2021-11-01 15:06:48 +00:00
|
|
|
}));
|
2021-11-01 00:12:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const messageHandlers = {
|
2021-11-01 15:06:48 +00:00
|
|
|
connect: onConnect,
|
|
|
|
rooms: onRooms,
|
|
|
|
message: onMessage,
|
2021-11-06 00:33:52 +00:00
|
|
|
join: onJoin,
|
|
|
|
leave: onLeave,
|
2021-10-31 21:33:18 +00:00
|
|
|
};
|
|
|
|
|
2021-11-01 02:45:04 +00:00
|
|
|
async function initPoints() {
|
2021-11-01 15:06:48 +00:00
|
|
|
try {
|
2021-11-09 12:17:53 +00:00
|
|
|
const pointsFile = await fs.readFile(`./points-${instance}.json`, 'utf-8');
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
Object.assign(points, JSON.parse(pointsFile));
|
|
|
|
} catch (error) {
|
|
|
|
if (error.code === 'ENOENT') {
|
|
|
|
logger.info('Creating new points file');
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-09 12:17:53 +00:00
|
|
|
await fs.writeFile(`./points-${instance}.json`, '{}');
|
2021-11-01 15:06:48 +00:00
|
|
|
initPoints();
|
|
|
|
}
|
2021-11-01 02:45:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-04 00:51:43 +00:00
|
|
|
function getGames(bot) {
|
2021-11-01 15:06:48 +00:00
|
|
|
const games = config.games.reduce((acc, key) => {
|
2021-11-06 00:33:52 +00:00
|
|
|
const game = require(`./games/${key.game || key}`); // eslint-disable-line global-require, import/no-dynamic-require
|
2021-11-01 15:06:48 +00:00
|
|
|
|
|
|
|
const sendMessage = (body, roomId) => {
|
2021-11-04 00:51:43 +00:00
|
|
|
bot.socket.transmit('message', {
|
2021-11-01 15:06:48 +00:00
|
|
|
roomId,
|
|
|
|
body: `[${game.name || key}] ${body}`,
|
|
|
|
style: config.style,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2021-11-12 15:43:20 +00:00
|
|
|
const setGamePoints = (userId, score, options) => setPoints(key, userId, score, options);
|
|
|
|
|
|
|
|
const curatedGame = {
|
|
|
|
...game,
|
|
|
|
...(key.game && key),
|
|
|
|
name: game.name || key,
|
|
|
|
key,
|
|
|
|
sendMessage,
|
|
|
|
setPoints: setGamePoints,
|
|
|
|
};
|
|
|
|
|
|
|
|
if (game.onStart) {
|
|
|
|
game.onStart({ ...curatedGame, bot });
|
|
|
|
}
|
2021-11-01 15:06:48 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
...acc,
|
2021-11-12 15:43:20 +00:00
|
|
|
[key]: curatedGame,
|
|
|
|
...game.commands?.reduce((commandAcc, command) => ({ ...commandAcc, [command]: curatedGame }), {}),
|
2021-11-01 15:06:48 +00:00
|
|
|
};
|
|
|
|
}, {});
|
|
|
|
|
2021-11-04 00:51:43 +00:00
|
|
|
return games;
|
|
|
|
}
|
2021-11-01 15:06:48 +00:00
|
|
|
|
2021-11-04 02:53:25 +00:00
|
|
|
function handleError(error, socket, domain, data) {
|
|
|
|
logger.error(`${domain} '${JSON.stringify(data)}' triggered error: ${error.message}`);
|
|
|
|
|
|
|
|
if (data?.roomId) {
|
|
|
|
socket.transmit('message', {
|
|
|
|
body: ':zap::robot::zap: Many fragments! Some large, some small.',
|
|
|
|
type: 'message',
|
|
|
|
roomId: data.roomId,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-04 00:51:43 +00:00
|
|
|
async function connect(wsCreds, sessionCookie, bot, games) {
|
|
|
|
const socket = { ws: { readyState: 0 } };
|
|
|
|
|
|
|
|
socket.connect = () => {
|
|
|
|
logger.info(`Attempting to connect to ${config.socket}`);
|
|
|
|
|
|
|
|
socket.ws = new WebSocket(`${config.socket}?${new URLSearchParams({ v: wsCreds.wsId, t: wsCreds.timestamp }).toString()}`, [], {
|
|
|
|
headers: {
|
|
|
|
cookie: sessionCookie,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2021-11-04 02:53:25 +00:00
|
|
|
socket.ws.on('message', async (msg) => {
|
2021-11-04 00:51:43 +00:00
|
|
|
const [domain, data] = JSON.parse(msg);
|
|
|
|
|
2021-11-09 02:11:29 +00:00
|
|
|
logger.debug(`Received ${domain}: ${JSON.stringify(data)}`);
|
|
|
|
|
2021-11-04 00:51:43 +00:00
|
|
|
if (messageHandlers[domain]) {
|
2021-11-04 02:53:25 +00:00
|
|
|
try {
|
|
|
|
await messageHandlers[domain](data, bot, games);
|
|
|
|
} catch (error) {
|
|
|
|
handleError(error, socket, domain, data);
|
|
|
|
}
|
2021-11-04 00:51:43 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
socket.ws.on('close', async (info) => {
|
|
|
|
logger.error(`WebSocket closed, reconnecting in ${config.reconnectDelay} seconds: ${info}`);
|
|
|
|
|
|
|
|
await delay(config.reconnectDelay * 1000);
|
|
|
|
socket.connect();
|
|
|
|
});
|
|
|
|
|
|
|
|
socket.ws.on('error', async (error) => {
|
|
|
|
logger.error(`WebSocket error: ${error.message}`);
|
|
|
|
});
|
|
|
|
|
|
|
|
logger.info(`Connected to ${config.socket}`);
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.transmit = (domain, data) => {
|
|
|
|
socket.ws.send(JSON.stringify([domain, data]));
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.connect();
|
|
|
|
|
|
|
|
return socket;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function init() {
|
|
|
|
const { user, httpSession, sessionCookie } = await auth();
|
|
|
|
const wsCreds = await getWsId(httpSession);
|
|
|
|
|
|
|
|
const bot = {
|
|
|
|
user,
|
|
|
|
httpSession,
|
|
|
|
rooms: [],
|
|
|
|
users: [],
|
|
|
|
};
|
|
|
|
|
|
|
|
const games = getGames(bot);
|
|
|
|
|
|
|
|
bot.socket = await connect(wsCreds, sessionCookie, bot, games);
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-01 15:06:48 +00:00
|
|
|
await initPoints();
|
2021-10-31 21:33:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
init();
|