Full-native go implementation of Telegram API

Overview

MTProto

godoc reference Go Report Card codecov license MIT chat telegram version v1.0.0 unstable

FINALLY! Full-native implementation of MTProto protocol on Golang!

english русский 简体中文

Features

Full native implementation

All code, from sending requests to encryption serialization is written on pure golang. You don't need to fetch any additional dependencies.





Latest API version (117+)

Lib is supports all the API and MTProto features, including video calls and post comments. You can create additional pull request to push api updates!






Reactive API updates (generated from TL schema)

All changes in TDLib and Android client are monitoring to get the latest features and changes in TL schemas. New methods are creates by adding new lines into TL schema and updating generated code!




Implements ONLY network tools

No more SQLite databases and caching unnecessary files, that you don't need. Also you can control how sessions are stored, auth process and literally everything that you want to!




Multiaccounting, Gateway mode

You can use more than 10 accounts at same time! xelaj/MTProto doesn't create huge overhead in memory or cpu consumption as TDLib. Thanks for that, you can create huge number of connection instances and don't worry about memory overload!




How to use

MTProto is really hard in implementation, but it's really easy to use. Basically, this lib sends serialized structures to Telegram servers (just like gRPC, but from Telegram LLC.). It looks like this:

func main() {
    client := &Telegram.NewClient()
    // for each method there is specific struct for serialization (<method_name>Params{})
    result, err := client.MakeRequest(&telegram.GetSomeInfoParams{FromChatId: 12345})
    if err != nil {
        panic(err)
    }

    resp, ok := result.(*SomeResponseObject)
    if !ok {
        panic("Oh no! Wrong type!")
    }
}

Not so hard, huh? But there is even easier way to send request, which is included in TL API specification:

func main() {
    client := &Telegram.NewClient()
    resp, err := client.GetSomeInfo(12345)
    if err != nil {
        panic(err)
    }

    // resp will be already asserted as described in TL specs of API
    // if _, ok := resp.(*SomeResponseObject); !ok {
    //     panic("No way, we found a bug! Create new issue!")
    // }

    println(resp.InfoAboutSomething)
}

You do not need to think about encryption, key exchange, saving and restoring session, and more routine things. It is already implemented just for you.

Code examples are here

Full docs are here

Getting started

Simple How-To

Installation is simple. Just do go get:

go get github.com/xelaj/mtproto

After that you can generate source structures of methods and functions if you wish to. To do it, use go generate

go generate github.com/xelaj/mtproto

That's it! You don't need to do anything more!

What is InvokeWithLayer?

It's Telegram specific feature. I you want to create client instance and get information about the current servers configuration, you need to do something like this:

    resp, err := client.InvokeWithLayer(apiVersion, &telegram.InitConnectionParams{
        ApiID:          124100,
        DeviceModel:    "Unknown",
        SystemVersion:  "linux/amd64",
        AppVersion:     "0.1.0",
        // just use "en", any other language codes will receive error. See telegram docs for more info.
        SystemLangCode: "en",
        LangCode:       "en",
        // HelpGetConfig() is ACTUAL request, but wrapped in InvokeWithLayer
        Query:          &telegram.HelpGetConfigParams{},
    })

Why? We don't know! This method is described in Telegram API docs, any other starting requests will receive error.

How to use phone authorization?

Example here

func AuthByPhone() {
    resp, err := client.AuthSendCode(
        yourPhone,
        appID,
        appHash,
        &telegram.CodeSettings{},
    )
	if err != nil {
        panic(err)
    }


    // You can make any way to enter verification code, like in
    // http requests, or what you like. You just need to call two
    // requests, that's main method.
	fmt.Print("Auth code:")
	code, _ := bufio.NewReader(os.Stdin).ReadString('\n')
    code = strings.Replace(code, "\n", "", -1)

    // this is ALL process of authorization! :)
    fmt.Println(client.AuthSignIn(yourPhone, resp.PhoneCodeHash, code))
}

That's it! You don't need any cycles, code is ready-to-go for async execution. You just need to follow the official Telegram API documentation.

Telegram Deeplinks

Want to deal those freaky tg:// links? See deeplinks package, here is the simplest how-to:

package main

import (
    "fmt"

    "github.com/xelaj/mtproto/telegram/deeplinks"
)

func main() {
    link, _ := deeplinks.Resolve("t.me/xelaj_developers")
    // btw, ResolveParameters is just struct for tg://resolve links, not all links are resolve
    resolve := link.(*deeplinks.ResolveParameters)
    fmt.Printf("Oh! Looks like @%v is the best developers channel in telegram!\n", resolve.Domain)
}

Docs are empty. Why?

There is a pretty huge chunk of documentation. We are ready to describe every method and object, but its requires a lot of work. Although all methods are already described here.

Does this project support Windows?

Technically — yes. In practice — components don't require specific architecture, but we didn't test it yet. If you have any problems running it, just create an issue, we will try to help.

Why Telegram API soooo unusable?

Well... Read this issue about TON source code. Use google translate, this issue will answer to all your questions.

Who use it

Contributing

Please read contributing guide if you want to help. And the help is very necessary!

Don't want code? Read this page! We love nocoders!

Security bugs?

Please, don't create issue which is describe security bug, this can be too offensive! Instead, please read this notifiaction and follow that steps to notify us about problem.

TODO

  • Basic MTProto implementation
  • Implement all Methods for latest layer
  • Make TL Encoder/Decoder
  • Get away from panics in parsing TL
  • Support MTProxy
  • Support socks5 as well
  • Multiple tests
  • Write amazing docs

Authors

License

WARNING! This project is only maintained by Xelaj inc., however copyright of this source code IS NOT owned by Xelaj inc. at all. If you want to connect with code owners, write mail to this email. For all other questions like any issues, PRs, questions, etc. Use GitHub issues, or find email on official website.

This project is licensed under the MIT License - see the LICENSE file for details

Comments
  • Get PHONE_MIGRATE_5 after sending AuthSendCode

    Get PHONE_MIGRATE_5 after sending AuthSendCode

    setCode, err := client.AuthSendCode(&telegram.AuthSendCodeParams{
    	"+86xxxx", 0000, "0000000", &telegram.CodeSettings{},
    })
    

    run auth example and get error msg like this.

    panic: Panicking because of error: sedning AuthSendCode: PHONE_MIGRATE_5 (code 303)
    
    bug fixed already 
    opened by xxxsen 24
  • Codegen: need improvements

    Codegen: need improvements

    Current version of codegen for Telegram API is awful. We need to make it more stable and better for reading.

    Also, we need to implement somehow auto documentation for types and methods. Looks like JSDoc way is good for us.

    This branch is start working on codegen tool

    enhancement fixed already 
    opened by quenbyako 18
  • Bug: api methods doesn't generate properly

    Bug: api methods doesn't generate properly

    • ОС windows 10
    • go version go1.14 windows/amd64

    взял пример https://github.com/xelaj/mtproto/tree/master/examples/auth (добавил go.mod) выполнил go get github.com/xelaj/mtproto, при выполнении go generate github.com/xelaj/mtproto выводится сообщение

    go: not generating in packages in dependency modules

    при сборки тестового примера получаю такое сообщение

    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\common.go:71:19: undefined: InputClientProxy
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\common.go:72:18: undefined: JSONValue
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\decoder_constructors.go:16:11: undefined: InputGameShortName
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\decoder_constructors.go:18:11: undefined: PageListOrderedItemText
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\decoder_constructors.go:20:11: undefined: UpdateBotInlineSend
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\decoder_constructors.go:22:11: undefined: SecureValueErrorFile
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\functions.go:26:15: undefined: CodeSettings
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\functions.go:43:88: undefined: CodeSettings
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\functions.go:43:104: undefined: AuthSentCode
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\functions.go:82:76: undefined: AuthAuthorization
    D:\GoMy\src\pkg\mod\github.com\xelaj\[email protected]\telegram\decoder_constructors.go:22:11: too many errors
    
    need investigation 
    opened by LazarenkoA 16
  • Codegen: unnecessary strict validation rules for int32 in structs

    Codegen: unnecessary strict validation rules for int32 in structs

    Let's take this piece of code for example:

    https://github.com/xelaj/mtproto/blob/b166a10d7c323689e0dd33f5cb61025d40ede778/telegram/methods.go#L3762-L3771

    For most of these fields default zero value is totally acceptable. The same goes for most structs. I believe this should be changed in the generator.

    duplicate good first issue question 
    opened by kochetkov-av 13
  • Is this repo couldn't run on windows?

    Is this repo couldn't run on windows?

    go run .\main.go panic: not implemented for windows

    goroutine 1 [running]: github.com/xelaj/go-dry.pathIsWirtable(...) D:/gopath/src/github.com/abserari/golangbot/vendor/github.com/xelaj/go-dry/path_windows.go:11
    github.com/xelaj/go-dry.PathIsWirtable(...) D:/gopath/src/github.com/abserari/golangbot/vendor/github.com/xelaj/go-dry/path.go:44 github.com/xelaj/mtproto/telegram.NewClient(0x8054c0, 0xe, 0x807247, 0x12, 0x803e67, 0xa, 0x0, 0x0, 0x0, 0x0, ...) D:/gopath/src/github.com/abserari/golangbot/vendor/github.com/xelaj/mtproto/telegram/common.go:41 +0x172 main.main() D:/gopath/src/github.com/abserari/golangbot/mtproto/auth_bot/main.go:30 +0x178 exit status 2

    bug good first issue 
    opened by abserari 12
  • [FEAT]: add support for WebSocket transports

    [FEAT]: add support for WebSocket transports

    Is your feature request related to a problem? Please describe.

    I think if this project can support MTProto connection over WebSocket, it'll be able to solve the blocking problem of some ISPs.

    Describe the solution you'd like

    For API, maybe we can add a field like WSEndpoint (an HTTP URL string) to the mtproto.Config. If both ServerHost and WSEndpoint have values, WSEndpoint takes precedence.

    Describe alternatives you've considered

    N/A

    Additional context

    https://core.telegram.org/mtproto/transports#websocket

    https://core.telegram.org/mtproto/mtproto-transports#transport-obfuscation

    enhancement help wanted 
    opened by aofei 8
  • [BUG]: getting stuck inside AddCustomServerRequestHandler

    [BUG]: getting stuck inside AddCustomServerRequestHandler

    i have this very short example of where i want to mark messages as read:

    client.AddCustomServerRequestHandler(func(update interface{}) bool {
    	switch u := update.(type) {
    	case *telegram.UpdateShortMessage:
    		peer := &telegram.InputPeerUser{
    			UserID:     123,
    			AccessHash: 456,
    		}
    
    		_, err := client.MessagesReadHistory(peer, u.ID)
    		if err != nil {
    			panic(err)
    		}
    
    		print("here") <----------------
    	}
    
    	return false
    })
    
    state, err := client.UpdatesGetState()
    if err != nil {
    	panic(err)
    }
    

    the message is being marked as read on the senders device but i am never getting to "here" so all other subsequent messages are stuck as well because AddCustomServerRequestHandler never returns.

    bug need investigation 
    opened by jackfreed 6
  • [BUG]: missing port in dc list

    [BUG]: missing port in dc list

    Description

    After getting PHONE_MIGRATE_5 err, it would call reconnect with new dc address from dclist, but the format of the ipaddress in dclist is wrong.

    in telegram/common.go func: NewClient image

    image

    valid format should like this: in utils.go func: defaultDCList image

    Failed snippet

    Expected behavior

    Additional context

    bug good first issue 
    opened by xxxsen 5
  • Need more examples

    Need more examples

    The lack of descriptions for methods and fields of structures makes it very difficult to work with the code, it is difficult to understand something yourself. Please post more working examples, such as getting a contact list, how to send a message to a specific user, etc., such basic things.

    question 
    opened by LazarenkoA 5
  • Panic when try to UploadSaveBigFilePart

    Panic when try to UploadSaveBigFilePart

    When I do

    _, err := client.UploadSaveBigFilePart(&telegram.UploadSaveBigFilePartParams{
    	FileId:         somefileid,
    	FilePart:       filepart,
    	FileTotalParts: total,
    	Bytes:          filepartBypes,
    })
    

    I always got an error

    panic: constructorID '0x997275b5' not found [recovered]
    	panic: constructorID '0x997275b5' not found
    
    goroutine 6 [running]:
    github.com/xelaj/mtproto.(*MTProto).recoverGoroutine(0xc0002fe000)
    	/home/paval/go/pkg/mod/github.com/xelaj/[email protected]/mtproto_utils.go:77 +0x125
    panic(0xb7d960, 0xc0002a0180)
    	/usr/local/go/src/runtime/panic.go:969 +0x175
    github.com/xelaj/mtproto/serialize.(*Decoder).PopObj(0xc0002a0100, 0x5fdbbf3000ed7490, 0xc0002a0120)
    	/home/paval/go/pkg/mod/github.com/xelaj/[email protected]/serialize/decoder.go:169 +0x23a
    github.com/xelaj/mtproto/serialize.(*RpcResult).DecodeFrom(0xc0002a0120, 0xc0002a0100)
    	/home/paval/go/pkg/mod/github.com/xelaj/[email protected]/serialize/common_types.go:279 +0x46
    github.com/xelaj/mtproto.(*MTProto).processResponse(0xc0002fe000, 0x5fdbbf3059fc5801, 0x7, 0xe238e0, 0xc0002e6000, 0xc0002e6000, 0x0)
    	/home/paval/go/pkg/mod/github.com/xelaj/[email protected]/mtproto.go:303 +0xbe5
    github.com/xelaj/mtproto.(*MTProto).startReadingResponses.func1(0xc0002fe000, 0xe25120, 0xc0002ea180)
    	/home/paval/go/pkg/mod/github.com/xelaj/[email protected]/mtproto.go:277 +0x296
    created by github.com/xelaj/mtproto.(*MTProto).startReadingResponses
    	/home/paval/go/pkg/mod/github.com/xelaj/[email protected]/mtproto.go:253 +0x70
    exit status 2
    
    good first issue fixed already 
    opened by blez 4
  • Codegen improvements

    Codegen improvements

    Добавлен альтернативный энкодер, не использующий reflect (work-in-progress) Сгенерил api_117.tl в out/ чисто чтобы визуально глянуть, вроде норм.

    Добавил сортировку полей чтобы не офигевать от дифов (https://github.com/xelaj/mtproto/issues/16) Исправил module path Пакет go-dry вырезал т.к. у меня почему-то с ним кодген не собирался. Ну и еще много чего вырезал (стдлиб вошел в чат)

    # github.com/xelaj/go-dry
    github.com\xelaj\[email protected]\path.go:48:9: undefined: unix.Access
    github.com\xelaj\[email protected]\path.go:48:34: undefined: unix.W_OK
    

    (Думаю из-за того что винда, а пакету нужна никсовая либа)

    enhancement need investigation good first PR hacktoberfest-accepted hacktoberfest 
    opened by shadowspore 4
  • Msgid fix

    Msgid fix

    Note Original author is @AmarnathCJD

    Describe your feature

    Possible fix for [reading message: processing response: msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno) (code 33)]

    • [x] this PR was checked by golangci-linter
    • [x] new code did not break current interfaces
    • [x] all comments were written on american english language
    • [x] all commit messages are spiced up with emojis, which wa defined in CG and in .gitmessage

    This PR improve... #103

    Main purpose

    Possible issues

    bug need investigation critical 
    opened by quenbyako 1
  • Make sure messageID never be lesser than previous messageID (code 33)

    Make sure messageID never be lesser than previous messageID (code 33)

    Describe your feature

    Possible fix for [reading message: processing response: msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno) (code 33)]

    • [x] this PR was checked by golangci-linter
    • [x] new code did not break current interfaces
    • [x] all comments were written on american english language
    • [x] all commit messages are spiced up with emojis, which wa defined in CG and in .gitmessage

    This PR improve... #103

    Main purpose

    Possible issues

    @quenbyako, please add these labels: label1,label2,label3

    bug need investigation good first PR critical 
    opened by AmarnathCJD 1
  • [BUG]: Wrong comments in generated code

    [BUG]: Wrong comments in generated code

    Description

    All methods in telegram/methods_gen.go have the same comment Sends a Telegram Passport authorization form, effectively sharing data with the service.

    It's already hard enough to use this library as it is but having no actual comments about what certain methods do makes it even harder. And always having to search the exact method in the telegram api specs is kinda annoying. Aren't there descriptions of the methods in the .tl files which can be adopted?

    bug 
    opened by jon4hz 1
  • [FEAT]: Move file /internal/session/interface.go from folder /internal

    [FEAT]: Move file /internal/session/interface.go from folder /internal

    Is your feature request related to a problem? Please describe.

    This small change will allow to:

    1. create implementation of SessionLoader for various client-server solutions;
    2. will allow to make a multi-user application, because. it will be possible for each user to load his own session.

    Describe the solution you'd like

    Just move file /internal/session/interface.go from folder /internal to make types SessionLoader and Session public.

    Thank you!

    enhancement 
    opened by Kalinin-Andrey 0
  • Function doesn't exist

    Function doesn't exist

    Hi everyone,

    In the Example folder for auth user in line 49 function IsSessionRegistred() cannot access from the code, if the name changed or you have implemented another function for this action please mention it.

    https://github.com/xelaj/mtproto/blob/497fd3728e4696e0a091332436f778af2062270a/examples/auth/main.go#L49

    Thanks

    opened by amirrmonfared 1
Releases(v1.0.0)
Owner
Xelaj technologies
Xelaj technologies
The serverless OTP telegram service use telegram as OTP service, and send OTP through webhook

Setup OTP First thing, you need prepare API(webhook) with POST method, the payload format as below { "first_name": "Nolan", "last_name": "Nguyen",

Dong Nguyen 3 Jul 24, 2022
Dlercloud-telegram-bot - A Telegram bot for managing your Dler Cloud account

Dler Cloud Telegram Bot A Telegram bot for managing your Dler Cloud account. Usa

Beta Kuang 1 Dec 30, 2021
Pro-bot - A telegram bot to play around with the community telegram channels

pro-bot ?? Pro Bot A Telegram Bot to Play Around With The Community Telegram Cha

TechProber 1 Jan 24, 2022
Tg-channel-api - A JSON API for latest messages of public Telegram channels

Telegram Channel API A JSON API for latest messages of public Telegram channels.

null 5 Oct 27, 2022
Golang telegram bot API wrapper, session-based router and middleware

go-tgbot Pure Golang telegram bot API wrapper generated from swagger definition, session-based routing and middlewares. Usage benefits No need to lear

Oleg Lebedev 118 Nov 16, 2022
Client lib for Telegram bot api

Micha Client lib for Telegram bot api. Supports Bot API v2.3.1 (of 4th Dec 2016). Simple echo bot example: package main import ( "log" "git

Andrey 23 Nov 10, 2022
Go library for Telegram Bot API

tbot - Telegram Bot Server Features Full Telegram Bot API 4.7 support Zero dependency Type-safe API client with functional options Capture messages by

Alexey Grachov 331 Nov 11, 2022
Golang bindings for the Telegram Bot API

Golang bindings for the Telegram Bot API All methods are fairly self explanatory, and reading the godoc page should explain everything. If something i

null 4.1k Nov 23, 2022
Bot that polls activity API for Github organisation and pushes updates to Telegram.

git-telegram-bot Telegram bot for notifying org events Requirements (for building) Go version 1.16.x Setup If you don't have a telegram bot token yet,

Skycoin 4 Apr 8, 2022
Flexible message router add-on for go-telegram-bot-api library.

telemux Flexible message router add-on for go-telegram-bot-api library. Table of contents Motivation Features Minimal example Documentation Changelog

Andrew Dunai 24 Oct 24, 2022
WIP Telegram Bot API server in Go

botapi The telegram-bot-api, but in go. WIP. Reference: https://core.telegram.org/bots/api Reference implementation: https://github.com/tdlib/telegram

gotd 17 Nov 25, 2022
A bot based on Telegram Bot API written in Golang allows users to download public Instagram photos, videos, and albums without receiving the user's credentials.

InstagramRobot InstagramRobot is a bot based on Telegram Bot API written in Golang that allows users to download public Instagram photos, videos, and

FTC Team 8 Dec 16, 2021
Golang bindings for the Telegram Bot API

Golang bindings for the Telegram Bot API All methods are fairly self explanatory, and reading the godoc page should explain everything. If something i

null 0 Nov 18, 2021
UcodeQrTelebot ver2 - Easy way to get QR and U-code using Utopia API in telegram bot

UcodeQrTelebot Easy way to get QR and U-code using Utopia API in telegram bot Us

null 1 Dec 30, 2021
IRC, Slack, Telegram and RocketChat bot written in go

go-bot IRC, Slack & Telegram bot written in Go using go-ircevent for IRC connectivity, nlopes/slack for Slack and Syfaro/telegram-bot-api for Telegram

null 766 Nov 26, 2022
Telegram Bot Framework for Go

Margelet Telegram Bot Framework for Go is based on telegram-bot-api It uses Redis to store it's states, configs and so on. Any low-level interactions

Gleb Sinyavskiy 75 Nov 16, 2022
Telebot is a Telegram bot framework in Go.

Telebot "I never knew creating Telegram bots could be so sexy!" go get -u gopkg.in/tucnak/telebot.v2 Overview Getting Started Poller Commands Files Se

Ian P Badtrousers 2.8k Nov 28, 2022
Golang Based Account Generator Telegram Bot

Account Generator Bot Account Generator Bot, written in GoLang via gotgbot library. Variables Env Vars - BOT_TOKEN - Get it from @BotFather CHANNEL_ID

Anonymous Indian 37 Nov 21, 2022
The command line utility for Telegram

cli The command line interface for telegram. $ go install github.com/gotd/cli/cmd/[email protected] Usage First, initialize configuration (currently only for

gotd 9 Nov 12, 2022