GO-SDK
DeBox Bot Go SDK Documentation
Introduction
debox-chat-go-sdk
is the official Golang SDK for DeBox chat bots. It encapsulates the core functionalities of message sending and receiving in DeBox, enabling developers to quickly and efficiently build DeBox chat bots. By leveraging this SDK, developers can tap into the DeBox ecosystem's traffic benefits, achieving dual enhancement of technical and commercial value.
With debox-chat-go-sdk
, you can easily implement the following features:
✅ Send Messages: Supports multiple message formats including text, Markdown, HTML, rich text, and button menus.
✅ Receive Messages: Monitor user messages and group chat information in real-time, and respond automatically.
✅ Handle Commands: Interact flexibly with users through custom commands.
✅ Webhook Extensions: Receive Webhook events to enable more complex functionality integration.
This guide provides a detailed introduction to the core features of debox-chat-go-sdk
, along with complete sample code to help developers get started quickly and develop efficiently.
About DeBox Command Bots
DeBox command bots are automated interactive entities on the DeBox platform. As a special type of user, they have the ability to send and receive messages and can integrate with external systems through Webhooks, suitable for message pushing, command interaction, automated operations, and other scenarios. For more information, see DeBox Command Bot Development Guide
Table of Contents
- DeBox Bot Go SDK Documentation
- Introduction
- Table of Contents
- Install SDK
- Initialize Bot
- Receive Message Updates
- Send Messages
- Message Button Menu
- Handle User Commands
- Use DeBox Open Platform API
- Reference Usage Example
- Frequently Asked Questions
- 1. I used the
GetUpdates
orGetUpdatesChan
method to listen for messages sent to the bot, but nothing was received. Why? - 2. I use the
GetUpdates
orGetUpdatesChan
method, but I can only get messages sent to the bot in private chats by DeBox users, and cannot get messages in group chats where the bot is present?
- 1. I used the
Install SDK
You can install the SDK via Go modules:
go get github.com/debox-pro/debox-chat-go-sdk
Initialize Bot
The first step to using the DeBox bot SDK is to create a BoxBotAPI
instance. You need to provide the Bot's API_KEY
to complete the bot creation authentication.
You can get the Bot's API_KEY on the DeBox Open Platform. Refer to DeBox Command Bot Development Guide
import (
"log"
boxbotapi "github.com/debox-pro/debox-chat-go-sdk/boxbotapi"
)
// Initialize bot
func getBot() (*boxbotapi.BotAPI, error) {
bot, err := boxbotapi.NewBotAPI("YOUR_BOT_API_KEY") // Please replace with your Bot's API_KEY
if err != nil{
log.Fatalf("Failed to initialize bot: %v", err)
return nil, err
}
// Enable Debug mode to record detailed logs
bot.Debug = true
log.Printf("Authorized on account %s, bot start running!", bot.Self.Name)
return bot, err
}
Be sure to keep your API_KEY
safe! Anyone with your API_KEY
can send and receive messages from your Bot!
Receive Message Updates
The DeBox bot SDK provides two ways to receive message updates:
- Continuously listen through Go channel
- Actively get the message list.
Here are the specific usage examples of these two methods.
If you want to use the DeBox Go SDK to handle message updates, do not set the Webhook URL on the [Open Platform Bot Control Page]. Once the Webhook URL is set, the message update function of the DeBox Go SDK will be ignored by the system, and all messages will be sent to the Webhook URL address you configured first.
1. Get message updates through go channel
Use the GetUpdatesChan
method to get message updates through the go channel:
// Get message updates through go channel
func GetUpdatesChanExample() {
// Initialize Bot
bot, _ := getBot()
// Set message update parameters
updateConfig := boxbotapi.NewUpdate(0)
updateConfig.Timeout = 60
// Create a cancellable context
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
// Get message update channel
updates := bot.GetUpdatesChan(updateConfig)
// Start goroutine to handle message updates asynchronously
go receiveUpdates(ctx, updates)
log.Println("Start listening for updates. Press enter to stop")
// Wait for the user to press Enter to stop processing
bufio.NewReader(os.Stdin).ReadBytes('\n')
cancel()
}
func receiveUpdates(ctx context.Context, updates boxbotapi.UpdatesChannel) {
// Continuously listen for message updates
for {
select {
// If the context is cancelled, stop the listening loop
case <-ctx.Done():
return
// Receive and handle new messages
case update := <-updates:
handleUpdate(update)
}
}
}
// Distribute handling logic based on message type
func handleUpdate(update boxbotapi.Update) {
switch {
// Handle text messages
case update.Message != nil:
handleMessage(update.Message)
// Handle button click events (feature not yet available)
case update.CallbackQuery != nil:
handleButton(update.CallbackQuery)
}
}
Notes:
GetUpdatesChan
method only allows your bot to process one update at a time. Please spawn goroutines to handle updates concurrently or switch to webhooks instead. Webhooks are suggested for high traffic bots.
2. Get message updates through list
If you need more flexible control over the message polling logic, you can directly use the GetUpdates
method to get the message update list:
// Actively get unread messages within the past 1 minute
// Note: Since messages are only retained for 1 minute, you need to poll regularly to continuously receive messages
func GetUpdatesExample() {
// Initialize Bot
bot, _ := getBot()
// Create update configuration
updateConfig := boxbotapi.NewUpdate(0) // Compatible with telegram API design, currently meaningless
// Get message update list
updates, err := bot.GetUpdates(updateConfig)
if err != nil {
log.Panic(err)
}
// Handle each message (in order from old to new)
for _, update := range updates {
handleUpdate(updates)
}
}
Send Messages
1. Send plain text messages
// Parameters used when sending messages
var (
chatID = "l3ixr31y" // Target group or target user's debox id
chatType = "group" // "group" or "private"
)
func SendMessageExample(chatId, chatType string) {
// Initialize bot
bot, _ := getBot()
// Plain text message
message := "This is an example message from debox go SDK"
// Build message structure
msg := boxbotapi.NewMessage(chatId, chatType, message)
// Send message
_, err := bot.Send(msg)
if err != nil {
log.Printf("An error occurred: %s", err.Error())
}
}
2. Send Markdown messages
DeBox bots support Markdown format messages, which can be used to create structured text:
func SendMarkdownMessageExample(chatId, chatType string) {
// Initialize bot
bot, _ := getBot()
// Markdown type message
markdownMessage := "#title,\nA test message from the test library in debox-bot-api"
// Build message structure
msg := boxbotapi.NewMessage(chatId, chatType, markdownMessage)
// Set message parsing mode
msg.ParseMode = boxbotapi.ModeMarkdownV2
// Send message
_, err := bot.Send(msg)
if err != nil {
log.Printf("An error occurred: %s", err.Error())
}
}
3. Send HTML messages
If you want to send more richly formatted text, you can use HTML format:
func SendHTMLMessageExample(chatId, chatType string) {
// Initialize bot
bot, _ := getBot()
// HTML type message
HTMLMessage := "A test <b>html</b> <font color=\"red\">message</font><br/><a href=\"https://debox.pro\">debox</a>"
// Build message structure
msg := boxbotapi.NewMessage(chatId, chatType, HTMLMessage)
// Set message parsing mode
msg.ParseMode = boxbotapi.ModeHTML
// Send message
_, err := bot.Send(msg)
if err != nil {
log.Printf("An error occurred: %s", err.Error())
}
}
4. Send rich text messages
Rich text messages support images, hyperlinks, and other UI components, suitable for more complex message content:
func SendRichTextExample(chatId, chatType string) {
var imageOne = "https://data.debox.pro/dao/newpic/one.png"
var imageTwo = "https://data.debox.pro/dao/newpic/two.png"
var href = "https://app.debox.pro/"
// Header image
var uiImgHead = boxbotapi.UITagImg{
Uitag: "img",
Src: imageOne,
Position: "head",
Href: href,
Height: "200",
}
jsonUIImgHead, _ := json.Marshal(uiImgHead)
// Footer image
var uiImgFoot = boxbotapi.UITagImg{
Uitag: "img",
Src: imageTwo,
Position: "foot",
Href: href,
Height: "300",
}
uiImgFootJson, _ := json.Marshal(uiImgFoot)
// Hyperlink
var uiA = boxbotapi.UITagA{
Uitag: "a",
Text: "DeBox",
Href: href,
}
uiAJson, _ := json.Marshal(uiA)
// Combine rich text content
RichTextContent := "richtext https://debox.pro " + string(jsonUIImgHead) + string(uiImgFootJson) + string(uiAJson)
// Initialize bot
bot, _ := getBot()
// Build message structure
msg := boxbotapi.NewMessage(chatId, chatType, RichTextContent)
// Send message
_, err := bot.Send(msg)
if err != nil {
log.Printf("An error occurred: %s", err.Error())
}
}
Message Button Menu
Create message button menu
You can create a message button menu to achieve click-to-jump and other interactive functions. Currently, each row supports a maximum of 5 buttons. More buttons will be hidden.
func SendMenuExample(chatId, chatType string) error {
// Initialize bot
bot, _ := getBot()
// Create buttons
// Message body
menuMessageText = "<b>Menu 1</b><br/>A box button message."
// Create button menu
firstMenuMarkup = boxbotapi.NewInlineKeyboardMarkup(
// Create the first row of the button menu
boxbotapi.NewInlineKeyboardRow(
// The first button in the first row
boxbotapi.NewInlineKeyboardButtonURL("url1", tokenUrl),
),
// Create the second row of the button menu
boxbotapi.NewInlineKeyboardRow(
// The first button in the second row
boxbotapi.NewInlineKeyboardButtonDataWithColor("BOX", "", swapUrl, "15%", "#ff0000"),
// The second button in the second row
boxbotapi.NewInlineKeyboardButtonDataWithColor("BTC", "", "https://debox.pro", "27.5%", "#00ff00"),
),
)
// Build message structure
msg := boxbotapi.NewMessage(chatId, chatType, menuMessageText)
// Set message parsing mode
msg.ParseMode = boxbotapi.ModeHTML
// Set message button menu
msg.ReplyMarkup = firstMenuMarkup
// Send message
_, err := bot.Send(msg)
return err
}
Handle User Commands
You can listen to and handle messages sent by users, perform specified operations after processing, and reply to user messages. Commands are messages that you can set in the bot panel, which users can easily reply to with one click, starting with "/". You can set specific responses to these commands.
// Handle received message updates
func handleUpdate(update boxbotapi.Update) {
// DeBox can send various types of updates based on your bot's activity. You can handle these separately.
// Since updates can be of various types, at most one field in an `Update` struct will be set to a non-nil value. Make sure to check if a field is nil before attempting to access it.
switch {
// Handle messages
case update.Message != nil:
handleMessage(update.Message)
// Handle button click events (feature not yet available)
case update.CallbackQuery != nil:
handleButton(update.CallbackQuery)
}
}
func handleMessage(message *boxbotapi.Message) {
// Print received message
log.Printf("%s wrote %s", message.From.Name, text)
// Handle "/" command messages:
if strings.HasPrefix(text, "/") {
switch text {
case "/menu":
// You can customize the response to the command, such as sending a message, performing an operation, etc.
err := sendMenu(message.Chat.ID, message.Chat.Type)
case "/menu2":
err := sendMenu2(message.Chat.ID, message.Chat.Type)
}
} else if len(text) > 0 {
// Handle other messages
// Here, get the Chat ID and Text from the incoming message and simply return the received message
msg := boxbotapi.NewMessage(message.Chat.ID, message.Chat.Type, message.Text)
// Send message reply
_, err := bot.Send(msg)
}
if err != nil {
log.Printf("An error occurred: %s", err.Error())
}
}
Use DeBox Open Platform API
After you complete the bot registration and obtain the API_KEY
, you can use a variety of DeBox Open Platform APIs! You can interact with DeBox through the DeBox Open Platform API, get the information needed for your product construction, and achieve various unique functions.
You can refer to DeBox Open Platform API Documentation for more information.
Some DeBox Open Platform APIs require signatures for authentication. The calculation of the signature for each API is described in the corresponding Open Platform API documentation. Here is an example of generating a signature and calling the DeBox Open Platform to get user information API:
import (
"crypto/sha1"
"encoding/json"
"fmt"
"io"
"math/rand"
"strconv"
"time"
)
// Generate the signature required by the API
func getSignature(appSecret string) (nonce, timestamp, signature string) {
nonceInt := rand.Int()
nonce = strconv.Itoa(nonceInt)
timeInt64 := time.Now().Unix()
timestamp = strconv.FormatInt(timeInt64, 10)
h := sha1.New()
_, _ = io.WriteString(h, appSecret+nonce+timestamp)
signature = fmt.Sprintf("%x", h.Sum(nil))
return
}
// Call the user information API
func TestUserInfot(t *testing.T) {
url := "https://open.debox.pro/openapi/user/info?user_id=uvg2p6ho"
nonce, timestamp, signature := getSignature("app_secret")
var headers = map[string]string{
"X-API-KEY": TestToken,
"nonce": nonce,
"timestamp": timestamp,
"signature": signature,
}
var resp = make(map[string]interface{})
err := HttpGet2Obj(url, headers, &resp)
if err != nil {
fmt.Println("send chat message fail:", err)
return
}
strRes, err := json.Marshal(resp)
if err != nil {
fmt.Println("error:" + err.Error())
return
}
fmt.Println("UserInfot_Test success." + string(strRes))
}
Reference Usage Example
We provide an example that uses various DeBox GO SDK features for your reference:
Example Code:
package main
import (
"bufio"
"context"
"log"
"os"
"strings"
boxbotapi "github.com/debox-pro/debox-chat-go-sdk/boxbotapi"
)
func main() {
var err error
// bot, err = boxbotapi.NewBotAPI("<YOUR_BOT_TOKEN_HERE>")//replace with your token
bot, err = boxbotapi.NewBotAPI("pPpHtOTtXsE6i5u6")
if err != nil {
// Abort if something is wrong
log.Panic(err)
}
// Set this to true to log all interactions with debox servers
bot.Debug = true
u := boxbotapi.NewUpdate(0)
u.Timeout = 60
// Create a new cancellable background context. Calling `cancel()` leads to the cancellation of the context
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
// `updates` is a golang channel which receives debox updates
updates := bot.GetUpdatesChan(u)
// Pass cancellable context to goroutine
go receiveUpdates(ctx, updates)
// Tell the user the bot is online
log.Println("Start listening for updates. Press enter to stop")
// Wait for a newline symbol, then cancel handling updates
bufio.NewReader(os.Stdin).ReadBytes('\n')
cancel()
}
func receiveUpdates(ctx context.Context, updates boxbotapi.UpdatesChannel) {
// `for {` means the loop is infinite until we manually stop it
for {
select {
// stop looping if ctx is cancelled
case <-ctx.Done():
return
// receive update from channel and then handle it
case update := <-updates:
handleUpdate(update)
}
}
}
func handleUpdate(update boxbotapi.Update) {
switch {
// Handle messages
case update.Message != nil:
handleMessage(update.Message)
break
// Handle button clicks
case update.CallbackQuery != nil:
handleButton(update.CallbackQuery)
break
}
}
func handleMessage(message *boxbotapi.Message) {
user := message.From
text := message.Text
if user == nil {
return
}
// You can process the received message here in various ways and send the result back to the DeBox user.
// In this example, we just print the raw message received by the bot to the console.
log.Printf("%s wrote %s", user.Name, text)
var err error
if strings.HasPrefix(text, "/") {
err = handleCommand(message.Chat.ID, message.Chat.Type, text)
} else if len(text) > 0 {
msg := boxbotapi.NewMessageResponse(message)
_, err = bot.Send(msg)
}
if err != nil {
log.Printf("An error occured: %s", err.Error())
}
}
// When we get a command, we react accordingly
func handleCommand(chatId, chatType string, command string) error {
var err error
switch command {
case "/menu":
err = sendMenu(chatId, chatType)
break
case "/menu2":
err = sendMenu2(chatId, chatType)
break
}
return err
}
func handleButton(query *boxbotapi.CallbackQuery) {
var text string
markup := boxbotapi.NewInlineKeyboardMarkup()
message := query.Message
if query.Data == nextButton {
text = secondMenu
markup = secondMenuMarkup
} else if query.Data == backButton {
text = firstMenu
markup = firstMenuMarkup
}
// callbackCfg := boxbotapi.NewCallback(query.ID, "")
// bot.Send(callbackCfg)
// Replace menu text and keyboard
msg := boxbotapi.NewEditMessageTextAndMarkup(message.Chat.ID, message.Chat.Type, message.MessageID, text, markup)
msg.ParseMode = boxbotapi.ModeHTML
bot.Send(msg)
}
func sendMenu(chatId, chatType string) error {
msg := boxbotapi.NewMessage(chatId, chatType, firstMenu)
msg.ParseMode = boxbotapi.ModeHTML
msg.ReplyMarkup = firstMenuMarkup
_, err := bot.Send(msg)
return err
}
func sendMenu2(chatId, chatType string) error {
msg := boxbotapi.NewMessage(chatId, chatType, firstMenu)
msg.ParseMode = boxbotapi.ModeHTML
msg.ReplyMarkup = secondMenuMarkup
_, err := bot.Send(msg)
return err
}
Frequently Asked Questions
1. I used the GetUpdates
or GetUpdatesChan
method to listen for messages sent to the bot, but nothing was received. Why?
- Have you set the Webhook URL for message callbacks on the [Open Platform Bot Control Page]? If you want to use the DeBox Go SDK to handle message updates, do not set the Webhook URL on the Open Platform Bot Control Page. Once the Webhook URL is set, the message update functionality of the DeBox Go SDK will be ignored, and all messages will be sent to the Webhook URL address you configured.
- If you are using the
GetUpdates
method, please note that this method can only retrieve messages received by the bot in the last 1 minute that have not been read. If the messages received by the bot are not obtained by theGetUpdates
orGetUpdatesChan
method within 1 minute, you will not be able to retrieve those messages again.
2. I use the GetUpdates
or GetUpdatesChan
method, but I can only get messages sent to the bot in private chats by DeBox users, and cannot get messages in group chats where the bot is present?
- If you want to listen to messages in group chats where the bot is present, you need to enable the Monitor group message option on the [Open Platform Bot Control Page]:
- When this option is enabled, all messages sent by all users in the groups where the bot is present will be sent to the bot;
- When this option is not enabled, only messages where users @ the bot in the groups where the bot is present will be sent to the bot;
- Note: Do not enable this feature unless necessary to avoid excessive message callbacks.