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:47:59 +00:00
|
|
|
async function setPoints(defaultKey, user, value, { mode = 'add', key } = {}) {
|
2021-11-12 15:43:20 +00:00
|
|
|
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-15 23:40:02 +00:00
|
|
|
function getPoints(game, rawUsername, { user, room, command }) {
|
|
|
|
const username = rawUsername?.replace(/^@/, '');
|
2021-11-15 21:50:25 +00:00
|
|
|
const gamePoints = points[command] || points[game.key];
|
2021-11-01 02:45:04 +00:00
|
|
|
|
2021-11-15 21:50:25 +00:00
|
|
|
const userPoints = username
|
|
|
|
? Object.entries(gamePoints || {}).find(([identifier]) => identifier.split(':')[1] === username)?.[1]
|
|
|
|
: gamePoints?.[`${user?.id}:${user?.username}`];
|
|
|
|
|
|
|
|
game.sendMessage(`${username ? `**${username}** has` : '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`;
|
|
|
|
})
|
2021-11-15 21:50:25 +00:00
|
|
|
.slice(0, 10)
|
2021-11-01 15:06:48 +00:00
|
|
|
.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-15 20:55:42 +00:00
|
|
|
const body = message.originalBody || message.body;
|
|
|
|
const [, command, subcommand] = body?.match(new RegExp(`^${config.prefix}(\\w+)(?:\\:(\\w+))?`)) || [];
|
2021-11-15 19:54:00 +00:00
|
|
|
const user = bot.users[message.userId] || message.user;
|
2021-11-09 23:06:28 +00:00
|
|
|
const room = bot.rooms[message.roomId];
|
2021-11-01 15:06:48 +00:00
|
|
|
|
|
|
|
if (command) {
|
2021-11-15 20:55:42 +00:00
|
|
|
const args = body.split(/\s+/).slice(1);
|
2021-11-01 15:06:48 +00:00
|
|
|
const game = games[command];
|
|
|
|
|
2021-11-15 21:50:25 +00:00
|
|
|
if (['leaderboard', 'lead', 'leader', 'leaders', 'scoreboard', 'best'].includes(subcommand) && games[command]) {
|
|
|
|
getLeaderboard(games[command], { user, room, command });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (['points', 'score'].includes(subcommand) && games[command]) {
|
|
|
|
getPoints(games[command], args[0], { user, room, command });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
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,
|
2022-01-07 23:26:01 +00:00
|
|
|
user: user && {
|
|
|
|
...user,
|
|
|
|
points: points[game.key]?.[`${user.id}:${user.username}`] || 0,
|
|
|
|
},
|
2021-11-01 02:45:04 +00:00
|
|
|
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
|
|
|
|
2022-01-07 21:52:44 +00:00
|
|
|
const sendMessage = (body, roomId, options, recipient) => {
|
2021-11-04 00:51:43 +00:00
|
|
|
bot.socket.transmit('message', {
|
2021-11-01 15:06:48 +00:00
|
|
|
roomId,
|
2022-01-07 21:52:44 +00:00
|
|
|
recipient,
|
|
|
|
type: recipient ? 'whisper' : 'message',
|
2021-11-15 19:44:34 +00:00
|
|
|
body: options?.label === false ? body : `[${game.name || key}] ${body}`,
|
2021-11-01 15:06:48 +00:00
|
|
|
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) {
|
2022-07-15 15:49:01 +00:00
|
|
|
logger.error(`${domain} '${JSON.stringify(data)}' triggered error: ${error.message} ${error.stack}`);
|
2021-11-04 02:53:25 +00:00
|
|
|
|
|
|
|
if (data?.roomId) {
|
|
|
|
socket.transmit('message', {
|
|
|
|
body: ':zap::robot::zap: Many fragments! Some large, some small.',
|
|
|
|
type: 'message',
|
|
|
|
roomId: data.roomId,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-06 22:55:41 +00:00
|
|
|
async function connect(bot, games) {
|
2021-11-04 00:51:43 +00:00
|
|
|
const socket = { ws: { readyState: 0 } };
|
|
|
|
|
2022-01-06 22:55:41 +00:00
|
|
|
socket.connect = async () => {
|
|
|
|
const { user, httpSession, sessionCookie } = await auth();
|
|
|
|
const wsCreds = await getWsId(httpSession);
|
|
|
|
|
|
|
|
bot.user = user;
|
|
|
|
bot.httpSession = httpSession;
|
|
|
|
|
2021-11-04 00:51:43 +00:00
|
|
|
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 bot = {
|
|
|
|
rooms: [],
|
|
|
|
users: [],
|
|
|
|
};
|
|
|
|
|
|
|
|
const games = getGames(bot);
|
|
|
|
|
2022-01-06 22:55:41 +00:00
|
|
|
bot.socket = await connect(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();
|