Documentation
¶
Index ¶
- Constants
- Variables
- func AsBot(botToken string) clientType
- func AsUser(phoneNumber string) clientType
- func ClientTypeBot(botToken string) clientType
- func ClientTypePhone(phoneNumber string) clientType
- func SendAuthStatus(conversator AuthConversator, event AuthStatusEvent)
- func SendAuthStatusWithRetrials(conversator AuthConversator, event AuthStatusEvent, attemptsLeft int)
- func Simple() clientType
- type AuthConversator
- type AuthStatus
- type AuthStatusEvent
- type Client
- func (c *Client) CreateContext() *adapter.Context
- func (c *Client) ExportSessionAsGramjs() (string, error)
- func (c *Client) ExportSessionAsMtcute() (string, error)
- func (c *Client) ExportSessionAsPyrogram() (string, error)
- func (c *Client) ExportSessionAsTelethon() (string, error)
- func (c *Client) ExportStringSession() (string, error)
- func (c *Client) Idle() error
- func (c *Client) RefreshContext(ctx *adapter.Context)
- func (c *Client) Start(opts *ClientOpts) error
- func (c *Client) Stop()
- type ClientOpts
- type Flow
- type FlowClient
- type KeyboardBuilder
- func (k *KeyboardBuilder) Build() tg.ReplyMarkupClass
- func (k *KeyboardBuilder) BuildReply(opts ...ReplyOptions) tg.ReplyMarkupClass
- func (k *KeyboardBuilder) Button(text, data string) *KeyboardBuilder
- func (k *KeyboardBuilder) Buy(text string) *KeyboardBuilder
- func (k *KeyboardBuilder) Copy(text, copyText string) *KeyboardBuilder
- func (k *KeyboardBuilder) Danger() *KeyboardBuilder
- func (k *KeyboardBuilder) Game(text string) *KeyboardBuilder
- func (k *KeyboardBuilder) Icon(icon int64) *KeyboardBuilder
- func (k *KeyboardBuilder) Next() *KeyboardBuilder
- func (k *KeyboardBuilder) Primary() *KeyboardBuilder
- func (k *KeyboardBuilder) RequestGeo(text string) *KeyboardBuilder
- func (k *KeyboardBuilder) RequestPhone(text string) *KeyboardBuilder
- func (k *KeyboardBuilder) RequestPoll(text string, quiz bool) *KeyboardBuilder
- func (k *KeyboardBuilder) Success() *KeyboardBuilder
- func (k *KeyboardBuilder) Switch(text string, samePeer bool, query string) *KeyboardBuilder
- func (k *KeyboardBuilder) Text(text string) *KeyboardBuilder
- func (k *KeyboardBuilder) URL(text, url string) *KeyboardBuilder
- func (k *KeyboardBuilder) WebApp(text, url string) *KeyboardBuilder
- type RecaptchaSolver
- type ReplyOptions
Constants ¶
const VERSION = "v1.0.0-beta23"
Variables ¶
var ( AuthStatusPhoneAsked = AuthStatusEvent("phone number asked") AuthStatusPhoneRetrial = AuthStatusEvent("phone number validation retrial") AuthStatusPhoneFailed = AuthStatusEvent("phone number validation failed") AuthStatusPhoneCodeAsked = AuthStatusEvent("phone otp asked") AuthStatusPhoneCodeVerified = AuthStatusEvent("phone code verified") AuthStatusPhoneCodeRetrial = AuthStatusEvent("phone code verification retrial") AuthStatusPhoneCodeFailed = AuthStatusEvent("phone code verification failed") AuthStatusPasswordAsked = AuthStatusEvent("2fa password asked") AuthStatusPasswordRetrial = AuthStatusEvent("2fa password verification retrial") AuthStatusPasswordFailed = AuthStatusEvent("2fa password verification failed") AuthStatusSuccess = AuthStatusEvent("authentification success") )
Functions ¶
func AsUser ¶
func AsUser(phoneNumber string) clientType
AsUser is a simpler alias for ClientTypePhone
func ClientTypeBot ¶
func ClientTypeBot(botToken string) clientType
func ClientTypePhone ¶
func ClientTypePhone(phoneNumber string) clientType
func SendAuthStatus ¶
func SendAuthStatus(conversator AuthConversator, event AuthStatusEvent)
SendAuthStatus sends an authentication status event to the conversator.
This is used to inform the user about the current state of the authentication process (phone number, OTP, password, etc.).
Parameters:
- conversator: The conversator to send the status to
- event: The authentication status event containing status and attempts info
Example:
SendAuthStatus(conversator, gotg.AuthStatusPhoneAsked)
func SendAuthStatusWithRetrials ¶
func SendAuthStatusWithRetrials(conversator AuthConversator, event AuthStatusEvent, attemptsLeft int)
SendAuthStatusWithRetrials sends an authentication status event with retry count.
This extends SendAuthStatus by including the number of attempts remaining before the authentication process should be considered failed.
Parameters:
- conversator: The conversator to send the status to
- event: The authentication status event containing status info
- attemptsLeft: Number of authentication attempts remaining
Example:
SendAuthStatusWithRetrials(conversator, gotg.AuthStatusPhoneAsked, 2)
Types ¶
type AuthConversator ¶
type AuthConversator interface {
// AskPhoneNumber is called to ask user for phone number.
// phone number to login should be returned.
AskPhoneNumber() (string, error)
// AskCode is called to ask user for OTP.
// OTP should be returned.
AskCode() (string, error)
// AskPassword is called to ask user for 2FA password.
// 2FA password should be returned.
AskPassword() (string, error)
// SendAuthStatus is called to inform the user about
// the status of the auth process.
// attemptsLeft is the number of attempts left for the user
// to enter the input correctly for the current auth status.
AuthStatus(authStatus AuthStatus)
}
AuthConversator is an interface for asking user for auth information.
func BasicConversator ¶
func BasicConversator() AuthConversator
BasicConversator creates a simple conversator for terminal-based authentication.
This conversator uses standard input/output (stdio/stdout and stdin) to collect user authentication information interactively.
Returns:
- An AuthConversator implementation that uses terminal I/O
Example:
conversator := gotg.BasicConversator()
type AuthStatus ¶
type AuthStatus struct {
Event AuthStatusEvent
AttemptsLeft int
SentCodeType tg.AuthSentCodeTypeClass
}
type AuthStatusEvent ¶
type AuthStatusEvent string
type Client ¶
type Client struct {
// Dispatcher handlers the incoming updates and execute mapped handlers. It is recommended to use dispatcher.MakeDispatcher function for this field.
Dispatcher dispatcher.Dispatcher
ConvManager *conv.Manager
// PublicKeys of telegram.
//
// If not provided, embedded public keys will be used.
PublicKeys []telegram.PublicKey
// DC ID to connect.
//
// If not provided, 2 will be used by default.
DC int
// DCList is initial list of addresses to connect.
DCList dcs.List
// Resolver to use.
Resolver dcs.Resolver
// MigrationTimeout configures migration timeout.
MigrationTimeout time.Duration
// AckBatchSize is limit of MTProto ACK buffer size.
AckBatchSize int
// AckInterval is maximum time to buffer MTProto ACK.
AckInterval time.Duration
// RetryInterval is duration between send retries.
RetryInterval time.Duration
// MaxRetries is limit of send retries.
MaxRetries int
// ExchangeTimeout is timeout of every key exchange request.
ExchangeTimeout time.Duration
// DialTimeout is timeout of creating connection.
DialTimeout time.Duration
// CompressThreshold is a threshold in bytes to determine that message
// is large enough to be compressed using GZIP.
// If < 0, compression will be disabled.
// If == 0, default value will be used.
CompressThreshold int
// Whether to show the copyright line in console or no.
DisableCopyright bool
Logger *gotglog.Logger
// Self contains details of logged in user in the form of *tg.User.
Self *tg.User
// Code for the language used on the device's OS, ISO 639-1 standard.
SystemLangCode string
// Code for the language used on the client, ISO 639-1 standard.
ClientLangCode string
// PeerStorage is the storage for all the peers.
// It is recommended to use storage.NewPeerStorage function for this field.
PeerStorage *storage.PeerStorage
// NoAutoAuth is a flag to disable automatic authentication
// if the current session is invalid.
NoAutoAuth bool
// NoUpdates is a flag to disable updates.
NoUpdates bool
*telegram.Client
// contains filtered or unexported fields
}
func NewClient ¶
func NewClient(apiID int, apiHash string, clientType clientType, opts *ClientOpts) (*Client, error)
NewClient creates a new gotg client and logs in to telegram.
func (*Client) CreateContext ¶
CreateContext creates a new pseudo updates context. A context retrieved from this method should be reused.
func (*Client) ExportSessionAsGramjs ¶
ExportSessionAsGramjs exports the current session as a GramJS-compatible string.
The GramJS session string contains DC ID, server address, port, and auth key.
Note: You must not share this string with anyone, it contains auth details for your logged-in account.
func (*Client) ExportSessionAsMtcute ¶
ExportSessionAsMtcute exports the current session as an mtcute v3-compatible string.
The mtcute session string contains DC info, optional user info, and auth key using TL-style binary serialization with URL-safe base64 encoding.
Note: You must not share this string with anyone, it contains auth details for your logged-in account.
func (*Client) ExportSessionAsPyrogram ¶
ExportSessionAsPyrogram exports the current session as a Pyrogram-compatible string.
The Pyrogram session string contains DC ID, App ID, test mode flag, auth key, user ID, and bot status.
Note: You must not share this string with anyone, it contains auth details for your logged-in account.
func (*Client) ExportSessionAsTelethon ¶
ExportSessionAsTelethon exports the current session as a Telethon-compatible string.
The Telethon session string contains DC ID, IP address, port, and auth key.
Note: You must not share this string with anyone, it contains auth details for your logged-in account.
func (*Client) ExportStringSession ¶
ExportStringSession EncodeSessionToString encodes the client session to a string in base64.
Note: You must not share this string with anyone, it contains auth details for your logged in account.
func (*Client) RefreshContext ¶
RefreshContext casts the new context.Context and telegram session to ext.Context (It may be used after doing Stop and Start calls respectively.)
func (*Client) Start ¶
func (c *Client) Start(opts *ClientOpts) error
Start connects the client to telegram servers and logins. It will return error if the client is already running.
type ClientOpts ¶
type ClientOpts struct {
// Whether to store session and peer storage in memory or not
//
// Note: Sessions and Peers won't be persistent if this field is set to true.
InMemory bool
// PublicKeys of telegram.
//
// If not provided, embedded public keys will be used.
PublicKeys []telegram.PublicKey
// DC ID to connect.
//
// If not provided, 2 will be used by default.
DC int
// DCList is initial list of addresses to connect.
DCList dcs.List
// Resolver to use.
Resolver dcs.Resolver
// Whether to show the copyright line in console or no.
DisableCopyright bool
// Session info of the authenticated user, use session.NewSession function to fill this field.
Session session.SessionConstructor
// Setting this field to true will lead to automatically fetch the reply_to_message for a new message update.
//
// Set to `false` by default.
AutoFetchReply bool
// Setting this field to true will lead to automatically fetch the entire reply_to_message chain for a new message update.
//
// Set to `false` by default.
FetchEntireReplyChain bool
// Code for the language used on the device's OS, ISO 639-1 standard.
SystemLangCode string
// Code for the language used on the client, ISO 639-1 standard.
ClientLangCode string
// Custom client device
Device *telegram.DeviceConfig
// Panic handles all the panics that occur during handler execution.
PanicHandler dispatcher.PanicHandler
// Error handles all the unknown errors which are returned by the handler callback functions.
ErrorHandler dispatcher.ErrorHandler
// Custom Middlewares
Middlewares []telegram.Middleware
// DispatcherMiddlewares are middleware handlers that run before user-added handlers.
// These are automatically added to groups 0, 1, 2, ... in order.
// Useful for i18n, authentication, logging, etc.
DispatcherMiddlewares []dispatcher.Handler
// Custom Run() Middleware
// Can be used for floodWaiter package
// https://github.com/pageton/gotg/blob/beta/examples/middleware/main.go#L41
RunMiddleware func(
origRun func(ctx context.Context, f func(ctx context.Context) error) (err error),
ctx context.Context,
f func(ctx context.Context) (err error),
) (err error)
// A custom context to use for the client.
// If not provided, context.Background() will be used.
// Note: This context will be used for the entire lifecycle of the client.
Context context.Context
// AuthConversator is the interface for the authenticator.
// gotg.BasicConversator is used by default.
AuthConversator AuthConversator
// MigrationTimeout configures migration timeout.
MigrationTimeout time.Duration
// AckBatchSize is limit of MTProto ACK buffer size.
AckBatchSize int
// AckInterval is maximum time to buffer MTProto ACK.
AckInterval time.Duration
// RetryInterval is duration between send retries.
RetryInterval time.Duration
// MaxRetries is limit of send retries.
MaxRetries int
// ExchangeTimeout is timeout of every key exchange request.
ExchangeTimeout time.Duration
// DialTimeout is timeout of creating connection.
DialTimeout time.Duration
// CompressThreshold is a threshold in bytes to determine that message
// is large enough to be compressed using GZIP.
// If < 0, compression will be disabled.
// If == 0, default value will be used.
CompressThreshold int
// NoAutoAuth is a flag to disable automatic authentication
// if the current session is invalid.
NoAutoAuth bool
// NoUpdates is a flag to disable updates.
NoUpdates bool
// SendOutgoing enables synthetic outgoing updates for send/edit/delete.
// When true, sent messages are re-dispatched through handlers with Out=true.
SendOutgoing bool
// LogConfig configures the built-in gotg logger attached to each Update.
// If nil, DefaultConfig() is used (info level, color, timestamps, no caller).
LogConfig *gotglog.Config
// SendCodeOptions allows overriding AuthSendCode behavior.
SendCodeOptions *auth.SendCodeOptions
// Only usable by Users not bots
// PeersFromDialogs is a flag to enable adding peers fetched
// from dialogs to memory/database on startup
PeersFromDialogs bool
// WaitOnPeersFromDialogs is a flag to enable waiting on
// PeersFromDialogs to complete during client start
WaitOnPeersFromDialogs bool
// MaxConcurrentUpdates limits parallel update handler goroutines.
// Default 1000 when 0.
MaxConcurrentUpdates int
// ParseMode sets the default parse mode for all message sending methods.
// If empty, no formatting is applied unless explicitly specified per-method.
// Supported values: "HTML", "Markdown", "MarkdownV2", or "" (none).
ParseMode string
}
type Flow ¶
Flow wraps auth.Flow to add custom sign-up handling. It extends the standard Telegram authentication flow with support for interactive sign-up prompts when required.
type FlowClient ¶
type FlowClient struct {
auth.FlowClient
// contains filtered or unexported fields
}
func (FlowClient) SendCode ¶
func (c FlowClient) SendCode(ctx context.Context, phone string, opts auth.SendCodeOptions) (tg.AuthSentCodeClass, error)
type KeyboardBuilder ¶
type KeyboardBuilder struct {
// contains filtered or unexported fields
}
KeyboardBuilder provides a fluent interface for constructing Telegram keyboards.
KeyboardBuilder supports both inline keyboards (for callback buttons, URLs, etc.) and reply keyboards (for regular text buttons that appear above the input field).
The builder uses a row-based approach where buttons are added to the current row, and the Next() method moves to the next row. The final keyboard is built using either Build() for inline keyboards or BuildReply() for reply keyboards.
Example (inline keyboard):
keyboard := gotg.Keyboard().
Button("Button 1", "data1").
Button("Button 2", "data2").
Next().
URL("Visit", "https://example.com").
Build()
Example (reply keyboard):
keyboard := gotg.Keyboard().
Text("Option 1").
Text("Option 2").
Next().
RequestPhone("Share Phone").
BuildReply(gotg.ReplyOptions{Resize: true})
func Keyboard ¶
func Keyboard() *KeyboardBuilder
Keyboard creates a new KeyboardBuilder instance for constructing Telegram keyboards.
The returned builder is initialized with empty rows and can be used to build both inline and reply keyboards through method chaining.
Returns a new KeyboardBuilder ready for button construction.
Example:
builder := gotg.Keyboard()
keyboard := builder.
Button("Click me", "callback_data").
Next().
Text("Another").
Build()
func (*KeyboardBuilder) Build ¶
func (k *KeyboardBuilder) Build() tg.ReplyMarkupClass
Build constructs an inline keyboard from the configured buttons.
Inline keyboards appear directly below the message and remain visible as the user scrolls. They are ideal for contextual actions, navigation, and interactive interfaces. Inline keyboards support callback buttons, URL buttons, and other inline-specific button types.
The returned tg.ReplyMarkupClass can be used when sending or editing messages via the reply markup parameter.
Returns a tg.ReplyInlineMarkup containing the configured rows, or nil if no buttons were added to the builder.
Example:
// Build an inline keyboard with callback and URL buttons
keyboard := gotg.Keyboard().
Button("View Details", "view_123").
Button("Delete", "delete_123").
Next().
URL("Website", "https://example.com").
Next().
Switch("Share", false, "share_123").
Build()
// Use the keyboard when sending a message
_, err := ctx.SendMessage(ctx, &tg.MessagesSendMessageRequest{
Peer: peer,
Message: "Choose an action:",
ReplyMarkup: keyboard,
})
Supported button types for inline keyboards: - Button() - Callback buttons (trigger OnCallbackQuery handlers) - URL() - Open a web link - Switch() - Switch to inline mode - Copy() - Copy text to clipboard - Game() - Launch an HTML5 game - Buy() - Payment button - WebApp() - Open a Telegram Mini App - Text() - Send text as a message (not recommended, use Button instead)
Note: For reply keyboards (which appear above the input field), use BuildReply() instead. RequestPhone, RequestGeo, and RequestPoll buttons are not supported in inline keyboards.
func (*KeyboardBuilder) BuildReply ¶
func (k *KeyboardBuilder) BuildReply(opts ...ReplyOptions) tg.ReplyMarkupClass
BuildReply constructs a reply keyboard from the configured buttons.
Reply keyboards appear above the message input field in the Telegram app and provide quick access to commands or actions. Unlike inline keyboards, reply keyboard buttons send their text as regular messages when tapped.
The returned tg.ReplyMarkupClass can be used when sending or editing messages via the reply markup parameter. To hide a reply keyboard, send a keyboard with ReplyKeyboardForceEmpty or use context.RemoveReplyKeyboard().
Parameters:
- opts: Optional ReplyOptions to configure keyboard behavior (resize, one-time, etc.). If omitted, default options are used.
Returns a tg.ReplyKeyboardMarkup containing the configured rows and options, or nil if no buttons were added to the builder.
Example:
// Basic reply keyboard
keyboard := gotg.Keyboard().
Text("Start").
Text("Help").
Next().
Text("Settings").
BuildReply()
// Reply keyboard with options
keyboard := gotg.Keyboard().
Text("Yes").
Text("No").
RequestPhone("Share Phone").
BuildReply(gotg.ReplyOptions{
Resize: true, // Smaller keyboard
OneTime: true, // Hide after selection
Placeholder: "Choose: Yes or No",
})
// Use the keyboard when sending a message
_, err := ctx.SendMessage(ctx, &tg.MessagesSendMessageRequest{
Peer: peer,
Message: "Please choose an option:",
ReplyMarkup: keyboard,
})
Supported button types for reply keyboards: - Text() - Send text as a message - RequestPhone() - Request the user's phone number - RequestGeo() - Request the user's location - RequestPoll() - Create a poll or quiz - WebApp() - Open a Telegram Mini App
Note: For inline keyboards (which appear below the message), use Build() instead. Callback buttons (Button()), URL buttons (URL()), and Switch buttons are not supported in reply keyboards.
To hide a reply keyboard after it's been shown:
_, err := ctx.SendMessage(ctx, &tg.MessagesSendMessageRequest{
Peer: peer,
Message: "Keyboard hidden",
ReplyMarkup: &tg.ReplyKeyboardHide{},
})
func (*KeyboardBuilder) Button ¶
func (k *KeyboardBuilder) Button(text, data string) *KeyboardBuilder
Button adds a callback button with data payload to the keyboard.
Callback buttons are designed for inline keyboards (built with Build). When tapped, they trigger a callback query that your bot can handle via OnCallbackQuery. The data parameter is passed back to your bot, allowing you to identify which button was clicked and take appropriate action.
The data parameter is limited to 64 bytes in Telegram's API.
Parameters:
- text: The label text to display on the button
- data: The callback data to send when the button is tapped (max 64 bytes)
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Button("Approve", "approve_123").
Button("Reject", "reject_123").
Next().
Button("View Details", "details_123").
Build()
Handling the callback:
dispatcher.OnCallbackQuery(func(ctx *context.Context, u *context.Update) error {
data := string(u.CallbackQuery.Data)
// data will be "approve_123", "reject_123", or "details_123"
return u.Answer("Received: " + data)
})
func (*KeyboardBuilder) Buy ¶
func (k *KeyboardBuilder) Buy(text string) *KeyboardBuilder
Buy adds a payment button to the keyboard.
Buy buttons are used with Telegram's payment API. When tapped, the user is prompted to complete a payment flow. The bot must have a payment provider configured via @BotFather.
Parameters:
- text: The label text to display on the button
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Buy("Pay $9.99").
Build()
func (*KeyboardBuilder) Copy ¶
func (k *KeyboardBuilder) Copy(text, copyText string) *KeyboardBuilder
Copy adds a button that copies text to the user's clipboard when tapped.
Copy buttons are designed for inline keyboards. When tapped, Telegram copies the specified text to the user's clipboard and shows a confirmation notification. The button text remains on the screen and can be tapped multiple times.
This is useful for sharing codes, tokens, addresses, or any text that the user might need to paste elsewhere.
Parameters:
- text: The label text to display on the button
- copyText: The text that will be copied to the clipboard when tapped
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Copy("Copy invite link", "https://t.me/examplebot?start=abc123").
Copy("Copy promo code", "SAVE20").
Next().
Copy("Copy address", "0x1234567890abcdef").
Build()
Note: The copyText can be different from the button label, allowing you to display user-friendly text while copying technical content like URLs or codes.
func (*KeyboardBuilder) Danger ¶
func (k *KeyboardBuilder) Danger() *KeyboardBuilder
Danger applies danger background color style to the last added button.
Danger style is used for destructive actions like delete or cancel. Can be chained after any button method — works on all button types.
Returns: builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Button("Delete", "delete").Danger().
Build()
func (*KeyboardBuilder) Game ¶
func (k *KeyboardBuilder) Game(text string) *KeyboardBuilder
Game adds an HTML5 game button to the keyboard.
Game buttons launch a Telegram HTML5 game when tapped. The bot must have a game registered via @BotFather. When pressed, Telegram opens the game interface for the user.
Parameters:
- text: The label text to display on the button
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Game("Play Now").
Build()
func (*KeyboardBuilder) Icon ¶
func (k *KeyboardBuilder) Icon(icon int64) *KeyboardBuilder
Icon applies a custom emoji icon to the last added button's style.
Use Telegram custom emoji document IDs (int64). Can be chained after any button method — works on all button types.
Returns: builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Button("OK", "ok").Icon(5368324170671202286).
Build()
func (*KeyboardBuilder) Next ¶
func (k *KeyboardBuilder) Next() *KeyboardBuilder
Next moves to the next row in the keyboard layout.
Telegram keyboards are organized into rows of buttons. The Next() method finalizes the current row and starts a new empty row. Any buttons added after calling Next() will appear in the next row of the keyboard.
If the current row is empty (no buttons added since the last Next() or since the builder was created), this method does nothing and returns the builder unchanged.
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Button("Row 1, Col 1", "r1c1").
Button("Row 1, Col 2", "r1c2").
Next(). // Move to row 2
Button("Row 2, Col 1", "r2c1").
Next(). // Move to row 3
Button("Row 3, Col 1", "r3c1").
Button("Row 3, Col 2", "r3c2").
Button("Row 3, Col 3", "r3c3").
Build()
Note: The Build() and BuildReply() methods automatically call Next() to finalize the last row, so you don't need to call it explicitly before building.
func (*KeyboardBuilder) Primary ¶
func (k *KeyboardBuilder) Primary() *KeyboardBuilder
Primary applies primary background color style to the last added button.
Primary style highlights the main action or confirmation button. Can be chained after any button method — works on all button types.
Returns: builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Button("Confirm", "confirm").Primary().
Button("Cancel", "cancel").Danger().
Build()
func (*KeyboardBuilder) RequestGeo ¶
func (k *KeyboardBuilder) RequestGeo(text string) *KeyboardBuilder
RequestGeo adds a button that requests the user's geolocation.
Location request buttons are designed for reply keyboards (built with BuildReply). When tapped, the user will be prompted to share their current location with the bot. The user can choose to share their location or cancel the request.
These buttons are commonly used for location-based features such as finding nearby places, delivery services, or location-aware content. Telegram handles the location request UI, ensuring a consistent user experience.
Only one location request button can exist per keyboard. Adding more than one may result in undefined behavior.
Parameters:
- text: The label text to display on the button (e.g., "Send Location")
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Text("Enter manually").
RequestGeo("Send Location").
BuildReply(gotg.ReplyOptions{Resize: true})
Handling the location:
dispatcher.OnMessage(func(ctx *context.Context, u *context.Update) error {
if m, ok := u.EffectiveMessage(); ok {
if geo := m.Geo(); ok {
lat := geo.Lat
long := geo.Long
// Process the coordinates
}
}
return nil
})
func (*KeyboardBuilder) RequestPhone ¶
func (k *KeyboardBuilder) RequestPhone(text string) *KeyboardBuilder
RequestPhone adds a button that requests the user's phone number.
Phone request buttons are designed for reply keyboards (built with BuildReply). When tapped, the user will be prompted to share their phone number with the bot. The user can choose to share their phone number or cancel the request.
These buttons are commonly used for collecting user contact information during registration or verification flows. Telegram handles the phone number input UI, ensuring a consistent user experience.
Only one phone request button can exist per keyboard. Adding more than one may result in undefined behavior.
Parameters:
- text: The label text to display on the button (e.g., "Share Phone Number")
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Text("Skip").
RequestPhone("Share Phone Number").
BuildReply(gotg.ReplyOptions{Resize: true})
Handling the phone number:
dispatcher.OnMessage(func(ctx *context.Context, u *context.Update) error {
if m, ok := u.EffectiveMessage(); ok {
if contact := m.Contact(); ok {
phone := contact.PhoneNumber
// Process the phone number
}
}
return nil
})
func (*KeyboardBuilder) RequestPoll ¶
func (k *KeyboardBuilder) RequestPoll(text string, quiz bool) *KeyboardBuilder
RequestPoll adds a button that creates a poll when tapped.
Poll request buttons are designed for reply keyboards (built with BuildReply). When tapped, the user will be prompted to create a poll or quiz and send it to the chat. Telegram provides a full UI for creating the poll with questions, options, and settings.
These buttons are useful for engaging users and collecting feedback or opinions in a structured format.
Only one poll request button can exist per keyboard. Adding more than one may result in undefined behavior.
Parameters:
- text: The label text to display on the button
- quiz: If true, creates a quiz (poll with correct answers); if false, creates a regular poll
Returns the builder for method chaining.
Example:
// Regular poll button
keyboard := gotg.Keyboard().
RequestPoll("Create Poll", false).
BuildReply(gotg.ReplyOptions{Resize: true})
// Quiz button
quizKeyboard := gotg.Keyboard().
RequestPoll("Create Quiz", true).
BuildReply(gotg.ReplyOptions{Resize: true})
Handling the poll:
dispatcher.OnMessage(func(ctx *context.Context, u *context.Update) error {
if m, ok := u.EffectiveMessage(); ok {
if poll := m.Poll(); ok {
// Access poll.Poll for the poll data
questions := poll.Poll.Questions
}
}
return nil
})
func (*KeyboardBuilder) Success ¶
func (k *KeyboardBuilder) Success() *KeyboardBuilder
Success applies success background color style to the last added button.
Success style is used for positive actions or confirmations. Can be chained after any button method — works on all button types.
Returns: builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Button("Approve", "approve").Success().
Build()
func (*KeyboardBuilder) Switch ¶
func (k *KeyboardBuilder) Switch(text string, samePeer bool, query string) *KeyboardBuilder
Switch adds a button that switches to inline mode when tapped.
Switch buttons are designed for inline keyboards. When tapped, they prompt user to select a chat where an inline query will be sent. Your bot will receive an inline query via OnInlineQuery that can be used to provide contextual results.
This is commonly used for features like "Share with friends" or "Send to another chat".
Parameters:
- text: The label text to display on the button
- samePeer: If true, the inline query will be sent in the current chat; if false, the user can select any chat
- query: The query string to pre-fill in the inline input
Returns: builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Switch("Share here", true, "share_item_123").
Next().
Switch("Share with friends", false, "share_item_123").
Build()
Handling: inline query:
dispatcher.OnInlineQuery(func(ctx *context.Context, u *context.Update) error {
query := u.InlineQuery.Query()
// query will contain "share_item_123" plus any user modifications
return u.AnswerInlineQuery(results, nil)
})
func (*KeyboardBuilder) Text ¶
func (k *KeyboardBuilder) Text(text string) *KeyboardBuilder
Text adds a simple text button to the keyboard.
Text buttons send their text as a message when tapped. These buttons are primarily used in reply keyboards (built with BuildReply), as inline keyboards should use Button() for callback buttons instead.
When used in an inline keyboard (built with Build), text buttons will still function but will send the text as a regular message from the user.
Parameters:
- text: The label text to display on the button (and the message text when clicked)
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
Text("Yes").
Text("No").
Next().
Text("Maybe").
BuildReply()
func (*KeyboardBuilder) URL ¶
func (k *KeyboardBuilder) URL(text, url string) *KeyboardBuilder
URL adds a button that opens a URL when tapped.
URL buttons are designed for inline keyboards. When the user taps the button, Telegram will open the specified URL in the user's browser. The button text is displayed as a clickable link.
These buttons are ideal for directing users to external resources such as websites, documentation, or payment pages.
Parameters:
- text: The label text to display on the button
- url: The URL to open when the button is tapped (must be valid)
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
URL("Visit Website", "https://example.com").
URL("Documentation", "https://docs.example.com").
Next().
URL("Support", "https://t.me/supportbot").
Build()
Note: HTTPS URLs are preferred. Telegram may show warnings for HTTP URLs.
func (*KeyboardBuilder) WebApp ¶
func (k *KeyboardBuilder) WebApp(text, url string) *KeyboardBuilder
WebApp adds a button that opens a Telegram Mini App (Web App) when tapped.
Web App buttons are designed for both inline and reply keyboards. When tapped, the specified web application opens in a full-screen in-app browser within Telegram. The Web App can interact with the bot via the Telegram JavaScript API.
Web Apps are ideal for complex interactive experiences that go beyond what's possible with regular Telegram bots, such as games, forms, or dashboards.
The URL must use HTTPS and point to a valid web application that implements the Telegram Web App API.
Parameters:
- text: The label text to display on the button
- url: The HTTPS URL of the web application to open
Returns the builder for method chaining.
Example:
keyboard := gotg.Keyboard().
WebApp("Open Game", "https://example.com/game").
Next().
WebApp("Settings", "https://example.com/settings").
Build()
Web App requirements: - URL must use HTTPS - The web app should include Telegram's Web App script - The web app can send data back to the bot via the WebAppData API
For more information on Web Apps, see: https://core.telegram.org/bots/webapps
type RecaptchaSolver ¶
type ReplyOptions ¶
type ReplyOptions struct {
// Resize controls whether the keyboard is resized vertically to fit its buttons.
// When true, the keyboard will be smaller and take up less screen space.
// This is recommended for keyboards with few buttons.
// Default: false (keyboard uses full height)
Resize bool
// OneTime controls whether the keyboard hides after one button press.
// When true, the keyboard disappears immediately after the user taps a button.
// This is useful for one-time selections like choosing a language or confirming an action.
// Default: false (keyboard remains visible)
OneTime bool
// Selective controls whether the keyboard is shown only to specific users.
// When true, the keyboard is shown only to users mentioned in the message's
// replied-to message or whose username is mentioned in the text.
// Default: false (keyboard shown to all users)
Selective bool
// Persistent controls whether the keyboard remains visible even when a message
// with a different keyboard is sent.
// When true, this keyboard will not be automatically hidden by other keyboards.
// Default: false (keyboard is replaced by new keyboards)
Persistent bool
// Placeholder sets the placeholder text shown in the input field when the
// keyboard is active. This provides a hint or prompt to the user.
// Empty string (default) uses the standard placeholder.
Placeholder string
}
ReplyOptions defines optional configuration for reply keyboards.
Reply keyboards appear above the message input field in the Telegram app and provide quick access to common commands or actions. These options control the keyboard's appearance and behavior.
Example:
keyboard := gotg.Keyboard().
Text("Option 1").
Text("Option 2").
BuildReply(gotg.ReplyOptions{
Resize: true,
OneTime: true,
Placeholder: "Select an option...",
})
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package adapter provides the CommandRegistry for registering Telegram bot commands.
|
Package adapter provides the CommandRegistry for registering Telegram bot commands. |
|
examples
|
|
|
account-management
command
|
|
|
auth-using-api-base
command
|
|
|
auth-using-tdata
command
|
|
|
bot-commands
command
Package main demonstrates how to register bot commands using CommandRegistry.
|
Package main demonstrates how to register bot commands using CommandRegistry. |
|
business-bot
command
|
|
|
conversation
command
|
|
|
custom-adapter
command
|
|
|
dispatcher-bot
command
|
|
|
downloader
command
|
|
|
downloader-v2
command
|
|
|
echo-bot/memory_session
command
|
|
|
echo-bot/sqlite_session
command
|
|
|
format-example
command
|
|
|
i18n-bot
command
|
|
|
logging
command
|
|
|
outgoing-updates
command
|
|
|
Package parsemode provides robust parsing for Telegram message formatting.
|
Package parsemode provides robust parsing for Telegram message formatting. |
|
backend/gormdb
Package gormdb provides a GORM-based Backend implementation.
|
Package gormdb provides a GORM-based Backend implementation. |
|
backend/memory
Package memory provides an in-memory Backend implementation.
|
Package memory provides an in-memory Backend implementation. |
|
backend/redisdb
Package redisdb provides a Redis-based Backend implementation.
|
Package redisdb provides a Redis-based Backend implementation. |
