Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions __tests__/scoring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,42 @@ describe('Tests for the scoring module', () => {

});

it('getTrending returns formatted top and bottom phrases from the last 7 days', async () => {
const { processScores, getTrending } = require('../scoring');
const phrases = [
'pizza++', 'pizza++', 'pizza++',
'jazz++', 'jazz++',
'mondays--', 'mondays--', 'mondays--',
'meetings--',
];
phrases.forEach(p => processScores({ content: p }));

const result = getTrending(2);
expect(result).toContain('pizza (+3)');
expect(result).toContain('jazz (+2)');
expect(result).toContain('mondays (-3)');
expect(result).toContain('meetings (-1)');
});

it('getTrending shows none when no data', async () => {
const { getTrending } = require('../scoring');
const result = getTrending(5);
expect(result).toContain('Top 5: none');
expect(result).toContain('Bottom 5: none');
});

it('getTrending excludes scores older than 7 days', async () => {
const { processScores, getTrending } = require('../scoring');
const { getDatabase } = require('../db');
processScores({ content: 'pizza++' });
const db = getDatabase();
const oldTimestamp = Date.now() - 8 * 24 * 60 * 60 * 1000;
db.prepare('INSERT INTO scoring (timestamp, phrase, score) VALUES (?, ?, ?)').run(oldTimestamp, 'ancient history', 10);

const result = getTrending(5);
expect(result).not.toContain('ancient history');
});

it('handles multiline scores', async () => {
const { processScores, getScore } = require('../scoring');
await getScore('urch', score => {
Expand Down
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { Client, GatewayIntentBits } = require('discord.js');
const config = require('./config').getConfig();
const { replaceFirstMessage, splitReplaceCommand } = require('./replacer');
const { processScores, getScore } = require('./scoring');
const { processScores, getScore, getTrending } = require('./scoring');
const { oneBlockedMessage } = require('./one-blocked-message');

/**
Expand Down Expand Up @@ -46,6 +46,10 @@ client.on('messageCreate', async (initialQuery) => {
}
}
}
else if (initialQuery.content.indexOf('!trending') === 0)
{
initialQuery.channel.send(getTrending(5));
}
else if (initialQuery.content.indexOf('!score ') == 0)
{
if (oneBlockedMessage(initialQuery)) {
Expand Down
11 changes: 6 additions & 5 deletions replacer.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function replaceFirstMessage(messages, regex, replacement, channel) {
const lowerCaseSearch = regex.toLocaleLowerCase();

return messages.every(msg => {
if(msg.author.bot || msg.content.toString().indexOf('!s') > -1) {
if(msg.author.bot || msg.content.toString().indexOf('!s') === 0) {
console.debug('Ignoring message from bot or search message');
return true;
}
Expand Down Expand Up @@ -144,13 +144,14 @@ function replaceFirstMessage(messages, regex, replacement, channel) {
* @returns {{search:RegExp, isBlockedPhrase:boolean, replacement:string}}
*/
function splitReplaceCommand(replaceCommand) {
var response = replaceCommand.replace(/!s /, '').split('/');
const search = response[0].unicodeToMerica();
const replacement = response[1];
const withoutCommand = replaceCommand.replace(/!s /, '');
const slashIndex = withoutCommand.indexOf('/');
const search = (slashIndex === -1 ? withoutCommand : withoutCommand.slice(0, slashIndex)).unicodeToMerica();
const replacement = slashIndex === -1 ? undefined : withoutCommand.slice(slashIndex + 1);

return {
search,
isBlockedPhrase: isBlockedSearchPhrase(response[0]) || isBlockedSearchPhrase(replacement),
isBlockedPhrase: isBlockedSearchPhrase(search) || (replacement !== undefined && isBlockedSearchPhrase(replacement)),
replacement
};
}
Expand Down
30 changes: 30 additions & 0 deletions scoring.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,37 @@ function processScores(message) {

}

/**
* Gets the top and bottom phrases by score delta over the last 7 days.
*
* @param {number} limit Number of phrases to return for each end.
* @returns {string} Formatted message ready to send to Discord.
*/
function getTrending(limit = 5) {
createSchema(db);
const since = Date.now() - 7 * 24 * 60 * 60 * 1000;
const rows = db.prepare(`
SELECT phrase, SUM(score) as total
FROM scoring
WHERE timestamp >= ?
GROUP BY phrase COLLATE NOCASE
HAVING total != 0
ORDER BY total DESC
`).all(since);

const top = rows.slice(0, limit);
const bottom = rows.slice(-limit).filter(r => !top.includes(r)).reverse();

const fmt = (rows, label) => {
if (rows.length === 0) return `*${label}: none*`;
return `**${label}**\n` + rows.map((r, i) => `${i + 1}. ${r.phrase} (${r.total > 0 ? '+' : ''}${r.total})`).join('\n');
};

return `Trending last 7 days:\n${fmt(top, 'Top 5')}\n\n${fmt(bottom, 'Bottom 5')}`;
}

module.exports = {
getScore,
getTrending,
processScores
};
Loading