@ affect-ak/tg-bot-客户端
Telegram Bot API的Type-safe HTTP客户端. 一个 execute 方法覆盖每个 API 方法,文件被编码到 FormData 自动输入错误。 土著 fetch,零运行时间依赖性——运行在Node.js 18+, Bun, Deno, Cloudflare Workers,浏览器上.
类型来自 @effect-ak/tg-bot-api; 机器人框架 @effect-ak/tg-bot 以此客户端为基础.
安装
npm install @effect-ak/tg-bot-client
Bot API 类型在子路径下被再导出,所以这是您唯一需要的软件包 :
import { makeTgBotClient } from "@effect-ak/tg-bot-client"
import type { Message, Update } from "@effect-ak/tg-bot-client/api"
快速启动
import { makeTgBotClient } from "@effect-ak/tg-bot-client"
const client = makeTgBotClient({ bot_token: "YOUR_BOT_TOKEN" })
// Method names are snake_case, exactly as in the official docs
const message = await client.execute("send_message", {
chat_id: 123456789,
text: "Hello!"
})
API 表面
makeTgBotClient({ bot_token, base_url?, timeout? }): TgBotClient
interface TgBotClient {
execute(method, params, options?): Promise<Result> // throws TgBotClientError
executeSafe(method, params, options?): Promise<ClientResult> // never throws
getFile({ fileId }): Promise<TgFile> // download by file_id
getFileSafe({ fileId }): Promise<ClientResult<TgFile>>
}
type ClientResult<T> = { ok: true; data: T } | { ok: false; error: ClientErrorReason }
type ClientErrorReason =
| { _tag: "NotOkResponse"; errorCode?: number; details?: string } // Telegram said ok:false
| { _tag: "RequestTimeout"; timeoutMs: number }
| { _tag: "NotJsonResponse" | "UnexpectedResponse" | "ClientInternalError" | "UnableToGetFile"; ... }
- 方法和参数名称 匹配 https://core.telegram.org/bots/api (英语) 内
snake_case(单位:千美元)send_message, (中文(简体) ),edit_message_text, (中文(简体) ),answer_callback_query) (中文(简体) ). 两者都是自动完成的;返回类型是推断的. - 文件: 通过
{ file_content: Uint8Array, file_name: string }(或 a 个)Blob编号 :File在API接受的情况下InputFile——客户端自动切换到多段. 对象内的文件( album 项在send_media_group贴纸,set_my_profile_photo) 工作方式相同:客户端上传各自作为自己的部分并发送attach://…参考文献。 或者通过一个file_id/ URL 字符串 . - 信件效果数字 :
message_effect_id接受 emoji 键MESSAGE_EFFECTS(单位:千美元)"🔥" | "👍" | "👎" | "❤️" | "🎉" | "💩"并被映射到真实的id. - 错误数字 :
execute掷出TgBotClientError(单位:千美元)error.reason上面贴有标签的结合;executeSafe返回结合 —— 选择一种风格并坚持它. - 选项数字 :
{ timeout }每个呼叫;base_url用于自动托管的 Bot API 服务器.
实例
// Safe variant
const result = await client.executeSafe("get_chat", { chat_id: 1 })
if (!result.ok) console.error(result.error._tag)
// Upload a file
await client.execute("send_document", {
chat_id,
document: { file_content: new TextEncoder().encode("hi"), file_name: "hi.txt" },
caption: "Generated on the fly"
})
// Download a file
const file = await client.getFile({ fileId })
file.content // ArrayBuffer
文档
- 指南 : tg-bot-sdk.website/客户/用户
- Bot API 参考文献( 每方法一页) : https://tg-bot-sdk.website/api/ 页面存档备份,存于互联网档案馆
- 对于 LLM/ 编码代理 : https://tg-bot-sdk.website/llms.txt
许可证
麻省理工学院