mygotg

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: GPL-3.0 Imports: 28 Imported by: 1 module, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

mygotg

hard fork of gotgproto

Registering handlers before recovery

Clients that register handlers after NewClient should set ClientOpts.DeferUpdateRecovery. After registering every handler, start recovery and check the result:

client, err := mygotg.NewClient(appID, apiHash, clientType, &mygotg.ClientOpts{
	Session:             sessionConstructor,
	DeferUpdateRecovery: true,
})
if err != nil {
	return err
}
defer client.Stop()
client.Dispatcher.AddHandler(messageHandler)
if err := client.StartUpdateRecovery(ctx); err != nil {
	return err
}
return client.Idle()
  • ctx limits recovery initialization. Canceling it after success does not stop the client; use client.Stop() or cancel ClientOpts.Context for shutdown.
  • Initialization failures can be retried while the client is running. A second successful start returns ErrUpdateRecoveryStarted; a stopped client returns ErrClientNotReady.
  • Updates received before recovery starts wait in memory. Start promptly after registration. Use NoUpdates: true for takeout/export clients that never consume updates, and do not share a recovery cursor between independent update consumers.
  • Omitting DeferUpdateRecovery keeps automatic recovery. Automatic initialization failures now return from NewClient/Start instead of leaving a client without working recovery.
  • Deferred startup captures the login-time update baseline, so NewClient/Start can also return an initial-state fetch error before recovery is explicitly started.

Documentation

Index

Constants

View Source
const VERSION = "v0.5.0"

Variables

View Source
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 ClientTypeBot

func ClientTypeBot(botToken string) clientType

func ClientTypePhone

func ClientTypePhone(phoneNumber string) clientType

func SendAuthStatus

func SendAuthStatus(conversator AuthConversator, event AuthStatusEvent)

func SendAuthStatusWithRetrials

func SendAuthStatusWithRetrials(conversator AuthConversator, event AuthStatusEvent, attemptsLeft int)

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

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

	// 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 is instance of zap.Logger. No logs by default.
	Logger *zap.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(appId int, apiHash string, cType clientType, opts *ClientOpts) (*Client, error)

NewClient creates a new mygotg client and logs in to telegram.

func (*Client) CreateContext

func (c *Client) CreateContext() *ext.Context

CreateContext creates a new pseudo updates context. A context retrieved from this method should be reused.

func (*Client) ExportStringSession

func (c *Client) ExportStringSession() (string, error)

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) Idle

func (c *Client) Idle() error

Idle keeps the current goroutined blocked until the client is stopped.

func (*Client) RefreshContext

func (c *Client) RefreshContext(ctx *ext.Context)

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 returns an error if already running or a synchronous peer preload fails; a failed preload stops the client.

func (*Client) StartUpdateRecovery added in v0.4.0

func (c *Client) StartUpdateRecovery(ctx context.Context) error

StartUpdateRecovery waits for recovery initialization after handlers have been registered. The context limits this call; after success, recovery runs until the client stops. Initialization failures leave recovery available for another start attempt. It returns ErrClientNotReady for stopped/uninitialized clients, ErrUpdateRecoveryOff when disabled, and ErrUpdateRecoveryStarted for an in-progress or completed start.

func (*Client) Stop

func (c *Client) Stop()

Stop cancels the context.Context being used for the client and stops it.

Notes:

1.) Client.Idle() will exit if this method is called.

2.) You can call Client.Start() to start the client again if it was stopped using this method.

type ClientOpts

type ClientOpts struct {
	// Logger is instance of zap.Logger. No logs by default.
	Logger *zap.Logger
	// 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
	// ErrorHandler handles unknown callback errors and background peer-preload failures (with a nil update).
	// Returning dispatcher.StopClient cancels the client.
	ErrorHandler dispatcher.ErrorHandler
	// Custom Middlewares
	Middlewares []telegram.Middleware
	// UpdateStateStorage persists the update manager state (pts/qts/seq and
	// per-channel pts), so updates missed while the client was offline are
	// recovered via updates.getDifference on the next start instead of being
	// lost. In-memory storage is used if not provided.
	UpdateStateStorage updates.StateStorage
	// DisableUpdateRecovery turns off missed-update (gap) recovery.
	//
	// With it, updates are handled as-is and anything missed after a reconnect
	// or an updatesTooLong is lost, which is the historic reason a long-running
	// client silently stops responding. Only enable this for debugging.
	DisableUpdateRecovery bool
	// DeferUpdateRecovery buffers updates until StartUpdateRecovery is called after handler registration.
	// No update cursor is persisted before recovery starts.
	// Requires update recovery; use NoUpdates for clients that never consume updates.
	DeferUpdateRecovery bool
	// Custom Run() Middleware
	// Can be used for floodWaiter package
	// https://github.com/krau/mygotg/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.
	// mygotg.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
	// SendCodeOptions allows overriding AuthSendCode behavior.
	SendCodeOptions *auth.SendCodeOptions
	// PeersFromDialogs preloads user-account dialogs; background failures use ErrorHandler or logging.
	PeersFromDialogs bool
	// WaitOnPeersFromDialogs waits for persistence; failure cancels startup and is returned to the caller.
	WaitOnPeersFromDialogs bool
}

type Flow

type Flow auth.Flow

type FlowClient added in v0.3.0

type FlowClient struct {
	auth.FlowClient
	// contains filtered or unexported fields
}

FlowClient wraps an auth.FlowClient and transparently retries auth.sendCode through invokeWithReCaptcha when Telegram answers with a RECAPTCHA_CHECK error.

func (FlowClient) SendCode added in v0.3.0

func (c FlowClient) SendCode(ctx context.Context, phone string, opts auth.SendCodeOptions) (tg.AuthSentCodeClass, error)

type RecaptchaSolver added in v0.3.0

type RecaptchaSolver interface {
	// SolveRecaptcha receives the action and key without their separating "__".
	SolveRecaptcha(packageID, action, key string) (string, error)
}

RecaptchaSolver enables phone-login challenge retries when implemented by an AuthConversator.

Jump to

Keyboard shortcuts

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