Где взять api hash telegram
Перейти к содержимому

Где взять api hash telegram

  • автор:

 

GramJS

Before working with Telegram’s API, you need to get your own API ID and hash:

    with the phone number of the developer account to use.
  1. Click under API Development tools.
  2. A Create new application window will appear. Fill in your application details. There is no need to enter any URL, and only the first two fields (App title and Short name) can currently be changed later.
  3. Click on Create application at the end. Remember that your API hash is secret and Telegram won’t let you revoke it. Don’t post it anywhere!

Logging in as a Bot

Using GramJS you can use a bot token to log in. Doing this is simple

Underneath this is just calling the RAW function ImportBotAuthorization . you can leave the string session empty for now.

Logging in as a User

Logging in as a user is a bit more complex because you’ll need to provide callbacks for when you receive the code from telegram. you can use the input package to manage that on Node or prompt on the browser

Using MTProxies and Socks5 Proxies.

You can also use MTProxies or a normal Socks proxy to connect to telegram servers.

Persistent Session

To avoid having to logging each time you’ll need to save the session after logging in. There are multiple types of sessions with the easiest being StringSession that will provide an Authorization string for you to use again. You can create your own Session by subclassing the MemorySession class.

If you have async logic in your custom session put it in the load() function that’s called before loading a session.

String Session

You can import it from telegram/session

If you’re using it for the first login you need to provide an empty String to the constructor

After logging in you’ll need to call the .save() method to receive the string

You can either do that by calling it directly on the stringSession variable or by using client.session

Store Session

Store session uses store2 with the help of node-localstorage to save the session automatically in files. it’s useful to save entities so you can access them later with just their ID and lowers the amount of requests needed to the telegram server. You just need to provide a session name to save it with

This session is still in Alpha and not tested that much so it might break. use carefully.

Создание своего клиента Telegram

Все разработчики могут использовать API и исходный код Telegram, чтобы бесплатно создавать похожие приложения на этой платформе.

В целях обеспечения совместимости и безопасности в экосистеме, все сторонние клиенты должны соответствовать Условиям использования API.

Получение api_id

Для получения API id и возможности разработать собственный клиент на основе Telegram API нужно сделать следующее:

  • Зарегистрироваться в Telegram, используя любой клиент.
  • Авторизоваться в Telegram по ссылке: https://my.telegram.org.
  • Перейти по ссылке ‘API development tools’ и заполнить форму.
  • Будут получены адреса и параметры api_id и api_hash, необходимые для авторизации пользователя.
  • На данный момент к любому номеру может быть привязан только один api_id.

Важные оповещения для разработчиков будут присылаться по указанному телефону, поэтому рекомендуется использовать актуальный номер, к которому привязан активный аккаунт Telegram.

Использование открытого исходного кода Telegram

Открытый исходный код Telegram доступен для всех. К нему также прилагается пример API id, использование которого ограничено и возможно лишь для серверной части. Его нельзя применять в приложениях для конечного пользователя – попытки использовать этот API id для любых целей, кроме тестирования, вызовут ошибку API_ID_PUBLISHED_FLOOD на стороне пользователей. Поэтому перед выпуском клиента необходимо получить собственный API id.

Для соответствия лицензии GNU GPL разработчику также необходимо выложить в открытый доступ исходный код своего приложения.

Сайт про Telegram на русском (неофициальный).

Здесь собраны приложения на базе MTProto, переведена некоторая документация с официального сайта, а также работает Webogram.

Создание и развертывание ретранслятора Telegram каналов, используя Python и Heroku

В данной инструкции построим Python приложение для зеркалирования сообщений из Telegram каналов и развернем его на облачной платформе Heroku.

Идея проста — получить сообщение и тут же переотправить или переслать его.

Ввиду ограниченности Bot API, нет возможности добавить бота в канал, где вы не администратор. Поэтому будем использовать клиентский API, заходя на нужные каналы вручную (хотя и этот шаг можно автоматизировать).

По ходу действий нам понадобятся:

  • Аккаунт Telegram. Лучше перестраховаться и завести отдельный аккаунт, благо на сервисах приема SMS его цена составляет

Для работы с клиентским API необходимо создать приложение Telegram. Сделать это можно по ссылке. Здесь нас интересуют два значения: api_id и api_hash.

Полученные значения api_id и api_hash занесем во вновь созданный файл переменных окружения .env:

При использовании системы контроля версий, не забудьте добавить файл .env в список исключения.

Создадим папку проекта. Все последующие действия будем делать в ней.

Настроим виртуальное Python окружение для изоляции приложения от других глобальных зависимостей системы:

Активируем виртуальное окружение:

Последующая установка новых Python пакетов будет производиться в данном виртуальной окружении.

В качестве библиотеки для взаимодействия с Telegram API будем использовать Telethon:

Для загрузки значений переменных окружения установим пакет python-dotenv:

Создадим файл config.py, где будем хранить и загружать переменные окружения в память приложения:

Скрипт авторизации, целью которого является получение идентификатора сессии, выглядит следующим образом:

После ввода номера телефона и кода, пришедшего в приложение Telegram, получаем заветный идентификатор сессии, который добавим в файл .env.

Теперь, используя вновь полученный идентификатор сессии, авторизуемся для дальнейшего взаимодействия с Telegram API:

Присоединившись к каналу, серверы Telegram начинают слать нам соответствующие обновления (новые сообщения, отредактированные сообщения и др.). Остается лишь перенаправить их в наш канал.

Определим идентификаторы канала-источника (SOURCE_CHANNEL) и канала-приемника (TARGET_CHANNEL):

Каналы имеют обыкновение менять свои ссылки, но что остается неизменным — это их идентификаторы (число с префиксом -100). Узнать идентификатор можно с помощью Telegram бота @messageinformationsbot, переслав ему любое сообщение из интересующего вас канала.

Следуя примеру из документации, добавим обработчик новых сообщений:

Для каждого нового сообщения в функцию handler_new_message приходит объект типа NewMessage, содержащий поле message с необходимой нам информацией. Т.к. нам необходимы обновления только от определенных каналов, при определении обработчика передадим ему параметр chats, содержащий идентификатор либо список идентификаторов каналов.

Для успешной отправки сообщений в Telegram канал необходимо, чтобы аккаунт, которым авторизовались в приложении, имел на это соответствующие права.

В случае переотправки пришедших сообщений (использование метода client.send_message), при отредактированном сообщении в канале-источнике, можем отредактировать его и в канале-приемнике.

Для реализации редактирования необходимо знать какое именно сообщение редактировать, поэтому при добавлении нового сообщения, нужно сохранить идентификаторы исходного и копии сообщения. В дальнейшем по идентификатору сообщения из источника сможем определить идентификатор сообщения в нашем канале.

Установим базу данных Postgres, если этого не было сделано ранее. Сама установка не должна вызвать сложностей:

  • Для вашей операционной системы скачать установщик;
  • Запустить его, оставив параметры по умолчанию. Единственное, что стоит запомнить это логин и пароль пользователя базы данных:
  • Добавить к переменной окружения PATH путь к используемым файлам Postgres.
    Для Windows: C:\Program Files\PostgreSQL\<ВЕРСИЯ>\bin, инструкция по установке переменных окружения.

Далее первоначальное взаимодействие с базой будем производить с помощью утилиты psql:

Для хранения соответствий идентификаторов определим простейшую таблицу BINDING_ID:

Создадим таблицу BINDING_ID в консоли утилиты psql командой:

Взаимодействие с базой данных будем производить с помощью пакета psycopg2:

В файл .env добавим строку подключения к базе данных вида:

В случае развертывания на Heroku и использования Postgresql дополнения, для приложения в облаке переменная окружения DATABASE_URL устанавливается автоматически. Поэтому при развертывании в облаке DATABASE_URL устанавливать не нужно.

Для работы с базой данных определим следующие базовые функции: добавление соответствия идентификаторов сообщений (insert) и поиск идентификатора сообщения-клона по идентификатору оригинального сообщения (find_by_id):

В функцию обработчика новых сообщений добавим сохранение идентификаторов сообщений в базе данных:

Тогда редактирование сообщений будет выглядеть следующим образом:

Ознакомиться с текущим вариантом проекта можно по ссылке ниже:

Для случая зеркалирования «один к одному» у нас все готово и можно переходить к развертыванию.

Когда каналов-источников и каналов, в которые необходимо пересылать сообщения, больше чем один, необходимо задать их взаимное соответствие.

Задавать карту соответствий прямо в коде — не вариант, поэтому для значения новой переменной окружения (CHANNELS_MAPPING) введем специальный формат записи:

Теперь вместо ранее заданных переменных SOURCE_CHANNEL и TARGET_CHANNEL имеем CHANNELS_MAPPING:

Для дальнейшей работы из строкового значения CHANNELS_MAPPING нужно получить представление в виде словаря (dict). Сделать это можно, разобрав строку по составляющим ее элементам с помощью регулярных выражений (модуль re) либо с помощью парсера грамматик (модуль pyparsing). В данном случае воспользуемся вторым вариантом.

 

Установим модуль pyparsing:

Так как входная строка для разбора состоит из отдельных элементов, для каждого такого элемента определим свою грамматику:

  • Основной элемент — идентификатор канала, состоящий из префикса -100 и последующих цифр:
  • Список каналов:

Подробнее о модуле pyparsing можно узнать в документации.

После составления грамматики, формируем результат разбора строки в виде словаря, где ключи — исходные каналы, значения — список целевых каналов (функция parse_string):

Инициализация переменной CHANNELS_MAPPING:

Расширим таблицу BINDING_ID двумя столбцами: идентификатор канала-зеркала (mirror_channel_id) и идентификатор канала-источника (channel_id):

Introduction to the Telegram API

Analyse your conversation history on Telegram programatically

T elegram is an instant messaging service just like WhatsApp, Facebook Messenger and WeChat. It has gained popularity in recent years for various reasons: its non-profit nature, cross-platform support, promises of security¹, and its open APIs.

In this post, we’ll use Telethon, a Python client library for the Telegram API to count the number of messages in each of our Telegram chats.

Telegram APIs

The more well-known of Telegram’s APIs is its Bot API, a HTTP-based API for developers to interact with the bot platform. The Bot API allows developers to control Telegram bots, for example receiving messages and replying to other users.

Besides the Bot API, there’s also the Telegram API itself. This is the API used by Telegram apps for all your actions on Telegram. To name a few: viewing your chats, sending and receiving messages, changing your display picture or creating new groups. Through the Telegram API you can do anything you can do in a Telegram app programatically.

The Telegram API is a lot more complicated than the Bot API. You can access the Bot API through HTTP requests with standard JSON, form or query string payloads, while the Telegram API uses its own custom payload format and encryption protocol.

The Telegram API

MTProto is the custom encryption scheme which backs Telegram’s promises of security. It is an application layer protocol which writes directly to an underlying transport stream such as TCP or UDP, and also HTTP. Fortunately, we don’t need to concern ourselves with it directly when using a client library. On the other hand, we do need to understand the payload format in order to make API calls.

Type Language

The Telegram API is RPC-based, so interacting with the API involves sending a payload representing a function invocation and receiving a result. For example, reading the contents of a conversation involves calling the messages.getMessage function with the necessary parameters and receiving a messages.Messages in return.

Type Language, or TL, is used to represent types and functions used by the API. A TL-Schema is a collection of available types and functions. In MTProto, TL constructs will be serialised into binary form before being embedded as the payload of MTProto messages, however we can leave this to the client library which we will be using.

An example of a TL-Schema (types are declared first, followed by functions with a separator in between):

A TL function invocation and result using functions and types from the above TL-Schema, and equivalent binary representation (from the official documentation):

TL-Schema layers

The Telegram API is versioned using TL-Schema layers; each layer has a unique TL-Schema. The Telegram website contains the current TL-Schema and previous layers at https://core.telegram.org/schema.

Or so it seems, it turns out that although the latest TL-Schema layer on the Telegram website is Layer 23, at time of writing the latest layer is actually already Layer 71. You can find the latest TL-Schema here instead.

Getting started

Creating a Telegram application

You will need to obtain an api_id and api_hash to interact with the Telegram API. Follow the directions from the official documentation here: https://core.telegram.org/api/obtaining_api_id.

You will have to visit https://my.telegram.org/ and login with your phone number and confirmation code which will be sent on Telegram, and fill in the form under “API Development Tools” with an app title and short name. Afterwards, you can find your api_id and api_hash at the same place.

Alternatively, the same instructions mention that you can use the sample credentials which can be found in Telegram source codes for testing. For convenience, I’ll be using the credentials I found in the Telegram Desktop source code on GitHub in the sample code here.

Installing Telethon

We’ll be using Telethon to communicate with the Telegram API. Telethon is a Python 3 client library (which means you will have to use Python 3) for the Telegram API which will handle all the protocol-specific tasks for us, so we’ll only need to know what types to use and what functions to call.

You can install Telethon with pip :

Use the pip corresponding to your Python 3 interpreter; this may be pip3 instead. (Random: Recently Ubuntu 17.10 was released, and it uses Python 3 as its default Python installation.)

Creating a client

Before you can start interacting with the Telegram API, you need to create a client object with your api_id and api_hash and authenticate it with your phone number. This is similar to logging in to Telegram on a new device; you can imagine this client as just another Telegram app.

Below is some code to create and authenticate a client object, modified from the Telethon documentation:

As mentioned earlier, the api_id and api_hash above are from the Telegram Desktop source code. Put your own phone number into the phone variable.

Telethon will create a .session file in its working directory to persist the session details, just like how you don’t have to re-authenticate to your Telegram apps every time you close and reopen them. The file name will start with the username variable. It is up to you if you want to change it, in case you want to work with multiple sessions.

If there was no previous session, running this code will cause an authorisation code to be sent to you via Telegram. If you have enabled Two-Step Verification on your Telegram account, you will also need to enter your Telegram password. After you have authenticated once and the .session file is saved, you won’t have to re-authenticate again until your session expires, even if you run the script again.

If the client was created and authenticated successfully, an object representing yourself should be printed to the console. It will look similar to (the ellipses … mean that some content was skipped):

Now you can use this client object to start making requests to the Telegram API.

Working with the Telegram API

Inspecting the TL-Schema

As mentioned earlier, using the Telegram API involves calling the available functions in the TL-Schema. In this case, we’re interested in the messages.GetDialogs function. We’ll also need to take note of the relevant types in the function arguments. Here is a subset of the TL-Schema we’ll be using to make this request:

It’s not easy to read, but note that the messages.getDialogs function will return a messages.Dialogs , which is an abstract type for either a messages.dialogs or a messages.dialogsSlice object which both contain vectors of Dialog , Message , Chat and User .

Using the Telethon documentation

Fortunately, the Telethon documentation gives more details on how we can invoke this function. From https://lonamiwebs.github.io/Telethon/index.html, if you type getdialogs into the search box, you will see a result for a method called GetDialogsRequest (TL-Schema functions are represented by *Request objects in Telethon).

The documentation for GetDialogsRequest states the return type for the method as well as slightly more details about the parameters. The “Copy import to the clipboard” button is particularly useful for when we want to use this object, like right now.

The messages.getDialogs function as well as the constructor for GetDialogsRequest takes an offset_peer argument of type InputPeer . From the documentation for GetDialogsRequest, click through the InputPeer link to see a page describing the constructors for and methods taking and returning this type.

Since we want to create an InputPeer object to use as an argument for our GetDialogsRequest , we’re interested in the constructors for InputPeer . In this case, we’ll use the InputPeerEmpty constructor. Click through once again to the page for InputPeerEmpty and copy its import path to use it. The InputPeerEmpty constructor takes no arguments.

Making a request

Here is our finished GetDialogsRequest and how to get its result by passing it to our authorised client object:

In my case, I got back a DialogsSlice object containing a list of dialogs, messages, chats and users, as we expected based on the TL-Schema:

Receiving a DialogsSlice instead of Dialogs means that not all my dialogs were returned, but the count attribute tells me how many dialogs I have in total. If you have less than a certain amount of conversations, you may receive a Dialogs object instead, in which case all your dialogs were returned and the number of dialogs you have is just the length of the vectors.

Terminology

The terminology used by the Telegram API may be a little confusing sometimes, especially with the lack of information other than the type definitions. What are “dialogs”, “messages”, “chats” and “users”?

  • dialogs represents the conversations from your conversation history
  • chats represents the groups and channels corresponding to the conversations in your conversation history
  • messages contains the last message sent to each conversation like you see in your list of conversations in your Telegram app
  • users contains the individual users with whom you have one-on-one chats with or who was the sender of the last message to one of your groups

For example, if my chat history was this screenshot I took from the Telegram app in the Play Store:

dialogs would contain the conversations in the screenshot: Old Pirates, Press Room, Monika, Jaina…

chats would contain entries for Old Pirates, Press Room and Meme Factory.

messages will contain the messages “All aboard!” from Old Pirates, “Wow, nice mention!” from Press Room, a message representing a sent photo to Monika, a message representing Jaina’s reply and so on.

users will contain an entry for Ashley since she sent the last message to Press Room, Monika, Jaina, Kate and Winston since he sent the last message to Meme Factory.

(I haven’t worked with secret chats through the Telegram API yet so I’m not sure how they are handled.)

Counting messages

Our objective is to count the number of messages in each conversation. To get the number of messages a conversation, we can use the messages.getHistory function from the TL-Schema:

Following a similar process as previously with messages.getDialogs , we can work out how to call this with Telethon using a GetHistoryRequest . This will return either a Messages or MessagesSlice object which either contains a count attribute telling us how many messages there are in a conversation, or all the messages in a conversation so we can just count the messages it contains.

However, we will first have to construct the right InputPeer for our GetHistoryRequest . This time, we use InputPeerEmpty since we want to retrieve the message history for a specific conversation. Instead, we have to use either the InputPeerUser , InputPeerChat or InputPeerChannel constructor depending on the nature of the conversation.

Manipulating the response data

In order to count the number of messages in each of our conversations, we will have to make a GetHistoryRequest for that conversation with the appropriate InputPeer for that conversation.

All of the relevant InputPeer constructors take the same id and access_hash parameters, but depending on whether the conversation is a one-on-one chat, group or channel, these values are found in different places in the GetDialogsRequest response:

  • dialogs : a list of the conversations we want to count the messages in and contains a peer value with the type and id of the peer corresponding to that conversation, but not the access_hash .
  • chats : contains the id , access_hash and titles for our groups and channels.
  • users : contains the id , access_hash and first name for our individual chats.

In pseudocode, we have:

Converting to Python code (note that dialogs , chats and users above are members of the result of our GetDialogsRequest which is also called dialogs ):

Our counts object is a dictionary of chat names to message counts. We can sort and pretty print it to see our top conversations:

Library magic

Telethon has some helper functions to simplify common operations. We could actually have done the above with two of these helper methods, client.get_dialogs() and client.get_message_history() , instead:

However, I felt that it a better learning experience to call the Telegram API methods directly first, especially since there isn’t a helper method for everything. Nevertheless, there are some things which are much simpler with the helper methods, such as how we authenticated our client in the beginning, or actions such as uploading files which would be otherwise tedious.

Wrapping up

There’s a lot more you can do with the Telegram API, especially from an analytics standpoint. I started looking into it after thinking about one of my older projects to try to create data visualisations out of exported WhatsApp chat histories: https://github.com/yi-jiayu/chat-analytics.

Using regex to parse the plain text emailed chat history, I could generate a chart similar to the GitHub punch card repository graph showing at what times of the week a chat was most active:

However, using the “Email chat” function to export was quite hackish, and you needed to manually export the conversation history for each chat, and it would be out of date once you received a new message. I didn’t pursue the project much further, but I always thought about other insights could be pulled from chat histories.

With programmatic access to chat histories, there’s lots more that can be done with Telegram chats. Methods such as messages.search could me exceptionally useful. Perhaps dynamically generating statistics on conversations which peak and die down, or which are consistently active, or finding your favourite emojis or most common n-grams? The sky’s the limit (or the API rate limit, whichever is lower).

Updates

(2017–10–25 09:45 SGT) Modified message counting to skip unexpected dialogs

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *