Telegram Bot

easy10 mintelegram-bot.ts

You want your agent as a Telegram bot with streamed replies, rate limiting and owner-only commands.

What it shows

  • Run a Gateway with telegramChannel()
  • Add rateLimit() and ownerCommands() middleware

The code

telegram-bot.ts
import { Agent, Cogitator, calculator, datetime } from '@cogitator-ai/core';
import { Gateway, ownerCommands, rateLimit, telegramChannel } from '@cogitator-ai/channels';

const token = process.env.TG_TOKEN;
const apiKey = process.env.GOOGLE_API_KEY;
const ownerId = process.env.OWNER_TG_ID;
if (!token || !apiKey) throw new Error('Set TG_TOKEN (from @BotFather) and GOOGLE_API_KEY');

const agent = new Agent({
  name: 'telegram-assistant',
  model: 'google/gemini-3.5-flash-lite',
  instructions: `You are a helpful personal assistant on Telegram.
Use the datetime tool for anything about the current date or time and the calculator for math.
Keep responses short — this is a chat, not an essay.`,
  tools: [datetime, calculator],
});

const cogitator = new Cogitator({ llm: { providers: { google: { apiKey } } } });

const middleware = [rateLimit({ maxPerMinute: 15 })];
if (ownerId) {
  middleware.unshift(
    ownerCommands({
      ownerIds: { telegram: ownerId },
      onStatus: () => `Uptime: ${Math.round(gateway.stats.uptime / 1000)}s, messages today: ${gateway.stats.messagesToday}`,
    })
  );
}

const gateway = new Gateway({
  agent,
  cogitator,
  channels: [telegramChannel({ token })],
  middleware,
  stream: { flushInterval: 600, minChunkSize: 30 },
  onError: (error, message) => console.error(`Message from ${message.userId} failed:`, error.message),
});

await gateway.start();
console.log('Telegram assistant is running. Press Ctrl+C to stop.');

process.on('SIGINT', async () => {
  await gateway.stop();
  await cogitator.close();
  process.exit(0);
});

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/channels grammy
EnvironmentTG_TOKENGOOGLE_API_KEYOWNER_TG_ID (optional)
run · bash
TG_TOKEN=your-key GOOGLE_API_KEY=your-key npx tsx telegram-bot.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/channels/01-telegram-assistant.ts

Learn more