# bot-api **Repository Path**: seemswork/bot-api ## Basic Information - **Project Name**: bot-api - **Description**: seemswork 机器人消息推送接口 - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-02-12 - **Last Updated**: 2026-02-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Telegram Bot API Server 一套完全兼容 Telegram Bot API 的自托管服务器实现,用 Go 编写。 ## 项目概述 Bot API Server 是一个自托管的 Telegram Bot API 服务器,允许你在自己的基础设施上运行 Bot API。它完全兼容官方 Telegram Bot API 规范,你可以让你的应用和你的客户都接入这个 API 服务器来集成机器人功能。 ## 主要特性 ✨ **完整的 API 实现** - 实现了 30+ 个 Telegram Bot API 端点 🔄 **双模式支持** - 支持长轮询(Long Polling)和 Webhook 两种更新接收方式 📦 **零依赖** - 仅使用 Go 标准库,没有外部依赖 ⚡ **易于集成** - 简洁的 API,易于集成到你的应用中 🚀 **自托管** - 完全控制你的 Bot API 服务器 ## 快速开始 ### 1. 启动服务器 ```go package main import ( "log" botapi "github.com/yourusername/bot-api" ) func main() { // 创建 Bot API 服务器(监听在 :8081) server := botapi.NewBotAPIServer("your_bot_token", 8081) // 启动服务器 if err := server.Start(); err != nil { log.Fatal(err) } } ``` ### 2. 发送请求 服务器提供了与 Telegram Bot API 兼容的 HTTP 端点: ```bash # 获取 Bot 信息 curl -X POST http://localhost:8081/getMe # 发送消息 curl -X POST http://localhost:8081/sendMessage \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "chat_id=123456789&text=Hello" # 设置 Webhook curl -X POST http://localhost:8081/setWebhook \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "url=https://yourserver.com/webhook" ``` ## 🎯 运行示例 项目包含了 3 个完整的示例,展示不同的使用方式。在项目根目录运行: ```bash # 基础示例(推荐首先查看) go run ./cmd/example -example basic # Webhook 示例 go run ./cmd/example -example webhook # 长轮询示例 go run ./cmd/example -example polling ``` ### 示例 1: 基础示例 展示如何创建服务器、发送消息和接收更新: ```bash go run example_main.go -example basic ``` **特点:** - 演示基本的服务器创建和启动 - 展示如何发送和接收消息 - 最简单的入门方式 **代码位置:** [example_basic.go](example_basic.go) ### 示例 2: Webhook 示例 展示如何设置 Webhook 接收实时更新: ```bash go run example_main.go -example webhook ``` **特点:** - 启动一个 HTTP 服务器接收 Webhook 回调 (:8080) - 启动 Bot API 服务器 (:8081) - 设置 Webhook 指向你的服务器 - 模拟接收用户消息 - 服务器自动转发更新到 Webhook **代码位置:** [example_webhook.go](example_webhook.go) **适合场景:** - 生产环境 - 需要实时处理更新 - 性能要求高 ### 示例 3: 长轮询示例 展示如何使用长轮询持续接收更新: ```bash go run example_main.go -example polling ``` **特点:** - 启动一个轮询循环持续获取更新 - 模拟用户发送消息 - 自动处理和回复消息 - 支持命令处理 (/start, /help) **代码位置:** [example_polling.go](example_polling.go) **适合场景:** - 开发和测试 - 简单应用 - 不需要实时性能 ## 使用模式详解 ### 模式 1: 长轮询(Long Polling) **最简单的方式,适合开发和测试:** ```go offset := 0 for { // 每30秒获取一次更新 resp, _ := http.Post( fmt.Sprintf("http://localhost:8081/getUpdates?offset=%d&timeout=30", offset), "application/json", nil, ) var apiResp botapi.ApiResponse json.NewDecoder(resp.Body).Decode(&apiResp) resp.Body.Close() var updates []*botapi.Update json.Unmarshal(apiResp.Result, &updates) for _, update := range updates { handleUpdate(update) offset = int(update.UpdateID) + 1 } } ``` **优点:** - 简单易实现 - 适合测试 - 无需公网 IP **缺点:** - 实时性一般 - 网络开销较大 - 服务器延迟 ### 模式 2: Webhook(推荐生产环境) **性能好,实时性强:** ```go // 1. 设置 Webhook http.Post( "http://localhost:8081/setWebhook", "application/x-www-form-urlencoded", // 参数: url=https://yourserver.com:8080/webhook ) // 2. 在你的服务器接收回调 http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) { var update botapi.Update json.NewDecoder(r.Body).Decode(&update) handleUpdate(&update) w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) ``` **优点:** - 实时性好 - 网络开销小 - 响应快 **缺点:** - 需要公网 IP 或反向代理 - 配置相对复杂 ## 📚 API 端点列表 ### 基础方法 - `POST /getMe` - 获取 Bot 信息 - `POST /getUpdates` - 获取待处理的更新(长轮询) - `POST /setWebhook` - 设置 Webhook URL - `POST /deleteWebhook` - 删除 Webhook ### 消息方法 - `POST /sendMessage` - 发送文本消息 - `POST /editMessageText` - 编辑消息文本 - `POST /deleteMessage` - 删除消息 - `POST /forwardMessage` - 转发消息 - `POST /copyMessage` - 复制消息 ### 媒体方法 - `POST /sendPhoto` - 发送照片 - `POST /sendVideo` - 发送视频 - `POST /sendAudio` - 发送音频 - `POST /sendDocument` - 发送文件 - `POST /sendSticker` - 发送贴纸 ### 交互方法 - `POST /answerCallbackQuery` - 回答回调查询 - `POST /editMessageReplyMarkup` - 编辑消息按钮 ### 群组/用户管理 - `POST /getChatMember` - 获取群组成员信息 - `POST /getChatMemberCount` - 获取群组成员数 - `POST /kickChatMember` - 踢出群组成员 - `POST /restrictChatMember` - 限制群组成员权限 - `POST /promoteChatMember` - 提升群组管理员 ### 命令管理 - `POST /setMyCommands` - 设置 Bot 命令 - `POST /getMyCommands` - 获取 Bot 命令列表 ### 内联查询 - `POST /answerInlineQuery` - 回答内联查询 ## 💻 核心数据类型 ### Update(更新) ```go type Update struct { UpdateID int64 `json:"update_id"` Message *Message `json:"message"` CallbackQuery *CallbackQuery `json:"callback_query"` InlineQuery *InlineQuery `json:"inline_query"` // ... } ``` ### Message(消息) ```go type Message struct { MessageID int64 `json:"message_id"` Date int64 `json:"date"` Chat *Chat `json:"chat"` From *User `json:"from"` Text string `json:"text"` ReplyMarkup interface{} `json:"reply_markup"` // ... } ``` ### User(用户) ```go type User struct { ID int64 `json:"id"` IsBot bool `json:"is_bot"` FirstName string `json:"first_name"` LastName string `json:"last_name"` Username string `json:"username"` // ... } ``` ### Chat(聊天) ```go type Chat struct { ID int64 `json:"id"` Type string `json:"type"` // "private", "group", "supergroup", "channel" Title string `json:"title"` Username string `json:"username"` FirstName string `json:"first_name"` LastName string `json:"last_name"` // ... } ``` 更多数据类型定义请查看 [types.go](types.go) ## 🎨 键盘和按钮 ### 创建内联按钮 ```go // 创建带按钮的键盘 buttons := []botapi.InlineKeyboardButton{ botapi.CreateInlineButton("Google", "https://google.com"), botapi.CreateInlineButton("GitHub", "https://github.com"), } keyboard := botapi.CreateInlineKeyboard(buttons) ``` ### 创建回复键盘 ```go // 创建回复键盘 keyboard := botapi.CreateReplyKeyboard( [][]botapi.KeyboardButton{ {{Text: "选项 1"}, {Text: "选项 2"}}, {{Text: "选项 3"}}, }, ) ``` ## 🛠️ 辅助工具函数 ```go // 从更新中提取文本 text := botapi.TextContent(update) // 提取 Chat ID chatID := botapi.GetChatID(update) // 提取 User ID userID := botapi.GetUserID(update) // 提取消息 ID msgID := botapi.GetMessageID(update) // 解析命令 cmd := botapi.GetCommand(update) args := botapi.GetCommandArg(update) // 检查消息类型 isText := update.Message.IsTextMessage() isCommand := update.Message.IsCommandMessage() isPrivate := update.Message.Chat.IsPrivate() ``` ## 📤 发送不同类型的消息 ### 发送文本消息 ```go resp, _ := http.Post( "http://localhost:8081/sendMessage", "application/json", bytes.NewBuffer([]byte(`{ "chat_id": 123456789, "text": "Hello World!", "parse_mode": "HTML" }`)), ) ``` ### 发送照片 ```go http.Post( "http://localhost:8081/sendPhoto?chat_id=123&photo=https://example.com/photo.jpg", "application/json", nil, ) ``` ### 发送视频/音频/文件 ```go http.Post( "http://localhost:8081/sendVideo?chat_id=123&video=file_id", "application/json", nil, ) ``` ## ❓ 常见问题 ### Q: 我应该使用长轮询还是 Webhook? **A:** - **长轮询**: 适合开发和测试,或者简单场景 - **Webhook**: 推荐生产环境,性能更好,响应时间更短 ### Q: 如何处理多个 Bot? **A:** 创建多个 `BotAPIServer` 实例,分别运行在不同端口: ```go bot1 := botapi.NewBotAPIServer("token1", 8081) bot2 := botapi.NewBotAPIServer("token2", 8082) go bot1.Start() go bot2.Start() ``` ### Q: 如何将现有的 Telegram Bot 迁移到这个服务器? **A:** 简单地将你的 Bot API 请求指向本服务器的 IP 和端口。API 完全兼容,无需改动你的 Bot 代码。 ### Q: 这个库有什么限制吗? **A:** 这是一个自托管的 Bot API 服务器实现,主要用于集成和部署。实现了所有常用的 API 端点。 ## 📁 项目结构 ``` bot-api/ ├── server.go # Bot API 服务器核心实现 (~400 行) ├── types.go # Telegram 兼容的数据类型定义 (~900 行) ├── utils.go # 辅助函数和数据提取工具 (~360 行) ├── example_basic.go # 基础示例 ├── example_webhook.go # Webhook 示例 ├── example_polling.go # 长轮询示例 ├── example_main.go # 示例启动文件 ├── go.mod # Go 模块定义 ├── README.md # 本文件 ├── LICENSE # MIT 许可证 └── .gitignore # Git 配置 ``` ## 🚀 集成到你的应用 ### 导入为 Go Module ```bash # 在你的项目中导入 go get github.com/yourusername/bot-api ``` ### 完整示例代码 ```go package main import ( "encoding/json" "fmt" "log" "net/http" botapi "github.com/yourusername/bot-api" ) func main() { // 创建并启动服务器 server := botapi.NewBotAPIServer("my_bot_token", 8081) // 处理更新的 goroutine go func() { offset := 0 for { resp, _ := http.Post( fmt.Sprintf("http://localhost:8081/getUpdates?offset=%d", offset), "application/json", nil, ) var apiResp botapi.ApiResponse json.NewDecoder(resp.Body).Decode(&apiResp) resp.Body.Close() var updates []*botapi.Update json.Unmarshal(apiResp.Result, &updates) for _, update := range updates { if update.Message != nil { handleMessage(update.Message) } offset = int(update.UpdateID) + 1 } } }() // 启动服务器 log.Fatal(server.Start()) } func handleMessage(msg *botapi.Message) { log.Printf("New message from @%s: %s", msg.From.Username, msg.Text) // 你的消息处理逻辑 // 可以在这里处理命令、回复消息等 } ``` ## 📝 许可证 MIT License - 详见 [LICENSE](LICENSE) 文件 --- **快速开始:** 1. 查看 [example_main.go](example_main.go) 2. 运行示例: `go run example_main.go -example basic` 3. 查看其他示例了解更多用法 **需要帮助?** - 查看代码示例了解基本用法 - 查看 types.go 了解所有数据结构 - 查看 utils.go 了解辅助函数