debox_chat_go_sdk

package module
v0.0.0-...-54fee8d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2023 License: GPL-3.0 Imports: 25 Imported by: 0

README

User Guide (中文)

README in English

基本介绍

本项目是Debox社交聊天服务(Chat Service)API的Golang编程接口,Chat Service Rest API的封装和实现,帮助Golang开发人员更快编程使用Debox的聊天消息服务。

详细API接口以及含义请参考:https://help.debox.pro/openapi_cn/a/api_method

安装

go get -u github.com/debox-pro/debox-chat-go-sdk

快速入门

前言: 所有的使用样例都位于example目录下。

  1. 注册回调地址

    参考register_url_sample.go

    package main
    
    import (
        "fmt"
        dbx_chat "github.com/debox-pro/debox-chat-go-sdk"
    )
    
    func main() {
    
        registerUrl := "www.xxx.pro/get_message"
        xApiKey := "xxxxxx"
    
        client := dbx_chat.CreateNormalInterface("https://open.debox.pro", xApiKey)
    
        _, err := client.RegisterCallbakUrl(registerUrl, "POST", "register")
    
        if err != nil {
            fmt.Println("register callback url  fail:", err)
            return
        }
    
        fmt.Println("register callback url success.")
    
    }
    
  2. 发送会话消息

    参考 send_chat_msg_sample.go

    package main
    
    import (
        "fmt"
        dbx_chat "github.com/debox-pro/debox-chat-go-sdk"
    )
    
    func main() {
    
        xApiKey := "xxxxxx"
        client := dbx_chat.CreateNormalInterface("https://open.debox.pro", xApiKey)
    
        toUserId := ""
        groupId := ""
        message := ""
        _, err := client.SendChatMsg(toUserId, groupId, message, "send_msg")
    
        if err != nil {
            fmt.Println("send chat message fail:", err)
            return
        }
    
        fmt.Println("send chat message success.")
    
    }
    
  3. 发送机器人消息

    参考 send_robot_msg_sample.go

    package main
    
    import (
        "fmt"
        dbx_chat "github.com/debox-pro/debox-chat-go-sdk"
    )
    
    func main() {
    
        xApiKey := "xxxxxx"
        client := dbx_chat.CreateNormalInterface("https://open.debox.pro", xApiKey)
    
        toUserId := ""
        fromUserId := ""
        objectName := ""
        message := ""
        _, err := client.SendRobotMsg(toUserId, message, objectName, "send_robot_msg")
    
        if err != nil {
            fmt.Println("send chat message fail:", err)
            return
        }
    
        fmt.Println("send chat message success.")
    
    }
    
  4. 发送机器人群组消息

    参考 send_robot_group_msg_sample.go

    package main
    
    import (
        "fmt"
        dbx_chat "github.com/debox-pro/debox-chat-go-sdk"
    )
    
    func main() {
    
         xApiKey := ""
         client := dbx_chat.CreateNormalInterface("https://open.debox.pro", xApiKey)
    
         toUserId := ""
         groupId := ""
         title := ""
         content := ""
         objectName := ""
         message := ""
         _, err := client.SendRobotGroupMsg(toUserId, groupId, title, content, message, objectName, "send_robot_group_msg")
    
         if err != nil {
     	    fmt.Println("send chat message fail:", err)
     	return
         }
    
         fmt.Println("send chat message success.")
    
    }
    

Documentation

Index

Constants

View Source
const (

	// RequestIDHeader stands for the requestID in all response
	RequestIDHeader  = "x-Chat-requestid"
	GetChatQueryInfo = "X-Chat-Query-Info"
)
View Source
const (
	HTTPHeaderAuthorization   = "Authorization"
	HTTPHeaderContentMD5      = "Content-MD5"
	HTTPHeaderContentType     = "Content-Type"
	HTTPHeaderContentLength   = "Content-Length"
	HTTPHeaderDate            = "Date"
	HTTPHeaderHost            = "Host"
	HTTPHeaderUserAgent       = "User-Agent"
	HTTPHeaderAPIVersion      = "x-chat-apiversion"
	HTTPHeaderSignatureMethod = "x-chat-signaturemethod"
	HTTPHeaderBodyRawSize     = "x-chat-bodyrawsize"
	ISO8601                   = "20060102T150405Z"
)
View Source
const BAD_REQUEST = "BadRequest"
View Source
const CONFIG_ALREADY_EXIST = "ConfigAlreadyExist"
View Source
const CONFIG_NOT_EXIST = "ConfigNotExist"
View Source
const DefaultLogUserAgent = "golang-sdk-v0.1.0"
View Source
const GROUP_ALREADY_EXIST = "GroupAlreadyExist"
View Source
const GROUP_NOT_EXIST = "GroupNotExist"
View Source
const INTERNAL_SERVER_ERROR = "InternalServerError"
View Source
const INVALID_API_VERSION = "InvalidAPIVersion"
View Source
const INVALID_BODY_RAW_SIZE = "InvalidBodyRawSize"
View Source
const INVALID_COMPRESS_TYPE = "InvalidCompressType"
View Source
const INVALID_CONTENT_TYPE = "InvalidContentType"
View Source
const INVALID_CURSOR = "InvalidCursor"
View Source
const INVALID_DATE_FORMAT = "InvalidDateFormat"
View Source
const INVALID_ENCODING = "InvalidEncoding"
View Source
const INVALID_KEY = "InvalidKey"
View Source
const INVALID_LINE = "InvalidLine"
View Source
const INVALID_OFFSET = "InvalidOffset"
View Source
const INVALID_PARAMETER = "InvalidParameter"
View Source
const INVALID_QUERY_STRING = "InvalidQueryString"
View Source
const INVALID_REVERSE = "InvalidReverse"
View Source
const INVALID_SIGNATURE_METHOD = "InvalidSignatureMethod"
View Source
const INVALID_TIMESTAMP = "InvalidTimestamp"
View Source
const INVALID_TIME_RANGE = "InvalidTimeRange"
View Source
const MISSING_API_VERSION = "MissingAPIVersion"
View Source
const MISSING_BODY_RAW_SIZE = "MissingBodyRawSize"
View Source
const MISSING_CONTENT_LENGTH = "MissingContentLength"
View Source
const MISSING_CONTENT_TYPE = "MissingContentType"
View Source
const MISSING_DATE = "MissingDate"
View Source
const MISSING_HOST = "MissingHost"
View Source
const MISSING_SIGNATURE_METHOD = "MissingSignatureMethod"
View Source
const MISS_ACCESS_KEY_ID = "MissAccessKeyId"
View Source
const PARAMETER_INVALID = "ParameterInvalid"
View Source
const POST_BODY_INVALID = "PostBodyInvalid"
View Source
const POST_BODY_TOO_LARGE = "PostBodyTooLarge"
View Source
const POST_BODY_UNCOMPRESS_ERROR = "PostBodyUncompressError"
View Source
const PROJECT_FORBIDDEN = "ProjectForbidden"
View Source
const PROJECT_NOT_EXIST = "ProjectNotExist"
View Source
const PROJECT_QUOTA_EXCEED = "ProjectQuotaExceed"
View Source
const READ_QUOTA_EXCEED = "ReadQuotaExceed"
View Source
const REQUEST_TIME_TOO_SKEWED = "RequestTimeTooSkewed"
View Source
const SERVER_BUSY = "ServerBusy"
View Source
const SHARD_NOT_EXIST = "ShardNotExist"
View Source
const SHARD_READ_QUOTA_EXCEED = "ShardReadQuotaExceed"
View Source
const SHARD_WRITE_QUOTA_EXCEED = "ShardWriteQuotaExceed"
View Source
const SHIPPER_NOT_EXIST = "ShipperNotExist"
View Source
const SIGNATURE_NOT_MATCH = "SignatureNotMatch"
View Source
const UN_AUTHORIZED = "Unauthorized"
View Source
const WRITE_QUOTA_EXCEED = "WriteQuotaExceed"

Variables

View Source
var GlobalDebugLevel = 0
View Source
var GlobalForceUsingHTTP = false

GlobalForceUsingHTTP if GlobalForceUsingHTTP is true, then all request will use HTTP(ignore LogProject's UsingHTTP flag)

View Source
var InvalidCompressError = errors.New("Invalid Compress Type")
View Source
var Logger = initDefaultSLSLogger()
View Source
var MaxCompletedRetryCount = 20
View Source
var MaxCompletedRetryLatency = 5 * time.Minute
View Source
var RetryOnServerErrorEnabled = true

RetryOnServerErrorEnabled if RetryOnServerErrorEnabled is false, then all error requests will not be retried

Functions

func GenerateInnerLogger

func GenerateInnerLogger(logFileName, isJsonType, logMaxSize, logFileBackupCount, allowLogLevel string) log.Logger

func IsDebugLevelMatched

func IsDebugLevelMatched(level int) bool

func IsTokenError

func IsTokenError(err error) bool

func Retry

func Retry(ctx context.Context, o backoff.Operation) error

Retry execute the input operation immediately at first, and do an exponential backoff retry when failed. The default max elapsed time is 15 minutes. The default retry intervals are shown below, in seconds.

1          0.5                     [0.25,   0.75]
2          0.75                    [0.375,  1.125]
3          1.125                   [0.562,  1.687]
4          1.687                   [0.8435, 2.53]
5          2.53                    [1.265,  3.795]
6          3.795                   [1.897,  5.692]
7          5.692                   [2.846,  8.538]
8          8.538                   [4.269, 12.807]
9         12.807                   [6.403, 19.210]

... The signature of backoff.Operation is "func() error".

func RetryWithAttempt

func RetryWithAttempt(ctx context.Context, maxAttempt int, o ConditionOperation) error

RetryWithAttempt ...

func RetryWithBackOff

func RetryWithBackOff(ctx context.Context, b backoff.BackOff, o backoff.Operation) error

RetryWithBackOff ...

func RetryWithCondition

func RetryWithCondition(ctx context.Context, b backoff.BackOff, o ConditionOperation) error

RetryWithCondition ...

Types

type AuthVersionType

type AuthVersionType string

AuthVersionType the version of auth

const (
	// AuthV1 v1
	AuthV1 AuthVersionType = "v1"
)

type AutoRetryClient

type AutoRetryClient struct {
	// contains filtered or unexported fields
}

func (*AutoRetryClient) Close

func (c *AutoRetryClient) Close() error

func (*AutoRetryClient) RegisterCallbakUrl

func (c *AutoRetryClient) RegisterCallbakUrl(url, method, operate string) (prj *ChatProject, err error)

func (*AutoRetryClient) ResetAccessKeyToken

func (c *AutoRetryClient) ResetAccessKeyToken(xApiKey string)

func (*AutoRetryClient) SendChatMsg

func (c *AutoRetryClient) SendChatMsg(toUserId, groupId, message, operate string) (prj *ChatProject, err error)

func (*AutoRetryClient) SendRobotGroupMsg

func (c *AutoRetryClient) SendRobotGroupMsg(toUserId, groupId, title, content, message, objectName, operate string) (prj *ChatProject, err error)

func (*AutoRetryClient) SendRobotMsg

func (c *AutoRetryClient) SendRobotMsg(toUserId, message, objectName, operate string) (prj *ChatProject, err error)

func (*AutoRetryClient) SetAuthVersion

func (c *AutoRetryClient) SetAuthVersion(version AuthVersionType)

SetAuthVersion set auth version that the client used

func (*AutoRetryClient) SetHTTPClient

func (c *AutoRetryClient) SetHTTPClient(client *http.Client)

SetHTTPClient set a custom http client, all request will send to sls by this client

func (*AutoRetryClient) SetUserAgent

func (c *AutoRetryClient) SetUserAgent(userAgent string)

type BadResponseError

type BadResponseError struct {
	RespBody   string
	RespHeader map[string][]string
	HTTPCode   int
}

BadResponseError : special sls error, not valid json format

func NewBadResponseError

func NewBadResponseError(body string, header map[string][]string, httpCode int) *BadResponseError

NewBadResponseError ...

func (BadResponseError) Error

func (e BadResponseError) Error() string

func (BadResponseError) String

func (e BadResponseError) String() string

type ChatProject

type ChatProject struct {
	Name           string `json:"projectName"`    // Project name
	Description    string `json:"description"`    // Project description
	Status         string `json:"status"`         // Normal
	Owner          string `json:"owner"`          // empty
	Region         string `json:"region"`         // region
	CreateTime     string `json:"createTime"`     // unix time seconds, eg 1524539357
	LastModifyTime string `json:"lastModifyTime"` // unix time seconds, eg 1524539357

	Endpoint      string // IP or hostname of endpoint
	XApiKey       string
	SecurityToken string
	UsingHTTP     bool   // default https
	UserAgent     string // default defaultLogUserAgent
	AuthVersion   AuthVersionType
	// contains filtered or unexported fields
}

ChatProject defines chat project

func NewChatProject

func NewChatProject(name, endpoint, xApiKey string) (p *ChatProject, err error)

NewLogProject creates a new SLS project.

func (*ChatProject) RawRequest

func (p *ChatProject) RawRequest(method, uri string, headers map[string]string, body []byte) (*http.Response, error)

RawRequest send raw http request to LogService and return the raw http response @note you should call http.Response.Body.Close() to close body stream

func (*ChatProject) WithRequestTimeout

func (p *ChatProject) WithRequestTimeout(timeout time.Duration) *ChatProject

WithRequestTimeout with custom timeout for a request

func (*ChatProject) WithRetryTimeout

func (p *ChatProject) WithRetryTimeout(timeout time.Duration) *ChatProject

WithRetryTimeout with custom timeout for a operation each operation may send one or more HTTP requests in case of retry required.

func (*ChatProject) WithToken

func (p *ChatProject) WithToken(token string) (*ChatProject, error)

WithToken add token parameter

type Client

type Client struct {
	Endpoint       string // IP or hostname of SLS endpoint
	XApiKey        string
	UserAgent      string // default defaultLogUserAgent
	RequestTimeOut time.Duration
	RetryTimeOut   time.Duration
	HTTPClient     *http.Client
	//Region         string
	AuthVersion AuthVersionType
	// contains filtered or unexported fields
}

Client ...

func (*Client) Close

func (c *Client) Close() error

Close the client

func (*Client) RegisterCallbakUrl

func (c *Client) RegisterCallbakUrl(url, method, operate string) (*ChatProject, error)

RegisterCallbakUrl create a new event.

func (*Client) ResetAccessKeyToken

func (c *Client) ResetAccessKeyToken(xApiKey string)

ResetAccessKeyToken reset client's access key token

func (*Client) SendChatMsg

func (c *Client) SendChatMsg(toUserId, groupId, message, opreate string) (*ChatProject, error)

SendChatMsg send recall message.

func (*Client) SendRobotGroupMsg

func (c *Client) SendRobotGroupMsg(toUserId, groupId, title, content, message, objectName, operate string) (*ChatProject, error)

SendRobotMsg send recall message.

func (*Client) SendRobotMsg

func (c *Client) SendRobotMsg(toUserId, message, objectName, opreate string) (*ChatProject, error)

SendRobotMsg send recall message.

func (*Client) SetAuthVersion

func (c *Client) SetAuthVersion(version AuthVersionType)

SetAuthVersion set signature version that the client used

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(client *http.Client)

SetHTTPClient set a custom http client, all request will send to sls by this client

func (*Client) SetUserAgent

func (c *Client) SetUserAgent(userAgent string)

SetUserAgent set a custom userAgent

type ClientInterface

type ClientInterface interface {
	SetUserAgent(userAgent string)
	SetHTTPClient(client *http.Client)
	// #################### Client Operations #####################
	// ResetAccessKeyToken reset client's access key token
	ResetAccessKeyToken(xApiKey string)
	// SetAuthVersion Set signature version
	SetAuthVersion(version AuthVersionType)
	// Close the client
	Close() error

	// #################### Chat Operations #####################
	SendChatMsg(toUserId, groupId, message, operate string) (*ChatProject, error)
	RegisterCallbakUrl(url, method, operate string) (*ChatProject, error)
	SendRobotMsg(toUserId, message, objectName, operate string) (*ChatProject, error)
	SendRobotGroupMsg(toUserId, groupId, title, content, message, objectName, operate string) (*ChatProject, error)
}

ClientInterface for all chat's open api

func CreateNormalInterface

func CreateNormalInterface(endpoint, xApiKey string) ClientInterface

CreateNormalInterface create a normal client

type ConditionOperation

type ConditionOperation func() (bool, error)

ConditionOperation : retry depends on the retured bool

type Error

type Error struct {
	HTTPCode  int32  `json:"httpCode"`
	Code      string `json:"errorCode"`
	Message   string `json:"errorMessage"`
	RequestID string `json:"requestID"`
}

Error defines sls error

func NewClientError

func NewClientError(err error) *Error

NewClientError new client error

func (Error) Error

func (e Error) Error() string

func (Error) String

func (e Error) String() string

type Signer

type Signer interface {
	// Sign modifies @param headers only, adds signature and other http headers
	// that log services authorization requires.
	Sign(method, uriWithQuery string, headers map[string]string, body []byte) error
}

type SignerV1

type SignerV1 struct {
	// contains filtered or unexported fields
}

SignerV1 version v1

func NewSignerV1

func NewSignerV1(xApiKey string) *SignerV1

func (*SignerV1) Sign

func (s *SignerV1) Sign(method, uri string, headers map[string]string, body []byte) error

type SignerV4

type SignerV4 struct {
	// contains filtered or unexported fields
}

SignerV4 sign version v4, a non-empty region is required

func NewSignerV4

func NewSignerV4(xApiKey, region string) *SignerV4

func (*SignerV4) Sign

func (s *SignerV4) Sign(method, uri string, headers map[string]string, body []byte) error

type UpdateTokenFunction

type UpdateTokenFunction func() (xApiKey string, expireTime time.Time, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL