Skip to content

Commit

Permalink
feat(*): use sapphire/luxure to parse arguments from the text, and ad…
Browse files Browse the repository at this point in the history
…ded edit method to Context

Signed-off-by: Hanif Dwy Putra S <[email protected]>
  • Loading branch information
hansputera committed Sep 30, 2023
1 parent 328ade7 commit ee54d72
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 46 deletions.
11 changes: 11 additions & 0 deletions examples/normal.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ client.command(
},
);

client.command(
'test-edit',
async (ctx) => {
const m = await ctx.reply('Hello Woh!');
setTimeout(async () => await m.edit('Hello World!'), 1000);
},
{
aliases: ['testdit'],
},
);

client.command(
'poll',
async (ctx) => {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"dependencies": {
"@adiwajshing/baileys": "npm:@whiskeysockets/baileys@^6.5.0",
"@adiwajshing/keyed-db": "^0.2.4",
"@sapphire/lexure": "^1.1.5",
"long": "^5.2.3",
"pino": "^8.15.1",
"pino-pretty": "^9.4.1",
Expand Down
15 changes: 15 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

162 changes: 116 additions & 46 deletions src/structures/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,20 @@ import { ButtonBuilder } from '../utils/builder';
import { MessageCollector } from './collector';
import { Document, Image, Sticker, Video } from './entities';
import { GroupContext } from './group';
import {
Lexer,
Parser,
ParserResult,
PrefixedStrategy,
} from '@sapphire/lexure';

/**
* @class Context
*/
export class Context {
public parser!: Parser;
public lexer!: Lexer;

/**
* @constructor
* @param {Client} client Gampang Client
Expand All @@ -32,7 +41,6 @@ export class Context {
private rawMessage: proto.IWebMessageInfo,
groupSync: boolean | null = false,
) {
this.#reloadQuery();
if (groupSync) this.syncGroup();

if (rawMessage.message?.documentWithCaptionMessage?.message) {
Expand All @@ -42,6 +50,14 @@ export class Context {
rawMessage.message.documentWithCaptionMessage.message.documentMessage,
);
}

this.parser = new Parser(new PrefixedStrategy(['--', '/'], ['=', ':']));
this.lexer = new Lexer({
quotes: [
["'", "'"],
['"', '"'],
],
});
}

/**
Expand Down Expand Up @@ -138,9 +154,6 @@ export class Context {
return responseButtons || undefined;
}

public flags: string[] = [];
public args: string[] = [];

/**
* Get command details.
* @return {Command}
Expand Down Expand Up @@ -197,47 +210,30 @@ export class Context {
return true;
}

/**
* Parse message to args and flags
*
* @return {{args: string[], flags: string[]}}
*/
#reloadQuery(): { args: string[]; flags: string[] } {
this.args = [];
this.flags = [];

for (const q of this.getArgs()) {
if (q.startsWith('--')) this.flags.push(q.slice(2).toLowerCase());
else this.args.push(q);
}

return { args: this.args, flags: this.flags };
}

/**
* Get the arguments of message (only available if it is a command)
*
* @param {boolean} withPrefix
* @return {string[]}
*/
public getArgs(withPrefix = false): string[] {
if (!this.isCommand()) return [];
let text = this.text;
const extendedMessage = this.raw.message?.extendedTextMessage;

if (
extendedMessage &&
extendedMessage.contextInfo &&
extendedMessage.contextInfo.quotedMessage
) {
text += ' ' + extendedMessage.contextInfo.quotedMessage.conversation;
}

return text
.slice(this.getPrefix().length)
.split(/ +/g)
.slice(withPrefix ? 0 : 1);
}
// /**
// * Get the arguments of message (only available if it is a command)
// *
// * @param {boolean} withPrefix
// * @return {string[]}
// */
// public getArgs(withPrefix = false): string[] {
// if (!this.isCommand()) return [];
// let text = this.text;
// const extendedMessage = this.raw.message?.extendedTextMessage;

// if (
// extendedMessage &&
// extendedMessage.contextInfo &&
// extendedMessage.contextInfo.quotedMessage
// ) {
// text += ' ' + extendedMessage.contextInfo.quotedMessage.conversation;
// }

// return text
// .slice(this.getPrefix().length)
// .split(/ +/g)
// .slice(withPrefix ? 0 : 1);
// }

/**
* Knows the message is command.
Expand Down Expand Up @@ -269,7 +265,17 @@ export class Context {
* @return {string}
*/
public getCommandName(): string {
return this.getArgs(true)[0];
if (!this.getPrefix().length) return '';
return this.#data.ordered.at(0)?.value.slice(this.getPrefix().length) ?? '';
}

/**
* Get option value
* @param {string} name Option name
* @return {string[]}
*/
public getOption(name: string): string[] {
return this.#data.options.get(name) ?? [];
}

/**
Expand Down Expand Up @@ -663,6 +669,38 @@ export class Context {
});
}

/**
* [EXPERIMENTAL] Edit the message text
* @param {string} text Newer text
* @param {proto.IMessage?} options IMessage options
* @return {Promise<void>}
*/
public async edit(text: string, options?: proto.IMessage): Promise<void> {
if (
this.authorNumber !==
this.client.raw?.user?.id?.replace(/:[0-9]+@.+/gi, '')
)
return;
await this.client.raw?.relayMessage(
this.raw.key.remoteJid as string,
{
editedMessage: {
message: {
protocolMessage: {
key: this.raw.key,
type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
editedMessage: {
conversation: text,
...options,
},
},
},
},
},
{},
);
}

/**
* Get collector instance.
* @param {CollectorOptions} options - Message Collector options.
Expand All @@ -678,6 +716,38 @@ export class Context {
get raw(): proto.IWebMessageInfo {
return this.rawMessage;
}

/**
* Get lexure raw data
*/
get #data(): ParserResult {
let text = this.text;
const extendedMessage = this.raw.message?.extendedTextMessage;

if (
extendedMessage &&
extendedMessage.contextInfo &&
extendedMessage.contextInfo.quotedMessage
) {
text += ' ' + extendedMessage.contextInfo.quotedMessage.conversation;
}

return this.parser.run(this.lexer.run(text));
}

/**
* Command's arguments (e.g. "000789xxx")
*/
get args(): string[] {
return this.#data.ordered.map((order) => order.value).slice(1);
}

/**
* Command's flags (e.g. --flag1, --flag2, /flag3)
*/
get flags(): string[] {
return [...this.#data.flags];
}
}
/**
* @class ContextInfo
Expand Down

0 comments on commit ee54d72

Please sign in to comment.