Custom Function
In this guide, we will explain how to create your own functions for aoitelegram
.
Why and When Do You Need This?
Since developers may not always add a particular function to the library, you can create a function yourself, which can be used not only by you but also by anyone who installs your npm package.
How to Use
In the PluginManager
class constructor, it's not mandatory to specify the parameter that searches for .aoiplugin.json
files in the node_modules
folders and moves them to the node_modules/.aoiplugins
directory for later use in your project.
const { AoiClient, PluginManager } = require("aoitelegram");
const bot = new AoiClient({
token: "",
});
const loadPlugin = new PluginManager({
client: bot,
searchingForPlugins: true, // node_modules searching
});
// dir: functions/
loadPlugin.loadDirPlugins("./functions");
// dir: node_modules/.aoiplugins/
loadPlugin.loadPlugins("path plugin", "commit");
const { AoiClient } = require("aoitelegram");
const bot = new AoiClient({
token: "",
});
// array or object
bot.addFunction([]);
bot.addFunction();
The structure of plugins for npm
packages should be as follows:
dirName
.aoiplugin.json
In aoiplugin.json
, the only parameter used is the path to the files or file that should be used:
{
"name": "./src/",
"version": "0.1.2"
}
Example of Creation
- JavaScript
- AoiTelegram
- ESModule
- Commonjs
export default {
name: "$await",
callback: context => {
const [time = 1] = context.splits;
return new Promise((res) => setTimeout(() => res(""), time * 1000));
},
};
module.exports = {
name: "$await",
callback: context => {
const [time = 1] = context.splits;
return new Promise((res) => setTimeout(() => res(""), time * 1000));
},
};
- ESModule
- Commonjs
export default {
name: "$log",
params: ["text"],
version: "0.1.0",
type: "aoitelegram",
code: `
$onlyIf[{text}!=undefined;Error parameter]
$print[{text}]
`,
};
module.exports = {
name: "$log",
params: ["text"],
version: "0.1.0",
type: "aoitelegram",
code: `
$onlyIf[{text}!=undefined;Error parameter]
$print[{text}]
`,
};
Function js
ctx
is the function context.
Ctx
ContextFunction {
data: { name: string; inside?: string; splits: string[] }[];
negative?: boolean;
inside: string | undefined;
splits: (string | undefined)[];
localVars: Collection<string, unknown>;
random: Collection<string, unknown>;
buffer: Collection<string, Buffer>;
array: Collection<string, unknown>;
callback_query: unknown[];
event: EventContext &
UserFromGetMe &
Message &
MessageReactionUpdated &
MessageReactionCountUpdated &
CallbackQuery &
InlineQuery &
ShippingQuery &
PreCheckoutQuery &
Poll &
PollAnswer &
ChatMemberUpdated &
ChatJoinRequest &
ChatBoostUpdated &
ChatBoostRemoved & { telegram: AoiClient };
telegram: AoiClient;
code: string;
command: { name: string; hasCommand?: boolean; hasEvent?: boolean };
isError: boolean;
argsCheck: (amount: number) => unknown;
checkArgumentTypes: (expectedArgumentTypes: string[]) => void;
sendError: (error: string, custom?: boolean) => unknown;
database: AoiManager | MongoDBManager;
currentFunction: string;
[key: string]: any;
suppressErrors?: string;
packageJSON: aoitelegram;
}
It has the following methods:
-
inside
- string of arguments that were passed. -
splits
- array of arguments provided by the user. -
argsCheck
- checks the number of arguments passed to the function.count
- the expected number of arguments in the function.
-
sendError
- sends reported errors and also halts the execution of subsequent functions in the context.text
- error text inHTML
style.custom
- (optional) custom error text, either user-defined or integrated into the library.
-
checkArgumentTypes
- Checks whether the provided arguments match the expected argument types for a function.expectedArgumentTypes
- Array of expected argument types- Types available for checking:
number
,object
,string
,nan
,undefined
,null
,unknown
,boolean
.
Example
client.addFunction({
name: "$log",
callback: context => {
context.argsCheck(1);
context.checkArgumentTypes(["string | number | boolean"]);
if (context.isError) return;
console.log(...context.splits);
return "";
}
});
client.addFunction({
name: "$onlyArgsType",
callback: context => {
context.argsCheck(2);
context.checkArgumentTypes(["...number"]);
if (context.isError) return;
let text = "";
context.splits.forEach((elem) => text += `${elem}\n`);
return text;
}
});
client.addFunction({
name: "$log",
callback: context => {
context.argsCheck(1);
context.checkArgumentTypes(["string | number | boolean"]);
if (context.isError) return;
console.log(context.inside);
// or
console.log(context.splits);
return "";
}
});
client.addFunction({
name: "$stopping",
callback: context => {
context.sendError(context.splits.join(", "));
}
});
If you specify a function that already exists in the library, it will be overwritten. This means custom functions take precedence over basic library functions.
Starting from aoitelegram@0.7.0
and above, the <AoiClient>.addFunction
method cannot modify a function, and <AoiClient>.editFunction
cannot add a function as before. Errors will occur when attempting to do so. To avoid such usage, use <AoiClient>.hasFunction
or <AoiClient>.ensureFunction
, which handle everything for you.
<AoiClient>.removeFunction(func: string | string[])
If you want to remove a function, there is a method called
<AoiClient>.editFunction(options: DataFunction | DataFunction[]): boolean
Edits or adds a data function to the available functions.
options
: A singleDataFunction
or an array ofDataFunction
objects.- Returns
true
after successfully editing or adding the function(s).
<AoiClient>.getFunction(options: string | string[])
Retrieves a function from the available functions.
options
: A single function name or an array of function names.- Returns the requested function(s).
<AoiClient>.countFunction
Gets the count of available functions.
- Returns the number of functions currently available.
<AoiClient>.ensureFunction(options: DataFunction | DataFunction[]): AoiClient
Ensures the registration of a data function or an array of data functions.
options
: A single data function or an array of data functions.- Returns the
AoiClient
instance for method chaining.
<AoiClient>.hasFunction(options: string | string[]): string | string[]
Checks if the specified function(s) exist(s).
options
: The name of the function or an array of function names.- Returns True if the function(s) exist(s).
Function aoitelegram
$argumentsCount
- Returns the number of function args