telegram

package
v0.15.1 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2020 License: MIT Imports: 31 Imported by: 205

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:

Variables

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 ErrPasswordNotProvided = errors.New("password requested but not provided")

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

View Source
var ErrSessionNotFound = errors.New("session storage: not found")

ErrSessionNotFound means that session is not found in storage.

Functions

This section is empty.

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

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{})
	check(client.Connect(ctx))

	codeAsk := func(ctx context.Context) (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(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) error
	AuthSendCode(ctx context.Context, phone string, options SendCodeOptions) (codeHash string, err error)
	AuthPassword(ctx context.Context, password string) 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.

func NewClient added in v0.9.0

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

NewClient creates new unstarted client.

func (*Client) AuthBot added in v0.10.0

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

AuthBot performs bot authentication request.

func (*Client) AuthPassword added in v0.10.0

func (c *Client) AuthPassword(ctx context.Context, password string) 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) (codeHash string, err 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) 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) AuthStatus

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

AuthStatus gets authorization status of client.

func (*Client) Close

func (c *Client) Close() error

Close closes underlying connection.

func (*Client) Connect added in v0.9.0

func (c *Client) Connect(ctx context.Context) (err error)

Connect initializes connection to Telegram server and starts internal read loop.

func (*Client) InvokeRaw

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

InvokeRaw sens input and decodes result into output.

NOTE: Assuming that call contains content message (seqno increment).

func (*Client) Ping

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

Ping sends ping request to server and waits until pong is received or context is canceled.

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) 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 CodeAuthenticator added in v0.14.0

type CodeAuthenticator interface {
	Code(ctx context.Context) (string, error)
}

CodeAuthenticator asks user for received authentication code.

type CodeAuthenticatorFunc added in v0.14.0

type CodeAuthenticatorFunc func(ctx context.Context) (string, error)

CodeAuthenticatorFunc is functional wrapper for CodeAuthenticator.

func (CodeAuthenticatorFunc) Code added in v0.14.0

Code implements CodeAuthenticator interface.

type Error

type Error struct {
	Code     int    // 420
	Message  string // FLOOD_WAIT_3
	Type     string // FLOOD_WAIT
	Argument int    // 3
}

Error represents RPC error returned to request.

func (Error) Error

func (e Error) Error() string

type FileSessionStorage

type FileSessionStorage struct {
	Path string
}

FileSessionStorage implements SessionStorage for file system as file stored in Path.

func (*FileSessionStorage) LoadSession

func (f *FileSessionStorage) LoadSession(_ context.Context) ([]byte, error)

LoadSession loads session from file.

func (*FileSessionStorage) StoreSession

func (f *FileSessionStorage) StoreSession(_ context.Context, data []byte) error

StoreSession stores session to file.

type Options

type Options struct {
	// PublicKeys of telegram.
	//
	// If not provided, embedded public keys will be used.
	PublicKeys []*rsa.PublicKey

	// Addr to connect.
	//
	// If not provided, AddrProduction will be used by default.
	Addr string

	// Transport to use. Default dialer will be used if not provided.
	Transport Transport
	// Network to use. Defaults to tcp.
	Network string
	// 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

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

	RetryInterval time.Duration
	MaxRetries    int
}

Options of Client.

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 interface {
	LoadSession(ctx context.Context) ([]byte, error)
	StoreSession(ctx context.Context, data []byte) error
}

SessionStorage is secure persistent storage for client session.

NB: Implementation security is important, attacker can use not only for connecting as authenticated user or bot, but even decrypting previous messages in some situations.

type Transport added in v0.12.0

type Transport interface {
	Codec() transport.Codec
	DialContext(ctx context.Context, network, address string) (transport.Conn, error)
}

Transport is MTProto connection creator.

type UpdateHandler

type UpdateHandler func(ctx context.Context, u *tg.Updates) error

UpdateHandler will be called on received updates from Telegram.

type UserAuthenticator added in v0.14.0

type UserAuthenticator interface {
	Phone(ctx context.Context) (string, error)
	Password(ctx context.Context) (string, 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 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.

Example
package main

import (
	"context"
	"crypto/rand"

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

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

	ctx := context.Background()
	client := telegram.NewClient(telegram.TestAppID, telegram.TestAppHash, telegram.Options{
		Addr: telegram.AddrTest,
	})
	if err := client.Connect(ctx); err != nil {
		panic(err)
	}

	if err := telegram.NewAuth(
		telegram.TestAuth(rand.Reader, dcID),
		telegram.SendCodeOptions{},
	).Run(ctx, client); err != nil {
		panic(err)
	}
}
Output:

Directories

Path Synopsis
Code generated for package internal by go-bindata DO NOT EDIT.
Code generated for package internal by go-bindata DO NOT EDIT.
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.
exchange
Package exchange contains Telegram key exchange algorithm flows.
Package exchange contains Telegram key exchange algorithm flows.
rpc
Package rpc implements rpc engine.
Package rpc implements rpc engine.
tgtest
Package tgtest provides test Telegram server for end-to-end test.
Package tgtest provides test Telegram server for end-to-end test.

Jump to

Keyboard shortcuts

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