kappelas

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 15 Imported by: 0

README

kappelas-sdk-go

Go Reference Go version GitHub

Official Go SDK for the Kappela messaging platform.
Build bots and personal automations — send messages, handle events, manage chats.


Table of contents


Prerequisites

You need a bot token from BotMother, the official Kappela bot manager.

  1. Open Kappela and start a conversation with BotMother
  2. Follow the instructions to create a bot
  3. BotMother gives you a token — keep it secret, it gives full control over your bot

For personal automation (sending messages as yourself), generate an API key from your Kappela account settings (sk_...).


Install

go get github.com/Arnel7/kappelas-sdk-go

Requires Go 1.21+.


Quick start

Bot
package main

import (
    "context"
    "fmt"

    "github.com/Arnel7/kappelas-sdk-go"
)

func main() {
    bot := kappelas.NewBot("YOUR_BOT_TOKEN")

    bot.OnMessage(func(msg *kappelas.Message) {
        ctx := context.Background()
        bot.Messages.Send(ctx, kappelas.SendMessageParams{
            ChatID: msg.ChatID,
            Text:   "Echo: " + *msg.Text,
        })
    })

    bot.OnCallbackQuery(func(cb *kappelas.CallbackQuery) {
        ctx := context.Background()
        bot.Messages.Send(ctx, kappelas.SendMessageParams{
            ChatID: cb.ChatID,
            Text:   "You clicked: " + cb.CallbackData,
        })
    })

    bot.Start()
    select {} // keep alive
}
Personal automation
me := kappelas.NewUser("sk_...")

me.OnMessage(func(msg *kappelas.Message) {
    if msg.Text != nil {
        fmt.Printf("[%d] %s\n", msg.ChatID, *msg.Text)
    }
})

me.Start()
select {}

Events — WebSocket vs Webhook

Mode Method Best for
WebSocket bot.Start() Development, local scripts
Webhook bot.Webhooks.Set() + bot.HandleWebhook() Production servers

The same OnMessage and OnCallbackQuery handlers work in both modes — no code change needed when switching.

WebSocket (development)
bot := kappelas.NewBot("YOUR_BOT_TOKEN")

bot.OnMessage(func(msg *kappelas.Message) { /* ... */ })
bot.OnCallbackQuery(func(cb *kappelas.CallbackQuery) { /* ... */ })

bot.Start()   // non-blocking, auto-reconnects on disconnect
select {}
Webhook (production)
import (
    "io"
    "net/http"

    "github.com/Arnel7/kappelas-sdk-go"
)

bot := kappelas.NewBot("YOUR_BOT_TOKEN")

// register once
ctx := context.Background()
bot.Webhooks.Set(ctx, kappelas.SetWebhookParams{
    URL: "https://your-server.com/kappela-webhook",
})

bot.OnMessage(func(msg *kappelas.Message) { /* ... */ })
bot.OnCallbackQuery(func(cb *kappelas.CallbackQuery) { /* ... */ })

http.HandleFunc("/kappela-webhook", func(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    bot.HandleWebhook(body)
    w.WriteHeader(http.StatusOK)
})

http.ListenAndServe(":8080", nil)

Do not call bot.Start() in webhook mode.

Event reference
Method Signature Description
OnMessage func(*Message) Incoming message of any type
OnCallbackQuery func(*CallbackQuery) Inline button clicked by a user
OnConnected func() WebSocket connected or reconnected
OnDisconnected func(code int, reason string) WebSocket disconnected
OnError func(error) Connection or transport error
CallbackQuery fields
bot.OnCallbackQuery(func(cb *kappelas.CallbackQuery) {
    cb.ChatID          // int64   — chat where the button was clicked
    cb.SenderID        // string  — UUID of the user who clicked
    cb.SenderNom       // *string — display name (e.g. "Arnel LAWSON")
    cb.SenderUsername  // *string — username (e.g. "arnell")
    cb.CallbackData    // string  — value set on the button
    cb.SentAt          // int64   — Unix timestamp (seconds)
})

Clicks are deduplicated server-side — your handler fires exactly once per click.


API reference

Constructor options
kappelas.NewBot(token string, opts ...BotOption) *Bot
Option Default Description
WithBaseURL(url) https://api.kappelas.com Override API base URL
WithMaxRetries(n) 2 HTTP retry count on 429 / 5xx
WithTimeout(d) 30s Per-request timeout
WithWSMaxRetries(n) 12 Max WebSocket reconnect attempts
kappelas.NewUser(apiKey string, opts ...UserOption) *User
Option Default Description
WithUserBaseURL(url) https://api.kappelas.com Override API base URL
WithUserMaxRetries(n) 2 HTTP retry count on 429 / 5xx
WithUserTimeout(d) 30s Per-request timeout
WithUserWSMaxRetries(n) 12 Max WebSocket reconnect attempts
bot := kappelas.NewBot("token",
    kappelas.WithTimeout(10 * time.Second),
    kappelas.WithMaxRetries(3),
)

messages
Messages.Send(ctx, params)(*SendResult, error)
yes, no := "yes", "no"
replyTo := int64(123) // optional — ID of the message to reply to

result, err := bot.Messages.Send(ctx, kappelas.SendMessageParams{
    ChatID:    42,
    Text:      "Hello!",
    ReplyToID: &replyTo,
    ReplyMarkup: kappelas.InlineKeyboard{
        InlineKeyboard: [][]kappelas.InlineKeyboardButton{{
            {Text: "Yes", CallbackData: &yes},
            {Text: "No",  CallbackData: &no},
        }},
    },
})
// → &SendResult{MessageID: ..., CreatedAt: ...}
Messages.SendPhoto(ctx, params)(*SendMediaResult, error)
data, _ := os.ReadFile("banner.png")
result, err := bot.Messages.SendPhoto(ctx, kappelas.SendMediaParams{
    ChatID:  42,
    File:    kappelas.FileInput{Data: data, Filename: "banner.png", ContentType: "image/png"},
    Caption: "Check this out!",
})
// → SendMediaResult{MessageID, CreatedAt, MediaID}
Messages.SendVideo / SendDocument / SendAudio(*SendMediaResult, error)

Same shape — pass the appropriate FileInput.

Messages.SendCarousel(ctx, params)(*SendCarouselResult, error)
btn := "Buy"
bot.Messages.SendCarousel(ctx, kappelas.SendCarouselParams{
    ChatID: 42,
    Text:   "Pick a product:",
    Carousel: []kappelas.CarouselCard{
        {ID: "p1", Title: "Widget A", ButtonText: &btn},
        {ID: "p2", Title: "Widget B", ButtonText: &btn},
    },
    QuickReplyButtons: []string{"See more", "Cancel"},
})
Messages.Edit(ctx, params)(*EditMessageResult, error)
// Edit text
bot.Messages.Edit(ctx, kappelas.EditMessageParams{
    ChatID: 42, MessageID: 123, NewText: "Updated!",
})

// Edit inline keyboard only
import "encoding/json"
done := "done"
kb, _ := json.Marshal(kappelas.InlineKeyboard{
    InlineKeyboard: [][]kappelas.InlineKeyboardButton{
        {{Text: "Done ✅", CallbackData: &done}},
    },
})
bot.Messages.Edit(ctx, kappelas.EditMessageParams{
    ChatID: 42, MessageID: 123, NewExtraData: kb,
})
// → EditMessageResult{Edited: true, MessageID: 123}
Messages.SendTyping(ctx, params)(*TypingResult, error)
bot.Messages.SendTyping(ctx, kappelas.SendTypingParams{ChatID: 42})                       // show (default)
f := false
bot.Messages.SendTyping(ctx, kappelas.SendTypingParams{ChatID: 42, IsTyping: &f})         // hide
Messages.Delete(ctx, params)(*DeleteResult, error)
bot.Messages.Delete(ctx, kappelas.DeleteMessageParams{ChatID: 42, MessageID: 123})
// → DeleteResult{Deleted: true}

chats
Chats.List(ctx, params)(ChatsResult, error)
result, err := bot.Chats.List(ctx, kappelas.GetChatsParams{Limit: 20, Offset: 0})
fmt.Println(result.Chats, result.HasMore)
Chats.Iterate(ctx, pageSize, fn)error
err := bot.Chats.Iterate(ctx, 50, func(chat *kappelas.Chat) bool {
    fmt.Println(chat.ChatID, chat.Type)
    return true // return false to stop early
})

webhooks
Webhooks.Set(ctx, params)(*WebhookSetResult, error)
bot.Webhooks.Set(ctx, kappelas.SetWebhookParams{
    URL: "https://your-server.com/kappela-webhook",
})
Webhooks.GetInfo(ctx)(*WebhookInfo, error)
info, err := bot.Webhooks.GetInfo(ctx)
// → WebhookInfo{Active: true, URL: &"https://...", CreatedAt: &1234567890}
Webhooks.Delete(ctx)(*WebhookDeleteResult, error)
bot.Webhooks.Delete(ctx)
// → WebhookDeleteResult{Active: false}

profile
Profile.Get(ctx)(*BotProfile, error) / (*UserProfile, error)
// Bot
profile, err := bot.Profile.Get(ctx)
// → BotProfile{UserID, Username, IsBot: true, About, Description, AvatarURL}

// User
profile, err := me.Profile.Get(ctx)
// → UserProfile{ID, Username, Nom, IsBot: false, IsPremium, AvatarURL, ...}

Keyboards

Three types of keyboard can be passed as ReplyMarkup on any Send* call:

// Inline buttons — attached to the message
yes, no := "yes", "no"
inline := kappelas.InlineKeyboard{
    InlineKeyboard: [][]kappelas.InlineKeyboardButton{{
        {Text: "Yes", CallbackData: &yes},
        {Text: "No",  CallbackData: &no},
    }},
}

// Reply keyboard — shown below the input bar
reply := kappelas.ReplyKeyboard{
    Keyboard: [][]string{
        {"Option A", "Option B"},
        {"Cancel"},
    },
}

// Scroll keyboard — horizontal scrollable chips
scroll := kappelas.ScrollKeyboard{
    ScrollKeyboard: []string{"Small", "Medium", "Large"},
}

bot.Messages.Send(ctx, kappelas.SendMessageParams{
    ChatID:      42,
    Text:        "Pick one:",
    ReplyMarkup: inline,
})

Error handling

All API errors return a *KappelaError with structured fields:

import "errors"

_, err := bot.Messages.Send(ctx, kappelas.SendMessageParams{ChatID: 999, Text: "Hi"})
if err != nil {
    var e *kappelas.KappelaError
    if errors.As(err, &e) {
        e.Code      // kappelas.ErrCodeNotFound
        e.Status    // 404
        e.Message   // server error message
        e.RequestID // mention this when contacting support
        fmt.Println(e) // full formatted block with hints and solutions
    }
}
Error codes
Code HTTP Meaning
ErrCodeUnauthorized 401 Token or API key invalid / expired
ErrCodeForbidden 403 Missing permission or role
ErrCodeNotFound 404 Resource does not exist
ErrCodeMissingField 400 Required parameter missing
ErrCodeInvalidField 400 Parameter has wrong type or format
ErrCodeConflict 409 Resource already exists
ErrCodeMethodNotAllowed 405 Wrong HTTP method
ErrCodeInvalidPath 404 API path does not exist
ErrCodeInternalError 500 Unexpected server error
ErrCodeServiceUnavailable 503 Service temporarily down
ErrCodeUpstreamError 502 Upstream service error

File input

Media methods accept a FileInput struct:

type FileInput struct {
    Data        []byte
    Filename    string
    ContentType string
}
// From disk
data, _ := os.ReadFile("photo.jpg")
bot.Messages.SendPhoto(ctx, kappelas.SendMediaParams{
    ChatID: 42,
    File:   kappelas.FileInput{Data: data, Filename: "photo.jpg", ContentType: "image/jpeg"},
})

// From memory
bot.Messages.SendDocument(ctx, kappelas.SendMediaParams{
    ChatID: 42,
    File:   kappelas.FileInput{Data: pdfBytes, Filename: "report.pdf", ContentType: "application/pdf"},
})

License

MIT © Arnel LAWSON

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bot

type Bot struct {
	// Messages provides methods to send and manage messages.
	Messages *MessagesResource
	// Chats provides methods to list and iterate over chats.
	Chats *ChatsResource
	// Webhooks provides methods to manage webhooks.
	Webhooks *WebhooksResource
	// Profile provides access to the bot's own profile.
	Profile *BotProfileResource
	// contains filtered or unexported fields
}

Bot is the Kappela bot client. Authenticate with a token from BotMother.

Example:

bot := kappelas.NewBot("YOUR_BOT_TOKEN")

bot.OnMessage(func(msg *kappelas.Message) {
    bot.Messages.Send(ctx, kappelas.SendMessageParams{
        ChatID: msg.ChatID,
        Text:   "Echo: " + *msg.Text,
    })
})

bot.OnCallbackQuery(func(cb *kappelas.CallbackQuery) {
    bot.Messages.Send(ctx, kappelas.SendMessageParams{
        ChatID: cb.ChatID,
        Text:   "Button clicked: " + cb.CallbackData,
    })
})

bot.Start()
select {} // keep alive

func NewBot

func NewBot(token string, opts ...BotOption) *Bot

NewBot creates a Bot authenticated with the given token.

func (*Bot) Connected

func (b *Bot) Connected() bool

Connected reports whether the WebSocket is currently open.

func (*Bot) HandleWebhook

func (b *Bot) HandleWebhook(body []byte)

HandleWebhook processes a webhook payload sent by Kappela to your server. Call this inside your HTTP handler and respond 200 immediately. The same OnMessage and OnCallbackQuery handlers fire for both WS and webhook events.

Example (net/http):

http.HandleFunc("/kappela-webhook", func(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    bot.HandleWebhook(body)
    w.WriteHeader(http.StatusOK)
})

func (*Bot) OnCallbackQuery

func (b *Bot) OnCallbackQuery(h func(*CallbackQuery))

OnCallbackQuery registers a handler called when a user clicks an inline button.

func (*Bot) OnConnected

func (b *Bot) OnConnected(h func())

OnConnected registers a handler called when the WebSocket connects (or reconnects).

func (*Bot) OnDisconnected

func (b *Bot) OnDisconnected(h func(code int, reason string))

OnDisconnected registers a handler called when the WebSocket disconnects.

func (*Bot) OnError

func (b *Bot) OnError(h func(error))

OnError registers a handler called on WebSocket or connection errors.

func (*Bot) OnMessage

func (b *Bot) OnMessage(h func(*Message))

OnMessage registers a handler called for every incoming message.

func (*Bot) Start

func (b *Bot) Start()

Start connects via WebSocket and begins receiving events in the background. Your OnMessage and OnCallbackQuery handlers will be called for each event.

func (*Bot) Stop

func (b *Bot) Stop()

Stop closes the WebSocket connection.

type BotOption

type BotOption func(*botConfig)

BotOption configures a Bot.

func WithBaseURL

func WithBaseURL(u string) BotOption

WithBaseURL overrides the API base URL (default: https://api.kappelas.com).

func WithMaxRetries

func WithMaxRetries(n int) BotOption

WithMaxRetries sets the maximum number of HTTP retry attempts (default: 2).

func WithTimeout

func WithTimeout(d time.Duration) BotOption

WithTimeout sets the HTTP request timeout (default: 30s).

func WithWSMaxRetries

func WithWSMaxRetries(n int) BotOption

WithWSMaxRetries sets the maximum WebSocket reconnect attempts (default: 12).

type BotProfile

type BotProfile struct {
	UserID      string  `json:"user_id"`
	Username    string  `json:"username"`
	IsBot       bool    `json:"is_bot"`
	About       string  `json:"about"`
	Description string  `json:"description"`
	AvatarURL   *string `json:"avatar_url"`
}

BotProfile is the profile returned for a bot account.

type BotProfileResource

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

BotProfileResource provides access to the bot's own profile.

func (*BotProfileResource) Get

Get returns the bot's own profile.

type CallbackQuery

type CallbackQuery struct {
	ChatID         int64   `json:"chat_id"`
	SenderID       string  `json:"sender_id"`
	SenderNom      *string `json:"sender_nom"`
	SenderUsername *string `json:"sender_username"`
	CallbackData   string  `json:"callback_data"`
	SentAt         int64   `json:"sent_at"`
}

CallbackQuery is fired when a user clicks an inline button.

type CarouselCard

type CarouselCard struct {
	ID         string  `json:"id"`
	Title      string  `json:"title"`
	Subtitle   *string `json:"subtitle,omitempty"`
	ImageURL   *string `json:"image_url,omitempty"`
	ButtonText *string `json:"button_text,omitempty"`
}

CarouselCard is a single card inside a carousel message.

type Chat

type Chat struct {
	ChatID             int64         `json:"chat_id"`
	ID                 int64         `json:"id"`
	Type               ChatType      `json:"type"`
	Title              *string       `json:"title"`
	Participants       []Participant `json:"participants"`
	LastMessageAt      *string       `json:"last_message_at"`
	CreatedAt          string        `json:"created_at"`
	CreatedBy          string        `json:"created_by"`
	IsPinned           bool          `json:"is_pinned"`
	IsPremium          bool          `json:"is_premium"`
	IsPublic           bool          `json:"is_public"`
	OnlyAdminsCanWrite bool          `json:"only_admins_can_write"`
	Labels             []string      `json:"labels"`
	Description        *string       `json:"description"`
	AvatarURL          *string       `json:"avatar_url"`
}

Chat represents a Kappela conversation.

type ChatType

type ChatType string

ChatType is the type of a conversation.

const (
	ChatTypePrivate ChatType = "private"
	ChatTypeGroup   ChatType = "group"
	ChatTypeChannel ChatType = "channel"
)

type ChatsResource

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

ChatsResource provides methods to access chats.

func (*ChatsResource) Iterate

func (r *ChatsResource) Iterate(ctx context.Context, pageSize int, fn func(*Chat) bool) error

Iterate calls fn for every chat, handling pagination automatically. Return false from fn to stop iteration early.

Example:

err := bot.Chats.Iterate(ctx, 50, func(chat *kappelas.Chat) bool {
    fmt.Println(chat.ChatID)
    return true // continue
})

func (*ChatsResource) List

func (r *ChatsResource) List(ctx context.Context, params GetChatsParams) (ChatsResult, error)

List returns a paginated list of chats accessible to this bot or user.

type ChatsResult

type ChatsResult struct {
	Chats   []Chat `json:"chats"`
	HasMore bool   `json:"has_more"`
}

ChatsResult is the paginated response from the list chats endpoint.

type DeleteMessageParams

type DeleteMessageParams struct {
	ChatID    int64 `json:"chat_id"`
	MessageID int64 `json:"message_id"`
}

DeleteMessageParams holds the parameters for deleting a message.

type DeleteResult

type DeleteResult struct {
	Deleted bool `json:"deleted"`
}

DeleteResult is returned by the deleteMessage endpoint.

type EditMessageParams

type EditMessageParams struct {
	ChatID       int64           `json:"chat_id"`
	MessageID    int64           `json:"message_id"`
	NewText      string          `json:"new_text,omitempty"`
	NewExtraData json.RawMessage `json:"new_extra_data,omitempty"`
}

EditMessageParams holds the parameters for editing a message.

type EditMessageResult

type EditMessageResult struct {
	Edited    bool  `json:"edited"`
	MessageID int64 `json:"message_id"`
}

EditMessageResult is returned after editing a message.

type ErrorCode

type ErrorCode string

ErrorCode is the machine-readable error code returned by the Kappela API.

const (
	ErrCodeUnauthorized       ErrorCode = "UNAUTHORIZED"
	ErrCodeForbidden          ErrorCode = "FORBIDDEN"
	ErrCodeNotFound           ErrorCode = "NOT_FOUND"
	ErrCodeInvalidField       ErrorCode = "INVALID_FIELD"
	ErrCodeMissingField       ErrorCode = "MISSING_FIELD"
	ErrCodeInternalError      ErrorCode = "INTERNAL_ERROR"
	ErrCodeServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"
	ErrCodeConflict           ErrorCode = "CONFLICT"
	ErrCodeMethodNotAllowed   ErrorCode = "METHOD_NOT_ALLOWED"
	ErrCodeInvalidPath        ErrorCode = "INVALID_PATH"
	ErrCodeUpstreamError      ErrorCode = "UPSTREAM_ERROR"
)

type FileInput

type FileInput struct {
	Data        []byte
	Filename    string
	ContentType string
}

FileInput holds a file to be uploaded.

type GetChatsParams

type GetChatsParams struct {
	Limit  int
	Offset int
}

GetChatsParams holds the parameters for listing chats.

type InlineKeyboard

type InlineKeyboard struct {
	InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
}

InlineKeyboard renders buttons attached to a message.

type InlineKeyboardButton

type InlineKeyboardButton struct {
	Text         string  `json:"text"`
	CallbackData *string `json:"callback_data,omitempty"`
	URL          *string `json:"url,omitempty"`
}

InlineKeyboardButton is a button inside an inline keyboard.

type KappelaError

type KappelaError struct {
	// Message is the human-readable error description from the API.
	Message string
	// Code is the machine-readable error code.
	Code ErrorCode
	// Status is the HTTP status code.
	Status int
	// RequestID can be quoted when contacting support.
	RequestID string
}

KappelaError is returned when the Kappela API responds with an error.

func (*KappelaError) Error

func (e *KappelaError) Error() string

type Message

type Message struct {
	ID              int64           `json:"id"`
	ChatID          int64           `json:"chat_id"`
	SenderID        *string         `json:"sender_id"`
	Type            MessageType     `json:"type"`
	Text            *string         `json:"text"`
	MediaID         *string         `json:"media_id"`
	ExtraData       json.RawMessage `json:"extra_data"`
	Status          MessageStatus   `json:"status"`
	EditedAt        *int64          `json:"edited_at"`
	DeletedAt       *int64          `json:"deleted_at"`
	CreatedAt       int64           `json:"created_at"`
	ReplyToID       *int64          `json:"reply_to_id"`
	ReplyToSnapshot *ReplySnapshot  `json:"reply_to_snapshot"`
	Mentions        []string        `json:"mentions"`
	ForwardedFrom   json.RawMessage `json:"forwarded_from"`
	ExpiresAt       *int64          `json:"expires_at"`
	SenderName      *string         `json:"sender_name,omitempty"`
	SenderAvatarURL *string         `json:"sender_avatar_url,omitempty"`
	ClientMsgID     string          `json:"client_msg_id,omitempty"`
	Width           *int            `json:"width,omitempty"`
	Height          *int            `json:"height,omitempty"`
}

Message represents a Kappela chat message.

type MessageStatus

type MessageStatus string

MessageStatus is the delivery status of a message.

const (
	MessageStatusSent      MessageStatus = "sent"
	MessageStatusDelivered MessageStatus = "delivered"
	MessageStatusRead      MessageStatus = "read"
)

type MessageType

type MessageType string

MessageType is the content type of a message.

const (
	MessageTypeText     MessageType = "text"
	MessageTypeImage    MessageType = "image"
	MessageTypeVideo    MessageType = "video"
	MessageTypeAudio    MessageType = "audio"
	MessageTypeDocument MessageType = "document"
	MessageTypeSystem   MessageType = "system"
	MessageTypePoll     MessageType = "poll"
	MessageTypeSticker  MessageType = "sticker"
	MessageTypeLocation MessageType = "location"
	MessageTypeContact  MessageType = "contact"
)

type MessagesResource

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

MessagesResource provides methods to send and manage messages.

func (*MessagesResource) Delete

Delete deletes a message sent by this bot or user.

func (*MessagesResource) Edit

Edit edits the text or inline keyboard of a message sent by this bot or user.

func (*MessagesResource) Send

Send sends a text message, with optional inline buttons or keyboard.

func (*MessagesResource) SendAudio

func (r *MessagesResource) SendAudio(ctx context.Context, params SendMediaParams) (*SendMediaResult, error)

SendAudio sends an audio file.

func (*MessagesResource) SendCarousel

SendCarousel sends a product or card carousel.

func (*MessagesResource) SendDocument

func (r *MessagesResource) SendDocument(ctx context.Context, params SendMediaParams) (*SendMediaResult, error)

SendDocument sends a document or generic file.

func (*MessagesResource) SendPhoto

func (r *MessagesResource) SendPhoto(ctx context.Context, params SendMediaParams) (*SendMediaResult, error)

SendPhoto sends a photo (image file).

func (*MessagesResource) SendTyping

func (r *MessagesResource) SendTyping(ctx context.Context, params SendTypingParams) (*TypingResult, error)

SendTyping shows or hides the typing indicator in a chat. IsTyping defaults to true when not set.

func (*MessagesResource) SendVideo

func (r *MessagesResource) SendVideo(ctx context.Context, params SendMediaParams) (*SendMediaResult, error)

SendVideo sends a video file.

type Participant

type Participant struct {
	ID        string  `json:"id"`
	Nom       string  `json:"nom"`
	IsBot     bool    `json:"is_bot"`
	IsPremium bool    `json:"is_premium"`
	AvatarURL *string `json:"avatar_url"`
}

Participant is a member of a chat.

type PrivacySetting

type PrivacySetting string

PrivacySetting is a user privacy configuration value.

const (
	PrivacyEveryone PrivacySetting = "everyone"
	PrivacyContacts PrivacySetting = "contacts"
	PrivacyNobody   PrivacySetting = "nobody"
)

type ReplyKeyboard

type ReplyKeyboard struct {
	Keyboard [][]string `json:"keyboard"`
}

ReplyKeyboard renders a custom reply keyboard below the input field.

type ReplySnapshot

type ReplySnapshot struct {
	MessageID int64       `json:"message_id"`
	SenderID  *string     `json:"sender_id"`
	Type      MessageType `json:"type"`
	Text      *string     `json:"text"`
	MediaID   *string     `json:"media_id"`
}

ReplySnapshot is a lightweight snapshot of the message being replied to.

type ScrollKeyboard

type ScrollKeyboard struct {
	ScrollKeyboard []string `json:"scroll_keyboard"`
}

ScrollKeyboard renders a horizontally scrollable keyboard.

type SendCarouselParams

type SendCarouselParams struct {
	ChatID            int64          `json:"chat_id"`
	Text              string         `json:"text,omitempty"`
	Carousel          []CarouselCard `json:"carousel"`
	QuickReplyButtons []string       `json:"quick_reply_buttons,omitempty"`
}

SendCarouselParams holds the parameters for sending a product carousel.

type SendCarouselResult

type SendCarouselResult struct {
	MessageID int64  `json:"message_id"`
	CreatedAt int64  `json:"created_at"`
	Type      string `json:"type"`
}

SendCarouselResult is returned after sending a carousel.

type SendMediaParams

type SendMediaParams struct {
	ChatID         int64
	File           FileInput
	Caption        string
	ReplyToID      *int64
	DeletePrevious bool
	// ReplyMarkup accepts InlineKeyboard, ReplyKeyboard, or ScrollKeyboard.
	ReplyMarkup any
}

SendMediaParams holds the parameters for sending a photo, video, document, or audio.

type SendMediaResult

type SendMediaResult struct {
	MessageID int64  `json:"message_id"`
	CreatedAt int64  `json:"created_at"`
	MediaID   string `json:"media_id"`
}

SendMediaResult is returned after sending a media message.

type SendMessageParams

type SendMessageParams struct {
	ChatID int64  `json:"chat_id"`
	Text   string `json:"text"`
	// ReplyMarkup accepts InlineKeyboard, ReplyKeyboard, or ScrollKeyboard.
	ReplyMarkup    any    `json:"reply_markup,omitempty"`
	ReplyToID      *int64 `json:"reply_to_id,omitempty"`
	DeletePrevious bool   `json:"delete_previous,omitempty"`
}

SendMessageParams holds the parameters for sending a text message.

type SendResult

type SendResult struct {
	MessageID int64 `json:"message_id"`
	CreatedAt int64 `json:"created_at"`
}

SendResult is returned after sending a text message.

type SendTypingParams

type SendTypingParams struct {
	ChatID   int64 `json:"chat_id"`
	IsTyping *bool `json:"is_typing,omitempty"`
}

SendTypingParams holds the parameters for the typing indicator. IsTyping defaults to true when nil (show indicator). Set to false to hide it.

type SetWebhookParams

type SetWebhookParams struct {
	URL    string  `json:"url"`
	Secret *string `json:"secret,omitempty"`
}

SetWebhookParams holds the parameters for registering a webhook.

type TypingResult

type TypingResult struct {
	Typing bool `json:"typing"`
}

TypingResult is returned by the sendTyping endpoint.

type User

type User struct {
	// Messages provides methods to send and manage messages.
	Messages *MessagesResource
	// Chats provides methods to list and iterate over chats.
	Chats *ChatsResource
	// Webhooks provides methods to manage webhooks.
	Webhooks *WebhooksResource
	// Profile provides access to your own profile.
	Profile *UserProfileResource
	// contains filtered or unexported fields
}

User is the Kappela personal automation client. Authenticate with a personal API key (sk_...) to send messages and receive events as yourself.

Example:

me := kappelas.NewUser("sk_...")

me.OnMessage(func(msg *kappelas.Message) {
    fmt.Println("New message:", msg.Text)
})

me.Start()
select {}

func NewUser

func NewUser(apiKey string, opts ...UserOption) *User

NewUser creates a User authenticated with the given personal API key.

func (*User) Connected

func (u *User) Connected() bool

Connected reports whether the WebSocket is currently open.

func (*User) HandleWebhook

func (u *User) HandleWebhook(body []byte)

HandleWebhook processes a webhook payload sent by Kappela to your server.

Example (net/http):

http.HandleFunc("/kappela-webhook", func(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    me.HandleWebhook(body)
    w.WriteHeader(http.StatusOK)
})

func (*User) OnCallbackQuery

func (u *User) OnCallbackQuery(h func(*CallbackQuery))

OnCallbackQuery registers a handler called when a user clicks an inline button.

func (*User) OnConnected

func (u *User) OnConnected(h func())

OnConnected registers a handler called when the WebSocket connects (or reconnects).

func (*User) OnDisconnected

func (u *User) OnDisconnected(h func(code int, reason string))

OnDisconnected registers a handler called when the WebSocket disconnects.

func (*User) OnError

func (u *User) OnError(h func(error))

OnError registers a handler called on WebSocket or connection errors.

func (*User) OnMessage

func (u *User) OnMessage(h func(*Message))

OnMessage registers a handler called for every incoming message.

func (*User) Start

func (u *User) Start()

Start connects via WebSocket and begins receiving events in the background.

func (*User) Stop

func (u *User) Stop()

Stop closes the WebSocket connection.

type UserOption

type UserOption func(*userConfig)

UserOption configures a User.

func WithUserBaseURL

func WithUserBaseURL(u string) UserOption

WithUserBaseURL overrides the API base URL for a User client.

func WithUserMaxRetries

func WithUserMaxRetries(n int) UserOption

WithUserMaxRetries sets the maximum number of HTTP retry attempts for a User client.

func WithUserTimeout

func WithUserTimeout(d time.Duration) UserOption

WithUserTimeout sets the HTTP request timeout for a User client.

func WithUserWSMaxRetries

func WithUserWSMaxRetries(n int) UserOption

WithUserWSMaxRetries sets the maximum WebSocket reconnect attempts for a User client.

type UserProfile

type UserProfile struct {
	ID            string         `json:"id"`
	Username      string         `json:"username"`
	Nom           string         `json:"nom"`
	IsBot         bool           `json:"is_bot"`
	IsPremium     bool           `json:"is_premium"`
	AvatarURL     *string        `json:"avatar_url"`
	AllowGroupAdd PrivacySetting `json:"allow_group_add"`
	AllowCalls    PrivacySetting `json:"allow_calls"`
}

UserProfile is the profile returned for a personal account.

type UserProfileResource

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

UserProfileResource provides access to the user's own profile.

func (*UserProfileResource) Get

Get returns your own profile.

type WebhookDeleteResult

type WebhookDeleteResult struct {
	Active bool `json:"active"`
}

WebhookDeleteResult is returned after removing a webhook.

type WebhookInfo

type WebhookInfo struct {
	Active    bool    `json:"active"`
	URL       *string `json:"url"`
	CreatedAt *int64  `json:"created_at"`
}

WebhookInfo describes the current webhook configuration.

type WebhookSetResult

type WebhookSetResult struct {
	URL    string `json:"url"`
	Active bool   `json:"active"`
}

WebhookSetResult is returned after registering a webhook.

type WebhooksResource

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

WebhooksResource provides methods to manage webhooks.

func (*WebhooksResource) Delete

Delete removes the webhook. Events will no longer be delivered via HTTP POST.

func (*WebhooksResource) GetInfo

func (r *WebhooksResource) GetInfo(ctx context.Context) (*WebhookInfo, error)

GetInfo returns the current webhook status and URL.

func (*WebhooksResource) Set

Set registers a webhook URL. Use this for production deployments.

Jump to

Keyboard shortcuts

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