Retour au classement

gotd/td

Gogotd.dev

Telegram client, in Go. (MTProto API)

telegrammtprotogotdlibgolangtelegram-bottelegram-apibot-api
Croissance des étoiles
Étoiles
2.3k
Forks
199
Croissance hebdomadaire
Issues
1
1k2k
nov. 2020sept. 2022août 2024juil. 2026
ArtefactsGo Modulesgo get github.com/gotd/td
README

td Go Reference codecov stable

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/gotd/td
package main

import (
	"context"

	"github.com/gotd/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

Dépôts similaires
DIYgod/RSSHub

🧡 Everything is RSSible

TypeScriptnpmGNU Affero General Public License v3.0rsstwitter
docs.rsshub.app
45.3k10k
AstrBotDevs/AstrBot

AI Agent Assistant & development framework that integrates lots of IM platforms, LLMs, plugins and AI feature, and can be your openclaw alternative. ✨

PythonPyPIGNU Affero General Public License v3.0aichatbot
astrbot.app
37.5k2.6k
telegramdesktop/tdesktop

Telegram Desktop messaging app

C++Othertelegramtelegram-desktop
desktop.telegram.org
32.4k6.9k
tqdm/tqdm

:zap: A Fast, Extensible Progress Bar for Python and CLI

PythonPyPIOtherprogressbarprogressmeter
tqdm.github.io
31.2k1.5k
DrKLO/Telegram

Telegram for Android source

JavaMavenGNU General Public License v2.0telegram
29.6k9.8k
python-telegram-bot/python-telegram-bot

We have made you a wrapper you can't refuse

PythonPyPIGNU General Public License v3.0pythontelegram
python-telegram-bot.org
29.3k6.1k
pppscn/SmsForwarder

短信转发器——监控Android手机短信、来电、APP通知,并根据指定规则转发到其他手机:钉钉群自定义机器人、钉钉企业内机器人、企业微信群机器人、飞书机器人、企业微信应用消息、邮箱、bark、webhook、Telegram机器人、Server酱、PushPlus、手机短信等。包括主动控制服务端与客户端,让你轻松远程发短信、查短信、查通话、查话簿、查电量等。(V3.0 新增)PS.这个APK主要是学习与自用,如有BUG请提ISSUE,同时欢迎大家提PR指正

KotlinBSD 2-Clause "Simplified" Licensesmsdingding
27.2k3.3k
AZeC4/TelegramGroup

2026最新悄咪咪收集的10000+个Telegram群合集,附全网最有趣好用的机器人BOT🤖【dianbaodaohang.com】

telegramtelegram-bot
dianbaodaohang.com
22.1k1.5k
lss233/kirara-ai

🤖 可 DIY 的 多模态 AI 聊天机器人 | 🚀 快速接入 微信、 QQ、Telegram、等聊天平台 | 🦈支持DeepSeek、Grok、Claude、Ollama、Gemini、OpenAI | 工作流系统、网页搜索、AI画图、人设调教、虚拟女仆、语音对话 |

PythonPyPIGNU Affero General Public License v3.0chatgptopenai
kirara-docs.app.lss233.com
18.9k1.8k
elizaOS/eliza

Open source agentic operating system

TypeScriptnpmMIT Licenseagentagentic
elizaos.ai
18.8k5.6k
xming521/WeClone

🚀 One-stop solution for creating your AI twin from chat history 💡 Fine-tune LLMs with your chat logs to capture your unique style, then bind to a chatbot to bring your digital self to life.

PythonPyPIGNU Affero General Public License v3.0llmqwen
weclone.love
18.1k1.5k
langbot-app/LangBot

Production-grade platform for building agentic IM bots - 生产级多平台智能机器人开发平台/ Agent、知识库编排、插件系统 / Bots for Discord / Slack / LINE / Telegram / WeChat(企业微信, 企微智能机器人, 公众号) / 飞书 / 钉钉 / QQ / Matrix e.g. Integrated with ChatGPT(GPT), DeepSeek, Dify, n8n, Langflow, Coze, Claude, Gemini, GLM, Ollama, SiliconFlow, Moonshot, openclaw / hermes agent, deerflow

PythonPyPIApache License 2.0qqopenai
langbot.app
17k1.5k