Skip to content

Commit

Permalink
Move CommandDispatcher#wasCommandCalled to Util
Browse files Browse the repository at this point in the history
Because it's useful in more than just the dispatcher, and I need it for a plugin
  • Loading branch information
zajrik committed Jul 28, 2017
1 parent ab433b9 commit ca2877b
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 52 deletions.
50 changes: 9 additions & 41 deletions src/command/CommandDispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { RateLimit } from './RateLimit';
import { Time } from '../util/Time';
import { Lang } from '../localization/Lang';
import { Util } from '../util/Util';
const { now } = Util;

/**
* Handles dispatching commands
Expand Down Expand Up @@ -44,7 +43,7 @@ export class CommandDispatcher<T extends Client>
*/
private async handleMessage(message: Message): Promise<void>
{
const dispatchStart: number = now();
const dispatchStart: number = Util.now();
const dm: boolean = message.channel.type !== 'text';

// Don't continue for bots and don't continue
Expand All @@ -58,13 +57,15 @@ export class CommandDispatcher<T extends Client>
// Don't bother with anything else if author is blacklisted
if (await this.isBlacklisted(message.author, message, dm)) return;

const lang: string = dm ? this._client.defaultLang
: await message.guild.storage.settings.get('lang');
const lang: string = dm
? this._client.defaultLang
: await message.guild.storage.settings.get('lang')
|| this._client.defaultLang;
const res: ResourceLoader = Lang.createResourceLoader(lang);

type CommandCallData = [boolean, Command<T>, string, string];
type CommandCallData = [boolean, Command, string, string];
const [commandWasCalled, command, prefix, name]: CommandCallData =
await this.wasCommandCalled(message, dm);
await Util.wasCommandCalled(message);

if (!commandWasCalled)
{
Expand All @@ -74,7 +75,7 @@ export class CommandDispatcher<T extends Client>
}

let validCall: boolean = false;
try { validCall = await this.canCallCommand(res, command, message, dm); }
try { validCall = await this.canCallCommand(res, <Command<T>> command, message, dm); }
catch (err) { message[this._client.selfbot ? 'channel' : 'author'].send(err); }
if (!validCall) return;

Expand Down Expand Up @@ -120,7 +121,7 @@ export class CommandDispatcher<T extends Client>
try { await command.action(message, args); }
catch (err) { this._logger.error(`Dispatch:${command.name}`, err.stack); }

const dispatchEnd: number = now() - dispatchStart;
const dispatchEnd: number = Util.now() - dispatchStart;
this._client.emit('command', command.name, args, dispatchEnd, message);
}

Expand All @@ -134,39 +135,6 @@ export class CommandDispatcher<T extends Client>
return false;
}

/**
* Return if a command has been called, the called command,
* the prefix used to call the command, and the name or alias
* of the command used to call it
*/
private async wasCommandCalled(message: Message, dm: boolean): Promise<[boolean, Command<T>, string, string]>
{
type CommandCallData = [boolean, Command<T>, string, string];
const negative: CommandCallData = [false, null, null, null];
const prefixes: string[] = [
`<@${this._client.user.id}>`,
`<@!${this._client.user.id}>`
];

if (!dm) prefixes.push(await message.guild.storage.settings.get('prefix'));
else prefixes.push(await this._client.storage.get('defaultGuildSettings.prefix'));

let prefix: string = prefixes.find(a => message.content.trim().startsWith(a));

if (dm && typeof prefix === 'undefined') prefix = '';
if (typeof prefix === 'undefined' && !dm) return negative;

const commandName: string = message.content.trim()
.slice(prefix.length).trim()
.split(' ')[0];

const command: Command<T> = this._client.commands.findByNameOrAlias(commandName);
if (!command) return negative;
if (command.disabled) return negative;

return [true, command, prefix, commandName];
}

/**
* Return whether or not the command is allowed to be called based
* on whatever circumstances are present at call-time, throwing
Expand Down
45 changes: 44 additions & 1 deletion src/util/Util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { BaseCommandName } from '../types/BaseCommandName';
import { Message } from '../types/Message';
import { Command } from '../command/Command';
import { Client } from '../client/Client';

/**
* Utility class containing handy static methods that can
Expand All @@ -7,7 +10,6 @@ import { BaseCommandName } from '../types/BaseCommandName';
*/
export class Util
{

/**
* Tangible representation of all base command names
* @static
Expand All @@ -16,6 +18,47 @@ export class Util
*/
public static baseCommandNames: BaseCommandName[] = require('./static/baseCommandNames.json');

/**
* Return whether or not a command was called in the given
* message, the called command, the prefix used to call the
* command, and the name or alias of the command used to call it.
* >Returns `[false, null, null, null]` if no command was called
* @static
* @method wasCommandCalled
* @param {Message} message Message to check
* @returns {Tuple<boolean, Command, string, string>}
*/
public static async wasCommandCalled(message: Message): Promise<[boolean, Command, string, string]>
{
type CommandCallData = [boolean, Command, string, string];

const client: Client = <Client> message.client;
const dm: boolean = message.channel.type !== 'text';
const negative: CommandCallData = [false, null, null, null];
const prefixes: string[] = [
`<@${client.user.id}>`,
`<@!${client.user.id}>`
];

if (!dm) prefixes.push(await message.guild.storage.settings.get('prefix'));
else prefixes.push(await client.storage.get('defaultGuildSettings.prefix'));

let prefix: string = prefixes.find(a => message.content.trim().startsWith(a));

if (dm && typeof prefix === 'undefined') prefix = '';
if (typeof prefix === 'undefined' && !dm) return negative;

const commandName: string = message.content.trim()
.slice(prefix.length).trim()
.split(' ')[0];

const command: Command = client.commands.findByNameOrAlias(commandName);
if (!command) return negative;
if (command.disabled) return negative;

return [true, command, prefix, commandName];
}

/**
* Pads the right side of a string with spaces to the given length
* @static
Expand Down
16 changes: 8 additions & 8 deletions test/commands/test_command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,19 @@ export default class extends Command
desc: 'test command',
usage: '<prefix>test <test> <foo>',
// overloads: 'ping',
ratelimit: '2/10s'
// ratelimit: '2/10s'
});
}

// @using((message, args) => [message, args.map(a => a.toUpperCase())])
@using(resolve(`test: Member, foo: String`))
@using(expect(`test: Member, foo: ['foo', 'bar']`))
@using(localize)
// @using(resolve(`test: Member, foo: String`))
// @using(expect(`test: Member, foo: ['foo', 'bar']`))
// @using(localize)
public action(message: Message, [res, ...args]: [ResourceLoader, string[]]): void
{
message.channel.send(res('FOO_BAR_BAZ'));
message.channel.send(args.join(' ') || 'MISSING ARGS');
this.logger.debug('Command:test', util.inspect(this.group));
throw new Error('foo');
// message.channel.send(res('FOO_BAR_BAZ'));
// message.channel.send(args.join(' ') || 'MISSING ARGS');
// this.logger.debug('Command:test', util.inspect(this.group));
// // throw new Error('foo');
}
}
4 changes: 2 additions & 2 deletions test/test_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Test extends Client
// defaultLang: 'al_bhed',
pause: true,
plugins: [TestPlugin],
ratelimit: '5/10s',
// ratelimit: '5/10s',
disableBase: ['setlang']
// disableBase: Util.baseCommandNames
// .filter(n => n !== 'help' && n !== 'eval')
Expand Down Expand Up @@ -60,7 +60,7 @@ class Test extends Client
{
logger.debug('Test', foo, bar.toString());
await this.setDefaultSetting('foo', 'bar');
// this.commands.registerExternal(this, new TestCommand());
this.on('command', (name, args, exec) => console.log(name, args, exec));
}
}
const test: Test = new Test();
Expand Down

0 comments on commit ca2877b

Please sign in to comment.