This library (telegram-client.js) enables programmatic interaction with Telegram via the user client API (not bot API).
- Authentication with Telegram (including 2FA support)
- Session management (automatic reuse of existing sessions)
- Retrieving chats/dialogs on demand
- Fetching messages from specific chats
- Filtering messages by pattern (e.g., regex)
// Example using the client library (see client.js for a more complete example)
import TelegramClient from "./telegram-client.js";
async function main() {
// Create a new client instance
const client = new TelegramClient(
process.env.TELEGRAM_API_ID,
process.env.TELEGRAM_API_HASH,
process.env.TELEGRAM_PHONE_NUMBER
// Optional: specify session path (default uses the tgcli store)
);
await client.initializeDialogCache();
const dialogs = await client.listDialogs(20);
dialogs.forEach((chat) => {
console.log(`Chat: ${chat.title} (ID: ${chat.id})`);
});
// Example: Get messages (replace 'your_channel_id' with an actual ID)
// const { messages } = await client.getMessagesByChannelId('your_channel_id', 50);
// console.log(messages);
}
main().catch(console.error);Run the standalone client example:
node client.jsconst client = new TelegramClient(apiId, apiHash, phoneNumber, sessionPath);apiId: Your Telegram API IDapiHash: Your Telegram API HashphoneNumber: Your phone number in international formatsessionPath: (Optional) Path to save the session file (default uses the tgcli store)
login(): Authenticates with Telegram (handles new logins, 2FA, and session reuse).initializeDialogCache(): Ensures authentication with Telegram.listDialogs(limit?): Returns the firstlimitdialogs as simple metadata objects.searchDialogs(keyword, limit?): Searches dialogs by title or username.ensureLogin(): Throws if the client is not currently authorized.getMessagesByChannelId(channelId, limit): Returns{ peerTitle, peerId, peerType, messages }for the requested chat/channel (messages includetopic_idwhen applicable).listForumTopics(channelId, options?): Returns forum topics for a supergroup (uses Telegram forum APIs).getTopicMessages(channelId, topicId, limit?): Returns{ total, next, messages }for a forum topic.filterMessagesByPattern(messages, pattern): Filters an array of message strings by a regex pattern.destroy(): Closes the underlying MTProto connection (useful for short-lived scripts).