AgentOS 的电讯包扩展
AgentOS代理的专业Telegram Bot API集成.
特征
- 📤 信件发送: 有格式的文本、相片、文档
- 📊 集团管理: Pin 消息, 更改设置( 需要管理员)
- 🔍 聊天信息: 获取聊天细节和成员数
- 🎛️ 内置键盘: 处理按钮的回调查询
- 🔐 弹性 Auth: 提供bot 令牌的多种方式
- ⚡ 限制费率自动队列管理
- 🔄 网页浏览/投放: 支持两种模式
安装
npm install @framers/agentos-ext-telegram
配置
环境变量
扩展支持多种方式提供您的 bot 符号 :
# .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
用法实例
基本设置
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'
}
});
高级配置
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
}
}
});
可用工具
1. 发送信息
用可选键盘发送格式化的文本消息.
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. 发送相片
发送带有标题的图像 .
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. 发送文档
发送任何类型的文件 .
const result = await telegramSendDocument.execute({
chatId: '@mychannel',
document: './report.pdf', // URL, file path, or base64
caption: 'Monthly Report',
filename: 'Report_December_2024.pdf'
});
4. 获取聊天信息
获取聊天信息 .
const result = await telegramGetChatInfo.execute({
chatId: '@mychannel',
includeMemberCount: true
});
// Returns: { id, type, title, username, memberCount }
5. 管理组
执行管理动作( 需要bot 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. 回电处理
响应内置键盘按钮按下.
const result = await telegramHandleCallback.execute({
callbackQueryId: 'query123',
text: 'Button clicked!',
showAlert: true // Shows as popup
});
机构整合
多GMI协作
// 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}}'
}
}
]
};
处理错误
扩展处理常见的Telegram API出错 :
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);
}
限制费率
扩展自动管理利率限制 :
- 队列信件以尊重 Telegram 的 30 msg/ sec 限制
- 每个聊天限制的可配置率
- 以指数回放自动重试
安保最佳做法
- 永远不要硬码的机器人符号 - 使用环境变量
- 验证 webhook 签名 生产
- 对用户输入进行保密 发送前
- 使用 HTTPS 用于网络用户
- 限制 Bot 权限 至最低需求
- 虐待监测 并执行用户费率限制
装瓶设置
- 创建机器人 @ 父爱 @ info
- 拿回你的宝物
- 设置机器人命令( 可选) :
/start - Start the bot
/help - Show help
/status - Check status
- 需要时配置隐私模式
- 在有适当权限的组合/通道中添加机器人
测试
// 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);
解决问题
瓶子没有响应
- 检查bot 令牌正确
- 确保不封存机器人
- 验证网络连接
- 检查可访问的 Webhook URL
费率限制出错
- 减少消息频率
- 执行信件批量
- 使用队列管理
权限错误
- 确保 bot 管理组管理
- 检查频道发布权限
- 校验用户没有屏蔽机器人
资源
- Telegram Bot API 文档
- 瓶装父亲 - 创建和管理波茨
- Telegram Bot 实例
释放
新版本发表于 架设层/剂-外延 由 GitHub Actions 通过 npm 信任的出版, 并附有出处声明 .
许可证
Apache-2.0 - 见 LICENSE 文件