跳到主要内容

DeBox 机器人 Python SDK 使用文档

源码仓库:

1. SDK 功能总览

debox-chat-python-sdk 提供:

  • Bot 初始化:NewBotAPI(api_key, api_secret)
  • 消息发送:bot.Send(...)
  • Long Polling 收消息:GetUpdates / GetUpdatesChan
  • 按钮与回调处理
  • 编辑消息:NewEditMessageText(...) / NewEditMessageTextAndMarkup(...)

2. 收消息模式说明

本文使用 Long Polling。运行前必须清空 BotMother 中已经配置的 Webhook URL,否则 Long Polling 不能用于收消息。模式选择和切换方法请查看DeBox 机器人开发总览,Webhook 实现请查看DeBox 机器人 Go SDK Webhook

3. 安装与初始化

3.1 安装 SDK

pip install git+https://github.com/debox-pro/debox-chat-python-sdk.git

或本地拉取安装:

git clone https://github.com/debox-pro/debox-chat-python-sdk.git
cd debox-chat-python-sdk
pip install -e .

3.2 准备凭证

BotMother 的 Bot 详情页显示 App KeyApp Secret,在 SDK 中按以下关系使用:

  • App KeyAPI_KEY(必须)
  • App SecretAPI_SECRET(建议)

完整对应关系和保存要求请查看DeBox 机器人开发总览中的凭证说明

export DEBOX_BOT_API_KEY="YOUR_APP_KEY"
export DEBOX_BOT_API_SECRET="YOUR_API_SECRET"

3.3 发送第一条消息

import os
import boxbotapi

bot = boxbotapi.NewBotAPI(
os.getenv("DEBOX_BOT_API_KEY", ""),
os.getenv("DEBOX_BOT_API_SECRET", ""),
)

msg = boxbotapi.NewMessage("cc0onr82", "group", "Hello from Python SDK")
msg.ParseMode = boxbotapi.ModeRichText

sent = bot.Send(msg)
print("sent message_id=", sent.MessageID)

4. Long Polling 收消息

import os
import boxbotapi
from boxbotapi import configs as cfg

cfg.Debug = False
cfg.MessageListener = True

bot = boxbotapi.NewBotAPI(
os.getenv("DEBOX_BOT_API_KEY", ""),
os.getenv("DEBOX_BOT_API_SECRET", ""),
)

u = boxbotapi.NewUpdate(0)
u.Timeout = 60

for update in bot.GetUpdatesChan(u):
if update.Message is not None:
text = update.Message.Text or ""
print("message:", text)

reply = boxbotapi.NewMessage(
update.Message.Chat.ID,
update.Message.Chat.Type,
f"Received: {text}",
)
reply.ParseMode = boxbotapi.ModeRichText
bot.Send(reply)

if update.CallbackQuery is not None:
print("callback:", update.CallbackQuery.Data)

5. ParseMode 常量

SDK 常量:

  • boxbotapi.ModeRichText
  • boxbotapi.ModeMarkdown
  • boxbotapi.ModeMarkdownV2
  • boxbotapi.ModeHTML
  • boxbotapi.ModeImage
  • boxbotapi.ModeVideo
  • boxbotapi.ModeFile

parse_modecontent、媒体 URL 和长度规则请查看 OpenAPI 消息字段说明

6. 按钮与回调

markup = boxbotapi.NewInlineKeyboardMarkup(
boxbotapi.NewInlineKeyboardRow(
boxbotapi.NewInlineKeyboardButtonData("查看详情", "detail"),
boxbotapi.NewInlineKeyboardButtonURL("打开文档", "https://docs.debox.pro"),
)
)

msg = boxbotapi.NewMessage("cc0onr82", "group", "请选择")
msg.ParseMode = boxbotapi.ModeRichText
msg.ReplyMarkup = markup
bot.Send(msg)

处理回调并编辑消息:

if update.CallbackQuery is not None:
data = update.CallbackQuery.Data
chat = update.CallbackQuery.Message.Chat
message_id = update.CallbackQuery.Message.MessageID

edit = boxbotapi.NewEditMessageText(chat.ID, chat.Type, message_id, f"clicked: {data}")
edit.ParseMode = boxbotapi.ModeRichText
bot.Send(edit)

7. 路由字段说明

请按照 OpenAPI 路由规则向 SDK 构造函数传入 chat_idchat_type

8. 常见问题

  1. 收不到消息:
  • 先检查是否已配置 webhook(与轮询互斥)。
  • 确保 cfg.MessageListener = True
  1. 鉴权失败:
  • 检查 API_KEY/API_SECRET 与签名链路。
  1. 媒体发送失败: