1.0.4 • Published 3 years ago
tg2js v1.0.4
tg2js
execute functions in node through telegram bot commands
usage
const Bot = require("tg2js");
const bot = new Bot(
"https://api.telegram.org/", // api url. usually 'https://api.telegram.org/'
"{token}", // token of the bot. see https://core.telegram.org/bots#6-botfather on how to get your bot token.
123456, // (optional) telegram user id. function will only be executed if command is send by this user
1000, // (optional) default update interval in ms
5 // (optional) default max number of retries before stopping the update loop ('-1' for unlimited tries)
);
// executed by '/stop'
function stop() {
bot.stop();
}
stop.description = "stop bot"; // optional custom description in command list
// executed by '/check', '/check 10', '/check not a number'
function check(value) {
if (isNaN(value)) { // check parameter. when command gets executed without arguments the parameter will be undefined or message of the user
throw "not a number";
}
return `${value} is a number`;
}
// executed by '/reply'
function replyToMessage(message) {
bot.sendMessage(message.chat.id, "This is a reply to the command", { reply_to_message_id: message.message.id });
}
replyToMessage.command = "reply"; // optional change of command
replyToMessage.description = "reply to the command";
class TestClass {
constructor() {
this.name = "test";
}
// executed by '/print'
print() {
console.log('this.name = ', this.name);
}
}
const test = new TestClass();
// allow bot to execute those functions
bot.bindFunctions(
stop,
check,
replyToMessage,
test.print.bind(test) // bind instance to function to use 'this' in the print function
);
// initialize bot
bot.init(() => {
bot.start(1000, 5); // start receiving updates in 1000 ms interval. stop after 5 unsuccessful retries.
});
// send message. see https://core.telegram.org/bots/api#sendmessage for more info
bot.sendMessage(
123456, // chat id / user id
"bot starting...", // message
{ disable_notification: true }, // (optional) optional properties
message => console.log(message), // (optional) callback on success
error => console.error(error) // (optional) callback on error
);