aboutsummaryrefslogtreecommitdiff
path: root/src/commands/utilities/calculator.ts
blob: 75dc63f28a358711d830e8e88547c9712d15fa4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { AllowedMentions, BushCommand, type BushMessage, type BushSlashMessage } from '#lib';
import assert from 'assert';
import { ApplicationCommandOptionType, Embed } from 'discord.js';
import { evaluate } from 'mathjs';

assert(evaluate);

export default class CalculatorCommand extends BushCommand {
	public constructor() {
		super('calculator', {
			aliases: ['calculator', 'calc', 'math'],
			category: 'utilities',
			description: 'Calculates math expressions.',
			usage: ['calculator <expression>'],
			examples: ['calculator 9+10'],
			args: [
				{
					id: 'expression',
					description: 'The expression to calculate.',
					type: 'string',
					match: 'rest',
					prompt: 'What would you like to calculate?',
					retry: '{error} Pick something to calculate.',
					slashType: ApplicationCommandOptionType.String
				}
			],
			slash: true,
			clientPermissions: (m) => util.clientSendAndPermCheck(m),
			userPermissions: []
		});
	}

	public override async exec(message: BushMessage | BushSlashMessage, args: { expression: string }) {
		const decodedEmbed = new Embed().addFields({
			name: '📥 Input',
			value: await util.inspectCleanRedactCodeblock(args.expression, 'mma')
		});
		try {
			const calculated = /^(9\s*?\+\s*?10)|(10\s*?\+\s*?9)$/.test(args.expression) ? '21' : evaluate(args.expression);
			decodedEmbed
				.setTitle(`${util.emojis.successFull} Successfully Calculated Expression`)
				.setColor(util.colors.success)
				.addFields({ name: '📤 Output', value: await util.inspectCleanRedactCodeblock(calculated.toString(), 'mma') });
		} catch (error) {
			decodedEmbed
				.setTitle(`${util.emojis.errorFull} Unable to Calculate Expression`)
				.setColor(util.colors.error)
				.addFields({ name: `📤 Error`, value: await util.inspectCleanRedactCodeblock(`${error.name}: ${error.message}`, 'js') });
		}
		return await message.util.reply({ embeds: [decodedEmbed], allowedMentions: AllowedMentions.none() });
	}
}