Tidak lagi seperti monster: 90% sumber daya tersedia, membuat bot Telegram menjadi mudah.

This the multi-page printable view of this section. Klik disini untuk ngeprint.
Tidak lagi seperti monster: 90% sumber daya tersedia, membuat bot Telegram menjadi mudah.

Lumpia Framework atau kita sebut saja lumpia adalah sebuah framework Google Apps Script untuk mempermudah pembuatan bot api pada Telegram.
Google Apps Script atau kita sebut GAS saja, menyediakan fitur library untuk menyematkan sumber kode pihak lain untuk mempermudah membangun sebuah aplikasi.
Lumpia Framework bekerja pada fitur modul library yang tersedia pada Google Apps Script.
Library Google Apps Script (GAS) untuk Telegram edisi ke-3, merupakan suksesi dari GAS Library sebelumnya, yakni GASLib edisi 1 dan edisi 2 Lib v2 yang telah berhasil banyak dimanfaatkan.
Terinspirasi dari Telegraf yang dirasa cukup praktis dan efektif pada penggunaan sehari-hari. GASLibv3 membuat karakteristiknya sendiri, lantaran coding pada GAS memiliki banyak keterbatasan seperti tidak support proses (true) async, promise, deteksi tipe blob / stream, tidak banyak paket ready yang bisa langsung diberdayakan, dan berbagai kendala lainnya.
Namun, tidak perlu bekecil hati, framework GASLibv3 ini insyaAllah, lebih dari cukup guna kebutuhan sebuah proyek dalam skala kecil hingga menengah. Apalagi ditambah dukungan komunitas Grup Telegram @botIndonesia yang cukup baik menjadikan kamu tidak bingung harus pergi kemana untuk sharing.
Pada edisi ini, terdapat perubahan cukup besar dan cukup signifikan secara struktur, konsep, dan penggunaan. Tidak lagi seolah sebuah library namun menjadi sebuah framework sempurna dan modern untuk bot telegram. Dengan demikian, harapannya, penggunaan bisa menjadi lebih produktif untuk kebutuhan pekerjaan, kesenangan, maupun tools pembantu lainnya.
Kelebihan dibandingkan versi lama
| Keterangan | Baru (v3.x) |
Lama (v2.x) |
|---|---|---|
| Penulisan | Lebih sederhana lagi dan lagi | Cukup |
| Handle Post | Sudah tersedia | Manual |
| Handle Error | Sudah tersedia | Manual |
| Shorthand | Ada | - |
| Middleware | Ada | - |
| Fetch | Ada | Ada |
| userDB | Ada | Ada |
| scriptDB | Tidak | Ada |
| Trigger Event | Ada | - |
| Context (ctx) | Ada | - |
| Debugging | Ada | - |
| Markup | Ada | - |
Dan masih banyak lainnya..
Bagi pengguna library versi 1 dan 2, lumpia (GAS Lib v3) tidak kompatible.
Selamat menyesuaikan!
Lumpia dibangun atas 3 segment saat prosesi. Karena GAS tidak support async, maka ketiganya dipilih secara berurutan.
Misalkan middleware diletakkan pada codingan paling bawah, tetep dijalankan dibagian paling atas (didahulukan).
graph TD;
lumpia("π₯ Lumpia") --- helper("π§± helper"):::green;
lumpia --- markup("π markup"):::green;
lumpia --- fetch("πΈ fetch");
lumpia --- db[("π₯ user db")];
lumpia --- init;
init --> bot((bot));
bot(("π€ bot")) -.-> debug([debug]);
tg("βοΈ telegram client") ---> |shorthand|bot
user(["π€ user"]) --> |text, photo, cb inline, etc..|update[/update/]
update --> |doPost|bot
lumpia -.- tg
subgraph .
bot --> |ctx|middleware;
middleware --> ctx{{context}}
ctx --> broadcast;
ctx --> trigger;
end
broadcast --> ends(["π€ user"])
trigger --> ends
style lumpia color:blue,fill:#bdd5ef
style fetch fill:#efd9bd;
style init fill:#e1efbd
style ctx fill:#ecedea,color:grey
style ends color:white,fill:#000;
style user color:white,fill:#000;
classDef green fill:#9de0b2
click broadcast "/docs/lumpia/konsep/#2-broadcast"
click ctx "/docs/lumpia/ctx"
Cakupan: use, middleware
Middleware ini bisa mengentikan proses. Misalnya:
bot.use(ctx => console.log('stop') );
Maka, proses akan terhenti tidak dilanjutkan pada event berikutnya.
Cakupan: on
Cek bagian update type
Cakupan: cmd, command, hear, hears, action
Broadcast dan triger berjalan bersamaan (didahulukan brodcast) ketika middleware sudah selesai diproses dan menghasilkan context
Keduanya tidak saling menghentikan.
Contoh:
bot.on('text' , ctx => ctx.reply('masuk 1'));
bot.cmd('start', ctx => ctx.reply('masuk 2'));
Pesan user yang berupa text dan trigger /start akan dieksekusi (ditangkap keduanya), yang didahulukan adalah jenis broadcast (bot.on), meskipun seandainya codingan diatas dibalik, diletakkan dibawahnya trigger (bot.cmd).
Bisa dianggap sebagai fitur, tapi juga bisa dianggap sebagai bugs juga.
Pandai-pandailah memanfaatkan setuasi-nya.
Adalah versi stabil dari GAS Lib v3.
Semua dokumentasi menggunakan acuan ini.
1Yo6vQRwjG5Gl9jeEF0g2tBTUa0XN5MyT4G_HeDpRr9DvabxhRcSdhPNjMUD_wfLskZT2D99lRXLh94vvg_do21SJRadalah versi beta, digunakan hanya oleh pengembang buat bahan testing.
1OSN8eNlJtw2ehf3ul7h48Jb8rdeljKhC5Rw3cJo4nkEFITdS01Di0N_SM2iDAxzI3JJ4n6a8sryWJsfvg_do21SJRJika menggunakan bakpia, set variable paling atas untuk menyesuaikan dengan seluruh isi dokumentasi dan sample yang berada di sini:
var lumpia = bakpia;
const token = '12345:abcde';
const bot = new lumpia.init(token);
// dst..
adalah versi alpha (tahap development)
ketikda dikonversi menjadi library, berubah nama menjadi bakpia dan lumpia.
Seperti halnya android, kita mengenal Kit Kat, Oreo, dlsb.
Maka, kode library ini diberi kode penamaan nama makanan yang ada di pasar. Jadi kalau dibahas jadi enak, kita ngobrolin makanan hehe..
Penomoran versi
Misalnya v3.1
3Dimana nomor 3 adalah generasi atau edisi ke-3 dari Library GAS untuk Telegram ini. Versi ini tidak berubah, atau setidaknya tidak akan berubah dalam jangka dekat bilamana belum ada edisi baru lagi.
1Versi minor adalah versi build. Yang akan terus bertambah nilainya lantaran hasil snapshot dari release versi pada GAS.
Jika terdapat nomor minor yang lompat (tidak ada), berarti dicabut rilisnya. Bisa jadi dikarenakan gagal / cacat, atau kesalahan teknis release.
Silakan cek pada halaman berikut:
Table resume semua properti yang melekat pada lumpia.
| method | params | type | keterangan |
|---|---|---|---|
| init | token options |
string* json |
menginisiasi atau menghubungkan lumpia dengan (token) bot |
| DEBUG | Β | boolean |
semua pesan masuk dari Telegram diubah outputnya menjadi json. Tidak mempedulikan middleware atau lainnya. |
| verbose | Β | boolean |
mengaktifkan full logging proses framework saat berada di editor |
| version | Β | Β | menampilkan informasi lumpia yang sedang dipakai saat ini |
Berikut ini penjelasan bagaimana mendeklarasikan, atau menginisasi awal object-object pada saat menggunakan lumpia
Dipergunakan saat pertama kali atau tiap kali membuat objek lumpia.
Syntax: new lumpia.init(token, options)
Diisi dalam format JSON.
| option | keterangan | type | default | contoh |
|---|---|---|---|---|
| prefix_command | awalan perintah command pada bot | string | / |
prefix_command: '/!.' |
| log_id | id/username untuk mengirimkan log apabil error. sebaiknya diisi number untuk user id atau chat id |
number, string | - | log_id: 213567634 |
| username | tersedia pada v3.7 mengeset username pada command /start@usernamebot |
string | kosong | username: 'strukturbot' |
const token = '123456:abcde';
const adminbot = 213567634;
const usernamebot = 'strukturbot';
const bot = new lumpia.init(token, {
log_id: adminbot,
username: usernamebot,
prefix_command: '.!/'
});
// ... next code
Dapat juga diakses secara langsung (sesudah bot diinisiasi) :
bot.options.log_id = 213567634;
bot.options.prefix_command = '.!/';
Memaksa bot menampilkan JSON apapun yang diterima ke log_id yang diseting saat pertama kali init.
Berguna untuk debugging isi message.
falseconst token = '123456:abcde';
const bot = new lumpia.init(token, { log_id: 213567634 });
lumpia.DEBUG = true;
function doPost(e) {
bot.doPost(e);
}
Mengaktifkan logging secara detail dipergunakan saat debugging.
Verbose hanya berjalan pada mode panel editor pada GAS ketika menjalanan sebuah fungsi ke doPost atau handleUpdate().
Di bot tidak ada perbedaan apa-apa. Matikan mode verbose ini jika sudah tahap produksi, agar tidak terlalu banyak script bekerja.
false;lumpia.verbose = true;
Untuk mengetahui versi lumpia yang sedang dipergunakan.
Syntax: lumpia.version
Hasil berupa tipe data object (json) bersifat informasi.
| field | keterangan |
|---|---|
active |
versi yang aktif saat ini |
number |
selalu 3, sesuai generasi yang direlease |
build |
nomor saat di build, terus bertambah |
name |
nama code library |
full |
penyebuatan secara penuh |
group |
informasi grup |
url |
informasi url |
bot.cmd(['ver', 'versi', 'version'], ctx => {
let version = lumpia.version;
let pesan = `π€ Bot ini dibangun menggunakan <b>${version.name}</b> <code>v${version.number}.${version.build}</code>`;
pesan += `\n\nβ
Sumber bersama belajar <b>Bot Telegram Indonesia</b>`
let keyboard = [
button.url('π Docs', 'https://lumpia.js.org'),
button.url('π₯ @botindonesia', 'https://t.me/botindonesia')
]
ctx.replyWithHTML(pesan, {
reply_markup: markup.inlineKeyboard(keyboard)
});
})
Resume method dan params yang dipergunakan oleh bot.
| method | params | type | keterangan |
|---|---|---|---|
| telegram | Β | class | untuk mengakses dari bot api telegram |
| tg | Β | Β | alias dari telegram |
| options | Β | json |
akses mengubah options secara langsung |
| token | Β | string |
set/get token |
| log_id | Β | number/string |
set/get target id log. Shorthand untuk options.log_id |
| handleUpdate | data |
json |
memproses data json |
| doPost | data |
Β | memproses data POST pada function doPost |
| on | tipe |
string |
menangkap proses event atas tipe update tertentu |
| start | fn |
function |
handle proses command start |
| cmd | event |
[string/regex] |
handle proses command secara umum |
| command | event |
[string/regex] |
alias untuk cmd |
| hears | event |
[string/regex] |
handle pesan text dari user |
| hear | event |
[string/regex] |
alias untuk hears |
| use | fn |
function |
mendaftarkan midleware |
| action | fn |
function |
handle callback data |
| middleware | fn |
function |
alias untuk use |
| compose | fn |
function |
menambahkan function pada handler message |
Adalah variable umum (kamu boleh menggantinya jika mau), yang berupa object gabungan segala middleware, method atau fungsi-fungsi, dan data-data penunjang lainnya.
Seperti halnya pada sistem lainnya (Ruby, Go, NodeJS, PHP, dsb), menggunakan bot sebagai variable untuk menghandlenya.
Contohnya sebagai berikut:
const token = '123:abc';
const bot = new lumpia.init(token);
bot menjadi sebuah object sebagai perwakilan atas bot Telegram dengan ‘jiwa’ token-nya.
Token bot adalah identitasnya. Sehingga misalnya, botnya adalah belarGASbot dengan token 123:abc. Maka ketika kita coding, menyebut bot adalah si belajarGASbot nya (yang telah disambungkan dengan identias token).
Sebagai permisalan dalam kehidupan ini, adalah sebagai berikut:
botfather adalah ortu yang melahirkan botbelajarGASBottoken sebagai nomor identitas (Akta Lahir) nya.bot dikalungkan token sebagai tanda peserta. Yakni di deklarasikan, diumumkan.. Wooi si bot ini adalah pengenal untuk belajarGASbotSehingga, menyebut bot adalah menyebut object yang telah ditentukan tersebut.
Sebagaimana manusia, bot memiliki fungsi atau istilahnya disebut method.
Kalau manusia bisa makan, minum, jalan-jalan, kencan, dan lainnya. Maka bot memiliki method untuk mengirim pesan, kirim gambar, suara, kick orang, dan lain lain.
Contoh fungsi dari telegram.. yakni mengirim pesan. Maka, cara mengaksesnya adalah:
bot.telegram.sendMessage(chat_id, text)
Terdapat 3 field pada susunan diatas:
bot penyebutan / pemanggilan bot kitatelegram method atau fungsi dari/untuk/ke TelegramsendMessage menjalankan fungsi untuk mengirim pesan.Fungsi kirim pesan (sendMessage) sendiri memiliki kelengkapan minimal 2 syarat agar terkirim:
chat_id adalah ruangan obrolantext adalah isi pesan yang akan dikirim.Misalnya, mau berkirim pesan ke ruangan (grup) yang memiliki id -10010000001, maka:
bot.telegram.sendMessage(-10010000001, 'Halo Brok!');
maka bot akan mengirim pesan Halo Brok! ke ruangan ber kode id -10010000001.
Darimana kode ruangan (chat_id) ini berasal? Chat ID ditentukan oleh telegram. Kita tidak bisa menentukan sendiri kodenya. Namun kita bisa mengetahui ID nya dengan beberapa cara yang (insyaAllah) nanti akan dijelaskan pada halaman lainnya.
// token bot dari bapak bot
const token = '123:abc';
// adminbot variable untuk chat_id: boleh id kamu sendiri, boleh id grup
const adminbot = 213567634; // ini adalah id saya, @hasanudinhs
// inisiasi bot
const bot = new lumpia.init(token);
// fungsi mengirim pesan
function sendMessage() {
let result = bot.tg.sendMessage(adminbot, 'halo mas brok');
Logger.log(JSON.stringify(result, null, 2));
}
Kemudian jalankan fungsi tersebut pada Google Apps Script. Cara menjalankannya, bisa disimak pada materi menjalankan fungsi.
Jika berhasil, pesan kamu akan terkirim. Dan pada program, mendapatkan log sendMessage.
{
"ok": true,
"result": {
"message_id": 885,
"from": {
"id": 1719983221,
"is_bot": true,
"first_name": "belajarBotGas",
"username": "belajarGASbot"
},
"chat": {
"id": 213567634,
"first_name": "βbangHasan",
"last_name": "HS",
"username": "hasanudinhs",
"type": "private"
},
"date": 1629863141,
"text": "halo mas brok"
}
}
Semoga penjelasan sederhana ini bisa dimengerti :-)
Secara fungsi sama seperti options dalam inisiasi.
Namun pada bot dapat diakses secara langsung sebagai setter atau getter.
bot.options.log_id = 213567634;
bot.options.prefix_command: '.!/';
bot.options.username: 'strukturbot';
Use this property to get/set bot token.
bot.token = [string]
Use this property to get/set bot options log_id.
Alias bot.options.log_id
bot.log_id = [number/string]
memproses data POST pada function doPost buil-in pada Google Apps Script
bot.doPost(e)
| Param | Type | Description |
|---|---|---|
| e | data |
data post |
Contoh:
function doPost(e) {
bot.doPost(e);
}
Menangkap event yang disediakan atas tangkapan ctx.broadcast
bot.on(updateTypes, fn)
| Param | Type | Description |
|---|---|---|
| updateTypes | string/string[] |
Update type |
| fn | function |
function |
Contoh:
bot.on('photo', ctx => console.log(ctx.photo));
Menangkap dan memproses pesan yang bertipe text.
Alias: hear
bot.hears(triggers, fn)
| Param | Type | Description |
|---|---|---|
| triggers | string/string[]/RegEx/RegEx[] |
Triggers |
| fn | function |
function |
use case
user: Assalamu'alaikum
bot: Waa'alaikumussalam Wr Wb
code:
bot.hears("Assalamu'alaikum", ctx => ctx.replyIt("Waa'alaikumussalam Wr Wb"));
Command handling.
Alias: cmd
bot.command(commands, fn)
| Param | Type | Description |
|---|---|---|
| commands | string/string[] |
Commands |
| fn | function |
function |
Use case:
user: /ping
bot: Pong!
Code:
bot.cmd("ping", ctx => ctx.reply("Pong!"));
Handler for /start command.
bot.start(fn)
| Param | Type | Description |
|---|---|---|
| fn | function |
function |
Dapat menghandle juga beberapa kondisi sebagai berikut :
/start@namabot jika nama bot di-set pada parameter username saat inisiasi (lumpia.init) pada optionsctx.payload jika terdapat data yang dikirimkan.Use case:
user: /start
bot: Hello Human!
Code:
bot.start(ctx => ctx.reply("Hello Human"));
Registers for handling callback_data actions with string or regular expressions.
bot.action(triggers, fn)
| Param | Type | Description |
|---|---|---|
| triggers | string/string[]/RegEx/RegEx[] |
Triggers |
| fn | function |
function |
Register a middleware.
Alias middleware
bot.use(fn)
fn is function. With Parameters:
| Param Type | Description | |
|---|---|---|
| ctx | context |
context |
| next | function |
next step |
bot.use( (ctx, next) => {
ctx.hooked = true;
// eksekusi next() untuk melanjutkan ke middleware berikutnya
next();
})
Table resume semua properti yang melekat pada bot.telegram.
bot.telegram dapat juga disingkat menjadi bot.tg
variable bot bisa apa saja. Oleh karena dalam list ini, cukup dituliskan method telegram agar disesuaikan dengan variable penyertanya sendiri.
Main method to call api telegram.
telegram.callApi(method, data)
| Param | Type | Description |
|---|---|---|
| method | string |
method of Bot Api Telegram |
| data | json |
params of Bot Api Telegram |
// call getMe() method
telegram.callApi('getMe', {});
// call sendMessage() method
telegram.callApi('sendMessage', {
chat_id: 213567634,
text: 'Hello Lumpia!'
});
Use this method to add a new sticker to a set created by the bot.
telegram.addStickerToSet(ownerId, name, stickerData)
ππΌ π
| Param | Type | Description |
|---|---|---|
| ownerId | string |
User identifier of sticker set owner |
| name | string |
Sticker set name |
| stickerData | Object |
Sticker data({png_sticker: ‘stiker file’, emojis: ‘π’, mask__position: '' }) |
alias untuk answerCbQuery
Use this method to send answers to callback queries.
telegram.answerCbQuery(callbackQueryId, text, [showAlert], [extra])
ππΌ π
| Param | Type | Description |
|---|---|---|
| callbackQueryId | string |
Query id |
| [text] | string |
Notification text |
| [showAlert] | bool |
Show alert instead of notification |
| [extra] | object |
Extra parameters |
Use this method to send answers to game query.
telegram.answerGameQuery(callbackQueryId, url)
| Param | Type | Description |
|---|---|---|
| callbackQueryId | string |
Query id |
| url | string |
Notification text |
Use this method to send answers to shipping query.
telegram.answerShippingQuery(shippingQueryId, ok, shippingOptions, [errorMessage])
| Param | Type | Description |
|---|---|---|
| shippingQueryId | string |
Shipping Query id |
| ok | bool |
Specify True if delivery to the specified address is possible |
| shippingOptions | object |
Shipping Options |
| [errorMessage] | string |
Error message in human readable form |
Use this method to send answers to shipping query.
telegram.answerPreCheckoutQuery(preCheckoutQueryId, ok, [errorMessage])
| Param | Type | Description |
|---|---|---|
| preCheckoutQueryId | string |
Shipping Query id |
| ok | bool |
Specify True if everything is alright (goods are available, etc.) |
| [errorMessage] | string |
Error message in human readable form |
Use this method to send answers to an inline query.
telegram.answerInlineQuery(inlineQueryId, results, [extra])
| Param | Type | Description |
|---|---|---|
| inlineQueryId | string |
Query id |
| results | object[] |
Results |
| [extra] | object |
Extra parameters |
Use this method to approve a chat join request.
telegram.approveChatJoinRequest(chatId, userId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User id |
| [extra] | object |
Extra parameters |
Use this method to ban a channel chat in a supergroup or a channel.
banChatSenderChat(chatId, senderChatId, extra)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| senderChatId | number |
Sender id |
| [extra] | object |
Extra parameters |
Use this method to create new sticker set owned by a user.
telegram.createNewStickerSet(ownerId, name, title, stickerData, [isMasks])
ππΌ π
| Param | Type | Description |
|---|---|---|
| ownerId | string |
User identifier of sticker set owner |
| name | string |
Sticker set name |
| title | string |
Sticker set title |
| stickerData | object |
Sticker data({png_sticker: ‘stiker file’, emojis: ‘π’, mask__position: '' }) |
| [isMasks] | bool |
Pass True, if a set of mask stickers should be created |
Use this method to decline a chat join request.
telegram.declineChatJoinRequest(chatId, userId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User id |
| [extra] | object |
Extra parameters |
Use this method to delete a group sticker set from a supergroup.
telegram.deleteChatStickerSet(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Use this method to delete bot messages.
telegram.deleteMessage(chatId, messageId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | string |
Message id |
Use this method to set the thumbnail of a sticker set.
telegram.setStickerSetThumb(name, userId, [thumb])
ππΌ π
| Param | Type | Description |
|---|---|---|
| name | string |
Sticker set name |
| userId | string |
User identifier of the sticker set owner |
| thumb | File |
A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size |
Use this method to delete a sticker from a set created by the bot.
telegram.deleteStickerFromSet(stickerId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| stickerId | string |
File identifier of the sticker |
Use this method to edit captions of messages sent by the bot or via the bot.
telegram.editMessageCaption(chatId, messageId, inlineMessageId, caption, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | string |
Message id |
| inlineMessageId | string |
Inline message id |
| caption | string |
Caption |
| [extra] | object |
Extra parameters |
Use this method to edit media of messages sent by the bot or via the bot.
telegram.editMessageMedia(chatId, messageId, inlineMessageId, media, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | string |
Message id |
| inlineMessageId | string |
Inline message id |
| media | InputMedia |
InputMedia |
| [extra] | object |
Extra parameters |
Use this method to edit live location messages sent by the bot or via the bot.
telegram.editMessageLiveLocation(latitude, longitude, chatId, messageId, inlineMessageId, [markup])
ππΌ π
| Param | Type | Description |
|---|---|---|
| latitude | string |
Latitude of new location |
| longitude | string |
Longitude of new location |
| chatId | number/string |
Chat id |
| messageId | string |
Message id |
| inlineMessageId | string |
Inline message id |
| [markup] | object |
Keyboard markup |
| [extra] | object |
Extra parameters |
Use this method to edit only the reply markup of messages sent by the bot or via the bot.
telegram.editMessageReplyMarkup(chatId, messageId, inlineMessageId, markup, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | string |
Message id |
| inlineMessageId | string |
Inline message id |
| markup | object |
Keyboard markup |
| [extra] | object |
Extra parameters |
Use this method to edit text messages sent by the bot or via the bot.
telegram.editMessageText(chatId, messageId, inlineMessageId, text, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | string |
Message id |
| inlineMessageId | string |
Inline message id |
| text | string |
Message |
| [extra] | object |
Extra parameters |
Forwards message.
telegram.forwardMessage(chatId, fromChatId, messageId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Target Chat id |
| fromChatId | number/string |
Source Chat id |
| messageId | number |
Message id |
| [extra] | object |
Extra parameters |
Sends message copy.
telegram.sendCopy(chatId, message, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Target Chat id |
| message | object |
Message |
| [extra] | object |
Extra parameters |
Use this method to copy messages of any kind.
telegram.copyMessage(chatId, message, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Target Chat id |
| fromChatId | number/string |
Source Chat id |
| messageId | number |
Message id |
| [extra] | object |
Extra parameters |
Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
telegram.getWebhookInfo()
Use this method to get up to date information about the chat (current name of the user for one-on-one conversatio ns, current username of a user, group or channel, etc.).
telegram.getChat(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
telegram.getChatAdministrators(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user’s current score in the chat.
telegram.setGameScore(userId, score, inlineMessageId, chatId, messageId, [editMessage], [force])
ππΌ π
| Param | Type | Description |
|---|---|---|
| userId | number |
Target User id |
| score | number |
Target User id |
| inlineMessageId | string |
Inline message id |
| chatId | number/string |
Target Chat id |
| messageId | number/string |
Message id |
| [editMessage] | boolean |
edit target message, default value is True |
| [force] | boolean |
Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters |
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
telegram.getGameHighScores(userId, inlineMessageId, chatId, messageId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| userId | number\ |
Target User id |
| inlineMessageId | string |
Inline message id |
| chatId | number/string |
Target Chat id |
| messageId | number/string |
Message id |
Use this method to get information about a member of a chat.
telegram.getChatMember(chatId, userId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User identifier |
Use this method to get the number of members in a chat.
telegram.getChatMembersCount(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Returns basic info about a file and prepare it for downloading.
telegram.getFile(fileId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| fileId | string |
File id |
Returns link to file.
telegram.getFileLink(fileId)
| Param | Type | Description |
|---|---|---|
| fileId | string/object |
File id or file object |
Returns basic information about the bot.
telegram.getMe()
ππΌ π
Use this method to get the current list of the bot’s commands. Requires no parameters. Returns Array of BotCommand on success.
telegram.getMyCommands()
ππΌ π
Use this method to get a sticker set.
telegram.getStickerSet(name)
| Param | Type | Description |
|---|---|---|
| name | string |
Short name of the sticker set |
| ππΌ π |
Returns profiles photos for provided user.
telegram.getUserProfilePhotos(userId, [offset], [limit])
ππΌ π
| Param | Type | Description |
|---|---|---|
| userId | number |
Chat id |
| [offset] | number |
Offset |
| [limit] | number |
Limit |
Use this method to set default chat permissions for all members.
telegram.setChatPermissions(chatId, permissions)
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| permissions | object |
New default chat permissions |
Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc.
telegram.banChatMember(chatId, userId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User id |
| [extra] | object |
Extra parameters |
Use this method to restrict a user in a supergroup.
telegram.restrictChatMember(chatId, userId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User id |
| [extra] | object |
Extra parameters |
Use this method to promote or demote a user in a supergroup or a channel.
telegram.promoteChatMember(chatId, userId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User id |
| [extra] | object |
Extra parameters |
New custom title for the administrator; 0-16 characters, emoji are not allowed
telegram.setChatAdministratorCustomTitle(chatId, userId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User id |
| title | string |
Custom title |
Use this method to export an invite link to a supergroup or a channel.
telegram.exportChatInviteLink(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Use this method to set a new profile photo for the chat.
telegram.setChatPhoto(chatId, photo)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| photo | File |
New chat photo |
Use this method to delete a chat photo.
telegram.deleteChatPhoto(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Use this method to change the title of a chat.
telegram.setChatTitle(chatId, title)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| title | string |
New chat title, 1-255 characters |
Use this method to change the description of a supergroup or a channel.
telegram.setChatDescription(chatId, description)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| description | string |
New chat description, 0-255 characters |
Use this method to set a new group sticker set for a supergroup.
telegram.setChatStickerSet(chatId, stickerSetName)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| stickerSetName | string |
Name of the sticker set |
Use this method to pin a message in a supergroup.
telegram.pinChatMessage(chatId, messageId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | number |
Message id |
| [extra] | object |
Extra parameters |
Use this method to unpin a message in a supergroup chat.
telegram.unpinChatMessage(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| [extra] | object |
Extra parameters |
Use this method to clear the list of pinned messages in a chat
telegram.unpinAllChatMessages(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Use this method for your bot to leave a group, supergroup or channel.
telegram.leaveChat(chatId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
Removes webhook integration.
telegram.deleteWebhook()
ππΌ π
| Param | Type | Description |
|---|---|---|
| [extra] | object |
Extra parameters |
Sends audio.
telegram.sendAudio(chatId, audio, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| audio | File |
Document |
| [extra] | object |
Extra parameters |
Sends game.
telegram.sendGame(chatId, gameName, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| gameName | String |
Game short name |
| [extra] | object |
Extra parameters |
Sends chat action.
telegram.sendChatAction(chatId, action)
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| action | string |
Chat action |
Sends document.
telegram.sendContact(chatId, phoneNumber, firstName, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| phoneNumber | string |
Contact phone number |
| firstName | string |
Contact first name |
| [extra] | object |
Extra parameters |
Sends dice.
telegram.sendDice(chatId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| [extra] | object |
Extra parameters |
Sends document.
telegram.sendDocument(chatId, doc, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| doc | File |
Document |
| [extra] | object |
Extra parameters |
Sends location.
telegram.sendLocation(chatId, latitude, longitude, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| latitude | number |
Latitude |
| longitude | number |
Longitude |
| [extra] | object |
Extra parameters |
Sends text message.
telegram.sendMessage(chatId, text, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| text | string |
Message |
| [extra] | object |
Extra parameters |
Sends a photo.
telegram.sendPhoto(chatId, photo, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| photo | File |
Photo |
| [extra] | object |
Extra parameters |
Sends media album.
telegram.sendMediaGroup(chatId, media, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| media | InputMedia[] |
Media array |
| [extra] | object |
Extra parameters |
Sends sticker.
telegram.sendSticker(chatId, sticker, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| sticker | File |
Document |
| [extra] | object |
Extra parameters |
Use this method to move a sticker in a set created by the bot to a specific position.
telegram.setStickerPositionInSet(sticker, position)
| Param | Type | Description |
|---|---|---|
| sticker | string |
File identifier of the sticker |
| position | number |
New sticker position in the set, zero-based |
Sends venue information.
telegram.sendVenue(chatId, latitude, longitude, title, address, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| latitude | number |
Latitude |
| longitude | number |
Longitude |
| title | string |
Venue title |
| address | string |
Venue address |
| [extra] | object |
Extra parameters |
Sends invoice.
telegram.sendInvoice(chatId, invoice)
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| invoice | object |
Invoice object |
Sends video.
telegram.sendVideo(chatId, video, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| video | File |
Document |
| [extra] | object |
Extra parameters |
Sends video.
telegram.sendAnimation(chatId, animation, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| animation | File |
Document |
| [extra] | object |
Extra parameters |
Sends round video.
telegram.sendVideoNote(chatId, video, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| video | File |
Video note file |
| [extra] | object |
Extra parameters |
Sends voice.
telegram.sendVoice(chatId, voice, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| voice | File/string |
File, file id or HTTP URL |
| [extra] | object |
Extra parameters |
Sends a poll.
telegram.sendPoll(chatId, question, options, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| question | string |
Poll question |
| options | string[] |
Answer options |
| [extra] | object |
Extra parameters |
Use this method to change the list of the bot’s commands
telegram.setMyCommands(commands)
| Param | Type | Description |
|---|---|---|
| commands | object[] |
List of bot commands |
Sends quiz.
telegram.sendQuiz(chatId, question, options, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| question | string |
Poll question |
| options | string[] |
Answer options |
| [extra] | object |
Extra parameters |
Stops anonymous poll.
telegram.stopPoll(chatId, messageId, [extra])
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | string |
Poll message id |
| options | string[] |
Answer options |
| [extra] | object |
Extra parameters |
Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires.
telegram.stopMessageLiveLocation(chatId, messageId, inlineMessageId, [markup])
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| messageId | string |
Message id |
| inlineMessageId | string |
Inline message id |
| [markup] | object |
Keyboard markup |
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods.
telegram.uploadStickerFile(ownerId, stickerFile)
ππΌ π
| Param | Type | Description |
|---|---|---|
| ownerId | string |
User identifier of sticker file owner |
| stickerFile | File |
Png image with the sticker |
Specifies an url to receive incoming updates via an outgoing webhook.
telegram.setWebhook(url, [extra])
ππΌ π
| Param | Type | Description |
|---|---|---|
| url | string |
Public url for webhook |
| [extra] | object |
Extra parameters |
Use this method to unban a previously kicked user in a supergroup.
telegram.unbanChatMember(chatId, userId)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| userId | number |
User id |
| [extra] | object |
Extra parameters |
Use this method to unban a previously banned channel chat in a supergroup or channel.
unbanChatSenderChat(chatId, senderChatId, extra)
ππΌ π
| Param | Type | Description |
|---|---|---|
| chatId | number/string |
Chat id |
| senderChatId | number |
Sender id |
| [extra] | object |
Extra parameters |
Informs a user that some Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change).
telegram.setPassportDataErrors(errors)
ππΌ π
| Param | Type | Description |
|---|---|---|
| [errors] | PassportElementError[] |
An array describing the errors |
Dimana itu ctx ?
Lihatlah code berikut:
bot.cmd('ping', ctx => ctx.reply('Pong!'));
Keterangan:
ctx adalah context itu.reply adalah method (shorthand) untuk menghandle pesanBerikut kerangka isi dari ctx.
Context dibuat per request dan berisi beberapa properti:
| Property | Description |
|---|---|
ctx.telegram |
Telegram client instance |
ctx.tg |
alias ctx.telegram |
ctx.updateType |
Update type (message, inline_query, etc.) |
[ctx.updateSubTypes] |
Update subtypes (text, sticker, audio, etc.) |
[ctx.message] |
Received message |
[ctx.editedMessage] |
Edited message |
[ctx.inlineQuery] |
Received inline query |
[ctx.chosenInlineResult] |
Received inline query result |
[ctx.callbackQuery] |
Received callback query |
[ctx.shippingQuery] |
Shipping query |
[ctx.preCheckoutQuery] |
Pre-checkout query |
[ctx.channelPost] |
New incoming channel post of any kind β text, photo, sticker, etc. |
[ctx.editedChannelPost] |
New version of a channel post that is known to the bot and was edited |
[ctx.poll] |
New version of a anonymous poll that is known to the bot and was changed |
[ctx.pollAnswer] |
This object represents an answer of a user in a non-anonymous poll. |
[ctx.chat] |
Current chat info |
[ctx.from] |
Sender info |
[ctx.match] |
Regex match |
[ctx.broadcast] |
update type bot.on |
Context shortcuts for message update:
Context shortcuts for callback_query update:
| Shortcut | Bound to | Available | Params |
|---|---|---|---|
addStickerToSet |
telegram.addStickerToSet |
||
answerCbQuery |
telegram.answerCbQuery |
text, showAlert, extra |
|
answerGameQuery |
telegram.answerGameQuery |
url |
|
createNewStickerSet |
telegram.createNewStickerSet |
||
deleteChatPhoto |
telegram.deleteChatPhoto |
||
deleteMessage |
telegram.deleteMessage |
||
deleteStickerFromSet |
telegram.deleteStickerFromSet |
||
editMessageCaption |
telegram.editMessageCaption |
caption, extra |
|
editMessageMedia |
telegram.editMessageMedia |
media, extra |
|
editMessageReplyMarkup |
telegram.editMessageReplyMarkup |
markup |
|
editMessageText |
telegram.editMessageText |
text, extra |
|
exportChatInviteLink |
telegram.exportChatInviteLink |
||
forwardMessage |
telegram.forwardMessage |
||
getChat |
telegram.getChat |
||
getChatAdministrators |
telegram.getChatAdministrators |
||
getChatMember |
telegram.getChatMember |
||
getChatMembersCount |
telegram.getChatMembersCount |
||
getStickerSet |
telegram.getStickerSet |
||
leaveChat |
telegram.leaveChat |
||
pinChatMessage |
telegram.pinChatMessage |
||
reply |
telegram.sendMessage |
text, extra |
|
replyWithAnimation |
telegram.sendAnimation |
animation, extra |
|
replyWithAudio |
telegram.sendAudio |
||
replyWithChatAction |
telegram.sendChatAction |
||
replyWithDice |
telegram.sendDice |
||
replyWithDocument |
telegram.sendDocument |
||
replyWithGame |
telegram.sendGame |
||
replyWithHTML |
telegram.sendMessage |
text, extra |
|
replyWithInvoice |
telegram.sendInvoice |
||
replyWithLocation |
telegram.sendLocation |
||
replyWithMarkdown |
telegram.sendMessage |
text, extra |
|
replyWithMediaGroup |
telegram.sendMediaGroup |
||
replyWithPhoto |
telegram.sendPhoto |
||
replyWithPoll |
telegram.sendPoll |
||
replyWithSticker |
telegram.sendSticker |
||
replyWithVideo |
telegram.sendVideo |
||
replyWithVideoNote |
telegram.sendVideoNote |
||
replyWithVoice |
telegram.sendVoice |
||
setChatDescription |
telegram.setChatDescription |
||
setChatPhoto |
telegram.setChatPhoto |
||
setChatTitle |
telegram.setChatTitle |
||
setStickerPositionInSet |
telegram.setStickerPositionInSet |
sticker, position |
|
setStickerSetThumb |
telegram.setStickerSetThumb |
||
stopPoll |
telegram.stopPoll |
||
unpinChatMessage |
telegram.unpinChatMessage |
||
unpinAllChatMessages |
telegram.unpinAllChatMessages |
||
uploadStickerFile |
telegram.uploadStickerFile |
||
unbanChatMember |
telegram.unbanChatMember |
||
replyIt |
telegram.sendMessage |
text, extra |
|
replyItWithAudio |
telegram.sendAudio |
(v3.6) | audio, extra |
replyItWithDocument |
telegram.sendDocument |
(v3.6) | doc, extra |
replyItWithHTML |
telegram.sendMessage |
(v3.6) | text, extra |
replyItWithLocation |
telegram.sendLocation |
(v3.6) | lat, lon, extras |
replyItWithMarkdown |
telegram.sendMessage |
(v3.6) | text, extra |
replyItWithPhoto |
telegram.sendPhoto |
(v3.6) | photo, extra |
replyItWithSticker |
telegram.sendSticker |
(v3.6) | sticker, extra |
replyItWithVideo |
telegram.sendVideo |
(v3.6) | video, extra |
Context shortcuts for inline_query update:
| Shortcut | Bound to |
|---|---|
answerInlineQuery |
telegram.answerInlineQuery |
Context shortcuts for shipping_query update:
| Shortcut | Bound to |
|---|---|
answerShippingQuery |
telegram.answerShippingQuery |
Context shortcuts for pre_checkout_query update:
| Shortcut | Bound to |
|---|---|
answerPreCheckoutQuery |
telegram.answerPreCheckoutQuery |
Check in this code:
const bot = new lumpia.init(token)
bot.command('quit', (ctx) => {
// Explicit usage
ctx.telegram.leaveChat(ctx.message.chat.id)
})
bot.on('text', (ctx) => {
// Explicit usage
ctx.telegram.sendMessage(ctx.message.chat.id, `Echo: ${ctx.message.text}`)
})
bot.on('callback_query', (ctx) => {
// Explicit usage
ctx.telegram.answerCbQuery(ctx.callbackQuery.id)
})
bot.on('inline_query', (ctx) => {
const result = []
// Explicit usage
ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result)
})const bot = new lumpia.init(token)
bot.command('quit', (ctx) => {
// Explicit usage
ctx.tg.leaveChat(ctx.chat.id)
})
bot.on('text', (ctx) => {
// Explicit usage
ctx.tg.sendMessage(ctx.chat.id, `Echo: ${ctx.message.text}`)
})
bot.on('callback_query', (ctx) => {
// Explicit usage
ctx.tg.answerCbQuery(ctx.callbackQuery.id)
})
bot.on('inline_query', (ctx) => {
const result = []
// Explicit usage
ctx.tg.answerInlineQuery(ctx.inlineQuery.id, result)
})const bot = new lumpia.init(token)
bot.command('quit', (ctx) => {
// Using context shortcut
ctx.leaveChat()
})
bot.on('text', (ctx) => {
// Using context shortcut
ctx.reply(`Echo: ${ctx.message.text}`)
})
bot.on('callback_query', (ctx) => {
// Using context shortcut
ctx.answerCbQuery()
})
bot.on('inline_query', (ctx) => {
const result = []
// Using context shortcut
ctx.answerInlineQuery(result)
})Adalah konsep jika dimasukkan sebuah trigger, jika trigger ditemukan maka tetep diteruskan ke trigger selanjutnya.
Untuk dapat berkesinambungan, perlu dijalankan fungsi next() pada context.
const bot = new lumpia.init(token)
bot.cmd('ping', (ctx) => {
// User typing: /ping
ctx.reply('pong!')
})
// tidak akan dieksekusi
bot.cmd('ping', (ctx) => {
// User typing: /ping
ctx.reply('pong 2!');
})const bot = new lumpia.init(token)
bot.cmd('ping', (ctx, next) => {
// User typing: /ping
ctx.reply('pong!');
next();
})
// perintah tetap dieksekusi
bot.cmd('ping', (ctx) => {
// User typing: /ping
ctx.reply('pong 2!')
})Di pergunakan saat deteksi trigger on.
bot.on('message', fn);
bot.on('photo', fn);
// ... etc
Tipe update tersedia adalah sebagai berikut. Keterangan masing-masing tipe ada di dalam referensi sumber asli.
Ref: update
Ref: message
mention @usernamehashtag #hashtagcashtag $USDbot_command /start@jobs_boturl https://telegram.orgemail do-not-reply@telegram.orgphone_number +1-212-555-0123bold bold textitalic italic textunderline underlined textstrikethrough strikethrough textcode monowidth stringpre monowidth blocktext_link for clickable text URLstext_mention for users without usernamesRef: Entity
Informasi bot type update dapat ditemukan pada:
ctx.broadcast dan ctx.updateType
Untuk inisiasi awal
const helper = lumpia.helper;
// atau
const Helper = lumpia.helper;
Silakan menggunakan huruf besar atau kecil untuk konstantanya, sesuaikan sendiri dengan kebiasaan masing-masing.
Koleksi method untuk membantu saat development.

membersihkan text dari tags html (meng-escape), sehingga tidak terjadi error saat berada pada parse_mode HTML.
Format:
clearHTML(text)
let text = 'Bilangan 12 < 23';
let pesan = helper.clearHTML(text);
membersihkan text dari tags markdown (meng-escape), sehingga tidak terjadi error saat berada pada parse_mode markdown.
Format:
clearMarkdown(text)
let text = 'Hitungan 2 * 3 adalah 6';
let pesan = helper.clearMarkdown(text);
seperti forEach pada javascript, namun bisa dipergunakan untuk objek (JSON).
Format:
forEach(object, callback);
callback memiliki 2 parameter:
var data = [ 'satu', 'dua', 'tiga']; // contoh tipe array
var data = { satu: 1, dua: 2}; // contoh tipe json
helper.forEach(data, (isi, index) => {
console.log(index, isi);
});
Memerika apakah suatu nilai terdapat pada sebuah array
Format:
isIn(list, index)
let admin = [ 123, 456 ];
let id = msg.from.id;
if (helper.isIn(admin, id)) {
console.log('Dia adalah admin!');
}
membuat hasil acak untuk bilangan atau array.
Format:
random(list);
random(min, max);
params:
list bertipe arraymin dan max bertipe integerlet list = ['aku', 'kamu', 'dia'];
helper.random(list) // hasil acakan dari aku, kamu, atau dia
helper.random(0,100) // hasil acakan antara angka 1 - 100
membuat text bertipe blob
Format:
textBlob(namaFile, text)
params:
namaFile tanpa ekstensi, otomatis akan ditambahkan .txttext bertipe stringlet blob = helper.textBlob('namaFile', 'Hasanudin H Syafaat');
Tipe output pada Google Apps Script dalam mode web app.
Secara umum dapat dipergunakan untuk merespon fungsi pada doPost(e).
Ada 3 yang tersedia:
outputText(text) menghasilkan keluaran bertipe textoutputJSON(data) menghasilkan keluaran bertipe JSON, biasanya cocok untuk pembuatan REST APIoutputHTML(html) menghasilkan keluaran bertipe HTML, biasanya cocok untuk bertipe website biasaalias: name
menghasilkan format nama user, baik plain text ataupun html.
Format:
name(object);
return:
let nama = helper.name(ctx.from);
console.log(nama.fullname);
mengecek tipe suatu variable
Format:
typeCheck(data);
let data = [ 1, 2, 3];
let tipe = helper.typeCheck(data);
console.log(tipe) // result: array
if (tipe === 'array') console.log('Data bertipe Array!');
membersihkan objek dari null / undefined.
Format:
compactOptions(data);
let options = { satu: 1, kosong: null, tidak: undefined };
compactOptions(options);
Memeriksa apakah objek tertentu memiliki properti dengan nama tertentu.
Format:
hasProp(object, key);
let obj = { 'foo': 'bar', 'baz': () => {} }
hasProp(obj, 'foo') // true
hasProp(obj, 'baz') // true
hasProp(obj, 'abc') // false
Checks if a given object has a property with a given name.
Furthermore performs a typeof check on the property if it exists
let obj = { 'foo': 'bar', 'baz': () => {} }
hasPropType(obj, 'foo', 'string') // true
hasPropType(obj, 'baz', 'function') // true
hasPropType(obj, 'abc', 'number') // false
bantuan untuk pembuatan keyboard inline, kompabilitas Lib V1/2.
| method | params | keterangan |
|---|---|---|
| text | text, data, hide | jika ditekan menghasilkan callback data |
| inline | text, data, hide | alias dari method text diatas |
| query | text, data | bounding ke switch_inline_queryjika ditekan, akan memilih jendala chat yang mana sebagai tujuan |
| queryChat | text, data | bounding ke switch_inline_query_current_chat jika ditekan, pada text box memunculkan username dan text isian. Digunakan untuk bot inline |
| url | text, url, hide | jika ditekan akan menuju ke url |
Default untuk hide adalah false.
Sample belum dibikin (lagi M π€£)
Silakan tinggalkan komentar saja jika ingin membantu melengkapi dokumentasi…