Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
typeofweb committed Sep 4, 2022
1 parent 7462f40 commit 435d31a
Show file tree
Hide file tree
Showing 26 changed files with 463 additions and 256 deletions.
6 changes: 5 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,11 @@
],
"functional/prefer-readonly-type": "error",
"functional/no-this-expression": "error",
"functional/no-loop-statement": "error"
"functional/no-loop-statement": "error",

"typescript-eslint/no-unsafe-assignment": "off",
"typescript-eslint/no-unsafe-call": "off",
"typescript-eslint/no-unsafe-member-access": "off"
},
"overrides": [
{
Expand Down
20 changes: 9 additions & 11 deletions count-messages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Discord, { Intents } from 'discord.js';
import Discord, { GatewayIntentBits } from 'discord.js';
import fetch from 'node-fetch';

import { getConfig } from './src/config';
Expand All @@ -23,11 +23,14 @@ async function init() {
process.exit(0);
}

const intents = new Intents([
Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need
'GUILD_MEMBERS', // lets you request guild members (i.e. fixes the issue)
]);
const client = new Discord.Client({ ws: { intents } });
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
});
await client.login(getConfig('DISCORD_BOT_TOKEN'));

const guild = await client.guilds.fetch(GUILD_ID);
Expand All @@ -42,11 +45,6 @@ async function init() {
await members.reduce(async (acc, member) => {
await acc;

if (member.deleted) {
// console.log(`Skipping… member.deleted`);
return acc;
}

const existingMember = await statsCollection.findOne({
memberId: member.id,
});
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
},
"keywords": [],
"author": "Michał Miszczyszyn <[email protected]> (https://typeofweb.com/)",
"license": "ISC",
"license": "AGPL",
"dependencies": {
"@types/bluebird": "3.5.36",
"algoliasearch": "4.14.2",
"bluebird": "3.7.2",
"bufferutil": "4.0.6",
"discord.js": "12.5.3",
"dotenv": "10.0.0",
"discord.js": "14.3.0",
"dotenv": "16.0.2",
"isolated-vm": "4.4.1",
"mongodb": "4.9.1",
"monitorss": "6.14.11",
Expand Down
39 changes: 23 additions & 16 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
import Discord from 'discord.js';
import Discord, { GatewayIntentBits } from 'discord.js';
import MonitoRSS from 'monitorss';
import type { ClientConfig } from 'monitorss';
import Cache from 'node-cache';

import { handleCommand } from './commands';
import { KARMA_REGEX } from './commands/karma';
import { getConfig } from './config';
import { createHttpServer } from './http-server';
import { InvalidUsageError } from './types';
import { getWeekNumber, wrapErr } from './utils';
import { getStatsCollection, initDb } from './db';
import { messageToReflinks } from './commands/reflink';
import { getConfig } from './config';
import { updateKarmaRoles } from './cron/roles/karma';
import { updateStatsRoles } from './cron/roles/stats';
import { getStatsCollection, initDb } from './db';
import { createHttpServer } from './http-server';
import { thx } from './thx';
import { InvalidUsageError } from './types';
import { getWeekNumber, wrapErr } from './utils';

const MESSAGE_COLLECTOR_CACHE_S = 60 * 60;
const messageCollectorCache = new Cache({ stdTTL: MESSAGE_COLLECTOR_CACHE_S });

const client = new Discord.Client();
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
});

const settings: { readonly setPresence: boolean; readonly config: ClientConfig } = {
setPresence: true,
Expand Down Expand Up @@ -77,7 +84,7 @@ function isCommand(msg: Discord.Message) {
// const ROLE_MUTED_NAME = 'muted' as const;
// const MAX_MENTIONS_PER_MESSAGE = 10;

client.on('message', async (msg) => {
client.on('messageCreate', async (msg) => {
if (msg.author.bot) {
return;
}
Expand All @@ -92,14 +99,15 @@ client.on('message', async (msg) => {
// }

if (msg.content === `(╯°□°)╯︵ ┻━┻`) {
return msg.channel.send(`┬─┬ノ( ◕◡◕ ノ)`);
await msg.channel.send(`┬─┬ノ( ◕◡◕ ノ)`);
return;
}

if (isCommand(msg)) {
try {
const collector = msg.channel.createMessageCollector(
(m: Discord.Message) => m.author.id === client.user?.id,
);
const collector = msg.channel.createMessageCollector({
filter: (m: Discord.Message) => m.author.id === client.user?.id,
});
await handleCommand(msg);
const ids = collector.collected.map((m) => m.id);
messageCollectorCache.set(msg.id, ids);
Expand All @@ -111,16 +119,15 @@ client.on('message', async (msg) => {
console.error(err);
void msg.reply('przepraszam, ale coś poszło nie tak…');
}
} finally {
return msg.channel.stopTyping(true);
}
}

void updateMessagesCount(msg.member?.id, msg.member?.displayName).catch(console.error);

const maybeReflinks = messageToReflinks(msg.content);
if (maybeReflinks.length > 0) {
return msg.reply(maybeReflinks);
await msg.reply(maybeReflinks.join('\n'));
return;
}

await thx(msg);
Expand Down Expand Up @@ -156,7 +163,7 @@ async function updateMessagesCount(
}

function revertCommand(msg: Discord.Message) {
if (!messageCollectorCache.has(msg.id) || msg.channel.type === 'dm') {
if (!messageCollectorCache.has(msg.id) || msg.channel.type === Discord.ChannelType.DM) {
return undefined;
}
// eslint-disable-next-line functional/prefer-readonly-type
Expand Down
13 changes: 8 additions & 5 deletions src/commands/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import * as Discord from 'discord.js';
import Sinon from 'sinon';
import { expect } from 'chai';
import type * as Discord from 'discord.js';
import Sinon from 'sinon';

import { getMessageMock } from '../../test/mocks';

import { handleCommand } from '.';

describe('index', () => {
describe('handleCommand', () => {
it('should show help message', async () => {
const msg = getMessageMock('msg', { content: '!help' });
const memberMock = {
hasPermission: Sinon.spy(),
permissions: {
has: Sinon.spy(),
},
};
msg.guild.member.returns(memberMock);
msg.guild.members.cache.get.returns(memberMock);
msg.author.send.resolves();
await handleCommand((msg as unknown) as Discord.Message);
await handleCommand(msg as unknown as Discord.Message);
expect(msg.reply).to.have.been.calledOnceWith('Wysłałam Ci DM ze wszystkimi komendami! 🎉');
});
});
Expand Down
26 changes: 13 additions & 13 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Discord from 'discord.js';
import type { PermissionString } from 'discord.js';
import type { PermissionsString } from 'discord.js';

import { getConfig } from '../config';
import type { Command } from '../types';
Expand Down Expand Up @@ -71,7 +71,7 @@ const allCommands = [
];

const cooldowns = new Discord.Collection<string, Discord.Collection<string, number>>();
const PERMISSION_TO_OVERRIDE_COOLDOWN: PermissionString = 'ADMINISTRATOR';
const PERMISSION_TO_OVERRIDE_COOLDOWN: PermissionsString = 'Administrator';

function verifyCooldown(msg: Discord.Message, command: Command) {
if (typeof command.cooldown !== 'number') {
Expand All @@ -92,8 +92,8 @@ function verifyCooldown(msg: Discord.Message, command: Command) {
const expirationTime = timestamps.get(msg.author.id)! + cooldownAmount;

if (now < expirationTime) {
const member = msg.guild.member(msg.author);
if (member?.hasPermission(PERMISSION_TO_OVERRIDE_COOLDOWN)) {
const member = msg.guild.members.cache.get(msg.author.id);
if (member?.permissions.has(PERMISSION_TO_OVERRIDE_COOLDOWN)) {
return;
}

Expand All @@ -114,7 +114,7 @@ function printHelp(msg: Discord.Message, member: Discord.GuildMember) {
return a.name.localeCompare(b.name);
})
.filter((command) => {
if (command.permissions && !member.hasPermission(command.permissions)) {
if (command.permissions && !member.permissions.has(command.permissions)) {
return false;
}
return true;
Expand All @@ -128,9 +128,9 @@ function printHelp(msg: Discord.Message, member: Discord.GuildMember) {
];

return msg.author
.send(data, { split: true })
.send(data.join('\n'))
.then(() => {
if (msg.channel.type === 'dm') {
if (msg.channel.type === Discord.ChannelType.DM) {
return undefined;
}
return msg.reply('Wysłałam Ci DM ze wszystkimi komendami! 🎉');
Expand All @@ -155,7 +155,7 @@ export function handleCommand(msg: Discord.Message) {
const [, maybeCommand, rest] = COMMAND_PATTERN.exec(msg.content) || [null, null, null];

if (maybeCommand === 'help') {
const member = msg.guild.member(msg.author);
const member = msg.guild.members.cache.get(msg.author.id);
if (member) {
return printHelp(msg, member);
}
Expand All @@ -170,16 +170,16 @@ export function handleCommand(msg: Discord.Message) {
return processCommand(msg, command, rest);
}

function processCommand(msg: Discord.Message, command: Command, rest: string | null) {
const member = msg.guild?.member(msg.author);
async function processCommand(msg: Discord.Message, command: Command, rest: string | null) {
const member = msg.guild?.members.cache.get(msg.author.id);

if (!member || (command.permissions && !member.hasPermission(command.permissions))) {
if (!member || (command.permissions && !member.permissions.has(command.permissions))) {
return undefined; // silence is golden
}

void msg.channel.startTyping();
await msg.channel.sendTyping();

if (command.guildOnly && msg.channel.type !== 'text') {
if (command.guildOnly && msg.channel.type !== Discord.ChannelType.GuildText) {
throw new InvalidUsageError(`to polecenie można wywołać tylko na kanałach.`);
}

Expand Down
6 changes: 3 additions & 3 deletions src/commands/karma.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import Discord from 'discord.js';
import Bluebird from 'bluebird';
import Discord from 'discord.js';

import type { KarmaAgg } from '../data/karma';
import {
getKarmaForMember,
getKarmaForAllMembers,
KarmaAgg,
getKarmaForMembers,
getKarmaDescription,
} from '../data/karma';
import { getKarmaCollection, initDb } from '../db';
import type { Command } from '../types';

export const KARMA_REGEX = new RegExp(
`^(${Discord.MessageMentions.USERS_PATTERN.source}).*\\+\\+\\s*`,
`^(${Discord.MessageMentions.UsersPattern.source}).*\\+\\+\\s*`,
);

const addKarma: Command = {
Expand Down
14 changes: 8 additions & 6 deletions src/commands/m1.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { Command } from '../types';
import type { Command } from '../types';

const m1: Command = {
name: 'm1',
description: 'Apple silicon m1',
args: 'prohibited',
cooldown: 10,
execute(msg) {
return msg.channel.send([
`👨‍💻 ***Czy Apple Silicon m1 jest gotowe dla developerów?*** 👩‍💻 \n`,
`https://isapplesiliconready.com/for/developer`,
`https://www.apple.com/mac/m1/`,
]);
return msg.channel.send(
[
`👨‍💻 ***Czy Apple Silicon m1 jest gotowe dla developerów?*** 👩‍💻 \n`,
`https://isapplesiliconready.com/for/developer`,
`https://www.apple.com/mac/m1/`,
].join('\n'),
);
},
};

Expand Down
Loading

0 comments on commit 435d31a

Please sign in to comment.