Last active
January 16, 2024 21:14
-
-
Save izzqz/24086734f245a9cbdd97ea3a4711d561 to your computer and use it in GitHub Desktop.
Telegram bot API in tree lines of code. Probably the only one lib which doesn't suck for javascript. Works in any js runtime. Good for serverless or whatever
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Telegram bot API wrapper | |
* | |
* @author @izzqz | |
*/ | |
const bot = new Proxy(new String(BOT_TOKEN), { | |
get: (token, method) => (params) => fetch(`https://api.telegram.org/bot${token}/${method}?${new URLSearchParams(params)}`), | |
}); | |
// Token can be env variable, global and etc | |
var BOT_TOKEN = 'super_token'; | |
// Usage | |
// This code will fetch https://api.telegram.org/botsuper_token/sendMessage?chat_id=1337&text=super_text | |
// And send message to specific chat_id | |
bot.sendMessage({ | |
chat_id: 1337, | |
text: 'super_text', | |
}); | |
// check available methods in docs => https://core.telegram.org/bots/api#available-methods | |
//# Diferent variations | |
//## Log api error | |
new Proxy(new String(BOT_TOKEN), { | |
get: (token, method) => (params) => | |
fetch( | |
`https://api.telegram.org/bot${token}/${method}?${new URLSearchParams(params)}`, | |
).then((res) => { | |
res.json().then((body) => { | |
if (!body.ok) console.error('TG API ERROR', body.description); | |
}); | |
return res; | |
}), | |
}); | |
//## Usign closure for token | |
const createBot = (token) => | |
new Proxy({}, { | |
get: (_, method) => (params) => | |
fetch( | |
`https://api.telegram.org/bot${token}/${method}?${new URLSearchParams(params)}`, | |
), | |
}, | |
); | |
const bot1 = createBot('super_token_1'); | |
const bot2 = createBot('super_token_2'); | |
const bot3 = createBot('super_token_3'); | |
//# BONUS | |
// Check this project if you one of typescript people | |
// https://github.com/KnorpelSenf/typegram |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment