telegram

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2026 License: MIT Imports: 8 Imported by: 0

README

Telegram Bot API Connector for Go

A high-performance, stream-first Go client library for the Telegram Bot API. Built on top of httpstream, it enables zero-buffer, O(1) memory-overhead streaming uploads for media files (documents and photos).


Features

  • Stream-first uploads: Stream files (documents, images) directly from any io.Reader (e.g., S3 streams, file systems, HTTP response bodies) without buffering them in RAM.
  • Structured models: Native Go structures for common Telegram types (Message, Update, User, Chat, CallbackQuery, etc.).
  • Interactive keyboards: Built-in support for InlineKeyboardMarkup and ReplyKeyboardMarkup.
  • Flexible client configuration: Easily customize the underlying http.Client or the API base URL (useful for local Bot API servers or test mocks).

Installation

Add the package to your module:

go get github.com/nativebpm/connectors/telegram

Usage

1. Initializing the Client

By default, the client points to the official Telegram Bot API gateway:

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/nativebpm/connectors/telegram"
)

func main() {
	httpClient := &http.Client{
		Timeout: 30 * time.Second,
	}

	client, err := telegram.NewClient("YOUR_BOT_TOKEN", telegram.WithHTTPClient(httpClient))
	if err != nil {
		log.Fatalf("Failed to initialize client: %v", err)
	}
	
	// Ready to use client
}
2. Sending Messages (with Markup)
package main

import (
	"context"
	"log"

	"github.com/nativebpm/connectors/telegram"
)

func main() {
	client, _ := telegram.NewClient("YOUR_BOT_TOKEN")

	// Create an inline keyboard
	markup := telegram.NewInlineKeyboard().
		AddButtonRow("Approve Task", "action_approve").
		Build()

	msg, err := client.NewMessage(int64(123456789), "**New BPM Task**: Please review and approve the request.").
		ParseMode("MarkdownV2").
		ReplyMarkup(markup).
		Send(context.Background())
	if err != nil {
		log.Fatalf("Failed to send message: %v", err)
	}

	log.Printf("Sent message ID: %d", msg.MessageID)
}
3. Streaming File Uploads (Zero-Buffer)

Rather than reading whole files into memory ([]byte), you can stream them directly using io.Reader:

package main

import (
	"context"
	"log"
	"os"

	"github.com/nativebpm/connectors/telegram"
)

func main() {
	client, _ := telegram.NewClient("YOUR_BOT_TOKEN")

	// Open a file (implements io.Reader)
	file, err := os.Open("invoice.pdf")
	if err != nil {
		log.Fatalf("Failed to open file: %v", err)
	}
	defer file.Close()

	// Send document (streamed directly)
	msg, err := client.NewDocument(int64(123456789), file, "invoice.pdf").
		Caption("Here is your invoice PDF.").
		Send(context.Background())
	if err != nil {
		log.Fatalf("Failed to stream document: %v", err)
	}

	log.Printf("Uploaded file ID: %s", msg.Document.FileID)
}
4. Fetching Updates (Long-Polling)

Ideal for worker programs or local testing:

package main

import (
	"context"
	"log"

	"github.com/nativebpm/connectors/telegram"
)

func main() {
	client, _ := telegram.NewClient("YOUR_BOT_TOKEN")

	ctx := context.Background()
	err := client.StartPolling(ctx, func(ctx context.Context, update telegram.Update) {
		if text := update.MessageText(); text != "" {
			log.Printf("Received message from %s: %s", update.SenderFirstName(), text)
		}
	})
	if err != nil {
		log.Fatalf("Polling failed: %v", err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIResponse

type APIResponse struct {
	Ok          bool            `json:"ok"`
	Result      json.RawMessage `json:"result,omitempty"`
	Description string          `json:"description,omitempty"`
	ErrorCode   int             `json:"error_code,omitempty"`
}

APIResponse represents the standard response wrapper from the Telegram Bot API.

type AnswerCallbackQueryParams

type AnswerCallbackQueryParams struct {
	CallbackQueryID string `json:"callback_query_id"`
	Text            string `json:"text,omitempty"`
	ShowAlert       bool   `json:"show_alert,omitempty"`
	URL             string `json:"url,omitempty"`
	CacheTime       int    `json:"cache_time,omitempty"`
}

AnswerCallbackQueryParams represents parameters for AnswerCallbackQuery.

type CallbackQuery

type CallbackQuery struct {
	ID              string   `json:"id"`
	From            User     `json:"from"`
	Message         *Message `json:"message,omitempty"`
	InlineMessageID string   `json:"inline_message_id,omitempty"`
	ChatInstance    string   `json:"chat_instance"`
	Data            string   `json:"data,omitempty"`
}

CallbackQuery represents an incoming callback query from a callback button in an inline keyboard.

type Chat

type Chat struct {
	ID        int64  `json:"id"`
	Type      string `json:"type"` // "private", "group", "supergroup" or "channel"
	Title     string `json:"title,omitempty"`
	Username  string `json:"username,omitempty"`
	FirstName string `json:"first_name,omitempty"`
	LastName  string `json:"last_name,omitempty"`
}

Chat represents a Telegram chat.

type Client

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

Client represents a Telegram Bot API client.

func NewClient

func NewClient(token string, opts ...ClientOption) (*Client, error)

NewClient creates a new Telegram Bot API client.

func (*Client) AnswerCallbackQuery

func (c *Client) AnswerCallbackQuery(ctx context.Context, params *AnswerCallbackQueryParams) (bool, error)

AnswerCallbackQuery sends a response to an interactive callback query.

func (*Client) GetUpdates

func (c *Client) GetUpdates(ctx context.Context, params *GetUpdatesParams) ([]Update, error)

GetUpdates fetches updates using long-polling.

func (*Client) NewDocument

func (c *Client) NewDocument(chatID any, document io.Reader, filename string) *DocumentBuilder

NewDocument initializes a fluent builder for sending a document stream.

func (*Client) NewMessage

func (c *Client) NewMessage(chatID any, text string) *MessageBuilder

NewMessage initializes a fluent builder for sending a text message.

func (*Client) NewPhoto

func (c *Client) NewPhoto(chatID any, photo io.Reader, filename string) *PhotoBuilder

NewPhoto initializes a fluent builder for sending a photo stream.

func (*Client) SendDocument

func (c *Client) SendDocument(ctx context.Context, params *SendDocumentParams) (*Message, error)

SendDocument sends a general file. The file is streamed without complete buffering in memory.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, params *SendMessageParams) (*Message, error)

SendMessage sends a text message.

func (*Client) SendPhoto

func (c *Client) SendPhoto(ctx context.Context, params *SendPhotoParams) (*Message, error)

SendPhoto sends a photo. The image is streamed without complete buffering in memory.

func (*Client) SetWebhook

func (c *Client) SetWebhook(ctx context.Context, params *SetWebhookParams) (bool, error)

SetWebhook registers a webhook URL for receiving updates.

func (*Client) StartPolling

func (c *Client) StartPolling(ctx context.Context, handler func(ctx context.Context, update Update)) error

StartPolling starts a polling loop to receive updates. It blocks until the context is canceled.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption defines functional options for Client initialization.

func WithAPIURL

func WithAPIURL(url string) ClientOption

WithAPIURL sets a custom API URL (useful for self-hosted Bot API servers or mock testing).

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets a custom http.Client for the underlying requests.

type Document

type Document struct {
	FileID       string     `json:"file_id"`
	FileUniqueID string     `json:"file_unique_id"`
	Thumbnail    *PhotoSize `json:"thumbnail,omitempty"`
	FileName     string     `json:"file_name,omitempty"`
	MimeType     string     `json:"mime_type,omitempty"`
	FileSize     int64      `json:"file_size,omitempty"`
}

Document represents a general file (as opposed to photos, voice messages and audio files).

type DocumentBuilder

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

DocumentBuilder provides a fluent interface for building and streaming document uploads.

func (*DocumentBuilder) Caption

func (b *DocumentBuilder) Caption(caption string) *DocumentBuilder

Caption sets the document caption text.

func (*DocumentBuilder) DisableNotification

func (b *DocumentBuilder) DisableNotification(disable bool) *DocumentBuilder

DisableNotification sends the document silently.

func (*DocumentBuilder) ParseMode

func (b *DocumentBuilder) ParseMode(mode string) *DocumentBuilder

ParseMode sets the parse mode for the document caption.

func (*DocumentBuilder) ReplyMarkup

func (b *DocumentBuilder) ReplyMarkup(markup any) *DocumentBuilder

ReplyMarkup attaches a keyboard layout to the document.

func (*DocumentBuilder) ReplyTo

func (b *DocumentBuilder) ReplyTo(messageID int64) *DocumentBuilder

ReplyTo sets the ID of the message to reply to.

func (*DocumentBuilder) Send

func (b *DocumentBuilder) Send(ctx context.Context) (*Message, error)

Send executes the streaming request and returns the sent Message.

type GetUpdatesParams

type GetUpdatesParams struct {
	Offset         int64    `json:"offset,omitempty"`
	Limit          int      `json:"limit,omitempty"`
	Timeout        int      `json:"timeout,omitempty"`
	AllowedUpdates []string `json:"allowed_updates,omitempty"`
}

GetUpdatesParams represents parameters for GetUpdates.

type InlineKeyboardBuilder

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

InlineKeyboardBuilder provides a fluent builder for InlineKeyboardMarkup.

func NewInlineKeyboard

func NewInlineKeyboard() *InlineKeyboardBuilder

NewInlineKeyboard initializes a fluent inline keyboard builder.

func (*InlineKeyboardBuilder) AddButton

func (b *InlineKeyboardBuilder) AddButton(text, callbackData string) *InlineKeyboardBuilder

AddButton adds an inline button to the last row, or creates a new row if empty.

func (*InlineKeyboardBuilder) AddButtonRow

func (b *InlineKeyboardBuilder) AddButtonRow(text, callbackData string) *InlineKeyboardBuilder

AddButtonRow adds a new row containing a single callback button.

func (*InlineKeyboardBuilder) AddURLButton

func (b *InlineKeyboardBuilder) AddURLButton(text, url string) *InlineKeyboardBuilder

AddURLButton adds a URL inline button to the last row, or creates a new row if empty.

func (*InlineKeyboardBuilder) AddURLButtonRow

func (b *InlineKeyboardBuilder) AddURLButtonRow(text, url string) *InlineKeyboardBuilder

AddURLButtonRow adds a new row containing a single URL button.

func (*InlineKeyboardBuilder) Build

Build constructs and returns the InlineKeyboardMarkup structure.

type InlineKeyboardButton

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

InlineKeyboardButton represents one button of an inline keyboard.

type InlineKeyboardMarkup

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

InlineKeyboardMarkup represents an inline keyboard that appears right next to the message it belongs to.

type KeyboardButton

type KeyboardButton struct {
	Text string `json:"text"`
}

KeyboardButton represents one button of the reply keyboard.

type Message

type Message struct {
	MessageID  int64       `json:"message_id"`
	From       *User       `json:"from,omitempty"`
	SenderChat *Chat       `json:"sender_chat,omitempty"`
	Date       int64       `json:"date"`
	Chat       Chat        `json:"chat"`
	Text       string      `json:"text,omitempty"`
	Photo      []PhotoSize `json:"photo,omitempty"`
	Document   *Document   `json:"document,omitempty"`
}

Message represents a Telegram message.

type MessageBuilder

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

MessageBuilder provides a fluent interface for building and sending text messages.

func (*MessageBuilder) DisableNotification

func (b *MessageBuilder) DisableNotification(disable bool) *MessageBuilder

DisableNotification sends the message silently without sound alerts.

func (*MessageBuilder) DisableWebPagePreview

func (b *MessageBuilder) DisableWebPagePreview(disable bool) *MessageBuilder

DisableWebPagePreview disables the preview of links in the message.

func (*MessageBuilder) ParseMode

func (b *MessageBuilder) ParseMode(mode string) *MessageBuilder

ParseMode sets the message parsing mode (e.g., "HTML", "Markdown", "MarkdownV2").

func (*MessageBuilder) ReplyMarkup

func (b *MessageBuilder) ReplyMarkup(markup any) *MessageBuilder

ReplyMarkup attaches an inline keyboard or reply keyboard.

func (*MessageBuilder) ReplyTo

func (b *MessageBuilder) ReplyTo(messageID int64) *MessageBuilder

ReplyTo sets the ID of the message to reply to.

func (*MessageBuilder) Send

func (b *MessageBuilder) Send(ctx context.Context) (*Message, error)

Send executes the request and returns the sent Message.

type PhotoBuilder

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

PhotoBuilder provides a fluent interface for building and streaming photo uploads.

func (*PhotoBuilder) Caption

func (b *PhotoBuilder) Caption(caption string) *PhotoBuilder

Caption sets the photo caption text.

func (*PhotoBuilder) DisableNotification

func (b *PhotoBuilder) DisableNotification(disable bool) *PhotoBuilder

DisableNotification sends the photo silently.

func (*PhotoBuilder) ParseMode

func (b *PhotoBuilder) ParseMode(mode string) *PhotoBuilder

ParseMode sets the parse mode for the photo caption.

func (*PhotoBuilder) ReplyMarkup

func (b *PhotoBuilder) ReplyMarkup(markup any) *PhotoBuilder

ReplyMarkup attaches a keyboard layout to the photo.

func (*PhotoBuilder) ReplyTo

func (b *PhotoBuilder) ReplyTo(messageID int64) *PhotoBuilder

ReplyTo sets the ID of the message to reply to.

func (*PhotoBuilder) Send

func (b *PhotoBuilder) Send(ctx context.Context) (*Message, error)

Send executes the streaming request and returns the sent Message.

type PhotoSize

type PhotoSize struct {
	FileID       string `json:"file_id"`
	FileUniqueID string `json:"file_unique_id"`
	Width        int    `json:"width"`
	Height       int    `json:"height"`
	FileSize     int64  `json:"file_size,omitempty"`
}

PhotoSize represents one size of a photo or a file / sticker photo.

type ReplyKeyboardBuilder

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

ReplyKeyboardBuilder provides a fluent builder for ReplyKeyboardMarkup.

func NewReplyKeyboard

func NewReplyKeyboard() *ReplyKeyboardBuilder

NewReplyKeyboard initializes a fluent reply keyboard builder.

func (*ReplyKeyboardBuilder) AddButton

func (b *ReplyKeyboardBuilder) AddButton(text string) *ReplyKeyboardBuilder

AddButton adds a keyboard button to the last row, or creates a new row if empty.

func (*ReplyKeyboardBuilder) AddButtonRow

func (b *ReplyKeyboardBuilder) AddButtonRow(text string) *ReplyKeyboardBuilder

AddButtonRow adds a new row containing a single reply keyboard button.

func (*ReplyKeyboardBuilder) Build

Build constructs and returns the ReplyKeyboardMarkup structure.

func (*ReplyKeyboardBuilder) OneTimeKeyboard

func (b *ReplyKeyboardBuilder) OneTimeKeyboard(oneTime bool) *ReplyKeyboardBuilder

OneTimeKeyboard requests clients to hide the keyboard as soon as it's been used.

func (*ReplyKeyboardBuilder) ResizeKeyboard

func (b *ReplyKeyboardBuilder) ResizeKeyboard(resize bool) *ReplyKeyboardBuilder

ResizeKeyboard requests clients to resize the keyboard vertically for optimal fit.

type ReplyKeyboardMarkup

type ReplyKeyboardMarkup struct {
	Keyboard        [][]KeyboardButton `json:"keyboard"`
	ResizeKeyboard  bool               `json:"resize_keyboard,omitempty"`
	OneTimeKeyboard bool               `json:"one_time_keyboard,omitempty"`
}

ReplyKeyboardMarkup represents a custom keyboard with reply options.

type ReplyParameters

type ReplyParameters struct {
	MessageID int64 `json:"message_id"`
}

ReplyParameters describes reply parameters for the message.

type SendDocumentParams

type SendDocumentParams struct {
	ChatID              any              // int64 or string
	Document            io.Reader        // streamed file
	Filename            string           // filename for multipart form
	Caption             string           // optional caption
	ParseMode           string           // optional parse mode for caption
	DisableNotification bool             // optional
	ReplyParameters     *ReplyParameters // optional
	ReplyMarkup         any              // optional
}

SendDocumentParams represents parameters for SendDocument.

type SendMessageParams

type SendMessageParams struct {
	ChatID                any              `json:"chat_id"` // int64 or string (username/channel)
	Text                  string           `json:"text"`
	ParseMode             string           `json:"parse_mode,omitempty"`
	DisableWebPagePreview bool             `json:"disable_web_page_preview,omitempty"`
	DisableNotification   bool             `json:"disable_notification,omitempty"`
	ReplyParameters       *ReplyParameters `json:"reply_parameters,omitempty"`
	ReplyMarkup           any              `json:"reply_markup,omitempty"` // InlineKeyboardMarkup, ReplyKeyboardMarkup, etc.
}

SendMessageParams represents parameters for SendMessage.

type SendPhotoParams

type SendPhotoParams struct {
	ChatID              any              // int64 or string
	Photo               io.Reader        // streamed image
	Filename            string           // filename for multipart form (e.g. photo.jpg)
	Caption             string           // optional caption
	ParseMode           string           // optional parse mode for caption
	DisableNotification bool             // optional
	ReplyParameters     *ReplyParameters // optional
	ReplyMarkup         any              // optional
}

SendPhotoParams represents parameters for SendPhoto.

type SetWebhookParams

type SetWebhookParams struct {
	URL            string   `json:"url"`
	IPAddress      string   `json:"ip_address,omitempty"`
	MaxConnections int      `json:"max_connections,omitempty"`
	AllowedUpdates []string `json:"allowed_updates,omitempty"`
}

SetWebhookParams represents parameters for SetWebhook.

type Update

type Update struct {
	UpdateID      int64          `json:"update_id"`
	Message       *Message       `json:"message,omitempty"`
	CallbackQuery *CallbackQuery `json:"callback_query,omitempty"`
}

Update represents an incoming update from Telegram.

func (Update) CallbackData

func (u Update) CallbackData() string

CallbackData returns the data associated with the callback query if available, otherwise an empty string.

func (Update) CallbackID

func (u Update) CallbackID() string

CallbackID returns the callback query ID if available, otherwise an empty string.

func (Update) ChatID

func (u Update) ChatID() int64

ChatID returns the chat ID for the update if available, otherwise 0.

func (Update) MessageText

func (u Update) MessageText() string

MessageText returns the text of the message if available, otherwise an empty string.

func (Update) SenderFirstName

func (u Update) SenderFirstName() string

SenderFirstName returns the first name of the sender if available, otherwise an empty string.

type User

type User struct {
	ID        int64  `json:"id"`
	IsBot     bool   `json:"is_bot"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name,omitempty"`
	Username  string `json:"username,omitempty"`
}

User represents a Telegram user or bot.

Directories

Path Synopsis
examples
polling command
send_document command
send_message command

Jump to

Keyboard shortcuts

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