Skip to content

iamxvbaba/td

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4,530 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

td Go Reference codecov stable

This fork publishes the generated multi-layer TL runtime used by telesrv under the Go module path github.com/iamxvbaba/td. Its upstream project and issue history remain at gotd/td.

The root module is the release boundary. The nested examples module is kept for source reference, but gif-download and userbot still depend on github.com/gotd/contrib, whose public interfaces use the upstream github.com/gotd/td types. Those two examples require a matching contrib fork before they can be built against this renamed module and are not part of this fork's release gate.

Fork maintenance

Upstream synchronization is selective by design. Do not merge or rebase the whole gotd/td branch into this fork's release line. For every fetched upstream range, record the old and candidate base commits, review each commit or cohesive feature group, and replay only the selected source, runtime, diagnostic, performance, security, and required dependency changes. Record skipped changes and the reason they do not belong in the fork.

Upstream-generated tg/*_gen.go files are never copied or conflict-merged. Schema changes enter through the versioned manifest, semantic policy audit, and sparse AOT generation workflow documented in _schema/layers/README.md. If the upstream schema has the same Layer, normalized SHA-256, and body as the fork's canonical schema, provenance-only differences do not trigger canonical regeneration. A candidate upstream base becomes the documented baseline only after deterministic generation, fork tests, downstream telesrv validation, and publication of a new immutable tag.

Fork CI deliberately has no scheduled schema updater and does not upload to the upstream Codecov project. Coverage is still generated and retained as a workflow artifact. Schema updates must use the reviewed local import and policy-audit workflow; they are never opened automatically by a credentialed GitHub Action.

Telegram MTProto API client in Go for users and bots.

Telegram: English chat Telegram: Russian chat Telegram: Chinese chat Telegram: Online count

Before using this library, read How To Not Get Banned guide.

Due to limitations of pkg.go.dev, documentation for tg package is not shown, but there is hosted version.

Higher level libraries

The gotd itself is a pretty low-level library, and you may want to use higher level libraries instead:

  • GoTGProto is a helper package for gotd library, It aims to make td's raw functions easy-to-use with the help of features like using session strings, custom helper functions, storing peers and extracting chat or user ids through it etc.

Usage

go get github.com/iamxvbaba/td
package main

import (
	"context"

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

func main() {
	// https://core.telegram.org/api/obtaining_api_id
	client := telegram.NewClient(appID, appHash, telegram.Options{})
	if err := client.Run(context.Background(), func(ctx context.Context) error {
		// It is only valid to use client while this function is not returned
		// and ctx is not cancelled.
		api := client.API()

		// Now you can invoke MTProto RPC requests by calling the API.
		// ...

		// Return to close client connection and free up resources.
		return nil
	}); err != nil {
		panic(err)
	}
	// Client is closed.
}

See examples for more info.

Features

  • Full MTProto 2.0 implementation in Golang, directly access any MTProto method with telegram.Client.API()
  • Voice and video calls (tgcalls), both 1:1 and group calls — see the call and groupcall examples
  • Highly optimized, low memory (150kb per idle client) and CPU overhead, can handle thousands concurrent clients
  • Code for Telegram types generated by ./cmd/gotdgen (based on gotd/tl parser) with embedded official documentation
  • Pluggable session storage
  • Automatic re-connects with keepalive
  • Vendored Telegram public keys that are kept up-to-date
  • Rigorously tested
    • End-to-end with real Telegram server in CI
    • End-to-end with gotd Telegram server (in pure Go)
    • Lots of unit testing
    • Fuzzing
    • 24/7 canary bot in production that tests reconnects, update handling, memory leaks and performance
  • No runtime reflection overhead
  • Conforms to Security guidelines for Telegram client software developers
    • Secure PRNG used for crypto
    • Replay attack protection
  • 2FA support
  • MTProxy support
  • Various helpers that lighten the complexity of the Telegram API
  • Connection pooling
  • Automatic datacenter migration and redirects handling
  • Graceful request cancellation via context
  • WebSocket transport support (works in WASM)

Status

The goal of this project is to implement a stable, performant and safe client for Telegram in pure Go while having a simple and convenient API and a feature parity with TDLib.

This project is fully non-commercial and not affiliated with any commercial organization (including Telegram LLC).

Examples

See examples directory.

Also take a look at

  • go-faster/bot as example of sophisticated telegram bot integration with GitHub
  • gotd/cli, command line interface for subset of telegram methods.

Auth

User

You can use td/telegram/auth.Flow to simplify user authentications.

codePrompt := func(ctx context.Context, sentCode *tg.AuthSentCode) (string, error) {
    // NB: Use "golang.org/x/crypto/ssh/terminal" to prompt password.
    fmt.Print("Enter code: ")
    code, err := bufio.NewReader(os.Stdin).ReadString('\n')
    if err != nil {
        return "", err
    }
    return strings.TrimSpace(code), nil
}
// This will setup and perform authentication flow.
// If account does not require 2FA password, use telegram.CodeOnlyAuth
// instead of telegram.ConstantAuth.
if err := auth.NewFlow(
    auth.Constant(phone, password, auth.CodeAuthenticatorFunc(codePrompt)),
    auth.SendCodeOptions{},
).Run(ctx, client.Auth()); err != nil {
    panic(err)
}

Bot

Use bot token from @BotFather.

if err := client.Auth().Bot(ctx, "token:12345"); err != nil {
    panic(err)
}

Calling MTProto directly

You can use the generated tg.Client that allows calling any MTProto method directly.

// Grab these from https://my.telegram.org/apps.
// Never share it or hardcode!
client := telegram.NewClient(appID, appHash, telegram.Options{})
client.Run(ctx, func(ctx context.Context) error {
  // Grab token from @BotFather.
  if _, err := client.Auth().Bot(ctx, "token:12345"); err != nil {
    return err
  }
  state, err := client.API().UpdatesGetState(ctx)
  if err != nil {
    return err
  }
  // Got state: &{Pts:197 Qts:0 Date:1606855030 Seq:1 UnreadCount:106}
  // This will close client and cleanup resources.
  return nil
})

Using MTProto JSON format

You can invoke methods using MTProto JSON format with InvokeJSON. This accepts JSON with @type field in MTProto format (e.g., "messages.sendMessage") and returns JSON response in MTProto format.

client := telegram.NewClient(appID, appHash, telegram.Options{})
client.Run(ctx, func(ctx context.Context) error {
  if _, err := client.Auth().Bot(ctx, "token:12345"); err != nil {
    return err
  }

  // Send message using MTProto JSON format
  jsonReq := `{
    "@type": "messages.sendMessage",
    "peer": {"@type": "inputPeerUser", "user_id": 123456789, "access_hash": 0},
    "message": "Hello from MTProto JSON!",
    "random_id": 0
  }`

  jsonResp, err := client.API().InvokeJSON(ctx, jsonReq, true)
  if err != nil {
    return err
  }
  // jsonResp contains MTProto JSON response with snake_case field names
  // {"@type":"messages.sentMessage",...} or error response
  return nil
})

Generated code

The code output of gotdgen contains references to TL types, examples, URL to official documentation and extracted comments from it.

For example, the auth.Authorization type in tg/tl_auth_authorization_gen.go:

// AuthAuthorizationClass represents auth.Authorization generic type.
//
// See https://core.telegram.org/type/auth.Authorization for reference.
//
// Example:
//  g, err := DecodeAuthAuthorization(buf)
//  if err != nil {
//      panic(err)
//  }
//  switch v := g.(type) {
//  case *AuthAuthorization: // auth.authorization#cd050916
//  case *AuthAuthorizationSignUpRequired: // auth.authorizationSignUpRequired#44747e9a
//  default: panic(v)
//  }
type AuthAuthorizationClass interface {
	bin.Encoder
	bin.Decoder
	construct() AuthAuthorizationClass
}

Also, the corresponding auth.signIn method:

// AuthSignIn invokes method auth.signIn#bcd51581 returning error if any.
// Signs in a user with a validated phone number.
//
// See https://core.telegram.org/method/auth.signIn for reference.
func (c *Client) AuthSignIn(ctx context.Context, request *AuthSignInRequest) (AuthAuthorizationClass, error) {}

The generated constructors contain detailed official documentation, including links:

// FoldersDeleteFolderRequest represents TL type `folders.deleteFolder#1c295881`.
// Delete a peer folder¹
//
// Links:
//  1) https://core.telegram.org/api/folders#peer-folders
//
// See https://core.telegram.org/method/folders.deleteFolder for reference.
type FoldersDeleteFolderRequest struct {
    // Peer folder ID, for more info click here¹
    //
    // Links:
    //  1) https://core.telegram.org/api/folders#peer-folders
    FolderID int
}

Contributions

Huge thanks to all contributors. Dealing with a project of this scale alone is impossible.

Special thanks:

  • tdakkota
    • Two-factor authentication (SRP)
    • Proxy support
    • Update dispatcher
    • Complete transport support (abridged, padded intermediate and full)
    • Telegram server for end-to-end testing
    • Multiple major refactorings, including critical cryptographical scope reduction
    • Code generation improvements (vector support, multiple modes for pretty-print)
    • And many other cool things and performance improvements
  • shadowspore
    • Background pings
    • Links in generated documentation
    • Message acknowledgements
    • Retries
    • RPC Engine
    • Gap (Updates) engine

Reference

The MTProto protocol description is hosted by Telegram.

Most important parts for client implementations:

Current implementation mostly conforms to security guidelines, but no formal security audit were performed.

Prior art

Who is using gotd?

  • The iyear/tdl, 📥 Telegram Downloader, but more than a downloader

Drop a comment here to add your project.

License

MIT License

Created by Aleksandr (ernado) Razumov

2020

Links

About

Telegram client, in Go. (MTProto API)

Resources

License

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages

  • Go 96.1%
  • Go Template 3.6%
  • Other 0.3%