Package Exports
- @taoya7/tg-bot
Readme
Telegram Bot Library
一个使用 TypeScript、Zod 和 Axios 构建的 Telegram Bot 推送库,提供类型安全的 API 和灵活的配置选项。
特性
- 🚀 完整的 TypeScript 支持和类型推导
- ✅ 使用 Zod 进行运行时类型验证
- 🌐 可配置的 baseUrl(支持代理)
- 📦 支持 ESM 和 CommonJS
- 🛡️ 完善的错误处理
- 📝 支持 Markdown 和 HTML 格式
- 🔧 智能 MarkdownV2 转义处理
安装
pnpm add @taoya7/tg-bot
# 或
npm install @taoya7/tg-bot
# 或
yarn add @taoya7/tg-bot
环境配置
使用环境变量(推荐)
- 复制环境变量模板:
cp .env.example .env
- 编辑
.env
文件,填入您的配置:
# 必需配置
BOT_TOKEN=your_bot_token_here
CHAT_ID=your_chat_id_here
# 可选配置
BASE_URL=https://api.telegram.org # 或使用代理地址
TIMEOUT=30000
- 测试配置:
node examples/test-config.js
使用代理
如果您需要通过代理访问 Telegram API,只需修改 BASE_URL
:
# 使用代理服务器
BASE_URL=https://tg-proxy.example.com
快速开始
import { TelegramBot } from '@taoya7/tg-bot'
// 创建机器人实例
const bot = new TelegramBot({
token: 'YOUR_BOT_TOKEN',
baseUrl: 'https://api.telegram.org', // 可选,支持自定义代理
timeout: 30000, // 可选,请求超时时间(毫秒)
})
// 发送文本消息
async function sendMessage() {
try {
const message = await bot.sendMessage(
'CHAT_ID', // 可以是字符串或数字
'Hello, World!',
{
parse_mode: 'Markdown',
disable_notification: false,
}
)
console.log('Message sent:', message)
}
catch (error) {
console.error('Failed to send message:', error)
}
}
主要功能
发送文本消息
// 普通文本消息
await bot.sendMessage(chatId, '这是一条普通消息')
// 使用参数
await bot.sendMessage(chatId, text, {
parse_mode: 'HTML', // 或 'MarkdownV2', 'Markdown'
disable_web_page_preview: true,
disable_notification: false,
reply_to_message_id: 123,
protect_content: true,
})
发送 Markdown 消息
// 直接输入标准 Markdown,程序会自动处理转义
await bot.sendMarkdown(chatId, `
*粗体文字*
_斜体文字_
__下划线文字__
~删除线文字~
\`行内代码\`
Hello World! 这里有特殊字符 . ! # + - = | { }
\`\`\`javascript
// 代码块
const message = "Hello, World!";
console.log(message);
\`\`\`
[Telegram 链接](https://telegram.org)
`)
// 支持额外选项(除了 parse_mode)
await bot.sendMarkdown(chatId, text, {
disable_web_page_preview: true,
disable_notification: false,
})
发送 HTML 消息
await bot.sendHTML(chatId, `
<b>📚 主标题</b>
<b>📌 子标题</b>
<i>斜体文字</i>
<u>下划线文字</u>
<s>删除线文字</s>
<code>行内代码</code>
<pre>
这是代码块
可以有多行
</pre>
<a href="https://telegram.org">这是链接</a>
`)
工具函数
import { escapeMarkdownV2 } from '@taoya7/tg-bot'
// 手动转义 MarkdownV2 特殊字符(通常不需要,sendMarkdown 已自动处理)
const safeText = escapeMarkdownV2('需要转义的文本: . ! # { }')
错误处理
import { NetworkError, TelegramError, ValidationError } from '@taoya7/tg-bot'
try {
await bot.sendMessage(chatId, text)
}
catch (error) {
if (error instanceof TelegramError) {
// Telegram API 错误
console.error('Telegram API error:', error.code, error.description)
// 例如: 400 - Bad Request: can't parse entities
}
else if (error instanceof NetworkError) {
// 网络连接错误
console.error('Network error:', error.message)
}
else if (error instanceof ValidationError) {
// 参数验证错误
console.error('Validation error:', error.errors)
}
}
配置选项
interface Config {
token: string // Bot token (必需)
baseUrl?: string // API base URL,默认: https://api.telegram.org
timeout?: number // 请求超时时间,默认: 30000ms
}
动态更新配置
// 获取当前配置
const config = bot.getConfig()
// 更新配置(token 除外)
bot.updateConfig({
timeout: 60000,
baseUrl: 'https://new-proxy.example.com',
})
TypeScript 类型
所有类型都已导出,可直接使用:
import type {
ChatId,
Config,
InlineKeyboardMarkup,
Message,
ParseMode,
SendMessageOptions,
Update,
} from '@taoya7/tg-bot'