@anura-gate/watcher-telegram
v0.5.0
Published
GATE Watcher — Self-hosted daemon for Telegram integration. Credentials never leave your machine.
Maintainers
Readme
GATE Watcher — Telegram
Self-hosted daemon that connects to Telegram (personal account) and pushes all message events to GATE cloud for security processing. Your Telegram session tokens never leave your machine.
How it works
Your Machine (Watcher) GATE Cloud
┌─────────────────────┐ ┌──────────────────┐
│ Telegram session │───────>│ Security pipeline │
│ (tokens stay HERE) │<───────│ (redact, policy, │
│ │ poll │ audit, forward) │
└─────────────────────┘ └──────────────────┘Quick Start (CLI)
The fastest way — runs standalone with QR in your terminal.
cd gate-watcher-telegram
npm install
# Create .env (or pass env vars directly)
cp .env.example .env
# Fill in GATE_KEY, GATE_INTEGRATION_ID, TELEGRAM_API_ID, TELEGRAM_API_HASH
npm startOpen Telegram on your phone → Settings → Devices → Link Desktop Device → Scan the QR code. Done.
Embed in Your App (SDK)
For production use — import the class, handle the QR however you want.
npm install @anura-gate/watcher-telegramSingle-session mode
One Telegram account per watcher instance.
const { GateTelegramWatcher } = require("@anura-gate/watcher-telegram");
const watcher = new GateTelegramWatcher({
gateUrl: "https://your-gate.vercel.app",
gateKey: "gk-xxx",
integrationId: "int_xxx",
apiId: "12345",
apiHash: "abc123",
sessionId: "user_123",
});
// Render QR however you want — web page, API response, etc.
watcher.on("qr", (loginUrl) => {
// loginUrl is a tg://login?token=... URL
// Generate a QR code from this URL for the user to scan
io.emit("telegram-qr", loginUrl);
});
watcher.on("ready", () => {
console.log("Telegram connected!");
});
// Every incoming message after GATE security processing
watcher.on("message", (msg, result) => {
console.log(`From: ${msg.senderId}, Text: ${msg.text}`);
console.log(`Security actions: ${result.securityActions}`);
console.log(`Blocked: ${result.blocked}`);
});
// Outgoing messages (sent from phone/desktop)
watcher.on("message_sent", (msg, result) => {
console.log(`Sent: ${msg.text}`);
console.log(`Security actions: ${result.securityActions}`);
});
// Outbound actions executed by the watcher
watcher.on("action_result", ({ action, success, error }) => {
console.log(`${action}: ${success ? "done" : error}`);
});
await watcher.start();
// Later...
await watcher.stop();Pool mode (multi-session)
Manage multiple Telegram accounts from a single watcher instance. Enabled by omitting sessionId.
const { GateTelegramWatcher } = require("@anura-gate/watcher-telegram");
const watcher = new GateTelegramWatcher({
gateKey: "gk-xxx",
integrationId: "int_xxx",
apiId: "12345",
apiHash: "abc123",
// No sessionId → pool mode
});
// Attach to your HTTP server with WebSocket support
watcher.attach(server, "/ws/telegram", {
resolveUser: (req) => req.session?.userId,
});
watcher.on("pool:qr", (userId, loginUrl) => {
// Send QR to the specific user's frontend
});
watcher.on("pool:ready", (userId) => {
console.log(`User ${userId} connected to Telegram`);
});
watcher.on("pool:message", (userId, msg, result) => {
console.log(`[${userId}] From: ${msg.senderId}, Text: ${msg.text}`);
});
watcher.on("pool:message_sent", (userId, msg, result) => {
console.log(`[${userId}] Sent: ${msg.text}`);
});
await watcher.start(); // Auto-restores previously connected sessions
// Send a message on behalf of a user
await watcher.sendMessage("user_123", "chatId", "Hello!");
// Get a user's recent chats
const dialogs = await watcher.getDialogs("user_123", 50);
// Disconnect a specific user
await watcher.disconnect("user_123");SDK Events
Single-session mode
| Event | Args | Description |
|---|---|---|
| qr | (loginUrl) | QR login URL — generate a QR code from this |
| authenticated | — | Telegram session authenticated (saved locally) |
| ready | — | Client ready, heartbeat + polling started |
| message | (msg, result) | Incoming message processed by GATE |
| message_sent | (msg, result) | Outgoing message (sent from phone/desktop) processed by GATE |
| catchup | (chatSummaries, result) | Initial unread messages bundled and sent to GATE |
| action | (action) | Outbound action received from GATE queue |
| action_result | ({ actionId, action, success, result, error }) | Outbound action completed |
| gate_error | ({ path, status, error }) | GATE API call failed |
| limit_reached | (type) | Plan limit hit (e.g. "watcher_agents") |
| auth_failure | (errorMessage) | Authentication failed |
| disconnected | (reason) | Telegram disconnected |
| stopped | — | Watcher fully shut down |
Pool mode
All pool events include userId as the first argument.
| Event | Args | Description |
|---|---|---|
| pool:qr | (userId, loginUrl) | QR login URL for a specific user |
| pool:authenticated | (userId) | User's session authenticated |
| pool:ready | (userId) | User's session ready |
| pool:message | (userId, msg, result) | Incoming message for a user |
| pool:message_sent | (userId, msg, result) | Outgoing message for a user |
| pool:catchup | (userId, chatSummaries, result) | Initial unread messages for a user |
| pool:action | (userId, action) | Outbound action for a user |
| pool:action_result | (userId, { actionId, action, success, result, error }) | Action completed for a user |
| pool:error | (userId, error) | Session error |
| pool:disconnected | (userId, reason) | User's session disconnected |
Event result shapes
// result from "message" / "pool:message"
{
ok: true, // GATE API call succeeded
status: 200, // HTTP status
securityActions: [], // Security actions applied (e.g. ["redact", "flag"])
blocked: false, // Whether message was blocked by policy
rateLimited: false, // Whether daily limit was hit (status 429)
}
// result from "message_sent" / "pool:message_sent"
{
ok: true,
securityActions: [],
}SDK Options
| Option | Required | Default | Description |
|---|---|---|---|
| gateUrl | No | "https://anuragate.com" | GATE cloud URL |
| gateKey | Yes | — | Virtual key (gk-xxx) |
| integrationId | Yes | — | Integration ID (int_xxx) |
| apiId | Yes | — | Telegram API ID from my.telegram.org |
| apiHash | Yes | — | Telegram API hash from my.telegram.org |
| sessionId | No | — | Session ID — if omitted, pool mode is enabled |
| sessionLabel | No | — | Human-readable session label |
| sessionMetadata | No | {} | Arbitrary metadata for the session |
| sessionDir | No | ./.telegram_session | Path to store session files |
| heartbeatInterval | No | 30000 | ms between heartbeats |
| pollInterval | No | 3000 | ms between outbound action polls |
| maxSessions | No | 50 | Max concurrent sessions (pool mode) |
| shouldRestore | No | — | (sessionInfo) => boolean filter for session restore |
Public Methods
General
| Method | Returns | Description |
|---|---|---|
| start() | Promise<void> | Start the watcher (restores sessions in pool mode) |
| stop() | Promise<void> | Stop the watcher and disconnect all clients |
| getTelegramClient() | TelegramClient \| null | Access the underlying GramJS client (single-session only) |
| getStatus() | string | Connection status: "disconnected" | "connecting" | "qr" | "connected" |
| getQR() | string \| null | Current QR login URL |
Pool mode
| Method | Returns | Description |
|---|---|---|
| attach(server, wsPath?, opts?) | PanelServer | Attach WebSocket handler to HTTP server |
| startPanel(port?) | PanelServer | Start standalone dev dashboard |
| disconnect(userId) | Promise<void> | Disconnect and remove a user's session |
| getSessionStatus(userId) | object \| null | { userId, status, ready, qrData, error } |
| getSessionQR(userId) | string \| null | QR login URL for a specific user |
| getSessions() | Array | All active sessions [{ userId, status, ready }] |
| sendMessage(userId, chatId, text) | Promise<object> | Send a message via a user's session |
| getDialogs(userId, limit?) | Promise<Array> | Get recent chats for a user |
| getContacts(userId, query?) | Promise<Array> | Get contacts, optionally filtered |
| markChatRead(userId, chatId) | Promise<void> | Mark a chat as read |
Advanced: Access GramJS directly
const client = watcher.getTelegramClient();
const dialogs = await client.getDialogs({ limit: 10 });Setup
- Go to my.telegram.org and create an application to get your API ID and API Hash
- Go to GATE Dashboard -> Integrations -> Add Integration
- Select Telegram, copy the Integration ID
- Copy your Virtual Key from the Keys page
- Set the env vars and run
Environment Variables
| Variable | Required | Description |
|---|---|---|
| GATE_KEY | Yes | Your GATE virtual key |
| GATE_INTEGRATION_ID | Yes | Integration ID from the dashboard |
| TELEGRAM_API_ID | Yes | API ID from my.telegram.org |
| TELEGRAM_API_HASH | Yes | API hash from my.telegram.org |
| GATE_URL | No | Custom GATE cloud URL |
| WEB_PORT | No | Port for the dev dashboard (CLI only) |
Security model
- Telegram session tokens stored in
.telegram_session/on YOUR machine - GATE cloud never sees or stores your Telegram credentials
- All message content passes through GATE's security pipeline
- Both incoming and outgoing messages are reported to GATE
- Billing, limits, and security enforced server-side
