telegram-sdk-core
v1.0.0
Published
Framework-agnostic Telegram SDK for Node.js - Works with Express, NestJS, Hono, Next.js, and more
Maintainers
Readme
@telegram-sdk/core
Framework-agnostic Telegram SDK for Node.js. Works with Express, NestJS, Hono, Next.js, Fastify, and any Node.js framework!
Features
- 🚀 Framework-agnostic - Works with any Node.js framework
- 📦 NPM-ready - Publishable to npm, dual ESM/CJS support
- 🔌 Pluggable storage - Adapter pattern for custom storage backends
- 📝 Type-safe - Full TypeScript support
- 🎯 Stateless - Pure functions, no global state
- 🔒 Zero dependencies - Only Telegram libraries (grammy, telegram)
Installation
npm install @telegram-sdk/core grammy telegramFor Prisma adapter (optional):
npm install @prisma/clientQuick Start
Basic Usage
import { createMTPClient, getChannelPosts } from '@telegram-sdk/core';
// Create client
const { client } = await createMTPClient({
apiId: 12345,
apiHash: 'your-api-hash',
sessionString: 'your-session-string',
});
// Fetch posts
const posts = await getChannelPosts(client, '@channel', { limit: 10 });
console.log(posts);Framework Examples
Express.js
import express from 'express';
import { createMTPClient, getChannelPosts } from '@telegram-sdk/core';
const app = express();
app.get('/api/posts/:channel', async (req, res) => {
try {
const { client } = await createMTPClient({
apiId: process.env.TELEGRAM_API_ID!,
apiHash: process.env.TELEGRAM_API_HASH!,
sessionString: process.env.TELEGRAM_SESSION_STRING!,
});
const posts = await getChannelPosts(client, req.params.channel, { limit: 10 });
res.json(posts);
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});NestJS
import { Injectable } from '@nestjs/common';
import { createMTPClient, getChannelPosts } from '@telegram-sdk/core';
import type { TelegramClient } from 'telegram';
@Injectable()
export class TelegramService {
private client: TelegramClient | null = null;
async initialize() {
if (!this.client) {
const result = await createMTPClient({
apiId: parseInt(process.env.TELEGRAM_API_ID!),
apiHash: process.env.TELEGRAM_API_HASH!,
sessionString: process.env.TELEGRAM_SESSION_STRING!,
});
this.client = result.client;
}
}
async fetchPosts(channel: string, limit = 20) {
if (!this.client) await this.initialize();
return await getChannelPosts(this.client!, channel, { limit });
}
}Hono
import { Hono } from 'hono';
import { createMTPClient, getChannelPosts } from '@telegram-sdk/core';
const app = new Hono();
app.get('/posts/:channel', async (c) => {
const { client } = await createMTPClient({
apiId: parseInt(c.env.TELEGRAM_API_ID),
apiHash: c.env.TELEGRAM_API_HASH,
sessionString: c.env.TELEGRAM_SESSION_STRING,
});
const posts = await getChannelPosts(client, c.req.param('channel'), { limit: 10 });
return c.json(posts);
});Next.js (App Router)
// app/api/posts/[channel]/route.ts
import { createMTPClient, getChannelPosts } from '@telegram-sdk/core';
import { NextResponse } from 'next/server';
export async function GET(
request: Request,
{ params }: { params: { channel: string } }
) {
const { client } = await createMTPClient({
apiId: parseInt(process.env.TELEGRAM_API_ID!),
apiHash: process.env.TELEGRAM_API_HASH!,
sessionString: process.env.TELEGRAM_SESSION_STRING!,
});
const posts = await getChannelPosts(client, params.channel, { limit: 20 });
return NextResponse.json(posts);
}Next.js (Pages Router)
// pages/api/posts/[channel].ts
import { createMTPClient, getChannelPosts } from '@telegram-sdk/core';
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { channel } = req.query;
const { client } = await createMTPClient({
apiId: parseInt(process.env.TELEGRAM_API_ID!),
apiHash: process.env.TELEGRAM_API_HASH!,
sessionString: process.env.TELEGRAM_SESSION_STRING!,
});
const posts = await getChannelPosts(client, channel as string, { limit: 20 });
res.json(posts);
}Storage Adapters
Memory Adapter (Default)
import { createMTPClient, MemorySessionAdapter } from '@telegram-sdk/core';
const adapter = new MemorySessionAdapter();
const { client } = await createMTPClient({
apiId: 12345,
apiHash: 'hash',
sessionAdapter: adapter,
sessionId: 'my-session',
});Prisma Adapter
import { createMTPClient, PrismaSessionAdapter } from '@telegram-sdk/core';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const adapter = new PrismaSessionAdapter(prisma);
const { client } = await createMTPClient({
apiId: 12345,
apiHash: 'hash',
sessionAdapter: adapter,
sessionId: 'my-session',
});Custom Adapter
import type { SessionAdapter } from '@telegram-sdk/core';
class MyCustomAdapter implements SessionAdapter {
async getSession(sessionId: string): Promise<string | null> {
// Your implementation
}
async saveSession(sessionId: string, sessionString: string): Promise<void> {
// Your implementation
}
async deleteSession(sessionId: string): Promise<void> {
// Your implementation
}
}API Reference
Client Operations
createMTPClient(options)- Create a Telegram MTP clientgetChannelPosts(client, channelId, options)- Fetch posts from a channelsendMessage(client, chatId, message, options)- Send a messagegetMessages(client, chatId, options)- Get messages from a chatgetEntity(client, identifier)- Get entity informationresolveUsername(client, username)- Resolve username to InputUseraddContactsToChat(client, chatId, usernames)- Add users to a chatscrapeContacts(client, chatId)- Scrape contacts from a chatdownloadMedia(client, chatId, messageId)- Download media from a message
Bot Operations
createBot(options)- Create a Telegram bot instancestartBot(bot)- Start bot in polling modestopBot(bot)- Stop bot
Adapters
MemorySessionAdapter- In-memory storage adapterPrismaSessionAdapter- Prisma-based storage adapter
TypeScript Support
Full TypeScript support with exported types:
import type {
CreateClientOptions,
GetPostsOptions,
SimplePost,
BulkAddResult,
SessionAdapter,
} from '@telegram-sdk/core';License
MIT
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
