1
0
Fork 0

handle help better, wrap channel and message, add crons

This commit is contained in:
Sean Sube 2022-12-26 18:01:51 -06:00
parent 47633e7e48
commit 8d7b3d998f
36 changed files with 523 additions and 165 deletions

View File

@ -8,8 +8,10 @@
"type": "module",
"dependencies": {
"@apextoaster/js-utils": "^0.5.0",
"@types/node-schedule": "^2.1.0",
"bunyan": "^1.8.15",
"discord.js": "^14.7.1",
"node-schedule": "^2.1.0",
"noicejs": "^5.0.0-3",
"rcon-client": "^4.2.3",
"sqlite3": "^5.1.4",

View File

@ -15,6 +15,11 @@ export interface ParsedArgs {
rconPassword: string;
rconPort: number;
sqliteDatabase: string;
/**
* Placeholder to allow better exit logic.
*/
help?: boolean;
}
export const APP_NAME = 'conan-discord';
@ -29,7 +34,6 @@ export async function parseArgs(argv: Array<string>): Promise<ParsedArgs> {
const parser = yargs(argv).usage(`Usage: ${APP_NAME} [options]`)
.options({
bots: {
// choices: Object.keys(BOTS),
default: ['discord'] as Array<string>,
desc: 'bots to launch',
string: true,

View File

@ -1,24 +1,25 @@
import { doesExist, mustExist } from '@apextoaster/js-utils';
import { Client, Events, FormattingPatterns, GatewayIntentBits, Message, Partials } from 'discord.js';
import {
ChannelType,
Client,
Events,
FormattingPatterns,
GatewayIntentBits,
Message as DiscordMessage,
Partials,
TextChannel,
} from 'discord.js';
import { Author, Command, CommandContext } from '../command/index.js';
import { CommandContext } from '../command/index.js';
import { catchAndLog } from '../utils/async.js';
import { authorName, matchCommands } from '../utils/command.js';
import { Bot, BotContext } from './index.js';
import { Author, Bot, BotContext, Channel, Message } from './index.js';
/**
* Discord-only methods.
*
* @public
*/
export interface DiscordBot extends Bot {
destroy(): void;
}
async function onMessage(context: CommandContext, client: Client<true>, message: Message) {
export async function onMessage(context: CommandContext, client: Client<true>, discordMessage: DiscordMessage): Promise<void> {
const { args, commands, logger } = context;
const { author, content } = message;
const { author, content } = discordMessage;
const name = authorName(author);
logger.debug({
text: content,
user: name,
@ -30,6 +31,8 @@ async function onMessage(context: CommandContext, client: Client<true>, message:
}
const matchingCommands = matchCommands(content, commands, args.commandPrefix);
const message = await messageFromDiscord(client, discordMessage);
for (const command of matchingCommands) {
logger.debug({
command: command.name,
@ -51,6 +54,45 @@ async function onMessage(context: CommandContext, client: Client<true>, message:
}
}
async function channelFromDiscord(client: Client, channel: TextChannel): Promise<Channel> {
return {
name: channel.id,
async edit(options) {
await channel.edit(options);
}
};
}
async function messageFromDiscord(client: Client, message: DiscordMessage): Promise<Message> {
const channel = await getChannel(client, message.channelId);
return {
author: {
discriminator: message.author.discriminator,
username: message.author.username,
},
channel,
content: message.content,
async reply(response: string) {
const reply = await message.reply(response);
return messageFromDiscord(client, reply);
},
};
}
async function getChannel(client: Client, name: string): Promise<Channel> {
const channel = await client.channels.fetch(name);
if (doesExist(channel)) {
if (channel.type === ChannelType.GuildText) {
return channelFromDiscord(client, channel);
} else {
throw new Error('invalid channel type');
}
} else {
throw new Error('channel does not exist');
}
}
async function getUser(client: Client, ident: string): Promise<Author> {
const match = FormattingPatterns.User.exec(ident);
@ -73,7 +115,7 @@ async function getUser(client: Client, ident: string): Promise<Author> {
*
* @public
*/
export async function discordConnect(botContext: BotContext, clientCtor: typeof Client = Client): Promise<DiscordBot> {
export async function discordConnect(botContext: BotContext, clientCtor: typeof Client = Client): Promise<Bot> {
const { args, logger } = botContext;
const client = new clientCtor({
@ -98,8 +140,11 @@ export async function discordConnect(botContext: BotContext, clientCtor: typeof
destroy() {
client.destroy();
},
getUser(ident: string): Promise<Author> {
return getUser(client, ident);
getChannel(name: string): Promise<Channel> {
return getChannel(client, name);
},
getUser(name: string): Promise<Author> {
return getUser(client, name);
},
};
@ -109,12 +154,10 @@ export async function discordConnect(botContext: BotContext, clientCtor: typeof
}, 'logged in and ready');
});
client.on(Events.MessageCreate, (message) => {
catchAndLog(onMessage({
...botContext,
bot,
}, client, message), logger, 'error handling message');
});
client.on(Events.MessageCreate, (message) => catchAndLog(onMessage({
...botContext,
bot,
}, client, message), logger, 'error handling message'));
return bot;
}

View File

@ -1,12 +1,44 @@
import { Logger } from 'noicejs';
import { ParsedArgs } from '../args.js';
import { Author, Command } from '../command/index.js';
import { Command } from '../command/index.js';
import { DataLayer } from '../data/index.js';
import { RconClient } from '../utils/rcon.js';
import { discordConnect } from './discord.js';
import { readlineConnect } from './readline.js';
/**
* Message author.
*
* @public
*/
export interface Author {
discriminator: string;
username: string;
}
export interface Channel {
name: string;
edit(options: {
name?: string;
topic?: string;
}): Promise<void>;
}
/**
* Text message with ability to reply.
*
* @public
*/
export interface Message {
author: Author;
channel: Channel;
content: string;
reply(message: string): Promise<Message>;
}
/**
* Necessary methods for a bot.
*
@ -15,7 +47,9 @@ import { readlineConnect } from './readline.js';
export interface Bot {
connect(): Promise<boolean>;
destroy(): void;
getUser(ident: string): Promise<Author | undefined>;
getChannel(name: string): Promise<Channel | undefined>;
getUser(name: string): Promise<Author | undefined>;
}
/**

View File

@ -2,27 +2,18 @@ import { doesExist } from '@apextoaster/js-utils';
import { stdin as input, stdout as output } from 'node:process';
import { createInterface, Interface as Readline } from 'node:readline/promises';
import { Author, CommandContext, Message } from '../command/index.js';
import { CommandContext } from '../command/index.js';
import { catchAndLog } from '../utils/async.js';
import { matchCommands } from '../utils/command.js';
import { LOCAL_DISCRIMINATOR } from '../utils/roles.js';
import { Bot, BotContext } from './index.js';
/**
* Readline-only methods.
*
* @public
*/
export interface ReadlineBot extends Bot {
destroy(): void;
}
import { Author, Bot, BotContext, Channel, Message } from './index.js';
export const READLINE_AUTHOR: Author = {
discriminator: LOCAL_DISCRIMINATOR,
username: 'readline',
};
async function onLine(context: CommandContext, rl: Readline, line: string): Promise<void> {
export async function onLine(context: CommandContext, channel: Channel, rl: Readline, line: string): Promise<void> {
const { args, commands, logger } = context;
logger.debug({ line }, 'message received');
@ -44,6 +35,7 @@ async function onLine(context: CommandContext, rl: Readline, line: string): Prom
const message: Message = {
author: READLINE_AUTHOR,
channel,
content: line,
async reply(reply: string) {
logger.info({ reply }, 'reply from command');
@ -73,10 +65,17 @@ async function onLine(context: CommandContext, rl: Readline, line: string): Prom
*
* @public
*/
export async function readlineConnect(botContext: BotContext, readlineFactory: typeof createInterface = createInterface): Promise<ReadlineBot> {
export async function readlineConnect(botContext: BotContext, readlineFactory: typeof createInterface = createInterface): Promise<Bot> {
const { logger } = botContext;
const rl = readlineFactory({ input, output });
const channel: Channel = {
name: 'readline',
async edit(options) {
logger.info({ options }, 'editing channel');
},
};
const bot: Bot = {
async connect() {
rl.prompt();
@ -85,17 +84,18 @@ export async function readlineConnect(botContext: BotContext, readlineFactory: t
destroy() {
rl.close();
},
async getChannel() {
return channel;
},
async getUser() {
return READLINE_AUTHOR;
},
};
rl.on('line', (line) => {
catchAndLog(onLine({
...botContext,
bot,
}, rl, line), logger, 'error handling line');
});
rl.on('line', (line) => catchAndLog(onLine({
...botContext,
bot,
}, channel, rl, line), logger, 'error handling line'));
rl.setPrompt('> ');

View File

@ -1,7 +1,8 @@
import { Author, Message } from '../../bot/index.js';
import { removeCommandName } from '../../utils/command.js';
import { sendWithRetry } from '../../utils/rcon.js';
import { checkAuthor, ROLE_ADMIN_ONLY } from '../../utils/roles.js';
import { Author, Command, CommandContext, Message } from '../index.js';
import { Command, CommandContext } from '../index.js';
/**
* Run a SQL query on an RCON game server.

View File

@ -1,7 +1,8 @@
import { Author, Message } from '../../bot/index.js';
import { removeCommandName } from '../../utils/command.js';
import { sendWithRetry } from '../../utils/rcon.js';
import { checkAuthor, ROLE_ADMIN_ONLY } from '../../utils/roles.js';
import { Author, Command, CommandContext, Message } from '../index.js';
import { Command, CommandContext } from '../index.js';
/**
* Run a command on an RCON game server.

View File

@ -1,7 +1,8 @@
import { codeBlock } from 'discord.js';
import { sendWithRetry } from '../../utils/rcon.js';
import { Command, CommandContext, Message } from '../index.js';
import { Message } from '../../bot/index.js';
import { sendWithRetry } from '../../utils/rcon.js';
import { Command, CommandContext } from '../index.js';
/**
* List players who are currently online. Should work for any RCON game server.

View File

@ -1,9 +1,10 @@
import { codeBlock } from 'discord.js';
import { Message } from '../../bot/index.js';
import { parseBody } from '../../utils/command.js';
import { sendWithRetry } from '../../utils/rcon.js';
import { parseTable } from '../../utils/table.js';
import { Command, CommandContext, Message } from '../index.js';
import { Command, CommandContext } from '../index.js';
/**
* Options for recent players command, row limit.

View File

@ -1,7 +1,8 @@
import { codeBlock } from 'discord.js';
import { Message } from '../bot/index.js';
import { commandName } from '../utils/command.js';
import { Command, CommandContext, Message } from './index.js';
import { Command, CommandContext } from './index.js';
/**
* Reply with a summary of the available commands.

View File

@ -1,7 +1,7 @@
import { Logger } from 'noicejs';
import { ParsedArgs } from '../args.js';
import { Bot } from '../bot/index.js';
import { Author, Bot, Message } from '../bot/index.js';
import { DataLayer } from '../data/index.js';
import { RconClient } from '../utils/rcon.js';
import { rconSQL } from './admin/rcon-sql.js';
@ -12,27 +12,6 @@ import { help } from './help.js';
import { karma } from './karma.js';
import { ping } from './ping.js';
/**
* Message author.
*
* @public
*/
export interface Author {
discriminator: string;
username: string;
}
/**
* Text message with ability to reply.
*
* @public
*/
export interface Message {
author: Author;
content: string;
reply(message: string): Promise<Message>;
}
/**
* Bot command with optional authn/authz.
*
@ -41,6 +20,7 @@ export interface Message {
export interface Command {
desc: string;
name: string;
auth?: (context: CommandContext, author: Author) => Promise<boolean>;
run: (context: CommandContext, message: Message) => Promise<void>;
}

View File

@ -1,7 +1,9 @@
import { mustDefault } from '@apextoaster/js-utils';
import { Message } from '../bot/index.js';
import { DataTable, intValue } from '../data/index.js';
import { authorName, parseBody } from '../utils/command.js';
import { Command, CommandContext, Message } from './index.js';
import { Command, CommandContext } from './index.js';
/**
* Options for recent players command, row limit.

View File

@ -1,4 +1,5 @@
import { Command, CommandContext, Message } from './index.js';
import { Message } from '../bot/index.js';
import { Command, CommandContext } from './index.js';
/**
* Respond with a pong message. Provides a basic health check.

View File

@ -1,7 +1,7 @@
import { doesExist } from '@apextoaster/js-utils';
import { ParseCallback } from 'yargs';
import { ParsedArgs } from '../args.js';
import { Author } from '../command/index.js';
import { Author } from '../bot/index.js';
import { MemoryDataLayer } from './memory.js';
import { SqliteDataLayer } from './sqlite.js';

View File

@ -1,5 +1,5 @@
import { ParsedArgs } from '../args.js';
import { Author } from '../command/index.js';
import { Author } from '../bot/index.js';
import { authorName } from '../utils/command.js';
import { DataLayer, DataTable, DataValue } from './index.js';

View File

@ -1,7 +1,7 @@
import sqlite3 from 'sqlite3';
import { ParsedArgs } from '../args.js';
import { Author } from '../command/index.js';
import { Author } from '../bot/index.js';
import { authorName } from '../utils/command.js';
import { DataLayer, DataTable, DataValue } from './index.js';

View File

@ -21,10 +21,10 @@ main(process.argv.slice(ARGS_START)).then((code) => {
/* c8 ignore stop */
export { ParsedArgs, parseArgs } from './args.js';
export { Author, Message, Command, CommandContext } from './command/index.js';
export { discordConnect, DiscordBot } from './bot/discord.js';
export { Bot, BotContext, BotCtor } from './bot/index.js';
export { readlineConnect, ReadlineBot } from './bot/readline.js';
export { Command, CommandContext } from './command/index.js';
export { discordConnect } from './bot/discord.js';
export { Author, Bot, BotContext, BotCtor, Channel, Message } from './bot/index.js';
export { readlineConnect } from './bot/readline.js';
export { authorName, BodyOptions, matchCommands, commandName, parseBody, removeCommandName, StringsOnly } from './utils/command.js';
export { RconClient, rconConnect, sendWithRetry } from './utils/rcon.js';
export { checkAuthor, ROLE_ADMIN_ONLY, Roles, LOCAL_DISCRIMINATOR } from './utils/roles.js';

27
src/job/cron.ts Normal file
View File

@ -0,0 +1,27 @@
import { mustExist } from '@apextoaster/js-utils';
import { gracefulShutdown, scheduleJob } from 'node-schedule';
import { Logger } from 'noicejs';
import { ParsedArgs } from '../args.js';
import { Bot } from '../bot/index.js';
export interface Job {
destroy(): Promise<void>;
}
export async function startCrons(args: ParsedArgs, logger: Logger, bot: Bot): Promise<Job> {
const job = scheduleJob('test', '*/1 * * * *', async () => {
logger.info('test job');
const channel = mustExist(await bot.getChannel('foo'));
await channel.edit({
topic: 'test',
});
});
return {
destroy() {
return gracefulShutdown();
},
};
}

View File

@ -5,6 +5,7 @@ import { APP_NAME, parseArgs } from './args.js';
import { Bot, BotContext, BOTS } from './bot/index.js';
import { COMMANDS } from './command/index.js';
import { DATA_LAYERS } from './data/index.js';
import { startCrons } from './job/cron.js';
import { rconConnect } from './utils/rcon.js';
/**
@ -20,6 +21,11 @@ export enum ExitCode {
*/
export async function main(argv: Array<string>): Promise<ExitCode> {
const args = await parseArgs(argv);
if (args.help === true) {
return ExitCode.SUCCESS;
}
const logger = createLogger({
name: APP_NAME,
level: DEBUG,
@ -31,15 +37,16 @@ export async function main(argv: Array<string>): Promise<ExitCode> {
logger.debug({ command }, 'command debug');
}
logger.debug({ data: args.data }, 'connecting to data store');
logger.info({ data: args.data }, 'connecting to data store');
const dataCtor = DATA_LAYERS[args.data];
const data = new dataCtor(args);
await data.connect();
logger.debug({ host: args.rconHost, port: args.rconPort }, 'connecting to rcon server');
logger.info({ host: args.rconHost, port: args.rconPort }, 'connecting to rcon server');
const rcon = await rconConnect(args, logger);
await rcon.connect();
logger.info('starting bots');
const bots: Array<Bot> = [];
const botContext: BotContext = {
args,
@ -61,8 +68,15 @@ export async function main(argv: Array<string>): Promise<ExitCode> {
}
}
logger.debug('starting cron jobs');
const cron = await startCrons(args, logger, bots[0]);
await signal(SIGNAL_STOP);
logger.info('stopping cron jobs');
await cron.destroy();
logger.info('stopping bots');
for (const bot of bots) {
bot.destroy();
}

View File

@ -1,6 +1,7 @@
import yargs, { PositionalOptions } from 'yargs';
import { Author, Command } from '../command/index.js';
import { Author } from '../bot/index.js';
import { Command } from '../command/index.js';
/**
* Friendly name for an Author.

View File

@ -1,4 +1,4 @@
import { Author } from '../command/index.js';
import { Author } from '../bot/index.js';
import { authorName } from './command.js';
/**

View File

@ -1,12 +1,16 @@
import { expect } from 'chai';
import { main } from '../src/main.js';
import { ExitCode, main } from '../src/main.js';
import { REQUIRED_ARGS } from './helpers.js';
describe('main function', () => {
xit('should run', async () => {
await expect(main([
'--discordToken=""',
'--rconPassword=""',
])).to.eventually.equal(1);
await expect(main(REQUIRED_ARGS)).to.eventually.equal(1);
});
it('should exit after printing the help', async () => {
await expect(main(['--help'])).to.eventually.equal(ExitCode.SUCCESS);
});
it('should run briefly in readline mode');
});

View File

@ -1,16 +1,18 @@
import { expect } from 'chai';
import { Client, ClientOptions } from 'discord.js';
import { ChannelManager, ChannelType, Client, ClientOptions, ClientUser, Message, User } from 'discord.js';
import { NullLogger } from 'noicejs';
import { createStubInstance, stub } from 'sinon';
import { parseArgs } from '../../src/args.js';
import { discordConnect } from '../../src/bot/discord.js';
import { discordConnect, onMessage } from '../../src/bot/discord.js';
import { Command, CommandContext } from '../../src/command/index.js';
import { ping } from '../../src/command/ping.js';
import { MemoryDataLayer } from '../../src/data/memory.js';
import { mockRcon } from '../helpers.js';
import { mockBot, mockRcon, REQUIRED_ARGS } from '../helpers.js';
describe('discord bot', () => {
it('should watch for the client ready event', async () => {
const args = await parseArgs(['--discordToken=""', '--rconPassword=""']);
const args = await parseArgs(REQUIRED_ARGS);
const rcon = mockRcon();
const destroyMock = stub<[], void>();
@ -38,5 +40,89 @@ describe('discord bot', () => {
expect(destroyMock).to.have.callCount(1);
});
it('should watch for messages and match commands');
it('should watch for messages and match commands', async () => {
const args = await parseArgs(REQUIRED_ARGS);
const bot = mockBot({});
const rcon = mockRcon();
const discord: Client = createStubInstance<Client<true>>(Client, {
destroy: stub(),
on: stub(),
once: stub(),
});
discord.channels = createStubInstance(ChannelManager);
discord.channels.fetch = stub().resolves({
id: 'test',
type: ChannelType.GuildText,
});
const user: ClientUser = createStubInstance(ClientUser);
discord.user = user;
const context: CommandContext = {
args,
bot,
commands: [ping],
data: new MemoryDataLayer(args),
logger: NullLogger.global,
rcon,
};
const author: User = createStubInstance(User);
const message: Message = createStubInstance(Message);
message.author = author;
message.content = '!ping';
await onMessage(context, discord, message);
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(message.reply).to.have.callCount(1);
});
it('should authenticate commands', async () => {
const command: Command = {
name: 'test',
desc: '',
auth: stub().resolves(false),
run: stub().resolves(),
};
const args = await parseArgs(REQUIRED_ARGS);
const bot = mockBot({});
const rcon = mockRcon();
const discord: Client = createStubInstance<Client<true>>(Client, {
destroy: stub(),
on: stub(),
once: stub(),
});
discord.channels = createStubInstance(ChannelManager);
discord.channels.fetch = stub().resolves({
id: 'test',
type: ChannelType.GuildText,
});
const user: ClientUser = createStubInstance(ClientUser);
discord.user = user;
const context: CommandContext = {
args,
bot,
commands: [command],
data: new MemoryDataLayer(args),
logger: NullLogger.global,
rcon,
};
const author: User = createStubInstance(User);
const message: Message = createStubInstance(Message);
message.author = author;
message.content = '!test';
await onMessage(context, discord, message);
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(message.reply).to.have.callCount(0);
});
it('should ignore its own messages');
it('should get author info based on user snowflake');
});

View File

@ -1,12 +1,15 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { expect } from 'chai';
import { createInterface } from 'node:readline/promises';
import { NullLogger } from 'noicejs';
import { stub } from 'sinon';
import { parseArgs } from '../../src/args.js';
import { BotContext } from '../../src/bot/index.js';
import { readlineConnect } from '../../src/bot/readline.js';
import { BotContext, Channel } from '../../src/bot/index.js';
import { onLine, readlineConnect } from '../../src/bot/readline.js';
import { Command, CommandContext } from '../../src/command/index.js';
import { MemoryDataLayer } from '../../src/data/memory.js';
import { mockRcon } from '../helpers.js';
import { mockBot, mockRcon, REQUIRED_ARGS } from '../helpers.js';
describe('readline bot', () => {
it('should close the underlying readline instance', async () => {
@ -18,8 +21,7 @@ describe('readline bot', () => {
});
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: BotContext = {
@ -37,6 +39,70 @@ describe('readline bot', () => {
expect(closeStub).to.have.callCount(1);
});
it('should read lines and turn them into a message from the local user');
it('should authenticate commands', async () => {
const args = await parseArgs([
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const channel: Channel = {
name: 'test',
edit: stub().resolves(),
};
const command: Command = {
name: 'test',
desc: 'test',
auth: stub().resolves(false),
run: stub().resolves(),
};
const context: CommandContext = {
args,
bot: mockBot({}),
commands: [command],
data: new MemoryDataLayer(args),
logger: NullLogger.global,
rcon: mockRcon(),
};
const rl = createInterface(process.stdin, process.stdout);
await onLine(context, channel, rl, '!test');
rl.close();
expect(command.run).to.have.callCount(0);
});
it('should read lines and turn them into a message from the local user', async () => {
const args = await parseArgs([
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const channel: Channel = {
name: 'test',
edit: stub().resolves(),
};
const command: Command = {
name: 'test',
desc: '',
run: stub().resolves(),
};
const context: CommandContext = {
args,
bot: mockBot({}),
commands: [command],
data: new MemoryDataLayer(args),
logger: NullLogger.global,
rcon: mockRcon(),
};
const rl = createInterface(process.stdin, process.stdout);
await onLine(context, channel, rl, '!test');
rl.close();
expect(command.run).to.have.callCount(1);
});
it('should prompt after errors');
});

View File

@ -3,16 +3,16 @@ import { NullLogger } from 'noicejs';
import { match, mock } from 'sinon';
import { parseArgs } from '../../src/args.js';
import { Message } from '../../src/bot/index.js';
import { help } from '../../src/command/help.js';
import { CommandContext, Message } from '../../src/command/index.js';
import { CommandContext } from '../../src/command/index.js';
import { MemoryDataLayer } from '../../src/data/memory.js';
import { mockBot, mockRcon } from '../helpers.js';
import { mockAuthor, mockBot, mockChannel, mockRcon, REQUIRED_ARGS } from '../helpers.js';
describe('help command', () => {
it('should reply with a list of commands', async () => {
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: CommandContext = {
@ -25,10 +25,8 @@ describe('help command', () => {
};
const replyMock = mock().named('Message.reply').resolves();
const message: Message = {
author: {
discriminator: '',
username: '',
},
author: mockAuthor(),
channel: mockChannel(),
content: '',
reply: replyMock,
};

View File

@ -3,27 +3,26 @@ import { NullLogger } from 'noicejs';
import { mock } from 'sinon';
import { parseArgs } from '../../src/args.js';
import { Author, CommandContext, Message } from '../../src/command/index.js';
import { Message } from '../../src/bot/index.js';
import { CommandContext } from '../../src/command/index.js';
import { karma } from '../../src/command/karma.js';
import { MemoryDataLayer } from '../../src/data/memory.js';
import { mockRcon } from '../helpers.js';
import { mockAuthor, mockBot, mockChannel, mockRcon, REQUIRED_ARGS } from '../helpers.js';
describe('karma command', () => {
it('should store karma', async () => {
const author: Author = {
discriminator: '0000',
username: 'test',
};
const author = mockAuthor();
const channel = mockChannel();
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: CommandContext = {
args,
bot: {
connect: () => Promise.resolve(true),
destroy: () => { /* noop */ },
...mockBot(),
getChannel: mock().atLeast(1).resolves(channel),
getUser: mock().atLeast(1).resolves(author),
},
commands: [],
@ -35,6 +34,7 @@ describe('karma command', () => {
const replyMock = mock().named('Message.reply').resolves();
const emptyMessage: Message = {
author,
channel,
content: '',
reply: replyMock,
};
@ -47,6 +47,7 @@ describe('karma command', () => {
replyMock.resetHistory();
const increaseMessage: Message = {
author,
channel,
content: '!karma ++++',
reply: replyMock,
};

View File

@ -3,20 +3,18 @@ import { NullLogger } from 'noicejs';
import { mock } from 'sinon';
import { parseArgs } from '../../src/args.js';
import { Author, CommandContext, Message } from '../../src/command/index.js';
import { Message } from '../../src/bot/index.js';
import { CommandContext } from '../../src/command/index.js';
import { ping } from '../../src/command/ping.js';
import { MemoryDataLayer } from '../../src/data/memory.js';
import { mockRcon } from '../helpers.js';
import { mockAuthor, mockChannel, mockRcon, REQUIRED_ARGS } from '../helpers.js';
describe('ping command', () => {
it('should reply with a pong', async () => {
const author: Author = {
discriminator: '0000',
username: 'test',
};
const author = mockAuthor();
const channel = mockChannel();
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: CommandContext = {
@ -24,6 +22,7 @@ describe('ping command', () => {
bot: {
connect: () => Promise.resolve(true),
destroy: () => { /* noop */ },
getChannel: mock().atLeast(1).resolves(channel),
getUser: mock().atLeast(1).resolves(author),
},
commands: [],
@ -35,6 +34,7 @@ describe('ping command', () => {
const replyMock = mock().named('Message.reply').resolves();
const message: Message = {
author,
channel,
content: '',
reply: replyMock,
};

View File

@ -3,10 +3,11 @@ import { NullLogger } from 'noicejs';
import { mock } from 'sinon';
import { parseArgs } from '../../../src/args.js';
import { Author, CommandContext, Message } from '../../../src/command/index.js';
import { Author, Message } from '../../../src/bot/index.js';
import { rcon } from '../../../src/command/admin/rcon.js';
import { CommandContext } from '../../../src/command/index.js';
import { MemoryDataLayer } from '../../../src/data/memory.js';
import { mockRcon } from '../../helpers.js';
import { mockRcon, REQUIRED_ARGS } from '../../helpers.js';
describe('rcon command', () => {
it('should execute the given command', async () => {
@ -15,8 +16,7 @@ describe('rcon command', () => {
username: 'test',
};
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: CommandContext = {
@ -24,6 +24,7 @@ describe('rcon command', () => {
bot: {
connect: () => Promise.resolve(true),
destroy: () => { /* noop */ },
getChannel: mock().resolves(),
getUser: mock().atLeast(1).resolves(author),
},
commands: [],
@ -35,6 +36,10 @@ describe('rcon command', () => {
const replyMock = mock().named('Message.reply').resolves();
const message: Message = {
author,
channel: {
name: 'test',
edit: mock().resolves(),
},
content: '',
reply: replyMock,
};

View File

@ -3,10 +3,11 @@ import { NullLogger } from 'noicejs';
import { mock } from 'sinon';
import { parseArgs } from '../../../src/args.js';
import { Author, Message } from '../../../src/bot/index.js';
import { rconSQL } from '../../../src/command/admin/rcon-sql.js';
import { Author, CommandContext, Message } from '../../../src/command/index.js';
import { CommandContext } from '../../../src/command/index.js';
import { MemoryDataLayer } from '../../../src/data/memory.js';
import { mockRcon } from '../../helpers.js';
import { mockRcon, REQUIRED_ARGS } from '../../helpers.js';
describe('rcon SQL command', () => {
it('should execute the given query', async () => {
@ -15,8 +16,7 @@ describe('rcon SQL command', () => {
username: 'test',
};
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: CommandContext = {
@ -24,6 +24,7 @@ describe('rcon SQL command', () => {
bot: {
connect: () => Promise.resolve(true),
destroy: () => { /* noop */ },
getChannel: mock().resolves(),
getUser: mock().atLeast(1).resolves(author),
},
commands: [],
@ -35,6 +36,10 @@ describe('rcon SQL command', () => {
const replyMock = mock().named('Message.reply').resolves();
const message: Message = {
author,
channel: {
name: 'test',
edit: mock().resolves(),
},
content: '',
reply: replyMock,
};

View File

@ -3,10 +3,11 @@ import { NullLogger } from 'noicejs';
import { mock } from 'sinon';
import { parseArgs } from '../../../src/args.js';
import { Author, Message } from '../../../src/bot/index.js';
import { conanOnline } from '../../../src/command/conan/online.js';
import { Author, CommandContext, Message } from '../../../src/command/index.js';
import { CommandContext } from '../../../src/command/index.js';
import { MemoryDataLayer } from '../../../src/data/memory.js';
import { mockRcon } from '../../helpers.js';
import { mockRcon, REQUIRED_ARGS } from '../../helpers.js';
describe('conan online command', () => {
it('should invoke rcon listplayers', async () => {
@ -15,8 +16,7 @@ describe('conan online command', () => {
username: 'test',
};
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: CommandContext = {
@ -24,6 +24,7 @@ describe('conan online command', () => {
bot: {
connect: () => Promise.resolve(true),
destroy: () => { /* noop */ },
getChannel: mock().resolves(),
getUser: mock().atLeast(1).resolves(author),
},
commands: [],
@ -35,6 +36,10 @@ describe('conan online command', () => {
const replyMock = mock().named('Message.reply').resolves();
const message: Message = {
author,
channel: {
name: 'test',
edit: mock().resolves(),
},
content: '',
reply: replyMock,
};

View File

@ -3,10 +3,11 @@ import { NullLogger } from 'noicejs';
import { mock } from 'sinon';
import { parseArgs } from '../../../src/args.js';
import { Author, Message } from '../../../src/bot/index.js';
import { conanRecent } from '../../../src/command/conan/recent.js';
import { Author, CommandContext, Message } from '../../../src/command/index.js';
import { CommandContext } from '../../../src/command/index.js';
import { MemoryDataLayer } from '../../../src/data/memory.js';
import { mockRcon } from '../../helpers.js';
import { mockRcon, REQUIRED_ARGS } from '../../helpers.js';
describe('conan recent command', () => {
it('should invoke rcon sql', async () => {
@ -15,8 +16,7 @@ describe('conan recent command', () => {
username: 'test',
};
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--commandPrefix="!"',
]);
const context: CommandContext = {
@ -24,6 +24,7 @@ describe('conan recent command', () => {
bot: {
connect: () => Promise.resolve(true),
destroy: () => { /* noop */ },
getChannel: mock().resolves(),
getUser: mock().atLeast(1).resolves(author),
},
commands: [],
@ -38,6 +39,10 @@ describe('conan recent command', () => {
const replyMock = mock().named('Message.reply').resolves();
const message: Message = {
author,
channel: {
name: 'test',
edit: mock().resolves(),
},
content: '',
reply: replyMock,
};

View File

@ -1,26 +1,20 @@
import { expect } from 'chai';
import { parseArgs } from '../../src/args.js';
import { Author } from '../../src/command/index.js';
import { DataTable } from '../../src/data/index.js';
import { MemoryDataLayer } from '../../src/data/memory.js';
import { mockAuthor, REQUIRED_ARGS } from '../helpers.js';
describe('memory data layer', () => {
// TODO: does this behavior actually make sense, considering data is persistent?
it('should clear existing records when it reconnects');
it('should store and fetch data', async () => {
const data = new MemoryDataLayer(await parseArgs([
'--discordToken=""',
'--rconPassword=""',
]));
const data = new MemoryDataLayer(await parseArgs(REQUIRED_ARGS));
await data.connect();
const author: Author = {
discriminator: '',
username: '',
};
const author = mockAuthor();
const value = {
value: Math.random().toString(),
};

View File

@ -3,12 +3,12 @@ import { parseArgs } from '../../src/args.js';
import { DataTable } from '../../src/data/index.js';
import { SqliteDataLayer } from '../../src/data/sqlite.js';
import { Author } from '../../src/index.js';
import { REQUIRED_ARGS } from '../helpers.js';
describe('sqlite data layer', () => {
it('should set up the schema', async () => {
const data = new SqliteDataLayer(await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--sqliteDatabase=":memory:"',
]));
@ -19,8 +19,7 @@ describe('sqlite data layer', () => {
it('should store data', async () => {
const data = new SqliteDataLayer(await parseArgs([
'--discordToken=""',
'--rconPassword=""',
...REQUIRED_ARGS,
'--sqliteDatabase=":memory:"',
]));

View File

@ -1,11 +1,18 @@
import { Bot } from '../src/bot/index.js';
import { Author } from '../src/command/index.js';
import { stub } from 'sinon';
import { Author, Bot, Channel, Message } from '../src/bot/index.js';
import { RconClient } from '../src/utils/rcon.js';
export function mockBot(users: Record<string, Author>): Bot {
export const REQUIRED_ARGS = [
'--discordToken=""',
'--rconPassword=""',
];
export function mockBot(users: Record<string, Author> = {}): Bot {
return {
connect: () => Promise.resolve(true),
destroy: () => { /* noop */ },
getChannel: (name: string) => Promise.resolve(mockChannel(name)),
getUser: (name: string) => Promise.resolve(users[name]),
};
}
@ -25,3 +32,28 @@ export function mockRcon(commands: Record<string, string> = {}): RconClient {
return client;
}
export function mockAuthor(username = 'test', discriminator = '0000'): Author {
return {
discriminator,
username,
};
}
export function mockChannel(name = 'test', edit = stub().resolves()): Channel {
return {
name,
edit,
};
}
export function mockMessage(content: string, author = mockAuthor(), channel = mockChannel()): Message {
const message: Message = {
author,
channel,
content,
reply: () => Promise.resolve(message),
};
return message;
}

View File

@ -5,14 +5,12 @@ import { mock, stub } from 'sinon';
import { parseArgs } from '../../src/args.js';
import { RconClient, rconConnect, RETRY_MESSAGE, sendWithRetry } from '../../src/utils/rcon.js';
import { REQUIRED_ARGS } from '../helpers.js';
describe('rcon utils', () => {
describe('rcon client', () => {
it('should attempt to reconnect on errors', async () => {
const args = await parseArgs([
'--discordToken=""',
'--rconPassword=""',
]);
const args = await parseArgs(REQUIRED_ARGS);
const client = await rconConnect(args, NullLogger.global);
const connectStub = stub(client, 'connect').resolves(client);

View File

@ -375,6 +375,13 @@
resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-10.0.1.tgz#2f4f65bb08bc368ac39c96da7b2f09140b26851b"
integrity sha512-/fvYntiO1GeICvqbQ3doGDIP97vWmvFt83GKguJ6prmQM2iXZfFcq6YE8KteFyRtX2/h5Hf91BYvPodJKFYv5Q==
"@types/node-schedule@^2.1.0":
version "2.1.0"
resolved "https://registry.yarnpkg.com/@types/node-schedule/-/node-schedule-2.1.0.tgz#60375640c0509bab963573def9d1f417f438c290"
integrity sha512-NiTwl8YN3v/1YCKrDFSmCTkVxFDylueEqsOFdgF+vPsm+AlyJKGAo5yzX1FiOxPsZiN6/r8gJitYx2EaSuBmmg==
dependencies:
"@types/node" "*"
"@types/node@*":
version "18.11.15"
resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.15.tgz#de0e1fbd2b22b962d45971431e2ae696643d3f5d"
@ -892,6 +899,14 @@ convert-source-map@^1.6.0:
resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.9.0.tgz#7faae62353fb4213366d0ca98358d22e8368b05f"
integrity sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==
cron-parser@^3.5.0:
version "3.5.0"
resolved "https://registry.yarnpkg.com/cron-parser/-/cron-parser-3.5.0.tgz#b1a9da9514c0310aa7ef99c2f3f1d0f8c235257c"
integrity sha512-wyVZtbRs6qDfFd8ap457w3XVntdvqcwBGxBoTvJQH9KGVKL/fB+h2k3C8AqiVxvUQKN1Ps/Ns46CNViOpVDhfQ==
dependencies:
is-nan "^1.3.2"
luxon "^1.26.0"
cross-spawn@^7.0.0, cross-spawn@^7.0.2:
version "7.0.3"
resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6"
@ -1799,6 +1814,14 @@ is-lambda@^1.0.1:
resolved "https://registry.yarnpkg.com/is-lambda/-/is-lambda-1.0.1.tgz#3d9877899e6a53efc0160504cde15f82e6f061d5"
integrity sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==
is-nan@^1.3.2:
version "1.3.2"
resolved "https://registry.yarnpkg.com/is-nan/-/is-nan-1.3.2.tgz#043a54adea31748b55b6cd4e09aadafa69bd9e1d"
integrity sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==
dependencies:
call-bind "^1.0.0"
define-properties "^1.1.3"
is-negative-zero@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.2.tgz#7bf6f03a28003b8b3965de3ac26f664d765f3150"
@ -2001,6 +2024,11 @@ log-symbols@4.1.0:
chalk "^4.1.0"
is-unicode-supported "^0.1.0"
long-timeout@0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/long-timeout/-/long-timeout-0.1.1.tgz#9721d788b47e0bcb5a24c2e2bee1a0da55dab514"
integrity sha512-BFRuQUqc7x2NWxfJBCyUrN8iYUYznzL9JROmRz1gZ6KlOIgmoD+njPVbb+VNn2nGMKggMsK79iUNErillsrx7w==
loupe@^2.3.1:
version "2.3.6"
resolved "https://registry.yarnpkg.com/loupe/-/loupe-2.3.6.tgz#76e4af498103c532d1ecc9be102036a21f787b53"
@ -2015,6 +2043,11 @@ lru-cache@^6.0.0:
dependencies:
yallist "^4.0.0"
luxon@^1.26.0:
version "1.28.0"
resolved "https://registry.yarnpkg.com/luxon/-/luxon-1.28.0.tgz#e7f96daad3938c06a62de0fb027115d251251fbf"
integrity sha512-TfTiyvZhwBYM/7QdAVDh+7dBTBA29v4ik0Ce9zda3Mnf8on1S5KJI8P2jKFZ8+5C0jhmr0KwJEO/Wdpm0VeWJQ==
make-dir@^3.0.0, make-dir@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-3.1.0.tgz#415e967046b3a7f1d185277d84aa58203726a13f"
@ -2299,6 +2332,15 @@ node-gyp@8.x:
tar "^6.1.2"
which "^2.0.2"
node-schedule@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/node-schedule/-/node-schedule-2.1.0.tgz#068ae38d7351c330616f7fe7cdb05036f977cbaf"
integrity sha512-nl4JTiZ7ZQDc97MmpTq9BQjYhq7gOtoh7SiPH069gBFBj0PzD8HI7zyFs6rzqL8Y5tTiEEYLxgtbx034YPrbyQ==
dependencies:
cron-parser "^3.5.0"
long-timeout "0.1.1"
sorted-array-functions "^1.3.0"
noicejs@^5.0.0-3:
version "5.0.0-3"
resolved "https://registry.yarnpkg.com/noicejs/-/noicejs-5.0.0-3.tgz#cbc2df81925c68f3cbc4de3fcb93092e891b6967"
@ -2736,6 +2778,11 @@ socks@^2.6.2:
ip "^2.0.0"
smart-buffer "^4.2.0"
sorted-array-functions@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/sorted-array-functions/-/sorted-array-functions-1.3.0.tgz#8605695563294dffb2c9796d602bd8459f7a0dd5"
integrity sha512-2sqgzeFlid6N4Z2fUQ1cvFmTOLRi/sEDzSQ0OKYchqgoPmQBVyM3959qYx3fpS6Esef80KjmpgPeEr028dP3OA==
source-map-support@^0.5.21:
version "0.5.21"
resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f"