Tinygram
Tiny Telegram Bot API client library with TypeScript types.
Automatically generated from telegram-bot-api-spec.
Usage
Import in Node.js:
import { initTgBot } from "tinygram";
Import in Deno:
import { initTgBot } from "https://deno.land/x/tinygram/mod.ts";
Initialize the bot:
const botToken = "YOUR_BOT_TOKEN";
const tgBot = initTgBot({ botToken });
Call the API:
const botUser = await tgBot.getMe();
console.log(botUser.username);
Get updates:
for await (const update of tgBot.listUpdates({ timeout: 10 })) {
console.log(update);
}
Download a file:
const botUser = await tgBot.getMe();
const botPhoto = await tgBot.getUserProfilePhotos({ user_id: botUser.id });
const botPhotoFileId = botPhoto.photos[0]?.[0]?.file_id;
const botPhotoFile = await tgBot.getFile({ file_id: botPhotoFileId });
const botPhotoBlob = await tgBot.getFileData(botPhotoFile.file_path);
// Save to file
await writeFile("bot.jpg", botPhotoBlob.stream());
// Set as img src
img.src = URL.createObjectURL(botPhotoBlob);
Example - Echo bot:
for await (const update of tgBot.listUpdates({ timeout: 10 })) {
if (update.message) {
const message = update.message;
if (message.chat.type === "private" && message.text) {
console.log(`Received message from ${message.from.first_name}: ${message.text}`);
await tgBot.sendMessage({ chat_id: message.chat.id, text: message.text });
}
}
}
Auto-abort all requests after a timeout:
const tgBot = initTgBot({
botToken: "YOUR_BOT_TOKEN",
fetch: (url, init) => fetch(url, { ...init, signal: AbortSignal.timeout(10_000) }),
});
Auto-retry rate-limited requests:
const tgBot = initTgBot({
botToken: "YOUR_BOT_TOKEN",
fetch: async (url, init) => {
let attempts = 0;
while (true) {
attempts++;
const response = await fetch(url, init);
if (attempts < 3 && response.status === 429) {
const error = await response.json();
await new Promise((resolve) => setTimeout(resolve, error.parameters.retry_after * 1000));
continue;
}
return response;
}
},
});
FAQ
fetch is not a function
If you're using Node.js without fetch support, you need to polyfill it or pass a custom fetch as an argument.
import fetch from "node-fetch";
const tgBot = initTgBot({ token: "YOUR_BOT_TOKEN", fetch });
If you're sending files, you need FormData too.
import fetch, { FormData } from "node-fetch";
const tgBot = initTgBot({ token: "YOUR_BOT_TOKEN", fetch, FormData });
Must use import to load ES Module
The library is only available as a module. If you're using CommonJS, you must import it using dynamic import:
const { initTgBot } = await import("tinygram");
Proxy is not defined
This library requires Proxy support, because the bot instance is actually a proxy.