Skip to content

Commit

Permalink
::refactor::
Browse files Browse the repository at this point in the history
  • Loading branch information
spuckhafte committed Sep 14, 2023
1 parent 6916367 commit 528630b
Show file tree
Hide file tree
Showing 11 changed files with 150 additions and 136 deletions.
47 changes: 2 additions & 45 deletions dist/helpers/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { err } from "./funcs.js";
import { extractFieldValuesHandler } from "./handlers.js";
const regex = {
stateOperateExp: /<<[a-zA-Z0-9$%+\-*/()\[\]<>?:="'^.! ]+?>>/g,
stateExp: /\$[a-zA-Z0-9-]+\$/g
};
import { err } from "./handlers.js";
import { extractFieldValuesHandler, formatString } from "./handlers.js";
export class Command {
constructor(settings) {
this.content = '';
Expand Down Expand Up @@ -174,42 +170,3 @@ export class TypicalCommand extends Command {
});
}
}
function formatString(text, states) {
if (!checkForOperation(text))
return stateExtracter(text, states);
const operations = text.match(regex.stateOperateExp);
//@ts-ignore - operations is not null, cause we are already checking for it (look up)
for (let rawOperation of operations) {
let operation = rawOperation.replace(/<<|>>/g, '');
operation = stateExtracter(operation, states);
let afterOperation;
try {
afterOperation = eval(operation);
}
catch (e) {
console.error(`[err] Invalid State Operation:\n\n${rawOperation}\n\n${e}`);
}
if (typeof afterOperation == 'undefined')
return text;
text = text.replace(rawOperation, afterOperation);
}
return stateExtracter(text, states);
}
function stateExtracter(text, states) {
const stateNames = text.match(regex.stateExp);
if (stateNames) {
for (let stateRaw of stateNames) {
const state = stateRaw.replace(/\$/g, '');
if (typeof states.states[state] == null)
continue;
let stateVal = states.get(state);
if (typeof stateVal == 'object')
stateVal = JSON.stringify(stateVal);
text = text.replace(stateRaw, `${stateVal}`);
}
}
return text;
}
function checkForOperation(text) {
return regex.stateOperateExp.test(text);
}
2 changes: 0 additions & 2 deletions dist/helpers/funcs.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Message, PermissionResolvable } from "discord.js";
export declare function err(desc: string, cmd?: string, warn?: boolean): string;
/**Listen to button interactions
* @param users - array of user-ids who can click on button, empty array => anyone can click
* @param msg - the msg sent containing the buttons
Expand All @@ -12,4 +11,3 @@ export declare function buttonSignal(users: string[], msg: Message | undefined,
}): import("discord.js").InteractionCollector<import("discord.js").MessageComponentInteraction<import("discord.js").CacheType>> | undefined;
/**Check if a user has a specific perm */
export declare function userHasPerm(perm: PermissionResolvable, userId: string, msg: Message): Promise<boolean>;
export declare function getIntents(): number[];
14 changes: 0 additions & 14 deletions dist/helpers/funcs.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { Intents } from "discord.js";
export function err(desc, cmd, warn = false) {
return `[${warn ? 'warn' : 'err'}][cmd: ${cmd}] ${desc}`;
}
/**Listen to button interactions
* @param users - array of user-ids who can click on button, empty array => anyone can click
* @param msg - the msg sent containing the buttons
Expand Down Expand Up @@ -41,13 +37,3 @@ export function userHasPerm(perm, userId, msg) {
return channel.permissionsFor(user).has(perm);
});
}
export function getIntents() {
return [
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.MESSAGE_CONTENT,
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS
];
}
6 changes: 6 additions & 0 deletions dist/helpers/handlers.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { StateManager } from './stateManager.js';
export declare const extractFieldValuesHandler: {
string: (data: string, strict: boolean, name: string | undefined) => string;
number: (data: string, strict: boolean, name: string | undefined) => string | number;
};
export declare function revealNameOfCmd(content: string, prefix: string): string | false;
export declare function formatString(text: string, states: StateManager): string;
export declare function stateExtracter(text: string, states: StateManager): string;
export declare function checkForOperation(text: string): boolean;
export declare function getIntents(): number[];
export declare function err(desc: string, cmd?: string, warn?: boolean): string;
62 changes: 61 additions & 1 deletion dist/helpers/handlers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { err } from './funcs.js';
import { Intents } from 'discord.js';
const regex = {
stateOperateExp: /<<[a-zA-Z0-9$%+\-*/()\[\]<>?:="'^.! ]+?>>/g,
stateExp: /\$[a-zA-Z0-9-]+\$/g
};
// Convert field values into their defined types.
export const extractFieldValuesHandler = {
'string': (data, strict, name) => {
if (strict && !isNaN(data))
Expand All @@ -21,3 +26,58 @@ export function revealNameOfCmd(content, prefix) {
return false;
return content.replace(prefix, '').replace(/[ ]+/g, ' ').trim().split(' ')[0].toLowerCase();
}
// Calculate and replace state references and [operations] in a string.
export function formatString(text, states) {
if (!checkForOperation(text))
return stateExtracter(text, states);
const operations = text.match(regex.stateOperateExp);
//@ts-ignore - operations is not null, cause we are already checking for it (look up)
for (let rawOperation of operations) {
let operation = rawOperation.replace(/<<|>>/g, '');
operation = stateExtracter(operation, states);
let afterOperation;
try {
afterOperation = eval(operation);
}
catch (e) {
console.error(`[err] Invalid State Operation:\n\n${rawOperation}\n\n${e}`);
}
if (typeof afterOperation == 'undefined')
return text;
text = text.replace(rawOperation, afterOperation);
}
return stateExtracter(text, states);
}
// Calculate and replace state references in a string.
export function stateExtracter(text, states) {
const stateNames = text.match(regex.stateExp);
if (stateNames) {
for (let stateRaw of stateNames) {
const state = stateRaw.replace(/\$/g, '');
if (typeof states.states[state] == null)
continue;
let stateVal = states.get(state);
if (typeof stateVal == 'object')
stateVal = JSON.stringify(stateVal);
text = text.replace(stateRaw, `${stateVal}`);
}
}
return text;
}
// check if their is any stateful-operation to calculate in a string
export function checkForOperation(text) {
return regex.stateOperateExp.test(text);
}
export function getIntents() {
return [
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.MESSAGE_CONTENT,
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS
];
}
export function err(desc, cmd, warn = false) {
return `[${warn ? 'warn' : 'err'}][cmd: ${cmd}] ${desc}`;
}
3 changes: 2 additions & 1 deletion dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import fs from 'fs';
import { revealNameOfCmd } from './helpers/handlers.js';
import { Command } from './helpers/command.js';
import { StateManager } from './helpers/stateManager.js';
import { buttonSignal, getIntents, userHasPerm } from './helpers/funcs.js';
import { buttonSignal, userHasPerm } from './helpers/funcs.js';
import { getIntents } from './helpers/handlers.js';
class Bot {
constructor(options) {
var _a;
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "breezer.js",
"version": "0.5.2",
"version": "0.5.3",
"description": "",
"main": "dist/index.js",
"scripts": {
Expand All @@ -13,4 +13,4 @@
"dependencies": {
"discord.js": "^13.14.0"
}
}
}
55 changes: 2 additions & 53 deletions src/helpers/command.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import { Message, PermissionResolvable, TextChannel } from "discord.js";
import { CmdStructure, CommandSettings, Payload } from "../../types";
import { err } from "./funcs.js";
import { extractFieldValuesHandler } from "./handlers.js";
import { err } from "./handlers.js";
import { extractFieldValuesHandler, formatString } from "./handlers.js";
import { StateManager } from "./stateManager.js";


const regex = {
stateOperateExp: /<<[a-zA-Z0-9$%+\-*/()\[\]<>?:="'^.! ]+?>>/g,
stateExp: /\$[a-zA-Z0-9-]+\$/g
}

export class Command<Structure extends (string|number|null)[]> {
structure:CmdStructure[];
name?:string;
Expand Down Expand Up @@ -181,49 +175,4 @@ export class TypicalCommand<T extends []> extends Command<T> {
async execute() {

}
}


function formatString(text:string, states:StateManager) {
if (!checkForOperation(text)) return stateExtracter(text, states);


const operations = text.match(regex.stateOperateExp);
//@ts-ignore - operations is not null, cause we are already checking for it (look up)
for (let rawOperation of operations) {
let operation = rawOperation.replace(/<<|>>/g, '');
operation = stateExtracter(operation, states);
let afterOperation:any;
try {
afterOperation = eval(operation);
} catch (e) {
console.error(
`[err] Invalid State Operation:\n\n${rawOperation}\n\n${e}`
)
}

if (typeof afterOperation == 'undefined') return text;
text = text.replace(rawOperation, afterOperation);
}
return stateExtracter(text, states);
}
function stateExtracter(text:string, states:StateManager) {
const stateNames = text.match(regex.stateExp);

if (stateNames) {
for (let stateRaw of stateNames) {
const state = stateRaw.replace(/\$/g, '');
if (typeof states.states[state] == null) continue;
let stateVal = states.get(state);
if (typeof stateVal == 'object')
stateVal = JSON.stringify(stateVal);
text = text.replace(stateRaw, `${stateVal}`);
}
}

return text;
}

function checkForOperation(text:string) {
return regex.stateOperateExp.test(text);
}
17 changes: 1 addition & 16 deletions src/helpers/funcs.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import { Intents, Message, PermissionResolvable, TextChannel } from "discord.js";

export function err(desc:string, cmd?:string, warn=false) {
return `[${warn ? 'warn' : 'err'}][cmd: ${cmd}] ${desc}`
}
import { Message, PermissionResolvable, TextChannel } from "discord.js";

/**Listen to button interactions
* @param users - array of user-ids who can click on button, empty array => anyone can click
Expand Down Expand Up @@ -35,15 +31,4 @@ export async function userHasPerm(perm:PermissionResolvable, userId:string, msg:
const user = await msg.guild?.members.fetch(userId);
if (!user) return false;
return channel.permissionsFor(user).has(perm);
}

export function getIntents() {
return [
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.MESSAGE_CONTENT,
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS
]
}
73 changes: 72 additions & 1 deletion src/helpers/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { err } from './funcs.js'
import { Intents } from 'discord.js';
import { StateManager } from './stateManager.js';

const regex = {
stateOperateExp: /<<[a-zA-Z0-9$%+\-*/()\[\]<>?:="'^.! ]+?>>/g,
stateExp: /\$[a-zA-Z0-9-]+\$/g
}

// Convert field values into their defined types.
export const extractFieldValuesHandler = {
'string': (data:string, strict:boolean, name:string|undefined) => {
if (strict && !isNaN(data as any))
Expand All @@ -20,4 +27,68 @@ export function revealNameOfCmd(content:string, prefix:string) {
content = content.trim();
if (!content.toLowerCase().startsWith(prefix)) return false;
return content.replace(prefix, '').replace(/[ ]+/g, ' ').trim().split(' ')[0].toLowerCase();
}

// Calculate and replace state references and [operations] in a string.
export function formatString(text:string, states:StateManager) {
if (!checkForOperation(text))
return stateExtracter(text, states);


const operations = text.match(regex.stateOperateExp);
//@ts-ignore - operations is not null, cause we are already checking for it (look up)
for (let rawOperation of operations) {
let operation = rawOperation.replace(/<<|>>/g, '');
operation = stateExtracter(operation, states);
let afterOperation:any;
try {
afterOperation = eval(operation);
} catch (e) {
console.error(
`[err] Invalid State Operation:\n\n${rawOperation}\n\n${e}`
)
}

if (typeof afterOperation == 'undefined') return text;
text = text.replace(rawOperation, afterOperation);
}
return stateExtracter(text, states);
}

// Calculate and replace state references in a string.
export function stateExtracter(text:string, states:StateManager) {
const stateNames = text.match(regex.stateExp);

if (stateNames) {
for (let stateRaw of stateNames) {
const state = stateRaw.replace(/\$/g, '');
if (typeof states.states[state] == null) continue;
let stateVal = states.get(state);
if (typeof stateVal == 'object')
stateVal = JSON.stringify(stateVal);
text = text.replace(stateRaw, `${stateVal}`);
}
}

return text;
}

// check if their is any stateful-operation to calculate in a string
export function checkForOperation(text:string) {
return regex.stateOperateExp.test(text);
}

export function getIntents() {
return [
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.MESSAGE_CONTENT,
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS
]
}

export function err(desc:string, cmd?:string, warn=false) {
return `[${warn ? 'warn' : 'err'}][cmd: ${cmd}] ${desc}`
}
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { TypicalCommand } from './helpers/command.js';
import { revealNameOfCmd } from './helpers/handlers.js';
import { Command } from './helpers/command.js';
import { StateManager } from './helpers/stateManager.js';
import { buttonSignal, getIntents, userHasPerm } from './helpers/funcs.js';
import { buttonSignal, userHasPerm } from './helpers/funcs.js';
import { getIntents } from './helpers/handlers.js';

class Bot {
commands:string[];
Expand Down

0 comments on commit 528630b

Please sign in to comment.