telegram

package
v0.116.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2024 License: MIT Imports: 41 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   = constant.TestAppID
	TestAppHash = constant.TestAppHash
)

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

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.

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 test server.

Types

type AuthTransferHandler added in v0.96.0

type AuthTransferHandler func(ctx context.Context, client *Client, fn func(context.Context) error) error

AuthTransferHandler is a function that is called during authorization transfer.

The fn callback should be serialized by user id via external locking. You can call Client.Self to acquire current user id.

The fn callback must return fn error if any.

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"

	"github.com/go-faster/errors"

	"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 errors.Wrap(err, "parse secret")
	}

	resolver, err := dcs.MTProxy(
		os.Getenv("PROXY_ADDR"),
		secret,
		dcs.MTProxyOptions{},
	)
	if err != nil {
		return errors.Wrap(err, "create MTProxy resolver")
	}

	client, err := telegram.ClientFromEnvironment(telegram.Options{
		Resolver: resolver,
	})
	if err != nil {
		return errors.Wrap(err, "create client")
	}

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

		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) API added in v0.43.0

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

API returns *tg.Client for calling raw MTProto methods.

func (*Client) Auth added in v0.43.0

func (c *Client) Auth() *auth.Client

Auth returns auth client.

Example (Bot)
package main

import (
	"context"
	"os"

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

func main() {
	ctx := context.Background()
	client := telegram.NewClient(telegram.TestAppID, telegram.TestAppHash, telegram.Options{})
	if err := client.Run(ctx, func(ctx context.Context) error {
		// Checking auth status.
		status, err := client.Auth().Status(ctx)
		if err != nil {
			return err
		}
		// Can be already authenticated if we have valid session in
		// session storage.
		if !status.Authorized {
			// Otherwise, perform bot authentication.
			if _, err := client.Auth().Bot(ctx, os.Getenv("BOT_TOKEN")); err != nil {
				return err
			}
		}

		// All good, manually authenticated.
		return nil
	}); err != nil {
		panic(err)
	}
}
Output:

Example (CodeOnly)
package main

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

	"github.com/gotd/td/telegram"
	"github.com/gotd/td/telegram/auth"
	"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")
	)
	if appIDString == "" || appHash == "" || phone == "" {
		log.Fatal("PHONE, 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 auth.NewFlow(
			auth.CodeOnly(phone, auth.CodeAuthenticatorFunc(codeAsk)),
			auth.SendCodeOptions{},
		).Run(ctx, client.Auth())
	}))
}
Output:

Example (Password)
package main

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

	"github.com/gotd/td/telegram"
	"github.com/gotd/td/telegram/auth"
	"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 auth.NewFlow(
			auth.Constant(phone, pass, auth.CodeAuthenticatorFunc(codeAsk)),
			auth.SendCodeOptions{},
		).Run(ctx, client.Auth())
	}))
}
Output:

Example (Test)
package main

import (
	"context"

	"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.Test(),
	})
	if err := client.Run(ctx, func(ctx context.Context) error {
		return client.Auth().Test(ctx, dcID)
	}); err != nil {
		panic(err)
	}
}
Output:

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) Invoke added in v0.43.0

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

Invoke invokes raw MTProto RPC method. It sends input and decodes result into output.

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) MigrateTo added in v0.52.0

func (c *Client) MigrateTo(ctx context.Context, dcID int) error

MigrateTo forces client to migrate to another DC.

func (*Client) Ping

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

Ping sends low level ping request to Telegram server.

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) QR added in v0.52.0

func (c *Client) QR() qrlogin.QR

QR returns QR login helper.

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 blocks 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. The ctx is used for background operations like updates handling or pools.

See `examples/bg-run` and `contrib/gb` package for classic approach without explicit callback, with Connect and defer close().

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 deprecated

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

SendMessage sends message to peer.

Deprecated: use helpers like message.NewSender.

type CloseInvoker added in v0.26.0

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

CloseInvoker is a closeable tg.Invoker.

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 InvokeFunc added in v0.43.0

type InvokeFunc func(ctx context.Context, input bin.Encoder, output bin.Decoder) error

InvokeFunc implements tg.Invoker as function.

func (InvokeFunc) Invoke added in v0.43.0

func (i InvokeFunc) Invoke(ctx context.Context, input bin.Encoder, output bin.Decoder) error

Invoke implements tg.Invoker.

type Middleware added in v0.43.0

type Middleware interface {
	Handle(next tg.Invoker) InvokeFunc
}

Middleware returns new InvokeFunc for next invoker.

Example
invoker := InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error {
	fmt.Println("invoke")
	return nil
})
printMiddleware := func(message string) Middleware {
	return MiddlewareFunc(func(next tg.Invoker) InvokeFunc {
		return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error {
			fmt.Println(message, "(start)")
			err := next.Invoke(ctx, input, output)
			fmt.Println(message, "(end)")
			return err
		}
	})
}

// Testing composed invoker.
_ = chainMiddlewares(invoker,
	printMiddleware("first"),
	printMiddleware("second"),
).Invoke(context.Background(), nil, nil)
Output:

first (start)
second (start)
invoke
second (end)
first (end)

type MiddlewareFunc added in v0.43.0

type MiddlewareFunc func(next tg.Invoker) InvokeFunc

MiddlewareFunc implements Middleware as function.

func (MiddlewareFunc) Handle added in v0.43.0

func (m MiddlewareFunc) Handle(next tg.Invoker) InvokeFunc

Handle implements Middleware.

type Options

type Options struct {
	// PublicKeys of telegram.
	//
	// If not provided, embedded public keys will be used.
	PublicKeys []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.
	//
	// Enabled by default if no UpdateHandler is provided.
	NoUpdates bool

	// ReconnectionBackoff configures and returns reconnection backoff object.
	ReconnectionBackoff func() backoff.BackOff
	// OnDead will be called on connection dead.
	OnDead func()
	// 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
	// Middlewares list allows wrapping tg.Invoker. Can be useful for metrics,
	// tracing, etc. Note that order is important, see ExampleMiddleware.
	//
	// Middlewares are called in order from first to last.
	Middlewares []Middleware

	// 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

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

	MessageID mtproto.MessageIDSource
	Clock     clock.Clock

	// OpenTelemetry.
	TracerProvider trace.TracerProvider

	// OnTransfer is called during authorization transfer.
	// See [AuthTransferHandler] for details.
	OnTransfer AuthTransferHandler

	// OnSelfError is called when client receives error calling Self() on connect.
	// Return error to stop reconnection.
	//
	// NB: this method is called immediately after connection, so it's not expected to be
	// non-nil error on first connection before auth, so it's safe to return nil until
	// first successful auth.
	OnSelfError func(ctx context.Context, err error) error
}

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 PublicKey added in v0.50.0

type PublicKey = exchange.PublicKey

PublicKey is a Telegram server public key.

type SessionStorage

type SessionStorage = session.Storage

SessionStorage is alias of mtproto.SessionStorage.

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)

Directories

Path Synopsis
Package auth provides authentication on top of tg.Client.
Package auth provides authentication on top of tg.Client.
qrlogin
Package qrlogin provides QR login flow implementation.
Package qrlogin provides QR login flow implementation.
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
deeplink
Package deeplink contains deeplink parsing helpers.
Package deeplink contains deeplink parsing helpers.
e2etest
Package e2etest contains some helpers to make external E2E tests using Telegram test server.
Package e2etest contains some helpers to make external E2E tests using Telegram test 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.
version
Package version contains gotd module version getter.
Package version contains gotd module version getter.
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/mkrun
Package mkrun contains some helpers for generation scripts.
Package mkrun contains some helpers for generation scripts.
internal/mktyping
Binary mktyping generates TypingActionBuilder.
Binary mktyping generates TypingActionBuilder.
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 peers contains helpers to work with Telegram peers.
Package peers contains helpers to work with Telegram peers.
members
Package members defines interfaces for working with chat/channel members.
Package members defines interfaces for working with chat/channel members.
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 thumbnail implements expanding of stripped telegram thumbnails.
Package thumbnail implements expanding of stripped telegram thumbnails.
Package tljson contains some helpers to work with JSONValue class.
Package tljson contains some helpers to work with JSONValue class.
Package updates provides a Telegram's internalState synchronization manager.
Package updates provides a Telegram's internalState synchronization manager.
hook
Package hook contains telegram update hook middleware.
Package hook contains telegram update hook middleware.
internal/e2e
Package e2e contains end-to-end updates processing test.
Package e2e contains end-to-end updates processing test.
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