Documentation
¶
Index ¶
- Constants
- Variables
- func ClientTypeBot(botToken string) clientType
- func ClientTypePhone(phoneNumber string) clientType
- func SendAuthStatus(conversator AuthConversator, event AuthStatusEvent)
- func SendAuthStatusWithRetrials(conversator AuthConversator, event AuthStatusEvent, attemptsLeft int)
- type AuthConversator
- type AuthStatus
- type AuthStatusEvent
- type Client
- func (c *Client) CreateContext() *ext.Context
- func (c *Client) ExportStringSession() (string, error)
- func (c *Client) Idle() error
- func (c *Client) RefreshContext(ctx *ext.Context)
- func (c *Client) Start(opts *ClientOpts) error
- func (c *Client) StartUpdateRecovery(ctx context.Context) error
- func (c *Client) Stop()
- type ClientOpts
- type Flow
- type FlowClient
- type RecaptchaSolver
Constants ¶
const VERSION = "v0.5.0"
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 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 ¶
CreateContext creates a new pseudo updates context. A context retrieved from this method should be reused.
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 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
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.
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 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.