telegram

package
v0.41.1 Latest Latest
Warning

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

Go to latest
Published: May 23, 2021 License: MIT Imports: 38 Imported by: 131

Documentation

Overview

Package telegram implements Telegram client.

Index

Examples

Constants

View Source
const (
	AddrProduction = "149.154.167.50:443"
	AddrTest       = "149.154.167.40:443"
)

Available MTProto default server addresses.

See https://my.telegram.org/apps.

View Source
const (
	TestAppID   = 17349
	TestAppHash = "344583e45741c457fe1862106095a5eb"
)

Test-only credentials. Can be used with AddrTest and TestAuth to test authentication.

Reference:

View Source
const ErrFloodWait = tgerr.ErrFloodWait

ErrFloodWait is error type of "FLOOD_WAIT" error.

View Source
const Port = 443

Port is default port used by telegram.

Variables

View Source
var AsFloodWait = tgerr.AsFloodWait // nolint:gochecknoglobals

AsFloodWait returns wait duration and true boolean if err is the "FLOOD_WAIT" error.

Client should wait for that duration before issuing new requests with same method.

View Source
var ErrPasswordAuthNeeded = errors.New("2FA required")

ErrPasswordAuthNeeded means that 2FA auth is required.

Call Client.AuthPassword to provide 2FA password.

View Source
var ErrPasswordInvalid = errors.New("invalid password")

ErrPasswordInvalid means that password provided to AuthPassword is invalid.

Note that telegram does not trim whitespace characters by default, check that provided password is expected and clean whitespaces if needed. You can use strings.TrimSpace(password) for this.

View Source
var ErrPasswordNotProvided = errors.New("password requested but not provided")

ErrPasswordNotProvided means that password requested by Telegram, but not provided by user.

Functions

func BotFromEnvironment added in v0.19.0

func BotFromEnvironment(
	ctx context.Context,
	opts Options,
	setup func(ctx context.Context, client *Client) error,
	cb func(ctx context.Context, client *Client) error,
) error

BotFromEnvironment creates bot client using ClientFromEnvironment connects to server and authenticates it.

Variables: BOT_TOKEN — token from BotFather.

func RunUntilCanceled added in v0.26.0

func RunUntilCanceled(ctx context.Context, client *Client) error

RunUntilCanceled is client callback which locks until client context is canceled.

func TestClient added in v0.19.0

func TestClient(ctx context.Context, opts Options, cb func(ctx context.Context, client *Client) error) error

TestClient creates and authenticates user telegram.Client using Telegram staging server.

Types

type AuthFlow added in v0.14.0

type AuthFlow struct {
	Auth    UserAuthenticator
	Options SendCodeOptions
}

AuthFlow simplifies boilerplate for authentication flow.

func NewAuth added in v0.14.0

func NewAuth(auth UserAuthenticator, opt SendCodeOptions) AuthFlow

NewAuth initializes new authentication flow.

func (AuthFlow) Run added in v0.14.0

func (f AuthFlow) Run(ctx context.Context, client AuthFlowClient) error

Run starts authentication flow on client.

Example
package main

import (
	"bufio"
	"context"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"

	"github.com/gotd/td/telegram"
	"github.com/gotd/td/tg"
)

func main() {
	check := func(err error) {
		if err != nil {
			panic(err)
		}
	}

	var (
		appIDString = os.Getenv("APP_ID")
		appHash     = os.Getenv("APP_HASH")
		phone       = os.Getenv("PHONE")
		pass        = os.Getenv("PASSWORD")
	)
	if appIDString == "" || appHash == "" || phone == "" || pass == "" {
		log.Fatal("PHONE, PASSWORD, APP_ID or APP_HASH is not set")
	}

	appID, err := strconv.Atoi(appIDString)
	check(err)

	ctx := context.Background()
	client := telegram.NewClient(appID, appHash, telegram.Options{})
	codeAsk := func(ctx context.Context, sentCode *tg.AuthSentCode) (string, error) {
		fmt.Print("code:")
		code, err := bufio.NewReader(os.Stdin).ReadString('\n')
		if err != nil {
			return "", err
		}
		code = strings.ReplaceAll(code, "\n", "")
		return code, nil
	}

	check(client.Run(ctx, func(ctx context.Context) error {
		return telegram.NewAuth(
			telegram.ConstantAuth(phone, pass, telegram.CodeAuthenticatorFunc(codeAsk)),
			telegram.SendCodeOptions{},
		).Run(ctx, client)
	}))
}
Output:

type AuthFlowClient added in v0.14.0

type AuthFlowClient interface {
	AuthSignIn(ctx context.Context, phone, code, codeHash string) (*tg.AuthAuthorization, error)
	AuthSendCode(ctx context.Context, phone string, options SendCodeOptions) (*tg.AuthSentCode, error)
	AuthPassword(ctx context.Context, password string) (*tg.AuthAuthorization, error)
	AuthSignUp(ctx context.Context, s SignUp) (*tg.AuthAuthorization, error)
}

AuthFlowClient abstracts telegram client for AuthFlow.

type AuthStatus

type AuthStatus struct {
	// Authorized is true if client is authorized.
	Authorized bool
	// User is current User object.
	User *tg.User
}

AuthStatus represents authorization status.

type Client

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

Client represents a MTProto client to Telegram.

Example (Mtproxy)
package main

import (
	"context"
	"encoding/hex"
	"fmt"
	"os"
	"os/signal"

	"golang.org/x/xerrors"

	"github.com/gotd/td/telegram"
	"github.com/gotd/td/telegram/dcs"
	"github.com/gotd/td/tg"
)

func connectViaMTProxy(ctx context.Context) error {
	secret, err := hex.DecodeString(os.Getenv("SECRET"))
	if err != nil {
		return xerrors.Errorf("parse secret: %w", err)
	}

	resolver, err := dcs.MTProxy(
		os.Getenv("PROXY_ADDR"),
		secret,
		dcs.MTProxyOptions{},
	)
	if err != nil {
		return xerrors.Errorf("create MTProxy resolver: %w", err)
	}

	client, err := telegram.ClientFromEnvironment(telegram.Options{
		Resolver: resolver,
	})
	if err != nil {
		return xerrors.Errorf("create client: %w", err)
	}

	return client.Run(ctx, func(ctx context.Context) error {
		cfg, err := tg.NewClient(client).HelpGetConfig(ctx)
		if err != nil {
			return xerrors.Errorf("get config: %w", err)
		}

		fmt.Println("This DC: ", cfg.ThisDC)
		return nil
	})
}

func main() {
	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
	defer cancel()

	if err := connectViaMTProxy(ctx); err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "%+v\n", err)
		os.Exit(1)
	}
}
Output:

func ClientFromEnvironment added in v0.19.0

func ClientFromEnvironment(opts Options) (*Client, error)

ClientFromEnvironment creates client using OptionsFromEnvironment but does not connect to server.

Variables:

APP_ID:   app_id of Telegram app.
APP_HASH: app_hash of Telegram app.

func NewClient added in v0.9.0

func NewClient(appID int, appHash string, opt Options) *Client

NewClient creates new unstarted client.

func (*Client) AuthAcceptTOS added in v0.17.0

func (c *Client) AuthAcceptTOS(ctx context.Context, id tg.DataJSON) error

AuthAcceptTOS accepts version of Terms Of Service.

func (*Client) AuthBot added in v0.10.0

func (c *Client) AuthBot(ctx context.Context, token string) (*tg.AuthAuthorization, error)

AuthBot performs bot authentication request.

func (*Client) AuthIfNecessary added in v0.23.0

func (c *Client) AuthIfNecessary(ctx context.Context, flow AuthFlow) error

AuthIfNecessary runs given auth flow if current session is not authorized.

func (*Client) AuthPassword added in v0.10.0

func (c *Client) AuthPassword(ctx context.Context, password string) (*tg.AuthAuthorization, error)

AuthPassword performs login via secure remote password (aka 2FA).

Method can be called after AuthSignIn to provide password if requested.

func (*Client) AuthSendCode added in v0.10.0

func (c *Client) AuthSendCode(ctx context.Context, phone string, options SendCodeOptions) (*tg.AuthSentCode, error)

AuthSendCode requests code for provided phone number, returning code hash and error if any. Use AuthFlow to reduce boilerplate.

This method should be called first in user authentication flow.

func (*Client) AuthSignIn added in v0.10.0

func (c *Client) AuthSignIn(ctx context.Context, phone, code, codeHash string) (*tg.AuthAuthorization, error)

AuthSignIn performs sign in with provided user phone, code and code hash.

If ErrPasswordAuthNeeded is returned, call AuthPassword to provide 2FA password.

To obtain codeHash, use AuthSendCode.

func (*Client) AuthSignUp added in v0.17.0

func (c *Client) AuthSignUp(ctx context.Context, s SignUp) (*tg.AuthAuthorization, error)

AuthSignUp registers a validated phone number in the system.

To obtain codeHash, use AuthSendCode. Use AuthFlow helper to handle authentication flow.

func (*Client) AuthStatus

func (c *Client) AuthStatus(ctx context.Context) (*AuthStatus, error)

AuthStatus gets authorization status of client.

func (*Client) Config added in v0.26.0

func (c *Client) Config() tg.Config

Config returns current config.

func (*Client) DC added in v0.22.0

func (c *Client) DC(ctx context.Context, dc int, max int64) (CloseInvoker, error)

DC creates new multi-connection invoker to given DC.

func (*Client) InvokeRaw

func (c *Client) InvokeRaw(ctx context.Context, input bin.Encoder, output bin.Decoder) error

InvokeRaw invokes raw MTProto RPC method. It sends input and decodes result into output. The request also goes through Middleware from Client’s Options.

func (*Client) MediaOnly added in v0.30.0

func (c *Client) MediaOnly(ctx context.Context, dc int, max int64) (CloseInvoker, error)

MediaOnly creates new multi-connection invoker to given DC ID. It connects to MediaOnly DCs.

func (*Client) Pool added in v0.22.0

func (c *Client) Pool(max int64) (CloseInvoker, error)

Pool creates new multi-connection invoker to current DC.

func (*Client) RandInt64

func (c *Client) RandInt64() (int64, error)

RandInt64 returns new random int64 from random source.

Useful helper for places in API where random int is required.

func (*Client) Run added in v0.18.0

func (c *Client) Run(ctx context.Context, f func(ctx context.Context) error) (err error)

Run starts client session and block until connection close. The f callback is called on successful session initialization and Run will return on f() result.

Context of callback will be canceled if fatal error is detected.

func (*Client) Self added in v0.11.0

func (c *Client) Self(ctx context.Context) (*tg.User, error)

Self returns current user.

You can use tg.User.Bot to check whether current user is bot.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, req *tg.MessagesSendMessageRequest) error

SendMessage sends message to peer.

type CloseInvoker added in v0.26.0

type CloseInvoker interface {
	tg.Invoker
	Close() error
}

CloseInvoker is a closeable tg.Invoker.

type CodeAuthenticator added in v0.14.0

type CodeAuthenticator interface {
	Code(ctx context.Context, sentCode *tg.AuthSentCode) (string, error)
}

CodeAuthenticator asks user for received authentication code.

type CodeAuthenticatorFunc added in v0.14.0

type CodeAuthenticatorFunc func(ctx context.Context, sentCode *tg.AuthSentCode) (string, error)

CodeAuthenticatorFunc is functional wrapper for CodeAuthenticator.

func (CodeAuthenticatorFunc) Code added in v0.14.0

func (c CodeAuthenticatorFunc) Code(ctx context.Context, sentCode *tg.AuthSentCode) (string, error)

Code implements CodeAuthenticator interface.

type DeviceConfig added in v0.21.0

type DeviceConfig = manager.DeviceConfig

DeviceConfig is config which send when Telegram connection session created.

type Error

type Error = tgerr.Error

Error represents RPC error returned to request.

type FileSessionStorage

type FileSessionStorage = session.FileStorage

FileSessionStorage is alias of mtproto.FileSessionStorage.

type Options

type Options struct {
	// PublicKeys of telegram.
	//
	// If not provided, embedded public keys will be used.
	PublicKeys []*rsa.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
	// NoUpdates enables no updates mode.
	NoUpdates bool
	// ReconnectionBackoff configures and returns reconnection backoff object.
	ReconnectionBackoff func() backoff.BackOff
	// MigrationTimeout configures migration timeout.
	MigrationTimeout time.Duration
	// Random is random source. Defaults to crypto.
	Random io.Reader
	// Logger is instance of zap.Logger. No logs by default.
	Logger *zap.Logger
	// SessionStorage will be used to load and save session data.
	// NB: Very sensitive data, save with care.
	SessionStorage SessionStorage
	// UpdateHandler will be called on received update.
	UpdateHandler UpdateHandler

	// Middleware to use for RPC calls.
	//
	// If not provided, no middleware is used.
	Middleware middleware.Middleware

	// AckBatchSize is maximum ack-s to buffer.
	AckBatchSize int
	// AckInterval is maximum time to buffer ack.
	AckInterval   time.Duration
	RetryInterval time.Duration
	MaxRetries    int

	// Device is device config.
	// Will be sent with session creation request.
	Device DeviceConfig

	MessageID mtproto.MessageIDSource
	Clock     clock.Clock
}

Options of Client.

func OptionsFromEnvironment added in v0.19.0

func OptionsFromEnvironment(opts Options) (Options, error)

OptionsFromEnvironment fills unfilled field in opts parameter using environment variables.

Variables:

SESSION_FILE:        path to session file
SESSION_DIR:         path to session directory, if SESSION_FILE is not set
ALL_PROXY, NO_PROXY: see https://pkg.go.dev/golang.org/x/net/proxy#FromEnvironment

type SendCodeOptions added in v0.10.0

type SendCodeOptions struct {
	// AllowFlashCall allows phone verification via phone calls.
	AllowFlashCall bool
	// Pass true if the phone number is used on the current device.
	// Ignored if AllowFlashCall is not set.
	CurrentNumber bool
	// If a token that will be included in eventually sent SMSs is required:
	// required in newer versions of android, to use the android SMS receiver APIs.
	AllowAppHash bool
}

SendCodeOptions defines how to send auth code to user.

type SessionStorage

type SessionStorage = session.Storage

SessionStorage is alias of mtproto.SessionStorage.

type SignUp added in v0.17.0

type SignUp struct {
	PhoneNumber   string
	PhoneCodeHash string
	FirstName     string
	LastName      string
}

SignUp wraps parameters for AuthSignUp.

type SignUpRequired added in v0.17.0

type SignUpRequired struct {
	TermsOfService tg.HelpTermsOfService
}

SignUpRequired means that log in failed because corresponding account does not exist, so sign up is required.

func (*SignUpRequired) Error added in v0.17.0

func (s *SignUpRequired) Error() string

func (*SignUpRequired) Is added in v0.17.0

func (s *SignUpRequired) Is(err error) bool

Is returns true if err is SignUpRequired.

type UpdateHandler

type UpdateHandler interface {
	Handle(ctx context.Context, u tg.UpdatesClass) error
}

UpdateHandler will be called on received updates from Telegram.

type UpdateHandlerFunc added in v0.39.0

type UpdateHandlerFunc func(ctx context.Context, u tg.UpdatesClass) error

UpdateHandlerFunc type is an adapter to allow the use of ordinary function as update handler.

UpdateHandlerFunc(f) is an UpdateHandler that calls f.

func (UpdateHandlerFunc) Handle added in v0.39.0

Handle calls f(ctx, u)

type UserAuthenticator added in v0.14.0

type UserAuthenticator interface {
	Phone(ctx context.Context) (string, error)
	Password(ctx context.Context) (string, error)
	AcceptTermsOfService(ctx context.Context, tos tg.HelpTermsOfService) error
	SignUp(ctx context.Context) (UserInfo, error)
	CodeAuthenticator
}

UserAuthenticator asks user for phone, password and received authentication code.

func CodeOnlyAuth added in v0.14.0

func CodeOnlyAuth(phone string, code CodeAuthenticator) UserAuthenticator

CodeOnlyAuth creates UserAuthenticator with constant phone and no password.

func ConstantAuth added in v0.14.0

func ConstantAuth(phone, password string, code CodeAuthenticator) UserAuthenticator

ConstantAuth creates UserAuthenticator with constant phone and password.

func EnvAuth added in v0.23.0

func EnvAuth(prefix string, code CodeAuthenticator) UserAuthenticator

EnvAuth creates UserAuthenticator which gets phone and password from environment variables.

func TestAuth added in v0.14.0

func TestAuth(randReader io.Reader, dc int) UserAuthenticator

TestAuth returns UserAuthenticator that authenticates via testing credentials.

Can be used only with testing server. Will perform sign up if test user is not registered.

Example
package main

import (
	"context"
	"crypto/rand"

	"github.com/gotd/td/telegram"
	"github.com/gotd/td/telegram/dcs"
)

func main() {
	// Example of using test server.
	const dcID = 2

	ctx := context.Background()
	client := telegram.NewClient(telegram.TestAppID, telegram.TestAppHash, telegram.Options{
		DC:     dcID,
		DCList: dcs.Staging(),
	})
	if err := client.Run(ctx, func(ctx context.Context) error {
		return telegram.NewAuth(
			telegram.TestAuth(rand.Reader, dcID),
			telegram.SendCodeOptions{},
		).Run(ctx, client)
	}); err != nil {
		panic(err)
	}
}
Output:

type UserInfo added in v0.17.0

type UserInfo struct {
	FirstName string
	LastName  string
}

UserInfo represents user info required for sign up.

Directories

Path Synopsis
Package dcs contains Telegram DCs list and some helpers.
Package dcs contains Telegram DCs list and some helpers.
Package downloader contains downloading files helpers.
Package downloader contains downloading files helpers.
internal
e2etest
Package e2etest contains some helpers to make external E2E tests using Telegram staging server.
Package e2etest contains some helpers to make external E2E tests using Telegram staging server.
manager
Package manager contains connection management utilities.
Package manager contains connection management utilities.
upconv
Package upconv contains updates conversion helpers.
Package upconv contains updates conversion helpers.
Package message contains some useful utilities for creating Telegram messages.
Package message contains some useful utilities for creating Telegram messages.
entity
Package entity contains message formatting and styling helpers.
Package entity contains message formatting and styling helpers.
html
Package html contains HTML styling options.
Package html contains HTML styling options.
inline
Package inline contains inline query results builder.
Package inline contains inline query results builder.
internal/deeplink
Package deeplink contains deeplink parsing helpers.
Package deeplink contains deeplink parsing helpers.
markup
Package markup contain bots inline markup builder.
Package markup contain bots inline markup builder.
peer
Package peer conatains some peer resolving and extracting helpers.
Package peer conatains some peer resolving and extracting helpers.
styling
Package styling contains styling options for Telegram messages.
Package styling contains styling options for Telegram messages.
unpack
Package unpack contains some updates result unpacking helpers.
Package unpack contains some updates result unpacking helpers.
Package query contains generic pagination helpers.
Package query contains generic pagination helpers.
cached
Package cached contains cached query helpers.
Package cached contains cached query helpers.
channels/participants
Package participants contains channel participants iteration helper.
Package participants contains channel participants iteration helper.
contacts/blocked
Package blocked contains blocked contacts iteration helper.
Package blocked contains blocked contacts iteration helper.
dialogs
Package dialogs contains dialog iteration helper.
Package dialogs contains dialog iteration helper.
hasher
Package hasher contains Telegram pagination hash implementation.
Package hasher contains Telegram pagination hash implementation.
internal/genutil
Package genutil is a utility package for query helpers codegeneration.
Package genutil is a utility package for query helpers codegeneration.
messages
Package messages contains message iteration helper.
Package messages contains message iteration helper.
messages/stickers/featured
Package featured contains featured stickers iteration helper.
Package featured contains featured stickers iteration helper.
photos
Package photos contains photos iteration helper.
Package photos contains photos iteration helper.
Package uploader contains uploading files helpers.
Package uploader contains uploading files helpers.
source
Package source contains remote source interface and implementations for uploader.
Package source contains remote source interface and implementations for uploader.

Jump to

Keyboard shortcuts

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