@framers/agentos-ext-telegram

中文文档
1.2.4发布于 2026/11/11Apache-2.0TypeScriptCommonJS构建来源已验证近 30 天下载 2.2万

Telegram Bot API integration for AgentOS - send messages, manage groups, handle callbacks

原始使用文档
文档目录26 节
  1. Features
  2. Installation
  3. Configuration
  4. Environment Variables
  5. Usage Examples
  6. Available Tools
  7. 1. Send Message
  8. 2. Send Photo
  9. 3. Send Document
  10. 4. Get Chat Info
  11. 5. Manage Group
  12. 6. Handle Callbacks
  13. Agency Integration
  14. Multi-GMI Collaboration
  15. Error Handling
  16. Rate Limiting
  17. Security Best Practices
  18. Bot Setup
  19. Testing
  20. Troubleshooting
  21. Bot not responding
  22. Rate limit errors
  23. Permission errors
  24. Resources
  25. Releases
  26. License

Telegram Bot Extension for AgentOS

Professional Telegram Bot API integration for AgentOS agents.

Features

  • 📤 Message Sending: Text, photos, documents with formatting
  • 📊 Group Management: Pin messages, change settings (requires admin)
  • 🔍 Chat Information: Get chat details and member counts
  • 🎛️ Inline Keyboards: Handle callback queries from buttons
  • 🔐 Flexible Auth: Multiple ways to provide bot token
  • ⚡ Rate Limiting: Automatic queue management
  • 🔄 Webhook/Polling: Both modes supported

Installation

npm install @framers/agentos-ext-telegram

Configuration

Environment Variables

The extension supports multiple ways to provide your bot token:

# .env file

# Method 1: Default environment variable
TELEGRAM_BOT_TOKEN=your-bot-token-here

# Method 2: Custom environment variable
MY_TELEGRAM_TOKEN=your-bot-token-here

# Method 3: Multiple bot support
TELEGRAM_MAIN_BOT=token1
TELEGRAM_SUPPORT_BOT=token2

Usage Examples

Basic Setup

import { createExtensionPack } from '@framers/agentos-ext-telegram';

// Auto-detect from environment
const telegramExt = createExtensionPack({
  options: {
    // Automatically reads TELEGRAM_BOT_TOKEN
  },
  logger: console
});

// Custom environment variable
const telegramExt = createExtensionPack({
  options: {
    botTokenEnv: 'MY_TELEGRAM_TOKEN'
  }
});

// Direct token (not recommended for production)
const telegramExt = createExtensionPack({
  options: {
    botToken: 'your-token-here'
  }
});

Advanced Configuration

const telegramExt = createExtensionPack({
  options: {
    // Webhook mode (for production)
    webhookUrl: 'https://your-domain.com/telegram-webhook',
    
    // Or polling mode (for development)
    pollingInterval: 300,
    
    // Message formatting
    defaultParseMode: 'Markdown', // or 'HTML'
    enableTypingAction: true,     // Show "typing..." indicator
    
    // Rate limiting
    rateLimit: {
      maxRequests: 30,  // Telegram's limit
      windowMs: 1000    // Per second
    }
  }
});

Available Tools

1. Send Message

Send formatted text messages with optional keyboards.

const result = await telegramSendMessage.execute({
  chatId: '@mychannel',  // or numeric chat ID
  text: '*Bold* _italic_ `code`',
  parseMode: 'Markdown',
  replyMarkup: {
    inline_keyboard: [[
      { text: 'Button 1', callback_data: 'btn1' },
      { text: 'Button 2', callback_data: 'btn2' }
    ]]
  }
});

2. Send Photo

Send images with captions.

const result = await telegramSendPhoto.execute({
  chatId: '@mychannel',
  photo: 'https://example.com/image.jpg', // URL, file path, or base64
  caption: 'Check out this image!',
  parseMode: 'Markdown'
});

3. Send Document

Send files of any type.

const result = await telegramSendDocument.execute({
  chatId: '@mychannel',
  document: './report.pdf', // URL, file path, or base64
  caption: 'Monthly Report',
  filename: 'Report_December_2024.pdf'
});

4. Get Chat Info

Retrieve information about a chat.

const result = await telegramGetChatInfo.execute({
  chatId: '@mychannel',
  includeMemberCount: true
});

// Returns: { id, type, title, username, memberCount }

5. Manage Group

Perform admin actions (requires bot to be admin).

// Pin a message
await telegramManageGroup.execute({
  chatId: -123456789,
  action: 'pinMessage',
  messageId: 42,
  disableNotification: false
});

// Set group description
await telegramManageGroup.execute({
  chatId: -123456789,
  action: 'setDescription',
  text: 'Welcome to our awesome group!'
});

6. Handle Callbacks

Respond to inline keyboard button presses.

const result = await telegramHandleCallback.execute({
  callbackQueryId: 'query123',
  text: 'Button clicked!',
  showAlert: true  // Shows as popup
});

Agency Integration

Multi-GMI Collaboration

// Research GMI finds information
const researcher = await createGMI({
  tools: ['webSearch', 'factCheck']
});

// Communications GMI sends to Telegram
const communicator = await createGMI({
  tools: ['telegramSendMessage', 'telegramSendPhoto']
});

// Workflow orchestrates both
const workflow = {
  tasks: [
    {
      executor: 'researcher',
      tool: 'webSearch',
      inputs: { query: '{{topic}}' }
    },
    {
      executor: 'communicator',
      tool: 'telegramSendMessage',
      inputs: {
        chatId: '{{telegram_channel}}',
        text: '📊 Research Results:\n{{results.research}}'
      }
    }
  ]
};

Error Handling

The extension handles common Telegram API errors gracefully:

try {
  const result = await tool.execute(args);
  if (!result.success) {
    console.error('Telegram error:', result.error);
    // Handle specific error codes
    if (result.details?.code === 403) {
      console.log('Bot was blocked by user');
    }
  }
} catch (error) {
  console.error('System error:', error);
}

Rate Limiting

The extension automatically manages rate limits:

  • Queues messages to respect Telegram's 30 msg/sec limit
  • Configurable rate limiting per chat
  • Automatic retry with exponential backoff

Security Best Practices

  1. Never hardcode bot tokens - Use environment variables
  2. Validate webhook signatures in production
  3. Sanitize user input before sending
  4. Use HTTPS for webhooks
  5. Restrict bot permissions to minimum needed
  6. Monitor for abuse and implement user rate limits

Bot Setup

  1. Create a bot with @BotFather
  2. Get your bot token
  3. Set bot commands (optional):
/start - Start the bot
/help - Show help
/status - Check status
  1. Configure privacy mode as needed
  2. Add bot to groups/channels with appropriate permissions

Testing

// Mock the Telegram service for testing
const mockService = {
  sendMessage: jest.fn().mockResolvedValue({
    message_id: 1,
    chat: { id: 123 },
    date: Date.now(),
    text: 'Test'
  })
};

const tool = new SendMessageTool(mockService);
const result = await tool.execute({
  chatId: 123,
  text: 'Test message'
}, context);

Troubleshooting

Bot not responding

  • Check bot token is correct
  • Ensure bot is not blocked
  • Verify network connectivity
  • Check webhook URL is accessible

Rate limit errors

  • Reduce message frequency
  • Implement message batching
  • Use queue management

Permission errors

  • Ensure bot is admin for group management
  • Check channel posting permissions
  • Verify user hasn't blocked bot

Resources

Releases

New versions are published from framerslab/agentos-extensions by GitHub Actions through npm trusted publishing, with a provenance statement.

License

Apache-2.0 - See LICENSE file

版本与发布记录

@framers/agentos-ext-telegram 共发布 8 个版本,首次发布于 2026/02/06;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.2.4latest2026/11/114 天前
1.2.32026/11/0114 天前
1.2.22026/11/0115 天前
1.2.12026/10/111 个月前
1.2.02026/10/081 个月前
1.1.22026/10/071 个月前

关于 @framers/agentos-ext-telegram 的常见问题

@framers/agentos-ext-telegram 是什么?

Telegram Bot API integration for AgentOS - send messages, manage groups, handle callbacks

如何安装 @framers/agentos-ext-telegram?

在项目目录运行 npm install @framers/agentos-ext-telegram,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@framers/agentos(>=0.10.40)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@framers/agentos-ext-telegram 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@framers/agentos-ext-telegram 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@framers/agentos-ext-telegram 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@framers/agentos-ext-telegram 可以商用吗?

@framers/agentos-ext-telegram 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@framers/agentos-ext-telegram 的下载量有多少?

根据 npm 官方下载统计,@framers/agentos-ext-telegram 在 2026/10/16 – 2026/11/14 这 30 天内被下载 21,739 次,日均约 725 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@framers/agentos-ext-telegram 还在维护吗?

最新版本 1.2.4 发布于 2026/11/11(4 天前);至今共发布 8 个版本,其中过去 12 个月发布了 8 个;首次发布于 2026/02/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。