Skip to content

Commit

Permalink
Merge branch 'auth_bot' into new_decoder_refactoring from #46
Browse files Browse the repository at this point in the history
  • Loading branch information
quenbyako committed Dec 21, 2020
2 parents 6582c6e + 4a75810 commit faf556e
Show file tree
Hide file tree
Showing 10 changed files with 217 additions and 62 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
# MTProto

![help wanted](https://img.shields.io/badge/-help%20wanted-success)
[![godoc reference](https://pkg.go.dev/badge/github.com/xelaj/mtproto?status.svg)](https://pkg.go.dev/github.com/xelaj/mtproto)
[![Go Report Card](https://goreportcard.com/badge/github.com/xelaj/mtproto)](https://goreportcard.com/report/github.com/xelaj/mtproto)
[![codecov](https://codecov.io/gh/xelaj/mtproto/branch/master/graph/badge.svg)](https://codecov.io/gh/xelaj/mtproto)
[![license MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/xelaj/mtproto/blob/master/README.md)
[![chat telegram](https://img.shields.io/badge/chat-telegram-0088cc)](https://bit.ly/2xlsVsQ)
![version v0.1.0](https://img.shields.io/badge/version-v0.1.0-red)
![version v0.5.0](https://img.shields.io/badge/version-v0.5.0-yellow)
![unstable](https://img.shields.io/badge/stability-unstable-yellow)
<!--
code quality
golangci
contributors
go version
gitlab pipelines
Expand Down Expand Up @@ -194,12 +192,14 @@ Technically — yes. In practice — components don't require specific architect

Please read [contributing guide](https://github.com/xelaj/mtproto/blob/master/docs/en_US/CONTRIBUTING.md) if you want to help. And the help is very necessary!

**Don't want code?** Read [this](https://github.com/xelaj/mtproto/blob/master/docs/en_US/nocode_contributing.md) page! We love nocoders!

## TODO

- [x] Basic MTProto implementation
- [x] Implement all Methods for latest layer
- [x] Make TL Encoder/Decoder
- [ ] Get away from panics in parsing TL
- [x] Get away from panics in parsing TL
- [ ] Support MTProxy
- [ ] Support socks5 as well
- [ ] Multiple tests
Expand Down
31 changes: 31 additions & 0 deletions docs/en_US/nocode_contributing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Ways to contribute, without coding, in just 5-10 minutes

So, you're ready to help this project, but you don't wanna code? This guide is right for you! Plenty of you wonderful people have asked how to help but don't know how to create any algorithms or even hot to write programs on golang 😄

Fear not! There are lots of things you can do to help the project, and here we collected some amazing ideas how to make this project rock!

## Help Spread the Word

* Write any tutorials, cheatsheets or just a review (it must be honest) at any programming forums, blogs, etc. good one are [golangbridge](https://forum.golangbridge.org/), [google group](https://groups.google.com/g/golang-nuts), [ycombinator](https://news.ycombinator.com/newest), [Habr](https://habr.com), (habr also welcoming english posts btw), yandex zen, etc. or any telegram channels like [gogolang](https://t.me/gogolang) (if you found any other resources, add it, just create PR here)
* Tell your friends! I mean, literally, tell someone in person, or (if Covid is still around) via some digital mechanism like chat or Zoom. If your company or team works with telegram api, tell them about it! it's dead simple, but can really help!
* Share on Twitter, Reddit, Facebook, or odnoklassniki or even Friendster (jk). Anyway, post your review with link to this repo.

The more people that use the package - the better it will get. I can share with you (don't tell anyone!) that this package uses 10-50 unique people every day. it can grow up up to hundreds or even thousands. So int this community we can find amazing developers which can improve this project!

## Send bug reports and ask questions

This is one of the most important contributions in any package for improving stability. Found bug? Create issue. Have some problems? ask it! (just don't ask about what food does love your cat, i mean, problems with this package)

## Improve docs or tell us about hacking package

* Did you learn how to do something cool in mtproto but it wasn't obvious on first try? You can contribute to our documentation!
* Docs doesn't cover some specific things? tell us about that!
* you know how to do something, which this package doesn't fit? Cool, share this info about that!

## Improve current TL schema!

Unfortunately, native telegram tl schema doesn't have docs. But we love docs! So just copypaste it from official telegram docs, it would be amazing contribution!

## Another ways to contribute

This is not **full** list of ideas, how to help this project. Wait, i got another one idea: if you have more nocode contributing ideas: **make PR, post this idea here!** No seriously, we can even make standard guide how to contribute for nocoders like code of conduct but in another way, you know, "code of nocode contributors" 🙃
57 changes: 0 additions & 57 deletions docs/ru_RU/README_old.md

This file was deleted.

31 changes: 31 additions & 0 deletions docs/ru_RU/nocode_contributing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Способы внести свой вклад без кода всего за 5-10 минут

Итак, вы готовы помочь этому проекту, но не хотите писать код? Это руководство написано специально для вас! Многие из вас спрашивали, как помочь в развитии проекта, но не все умеют писать какие-либо алгоритмы или даже не умеют писать программы на го 😄

Но боятся не нужно! Есть много проблем, которые вы можете решить, чтобы помочь проекту! Так что здесь мы собрали несколько замечательных идей, как сделать этот проект лучше!

## Помогите распостранить информацию

* Напишите туториалы, cheatsheets или просто обзор (только чур честный) на любых форумах разработки, в блогах и подобных местах. Хорошими вариантами являются [golangbridge](https://forum.golangbridge.org/), [группа в Google](https://groups.google.com/g/golang-nuts), [ycombinator](https://news.ycombinator.com/newest), [Habr] (http://habr.com), (хабр кстати приветствует английские посты, можете писать на английском), яндекс дзен и т. д. или любые телеграммы, такие как [gogolang](https://t.me/gogolang) (если вы нашли какие-либо другие ресурсы, добавьте их, просто создайте PR, в котором допишите еще интересные места)
* Друзьям расскажите своим! Ну типа, прям буквально, поделитесь информацией об этом проекте с кем-нибудь лично или (если в вашем будущем из-за ковида еще ничего не открылось) через какой-нибудь цифровой механизм, типа чатов, или зума. А если ваша компания или команда работает с апи телеграма, то это еще лучше, поделитесь с ними! Это очень просто, но действительно может помочь!
* Share on Twitter, Reddit, Facebook, or odnoklassniki or even Friendster (jk). Anyway, post your review with link to this repo.

The more people that use the package - the better it will get. I can share with you (don't tell anyone!) that this package uses 10-50 unique people every day. it can grow up up to hundreds or even thousands. So int this community we can find amazing developers which can improve this project!

## Send bug reports and ask questions

This is one of the most important contributions in any package for improving stability. Found bug? Create issue. Have some problems? ask it! (just don't ask about what food does love your cat, i mean, problems with this package)

## Improve docs or tell us about hacking package

* Did you learn how to do something cool in mtproto but it wasn't obvious on first try? You can contribute to our documentation!
* Docs doesn't cover some specific things? tell us about that!
* you know how to do something, which this package doesn't fit? Cool, share this info about that!

## Improve current TL schema!

Unfortunately, native telegram tl schema doesn't have docs. But we love docs! So just copypaste it from official telegram docs, it would be amazing contribution!

## Another ways to contribute

This is not **full** list of ideas, how to help this project. Wait, i got another one idea: if you have more nocode contributing ideas: **make PR, post this idea here!** No seriously, we can even make standard guide how to contribute for nocoders like code of conduct but in another way, you know, "code of nocode contributors" 🙃
44 changes: 44 additions & 0 deletions examples/auth_bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Example of using Mtproto for Telegram bot

Mtproto lib can be used with Telegram bot, that can acess to full Telegram API, not just the simplified Telegram Bot API.

First, we need get register our bot via Telegram [@BotFather](https://t.me/BotFather) and obtain *bot token* and *bot username*.

![Obtain bot token via BotFather](img/bot_father.jpg)

Next we [register our app in Telegram](https://my.telegram.org/apps) and obtain

- ApiID
- ApiHash
- IP addresses of MTProto servers
- Public keys

![App credentials](img/telegram_org.jpg)

Save text from "Public keys" field to the `keys.pem` file.

Other credentials put to `const` section of `main.go` file.

```go
const (
// from https://my.telegram.org/apps
TgAppID = XXXXX // integer value from "App api_id" field
TgAppHash = "XXXXXXXXXXXX" // string value from "App api_hash" field
TgTestServer = "149.154.167.40:443" // string value from "Test configuration" field
TgProdServer = "149.154.167.50:443" // string value from "Production configuration" field

// from https://t.me/BotFather
TgBotToken = "XXXXX" // bot token from BotFather
TgBotUserName = "YourBotUserName" // username of the bot
)
```

Then run:

```
go run main.go
```

For my bot I have next output:

![Bot info](img/go_run.jpg)
Binary file added examples/auth_bot/img/bot_father.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/auth_bot/img/go_run.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/auth_bot/img/telegram_org.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/auth_bot/keys.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
put here the text from "Public keys" field at https://my.telegram.org/apps
105 changes: 105 additions & 0 deletions examples/auth_bot/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Example of using Mtproto for Telegram bot
package main

import (
"fmt"
"os"

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

const (
// from https://my.telegram.org/apps
TgAppID = XXXXX // integer value from "App api_id" field
TgAppHash = "XXXXXXXXXXXX" // string value from "App api_hash" field
TgTestServer = "149.154.167.40:443" // string value from "Test configuration" field
TgProdServer = "149.154.167.50:443" // string value from "Production configuration" field

// from https://t.me/BotFather
TgBotToken = "XXXXX" // bot token from BotFather
TgBotUserName = "YourBotUserName" // username of the bot
)

func main() {
client, err := telegram.NewClient(telegram.ClientConfig{
// current dir must be writable
// file 'session.json' will be created here
SessionFile: "./session.json",
// file 'keys.pem' must contain text from "Public keys" field
// from https://my.telegram.org/apps
PublicKeysFile: "./keys.pem",
// we need to use production Telegram API server
// because test server don't know about our bot
ServerHost: TgProdServer,
AppID: TgAppID,
AppHash: TgAppHash,
})
if err != nil {
fmt.Println("NewClient error:", err.Error())
os.Exit(1)
}

// Trying to auth as bot with our bot token
_, err = client.AuthImportBotAuthorization(&telegram.AuthImportBotAuthorizationParams{
Flags: 1, // reserved, must be set (not 0)
ApiId: TgAppID,
ApiHash: TgAppHash,
BotAuthToken: TgBotToken,
})
if err != nil {
fmt.Println("ImportBotAuthorization error:", err.Error())
os.Exit(1)
}

// Request info about username of our bot
uname, err := client.ContactsResolveUsername(&telegram.ContactsResolveUsernameParams{Username: TgBotUserName})
if err != nil {
fmt.Println("ResolveUsername error:", err.Error())
os.Exit(1)
}

chatsCount := len(uname.Chats)
// No chats for requested username of our bot
if chatsCount > 0 {
fmt.Println("Chats number:", chatsCount)
os.Exit(1)
}

usersCount := len(uname.Users)
// Users vector must contain single item with information about our bot
if usersCount != 1 {
fmt.Println("Users number:", usersCount)
os.Exit(1)
}

user := uname.Users[0].(*telegram.UserObj)

// dump our bot info
fmt.Println("\nSelf ->", user.Self)
fmt.Println("Username ->", user.Username)
fmt.Println("FirstName ->", user.FirstName)
fmt.Println("LastName ->", user.LastName)
fmt.Println("Id ->", user.Id)
fmt.Println("Bot ->", user.Bot)
fmt.Println("Verified ->", user.Verified)
fmt.Println("Restricted ->", user.Restricted)
fmt.Println("Support ->", user.Support)
fmt.Println("Scam ->", user.Scam)
fmt.Println("BotInfoVersion ->", user.BotInfoVersion)

// fmt.Println("Contact ->", user.Contact)
// fmt.Println("MutualContact ->", user.MutualContact)
// fmt.Println("Deleted ->", user.Deleted)
// fmt.Println("BotChatHistory ->", user.BotChatHistory)
// fmt.Println("BotNochats ->", user.BotNochats)
// fmt.Println("Min ->", user.Min)
// fmt.Println("BotInlineGeo ->", user.BotInlineGeo)
// fmt.Println("ApplyMinPhoto ->", user.ApplyMinPhoto)
// fmt.Println("AccessHash ->", user.AccessHash)
// fmt.Println("Phone ->", user.Phone)
// fmt.Println("Photo ->", user.Photo)
// fmt.Println("Status ->", user.Status)
// fmt.Println("RestrictionReason ->", user.RestrictionReason)
// fmt.Println("BotInlinePlaceholder ->", user.BotInlinePlaceholder)
// fmt.Println("LangCode ->", user.LangCode)
}

0 comments on commit faf556e

Please sign in to comment.