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

Issues
  • 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 21
  • 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
  • MTProto 1.0! Now ready to release!

    MTProto 1.0! Now ready to release!

    This branch contains stable 1.0 release candidate.

    Leave here feedback about how does it works!

    opened by quenbyako 9
  • [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
  • Replace github.com/pkg/errors with stdlib errors wrapping

    Replace github.com/pkg/errors with stdlib errors wrapping

    enhancement good first PR wontfix 
    opened by xakep666 6
  • 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
  • Recommend getting latest commit?

    Recommend getting latest commit?

    Description

    The current stable version (v1.0.0), which is the version you get with go get github.com/xelaj/mtproto has various issues that have since been resolved. For example this issue. Also, some functions like client.IsSessionRegistered(), which exist in the example codes don't exist in the current release. (Typo in the function name btw.).

    Proposition

    Change the go get command in the README to go get -u github.com/xelaj/[email protected] as this (with @main) fetches the latest commit. Alternatively you could release a new Release (v1.1.0 ?). This would've saved me some time.

    bug 
    opened by mqrc81 0
  • Possible fix of #49

    Possible fix of #49

    opened by hookzof 2
  • Add example for entities formatting

    Add example for entities formatting

    I've decomposed my work on formatting the text with telegram.MessageEntity from https://github.com/umputun/feed-master/pull/37 into the smallest example I could prepare to simplify writing this code for future generations.

    opened by paskal 1
  • Add example for big audio file upload

    Add example for big audio file upload

    I've decomposed my work on uploading a big (50Mb+) audio file from https://github.com/umputun/feed-master/pull/37 into the smallest example I could prepare to simplify writing this code for future generations.

    enhancement good first PR 
    opened by paskal 1
  • update to latest layer 129

    update to latest layer 129

    when trying to update to the latest layer 129 i am getting an error about PseudoBool not found.

    any idea?

    bug critical 
    opened by jackfreed 2
  • [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 3
  • Reconnection doesn't work

    Reconnection doesn't work

    Hi,

    If you try calling client.Reconnect() after the connection is successful (let's say 30 seconds after connection) the app is unable to reconnect to the Telegram servers. It just hangs... (maybe some mutex or full channel)

    Daniel

    bug 
    opened by innovative-sol 2
  • [FEAT]: please add support for receiving media

    [FEAT]: please add support for receiving media

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

    There is no support of media updates. I'm receiving message of objects.GzipPacked type, which is internal type. 😞

    Describe the solution you'd like

    I want to receive different types depending on the message (audio, video, document), and content in bytes.

    Describe alternatives you've considered

    Don't see alternatives.

    Additional context

    I'm receiving objects.GzipPacked in CustomServerRequestHandler function

    enhancement need investigation 
    opened by path22 3
  • [FEAT]: add support for context.Context

    [FEAT]: add support for context.Context

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

    I think people may prefer to have the ability to cancel their requests at any time.

    Describe the solution you'd like

    Add context.Context to every func/method that involves network operations.

    Describe alternatives you've considered

    N/A

    Additional context

    This isn't a difficult feature to implement. What needs to be considered is the API compatibility (since this module have already released v1.0.0).

    enhancement good first issue 
    opened by aofei 1
  • [FEAT]: Create updates processing subsystem

    [FEAT]: Create updates processing subsystem

    Problem description:

    Since we have a lot of issues and requests for making utilities to get, handle and process telegram updates, we need to create separate subsystem for it. It must be splitted by specific subsystem. cause some projects doesn't need get updates at all.

    Solution:

    The idea is to make a separate subpackage that wraps around the telegram.Client itself, very similar to the existing deeplinks package. Perhaps we will be able to make a manager of such updates so as not to load the main components (telegram.Client andmtproto.Client), since not in all cases users need to receive updates.

    Possible alternatives:

    Leave this problem to end users, but i'm not sure that it's a good solution.

    Additional context

    Linked issues:

    • #72 updates channel stops exactly after 1 minute after calling cleint.UpdatesGetState
    • multiple requests in our telegram chat
    enhancement 
    opened by quenbyako 0
Releases(v1.0.0)
Owner
Xelaj technologies
Xelaj technologies
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 12 Jul 20, 2021
easy-peasy wg tg bot

wireguard-telegram-bot Simple-Dimple Telegram Bot for Wireguard VPN config generation Functionality /menu — list available commands /newkeys — create

Sergey Skaredov 12 Jun 7, 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 3k Jul 23, 2021
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 2k Jul 22, 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 686 Jul 17, 2021
A lightweight, universal cloud drive upload tool for all platforms

简体中文 LightUploader MoeClub wrote a very good version, but unfortunately it's not open source and hasn't been updated in a while. This project is a sim

高玩梁 178 Jul 13, 2021
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 3 May 13, 2021
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 62 Jul 15, 2021
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 107 May 28, 2021
A lightweight, universal OneDrive upload tool for all platforms

简体中文 OneDriveUploader MoeClub wrote a very good version, but unfortunately it's not open source and hasn't been updated in a while. This project is a

高玩梁 178 Jul 13, 2021
lightning - forward messages between a qq group and a telegram group

lightning The purpose of this project is to forward messages between a qq group and a telegram group. Getting Started Clone this project: git clone ht

方泓睿 6 Jun 17, 2021
Telegram bot to get information on vaccine availabilities.

?? berlin-vaccine-alert Telegram bot to get information on vaccine availabilities. Get the latest appointments directly on telegram. The bot listen to

Erwan Leboucher 14 Jul 20, 2021
A Telegram Repo For Bots Under Maintenance Which Gives Faster Response To Users

Maintenance Bot A Telegram Repo For Bots Under Maintenance Which Gives Faster Response To Users Requests » Report a Bug | Request Feature Table of Con

HEIMAN PICTURES 6 Jul 4, 2021
The modern cryptocurrency trading bot written in Go.

bbgo A trading bot framework written in Go. The name bbgo comes from the BB8 bot in the Star Wars movie. aka Buy BitCoin Go! Current Status Features E

Yo-An Lin 331 Jul 24, 2021