How to use telegram api


Telegram APIs

We offer two kinds of APIs for developers. The Bot API allows you to easily create programs that use Telegram messages for an interface. The Telegram API and TDLib allow you to build your own customized Telegram clients. You are welcome to use both APIs free of charge.

You can also add Telegram Widgets to your website.

Designers are welcome to create Animated Stickers or Custom Themes for Telegram.


Bot API

This API allows you to connect bots to our system. Telegram Bots are special accounts that do not require an additional phone number to set up. These accounts serve as an interface for code running somewhere on your server.

To use this, you don't need to know anything about how our MTProto encryption protocol works — our intermediary server will handle all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API.

Learn more about the Bot API here »

Bot developers can also make use of our Payments API to accept payments from Telegram users around the world.


TDLib – build your own Telegram

Even if you're looking for maximum customization, you don't have to create your app from scratch. Try our Telegram Database Library (or simply TDLib), a tool for third-party developers that makes it easy to build fast, secure and feature-rich Telegram apps.

TDLib takes care of all network implementation details, encryption and local data storage, so that you can dedicate more time to design, responsive interfaces and beautiful animations.

TDLib supports all Telegram features and makes developing Telegram apps a breeze on any platform. It can be used on Android, iOS, Windows, macOS, Linux and virtually any other system. The library is open source and compatible with virtually any programming language.

Learn more about TDLib here »


Telegram API

This API allows you to build your own customized Telegram clients. It is 100% open for all developers who wish to create Telegram applications on our platform. Feel free to study the open source code of existing Telegram applications for examples of how things work here. Don't forget to register your application in our system.

  • Getting Started
  • Security
  • Optimization
  • API methods

Getting started

Creating an application

How to get your application identifier and create a new Telegram app.

User authorization

How to register a user's phone to start using the API.

Two-factor authentication

How to login to a user's account if they have enabled 2FA, how to change password.

QR code login

QR code login flow

Error handling

How to handle API return errors correctly.

Handling different data centers

How to connect to the closest DC access point for faster interaction with the API, and things to watch out for when developing a client.

Handling updates

How to subscribe to updates and handle them properly.

Handling PUSH-notifications

How to subscribe and handle them properly.

Channels, supergroups, gigagroups and basic groups

How to handle channels, supergroups, gigagroups, basic groups, and what's the difference between them.

Channel statistics

Telegram offers detailed channel statistics for channels and supergroups.

Calling methods

Additional options for calling methods.

Uploading and Downloading Files

How to transfer large data batches correctly.

Pagination

How to fetch results from large lists of objects.

Client configuration

The MTProto API has multiple client configuration parameters that can be fetched with the appropriate methods.

Security

Secret chats, end-to-end encryption

End-to-end-encrypted messaging.

Security guidelines

Important checks required in your client application.

Perfect Forward Secrecy

Binding temporary authorization key to permanent ones.

End-to-End Encryption in Voice and Video Calls

End-to-end-encrypted calls.

Optimization

Client optimization

Ways to boost API interactions.

API methods

Available method list

A list of available high-level methods.

API TL-schema, as JSON

Text and JSON-presentation of types and methods used in API.

Available layer list

A list of available schema versions.

Other articles

Working with bots, using the MTProto API

How to work with bots using the MTProto API.

Commands

Bots offer a set of commands that can be used by users in private, or in a chat.

Buttons

Users can interact with your bot via buttons or even inline buttons, straight from inline messages in any chat.

Menu button

Bots can choose the behavior of the menu button shown next to the text input field.

Inline queries

Users can interact with your bot via inline queries, straight from the text input field in any chat.

Games

Bots can offer users HTML5 games to play solo or to compete against each other in groups and one-on-one chats; how to work with games in the MTProto API.

Web apps

Bots can offer users interactive HTML5 web apps to completely replace any website.

Attachment menu

Bots can install attachment menu entries, offering conveniently accessible, versatile web apps.

Search & filters

Telegram allows applying detailed message filters while looking for messages in chats. This allows the server to filter messages based on a text query, and even on their type, and this feature is often used by graphical clients to implement features like the chat gallery, chat profile pictures and more.

Polls

Telegram allows sending polls and quizzes, that can be voted on by thousands, if not millions of users in chats and channels.

Reactions

Telegram allows users to react on any message using specific emojis, triggering cute lottie animations.

Emoji status

Telegram allows users to set an emoticon or a custom emoji as status, to show next to their name in chats and profiles.

Invite links and join requests

Channels, basic groups and supergroups may have a public username or a private invite link: private invite links may be further enhanced with per-user join requests.

Admin, banned and default rights for channels, supergroups and groups

How to handle admin permissions, granular bans and global permissions in channels, groups and supergroups.

Discussion groups

Groups can be associated to a channel as a discussion group, to allow users to discuss about posts.

Channel comments and message threads

Telegram allows commenting on a channel post or on a generic group message, thanks to message threads.

Admin log

Both supergroups and channels offer a so-called admin log, a log of recent relevant supergroup and channel actions, like the modification of group/channel settings or information on behalf of an admin, user kicks and bans, and more.

Pinned messages

Telegram allows pinning multiple messages on top of a specific chat.

Mentions

Telegram allows mentioning other users in case of urgent duckling matters, and quickly navigating to those mentions in order to read them as swiftly as possible.

Scheduled messages

Telegram allows scheduling messages.

Live geolocations

Telegram allows sending the live geolocation of a user in a chat, optionally setting a proximity alert.

Min constructors

Sometimes, user and channel constructors met in group chat updates may not contain full info about the user: how to handle such constructors.

Account deletion

How to delete a Telegram account.

Imported messages

Telegram allows importing messages and media from foreign chat apps.

Telegram Passport

How to work with Telegram Passport directly using the MTProto API.

Telegram Payments

How to work with Telegram Payments directly using the MTProto API.

Styled text with message entities

How to create styled text with message entities

Working with stickers

Telegram clients support displaying animated, static and video stickers.

Working with custom emojis

Telegram allows including custom animated, static and video emojis directly inside of messages.

Working with animated emojis

Graphical telegram clients should transform emojis into their respective animated version.

Working with animated dice

Telegram supports sending animated dice emojis.

Message drafts

How to handle message drafts

Folders

Working with folders

Top peer rating

If enabled, the rating of top peers indicates the relevance of a frequently used peer in a certain category (frequently messaged users, frequently used bots, inline bots, frequently visited channels and so on).

Handling file references

How to handle file references.

Seamless Telegram Login

Handle Seamless Telegram Login URL authorization requests.

Wallpapers

How to work with chat backgrounds.

Notification sounds

How to work with chat notification sounds.

Message transcription

How to transcribe voice messages.

Web events

When interacting with HTML5 games and the websites of payment gateways, Telegram apps should expose the following JS APIs.

Telegram APIs

We offer two kinds of APIs for developers. The Bot API allows you to easily create programs that use Telegram messages for an interface. The Telegram API and TDLib allow you to build your own customized Telegram clients. You are welcome to use both APIs free of charge.

You can also add Telegram Widgets to your website.

Designers are welcome to create Animated Stickers or Custom Themes for Telegram.


Bot API

This API allows you to connect bots to our system. Telegram Bots are special accounts that do not require an additional phone number to set up. These accounts serve as an interface for code running somewhere on your server.

To use this, you don't need to know anything about how our MTProto encryption protocol works — our intermediary server will handle all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API.

Learn more about the Bot API here »

Bot developers can also make use of our Payments API to accept payments from Telegram users around the world.


TDLib – build your own Telegram

Even if you're looking for maximum customization, you don't have to create your app from scratch. Try our Telegram Database Library (or simply TDLib), a tool for third-party developers that makes it easy to build fast, secure and feature-rich Telegram apps.

TDLib takes care of all network implementation details, encryption and local data storage, so that you can dedicate more time to design, responsive interfaces and beautiful animations.

TDLib supports all Telegram features and makes developing Telegram apps a breeze on any platform. It can be used on Android, iOS, Windows, macOS, Linux and virtually any other system. The library is open source and compatible with virtually any programming language.

Learn more about TDLib here »


Telegram API

This API allows you to build your own customized Telegram clients. It is 100% open for all developers who wish to create Telegram applications on our platform. Feel free to study the open source code of existing Telegram applications for examples of how things work here. Don't forget to register your application in our system.

  • Getting Started
  • Security
  • Optimization
  • API methods

Getting started

Creating an application

How to get your application identifier and create a new Telegram app.

User authorization

How to register a user's phone to start using the API.

Two-factor authentication

How to login to a user's account if they have enabled 2FA, how to change password.

QR code login

QR code login flow

Error handling

How to handle API return errors correctly.

Handling different data centers

How to connect to the closest DC access point for faster interaction with the API, and things to watch out for when developing a client.

Handling updates

How to subscribe to updates and handle them properly.

Handling PUSH-notifications

How to subscribe and handle them properly.

Channels, supergroups, gigagroups and basic groups

How to handle channels, supergroups, gigagroups, basic groups, and what's the difference between them.

Channel statistics

Telegram offers detailed channel statistics for channels and supergroups.

Calling methods

Additional options for calling methods.

Uploading and Downloading Files

How to transfer large data batches correctly.

Pagination

How to fetch results from large lists of objects.

Client configuration

The MTProto API has multiple client configuration parameters that can be fetched with the appropriate methods.

Security

Secret chats, end-to-end encryption

End-to-end-encrypted messaging.

Security guidelines

Important checks required in your client application.

Perfect Forward Secrecy

Binding temporary authorization key to permanent ones.

End-to-End Encryption in Voice and Video Calls

End-to-end-encrypted calls.

Optimization

Client optimization

Ways to boost API interactions.

API methods

Available method list

A list of available high-level methods.

API TL-schema, as JSON

Text and JSON-presentation of types and methods used in API.

Available layer list

A list of available schema versions.

Other articles

Working with bots, using the MTProto API

How to work with bots using the MTProto API.

Commands

Bots offer a set of commands that can be used by users in private, or in a chat.

Buttons

Users can interact with your bot via buttons or even inline buttons, straight from inline messages in any chat.

Menu button

Bots can choose the behavior of the menu button shown next to the text input field.

Inline queries

Users can interact with your bot via inline queries, straight from the text input field in any chat.

Games

Bots can offer users HTML5 games to play solo or to compete against each other in groups and one-on-one chats; how to work with games in the MTProto API.

Web apps

Bots can offer users interactive HTML5 web apps to completely replace any website.

Attachment menu

Bots can install attachment menu entries, offering conveniently accessible, versatile web apps.

Search & filters

Telegram allows applying detailed message filters while looking for messages in chats. This allows the server to filter messages based on a text query, and even on their type, and this feature is often used by graphical clients to implement features like the chat gallery, chat profile pictures and more.

Polls

Telegram allows sending polls and quizzes, that can be voted on by thousands, if not millions of users in chats and channels.

Reactions

Telegram allows users to react on any message using specific emojis, triggering cute lottie animations.

Emoji status

Telegram allows users to set an emoticon or a custom emoji as status, to show next to their name in chats and profiles.

Invite links and join requests

Channels, basic groups and supergroups may have a public username or a private invite link: private invite links may be further enhanced with per-user join requests.

Admin, banned and default rights for channels, supergroups and groups

How to handle admin permissions, granular bans and global permissions in channels, groups and supergroups.

Discussion groups

Groups can be associated to a channel as a discussion group, to allow users to discuss about posts.

Channel comments and message threads

Telegram allows commenting on a channel post or on a generic group message, thanks to message threads.

Admin log

Both supergroups and channels offer a so-called admin log, a log of recent relevant supergroup and channel actions, like the modification of group/channel settings or information on behalf of an admin, user kicks and bans, and more.

Pinned messages

Telegram allows pinning multiple messages on top of a specific chat.

Mentions

Telegram allows mentioning other users in case of urgent duckling matters, and quickly navigating to those mentions in order to read them as swiftly as possible.

Scheduled messages

Telegram allows scheduling messages.

Live geolocations

Telegram allows sending the live geolocation of a user in a chat, optionally setting a proximity alert.

Min constructors

Sometimes, user and channel constructors met in group chat updates may not contain full info about the user: how to handle such constructors.

Account deletion

How to delete a Telegram account.

Imported messages

Telegram allows importing messages and media from foreign chat apps.

Telegram Passport

How to work with Telegram Passport directly using the MTProto API.

Telegram Payments

How to work with Telegram Payments directly using the MTProto API.

Styled text with message entities

How to create styled text with message entities

Working with stickers

Telegram clients support displaying animated, static and video stickers.

Working with custom emojis

Telegram allows including custom animated, static and video emojis directly inside of messages.

Working with animated emojis

Graphical telegram clients should transform emojis into their respective animated version.

Working with animated dice

Telegram supports sending animated dice emojis.

Message drafts

How to handle message drafts

Folders

Working with folders

Top peer rating

If enabled, the rating of top peers indicates the relevance of a frequently used peer in a certain category (frequently messaged users, frequently used bots, inline bots, frequently visited channels and so on).

Handling file references

How to handle file references.

Seamless Telegram Login

Handle Seamless Telegram Login URL authorization requests.

Wallpapers

How to work with chat backgrounds.

Notification sounds

How to work with chat notification sounds.

Message transcription

How to transcribe voice messages.

Web events

When interacting with HTML5 games and the websites of payment gateways, Telegram apps should expose the following JS APIs.

Introduction to Telegram API

Publication date Oct 24, 2017

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

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

" telegram has an open API and protocol free for everyone." - Telegram homepage

The most famous of the Telegram APIs is its Bot API, an HTTP-based API for developers interacting with the bot platform. The Bot API allows developers to manage Telegram bots, such as receiving messages and replying to other users.

In addition to the Bot API, there is also the Telegram API itself. This is the API used by Telegram apps for all your actions on Telegram. To name a few: view your chats, send and receive messages, change the display image, or create new groups. With the Telegram API, you can do everything you can programmatically within the Telegram app.

The Telegram API is much more complex than the Bot API. You can access the bot API via HTTP requests with standard JSON, form or query string payloads, while the Telegram API uses its own payload format and encryption protocol.

MTProto Server-Client Stream Diagram

MTProto is a custom encryption scheme that upholds Telegram's security promises. It is an application layer protocol that writes directly to an underlying transport stream such as TCP or UDP as well as HTTP. Luckily, we don't have to deal with this directly when using the client library. On the other hand, we need to understand the payload format in order to make API calls.

Type Language

The Telegram API is based on RPC, so interacting with the API involves sending a payload representing a function call and receiving the result. For example, reading the content of a conversation involves calling the messages.getMessage function with the required parameters and getting messages.Messages in response.

The Type Language, or TL, is used to represent the types and functions used by the API. A TL schema is a set of available types and functions. In MTProto, TL constructs will be serialized into binary form before being injected as the payload of MTProto messages, however we can leave that to the client library we will be using.

TL schema example (types are declared first, followed by delimited functions): Bool phone_code_hash:string send_call_timeout:int is_password:Bool = auth.SentCode;---functions---auth.sendCode#768d5f4d phone_number:string sms_type:int api_id:int api_hash:string lang_code:string = auth.SentCode;

TL function call and result using functions and types from above TL schema and equivalent binary representation (from official documentation): auth.sentCode
phone_registered:(boolFalse)
phone_code_hash:"2dc02d2cda9e615c84"
)

d16ff372 3939370b 33323139 37363534 00000001 00000020 73657409 61682d74 00006873 e77e812d
=
2215bcbd bc799737 63643212 32643230 39616463 35313665 00343863 e12b7901

TL-schema layers

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

Or it seems that although the last level of the TL schema on the Telegram website is level 23, on at the time of writing the last level was actually already level 71. You can find the latest version of the TL schema here instead.

Creation of the Telegram 9 application0021

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

You will have to visit https://my.telegram.org/log in with your phone number and a verification code that will be sent to Telegram. and fill out the form in the API Development Tools section with the application name and short name. After that you can find your api_id and api_hash in the same place.

Also, the same instructions mention that you can use the sample credentials found in the Telegram source codes for testing. For convenience, I'll use the credentials I found in the Telegram Desktop Source Code on GitHub in the sample code here.

Installing Telethon

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

You can install Telethon with pip :

 pip install telethon 

Use pip matches your Python 3 interpreter; it could be pip3 instead of . (Random: Ubuntu 17.10 was recently released and uses Python 3 as the default Python install.)

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 validate it with your phone number. It's like logging into Telegram on a new device; you can think of this client as another Telegram application

Here is the code to create and authenticate the client object, modified from the Telethon documentation: values ​​here
api_id = 17349
api_hash = '344583e45741c457fe1862106095a5eb'

phone = 'YOUR_NUMBER_HERE'
username = 'username'

# (2) Create the client and connect
client = TelegramClient(username, api_id, api_hash)
client. connect()

# Ensure you're authorized
if not client.is_user_authorized():
client.send_code_request(phone)
try:
client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
client.sign_in( password=input('Password: '))

me = client.get_me()
print(me)

As mentioned earlier, api_id and api_hash above are taken from the Telegram Desktop source code. Enter your phone number in the phone variable.

Telethon will create a .session save the session details in your working directory, just like you don't have to re-authenticate on Telegram apps every time you close and re-open them. File name starts with username variable. It's up to you if you want to change it if you want to work with multiple sessions.

If there was no previous session, executing this code will send you an authorization code via Telegram. If you have enabled 2-Step Verification on your Telegram account, you will also be required to enter your Telegram password. Once you've authenticated once and the .session file is saved, you won't have to re-authenticate until the session times out, even if you run the script again.

If the client was created and authenticated successfully, an object representing itself should be printed to the console. It will be like (ellipses ... means some content was skipped)

 User(is_self=True ... first_name='Jiayu', last_name=None, username='USERNAME', phone='PHONE_NUMBER' ... 

You can now use this client object to start making requests to the Telegram API

Checking the TL schema

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

 messages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages. Dialogs ;messages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;---functions---messages.getDialogs#191ba9c5 flags:# exclude_pinned:flags.0?true offset_date:int offset_id:int offset_peer:InputPeer limit:int = messages.Dialogs; 

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

Using Telethon 9 Documentation0021

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

The documentation for GetDialogsRequest specifies the return type for the method, as well as slightly more detailed information about the parameters. The "Copy import to clipboard" button is especially useful when we want to use this object like we do now.

https://lonamiwebs.github.io/Telethon/methods/messages/get_dialogs.html

messages.getDialogs function as well as constructor for GetDialogsRequest takes offset_peer argument of type InputPeer . click through InputPeer link to see a page describing constructors and methods that accept and return this type.

https://lonamiwebs.github.io/Telethon/types/input_peer.html

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

Make a request

Here is our completed GetDialogsRequest and how to get its result by passing it to our authorized client object:
offset_peer=InputPeerEmpty(),
limit=30,
)dialogs = client(get_dialogs)
print(dialogs)

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

 DialogsSlice(count=204, dialogs=[…], messages=[…], chats=[…], users=[…]) 

Getting DialogsSlice instead of Dialogs means not all of my dialogs were returned, but count The attribute tells me how many dialogs I have in total. If you have less than a certain number of conversations, you can get Dialogs instead of an object, in which case all your dialogs have been returned and the number of dialogs you have is just the length of the vectors.

terminology

The terminology used by the Telegram API can sometimes be a little confusing, especially due to the lack of information other than 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 the conversation history
  • messages contains the last message sent to each conversation as you see in the chat list in the Telegram app
  • users contains individual users with whom you have private conversations or who was the sender of the last message in one of your groups

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

dialogs will contain conversations in the screenshot: Old Pirates, Press Room, Monica, Jaina…

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

messages will contain messages "All aboard!" from The Old Pirates, "Wow, nice mention!" from the press room, a message representing the photo sent to Monica, a message representing Jaina's response, and so on.

users will contain an entry for Ashley since she sent the last message to the press room, Monica, Jaina, Kate and Winston since he sent the last message to the Meme Factory.

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

Message count

Our goal is to count the number of messages in each conversation. To find out the number of messages in a conversation, we can use the messages.getHistory function from the TL schema:

 messages.getHistory#afa92846 peer:InputPeer offset_id:int offset_date:date add_offset:int limit:int max_id:int min_id:int = messages .Messages 

After the same process as before with messages.getDialogs we can decide how to call this from Telethon using GetHistoryRequest . This will return either a Messages or MessagesSlice object that either contains a count attribute telling us how many messages are in the conversation or all messages in the conversation so we can simply count the messages it contains.

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

Manage response data

To count the number of messages in each of our conversations, we need to do GetHistoryRequest for this conversation with the corresponding InputPeer for this conversation.

All corresponding InputPeer constructors accept the same id and access_hash parameters, but depending on whether the conversation is an individual chat, a group or a channel, these values ​​are in different places peer value with type and id of the peer corresponding to this conversation, but not access_hash ,

  • chats : contains id , access_hash and names for our groups and channels.
  • users : contains id , access_hash and a name for our individual chats.
  • In pseudocode we have: .id
    access_hash = channel.access_hash
    peer = InputPeerChannel(id, access_hash)
    else if dialog.peer is a group:
    group = corresponding object in chats
    name = group.title
    id = group.id
    peer = InputPeerChat(id)
    else if dialog.peer is a user:
    user = corresponding object in users
    name = user.first_name
    id = user.id
    access_hash = user.access_hash
    peer = InputPeerUser(id, access_hash) history = message history for peer
    count = number of messages in history counts[name] = count

    what dialogs , chats and users above are members of the result of our GetDialogsRequest which is also called dialogs ):

     counts = {} 

    # create dictionary of ids to users and chats
    users3 = {}
    {}

    for u in dialogs. users:
    users[u.id] = u

    for c in dialogs.chats:
    chats[c.id] = c

    for d in dialogs.dialogs:
    peer = d.peer
    if isinstance(peer, PeerChannel):
    id = peer.channel_id
    channel = chats[id]
    access_hash = channel.access_hash
    name = channel.title

    input_peer = InputPeerChannel(id, access_hash)
    elif isinstance(peer, PeerChat):
    id = peer.chat_id
    group = chats[id ]
    name = group.title

    input_peer = InputPeerChat(id)
    elif isinstance(peer, PeerUser):
    id = peer.user_id
    user = users[id]
    access_hash = user.access_hash
    name = user.first_name

    input_peer = InputPeerUser(id, access_hash)
    else:
    continue

    get_history = GetHistoryRequest(
    peer=input_peer,
    offset_id=0,
    offset_date=None,
    add_offset=0,
    limit=1,
    max_id=0,
    min_id=0, 9005 )
    history = client(get_history)
    if isinstance(history, Messages):
    count = len(history. messages)
    else:
    count = history.count

    counts[name] = count

    print(counts)

    our counts Object is a dictionary of chat names to count messages. We can sort it and print it to see our top 9 conversations0005

     sorted_counts = sorted(counts.items(), key=lambda x: x[1], reverse=True) 
    for name, count in sorted_counts:
    print('{}: {}'.format(name, count ))

    Sample output:

     Group chat 1: 10000 
    Group chat 2: 3003
    Channel 1: 2000
    Chat 1: 1500
    Chat 2: 300

    . Actually we could do the above with two of these helper methods,0023 client.get_dialogs()

    and client.get_message_history() instead of:

     from telethon.tl.types import User 

    _, entities = client.get_dialogs(limit=30)

    counts = []
    for e in entities:
    if isinstance(e, User):
    name = e.first_name
    else:
    name = e.title

    count, _, _ = client.get_message_history(e, limit=1)
    counts. append( (name, count))

    message_counts.sort(key=lambda x: x[1], reverse=True)
    for name, count in counts:
    print('{}: {}'.format(name, count))

    However, I felt it was better to learn the Telegram API methods directly first, especially since there is no helper method for everything. However, there are some things that are much easier with helper methods, like how we authenticated our client at the beginning, or things like uploading files that would otherwise be tedious.

    The complete code for this example can be found here: https://gist.github.com/yi-jiayu/7b34260cfbfa6cbc2b4464edd41def42

    You can do a lot more with the Telegram API, especially in terms of analytics. I started looking into it after thinking about one of my old projects to try and create a data visualization from exported WhatsApp chat histories: https://github.com/yi-jiayu/chat-analytics,

    Using regular expressions to parse chat history in in plain text, I could create a chart similar to GitHub's punchcard storage graph, showing what time of the week the chat was most active:0005

    However, using the "Chat by Email" feature to export was quite hacky and you had to manually export the conversation history for each chat and this will be out of date as soon as you get a new message. I did not push the project further, but I always thought that other stories could be extracted from the chat history.

    With programmatic access to chat history, you can do much more with Telegram chats. Methods like messages.search 9Personally, I can't comment on Telegram's security other than to point out that Telegram conversations are not end-to-end encrypted by default, as well as to generalize that Telegram's encryption protocol is self-developed and less well understood compared to more established protocols such as the Signaling Protocol. .

    Original article

    Everything a Telegram bot developer should know about / Sudo Null IT News

    and tutorials like "how to make a bot that says hello world". At the same time, many non-obvious points are simply not described anywhere.

    How do bots work in general? How do they interact with users? What can be achieved with their help, and what cannot?

    A detailed guide on how to work with bots is under the cut.

    Article updated in January 2022
    • Information about user and chat ids has been updated: now they cannot be stored in a 32-bit number type.

    • Added section on messaging on behalf of groups and channels

    • Updated information on various command menus for individual chats and users.

    • Added information about spoilers in message markup.

    • Added section on Bot API updates.

    Content

    Start of work
    - Telegram API VS Telegram Bot API
    - What are the telegram bots
    - Creating the bot
    - Bota 9000 bot user
    - Messages
    - Where the bot can write
    - Supergroups
    - id of users and chats
    - id of messages
    - Visibility of messages in groups
    - Messages on behalf of groups and channels
    - Commands
    - Markup of messages
    - Buttons

    Interaction with the bot 9037 - Links to the bot - Inline mode
    - Creation of sticker packs
    - Payments via bots
    - HTML games in bots
    - Telegram Login Widget

    Development of bots
    - What updates can I receive
    - API Updates
    - Limits
    - Mailing to Users
    - Bot Owner Change
    - Bot API Local Server
    - Userbots

    Conclusion

    Getting Started

    Telegram0 API Showing 9 order.

    Telegram uses its own MTProto encryption protocol. MTProto API (aka Telegram API) is the API through which your Telegram application communicates with the server. The Telegram API is completely open, so any developer can write their own messenger client.

    To write bots, the Telegram Bot API was created - an add-on for the Telegram API. Translation from the official website:

    To use the Bot API, you do not need to know anything about how the MTProto encryption protocol works - our auxiliary server will handle all the encryption and communication with the Telegram API. You connect to the server through a simple HTTPS interface that provides a simple version of the Telegram API.

    Among the simplifications of the Bot API: work through webhooks, simplified message markup, and more.

    For some reason, few people know that bots can work directly through the Telegram API. Moreover, this way you can even get around some of the limitations that the Bot API gives.

    Bot authorization via Telegram API in the official documentation

    All information below will by default apply to both Bot API and Telegram API I will mention the differences. You can get rid of some Bot API restrictions using a local server, more on that at the end of the article.

    What Telegram bots write in

    The bot must be able to send requests to the Telegram server and receive updates (updates, updates) from it.

    How to receive updates in the Bot API

    You can receive updates in one of two ways:

    • Polling - just send a request to the Telegram server regularly to receive updates,

    • Webhook - make Telegram send requests to the desired URL .

    Of course, it is more convenient to use libraries than to make http requests "by hand".

    If you try to google how to write a Telegram bot in Python, you will be prompted to use the python-telegram-bot and telebot libraries. But not worth it.

    Well, if you just want to get familiar with bot development and write your own hello-world bot, you can certainly use them. But these libraries can not do everything. Among bot developers, the best Python bot library is aiogram. It is asynchronous, uses decorators, and provides handy development tools. There was also a good Rocketgram, but it has not been updated for a long time.

    Also, bots are often written in JavaScript, usually Telegraf is used for this. There are libraries for many other languages, but they are used less often.

    If you want to use the Telegram API, you can use Python's Telethon and Pyrogram.

    Bot code example

    If you want to get some idea of ​​what the bot code looks like in general, here's a usage example on aiogram from his GitHub page:

     import asyncio from aiogram import Bot, Dispatcher, types async def start_handler(event: types.Message): await event.answer( f"Hello, {event.from_user.get_mention(as_html=True)} ?!", parse_mode=types.ParseMode.HTML, ) async def main(): bot = Bot(token=BOT-TOKEN) try: disp = Dispatcher(bot=bot) disp. register_message_handler(start_handler, commands={"start", "restart"}) await disp.start_polling() finally: await bot.close() asyncio.run(main()) 

    This bot will respond to commands /start and /restart.

    Creation of a bot

    The only information about Telegram bots that is abundant on the Internet is how to create a bot. This is done through a special BotFather bot. When you create a bot, BotFather will give you its token. The token looks something like this: 110201543:AAHdqTcvCh2vGWJxfSeofSAs0K5PALDsaw . It is with the help of the token that you can control the bot.

    One user can create up to 20 bots.

    In BotFather it is convenient to manage bots with your command /mybots .

    Usernames

    When creating a bot, you need to select a username. After that, it will be very difficult to change it.

    How to change the username of a bot

    If you have a bot and you want to give it a shorter username (which can be taken by a broken bot), then you can theoretically do this via @BotSupport.

    To do this, the bot must (suddenly) be working, and also support English.

    It is customary to use the following format for contacting support:

    1. @old_username,

    2. @new_username,

    3. What the bot does.

    If you are lucky 9999 lvl - you will be answered.

    The bot username looks like a normal username, but it must end with "bot".
    You may have seen bots with the names @pic, @vid, @sticker, @gamee - these are the official Telegram bots. They can break all the rules :)

    A lot of usernames are already taken. There are very few free short usernames left. And the saddest thing is that almost all of these bots are dead. They just don't respond to messages. Probably, these are just different curious people who want to make a bot, create it, and then kill it. I myself have several lying bots. So, I think the limit of 20 bots per owner is quite justified :)

    Bot design

    By opening the bot, users can see its profile.

    Bot appearance is configured in BotFather: menu /mybots Edit Bot . There you can change:

    1. Bot name.

    2. Description is the text that users will see at the beginning of the dialogue with the bot under the heading "What can this bot do?"

    3. Information (About) is the text that will be visible in the bot profile.

    4. Avatar. Bot avatars, unlike user and chat avatars, cannot be animated. Only pictures.

    5. Commands - here we mean command prompts in the bot. More about commands below.

    6. Inline Placeholder - see below for inline mode.

    Standard Tip: Take the time to fill in the bot description and information to make it clearer and easier for users to use. You can leave your contacts there. And put an avatar to make it easier to distinguish the bot from other chats in the list.

    Messages and chats

    User start bot

    When the user opens the bot for the first time, he sees the "Run" or "Start" button (depending on the user's platform), in English - "Start". By pressing this button, he sends the command /start .

    Thus, the first message from the user is always /start (or /start with parameters, see below in the "Deeplinks" section).

    ...if the user is using the official client

    This is not checked on the server side, so in theory the user can send any message to the bot via the Telegram API.

    Messages

    Clearly, the main function of a bot is to send and receive messages.

    Both can be done with all kinds of messages (photos and videos, files, polls, voice messages, etc.).

    Telegram allows you to share files up to 2 GB, but the Bot API has tighter limits: bots can download files up to 20 MB and send files up to 50 MB.

    Working with files in the Bot API

    If the bot has already uploaded a file to the Telegram server, then it can use the file_id to send this file.

    You can also upload a file to the server using the file's URL.

    More about sending files to the Bot API

    Where the bot can write to

    The bot can only write to the users who launched it. The user can block the bot, and then the bot will not be able to write to him again.

    Bots cannot write to other bots.

    A bot can be added to a group (if the appropriate setting is enabled in BotFather). By default, he does not see all messages (more on this below, in the "Visibility of messages in groups" section).

    In the group, the bot can be given administrator rights so that it can perform the actions of admins.

    One group can have up to 20 bots. Only admins can add bots to public groups (groups with a username).

    You can also add a bot to a channel, and only as an administrator. The most common way to use bots in channels is to add buttons under posts ("likes", links, etc.).

    How bots add buttons

    The channel admin can have a special right: "Edit other people's publications". With it, bots edit posts by adding buttons to them.

    More details about the buttons are also below.

    Supergroups

    In fact, many Telegram groups are supergroups.

    Why is that? Previously, there was a clear division into groups and supergroups. By design, supergroups are groups for communities. Supergroups can have more members, public links, and other perks.

    Over time, apparently, they decided that this was an inconvenient concept. Now a regular group becomes a supergroup when some settings of the group change (read more here). Here is such a crutch.

    In this article, by groups I mean both supergroups and regular groups.

    A supergroup cannot be turned back into a group. From an API point of view, a supergroup is structured in the same way as a channel. An important difference between supergroups and regular groups is the numbering of messages: more on that below.

    id of users and chats

    Each user, bot, group, channel in Telegram has its own id. It is necessary to distinguish between chats in the bot code by id, because it never changes.

    In the bot token, the first part is its id. For example, token 110201874:AAHdqTcvCh2vGWJxfSeofSAs0K5PALDsaw belongs to the bot with id 110201874 .

    In the Bot API, -100 is written before the id of supergroups and channels. So, id 1356415630 becomes -1001356415630 .

    Do not store user and chat id in 32-bit number type: now id can exceed 2 31 -1.

    message id

    Each message in Telegram has its own id. This also applies to system messages (the user has joined the group, the name of the group has changed, etc.)

    Through the Telegram API, bots can receive messages on request in any chat by their id.

    message ids in supergroups and channels are unique for the chat: the first message in the chat has number 1, the second has number 2, and so on.

    message id in private messages and regular groups work differently. There, one might say, the numbering is end-to-end: the message id is unique for each user who sent it. So, the first message from a user in all personals and groups has number 1, the second message from the same user has number 2, and so on.

    Visibility of messages in groups

    Usually the bot should respond to commands. Telegram does not notify the bot about other messages, and this guarantees the privacy of the correspondence.

    But if the bot needs to see all messages in the group (for example, if it is a chat bot or an anti-spam bot), you can disable Privacy mode for it.

    Privacy mode is a setting in BotFather that is enabled by default. In this mode, the bot in groups sees only such messages:

    • Messages mentioning a bot,

    • Replies to a bot message, replies to replies, etc.

    And if Privacy mode is disabled, then the bot sees all messages in the group.

    If the bot is an admin in the group, then it sees all messages anyway.

    A bot working through the Bot API will not see messages from other bots anyway.

    The bot can't see all the messages I enabled Privacy mode, but it doesn't work

    You need to remove the bot from the group and add it again.

    Fixed bug with message visibility

    A bug was recently found: bots could not see some messages from users if the messages look like commands with the user's username at the end.

    This could disrupt anti-spam and other bots.

    The bug has now been fixed.

    About Privacy mode in the Bot API documentation

    Posting on behalf of groups and channels

    Groups can contain not only messages from users, but also:

    • Messages in a group from an associated channel (from the point of view of the API, these are forwarded messages)

    • Messages on behalf of a group from anonymous administrators of the same group

    • Messages on behalf of public channels from any users

    Consider this when developing bots for groups.

    Commands

    Commands are a commonly used way for users to communicate with a bot. Commands begin with "/" and consist of Latin letters (you can use numbers and underscores).

    Commands are highlighted as links: pressing sends a command to the chat.

    In groups, in order to distinguish commands from different bots, Telegram suggests putting the username of the bot at the end of the command. For example: /start@examplebot .

    In BotFather, you can specify command hints for the bot. It will be displayed when you enter "/" and commands. If there are hints, a button appears next to the Submit button to open the command menu.

    If command prompts contain /help , the "Help with the bot" button appears in the bot's profile. Pressing the button sends this command.

    If the command prompt contains /settings , the Bot Settings button appears in the bot profile. Pressing the button sends this command.

    From 2021, bots can show different command menus for different users and groups, and the command menu can vary depending on the user's language and whether the group member is an admin.

    Message markup

    As you probably know, messages in Telegram can contain not only plain text, but also bold, italic, etc. In the Bot API, message markup can be done in HTML and Markdown.

    Markup in the Telegram API

    In the Telegram API, for markup, entities (MessageEntityBold, MessageEntityItalic, and so on) must be passed along with the message. Good libraries turn HTML/Markdown into text and entities themselves.

    Text selection methods:

    • Bold text

    • Cauced

    • 2 2 Undressed text

    • Crossed Text

    • Monoshirin text ("In the line" and "Block")

    • Spoiler - text that is shown only after clicking on the badge

    • User mention - text that looks like a link, clicking on which opens the user's profile. If you mention a member in a group, he will receive a notification.
      To insert a mention of a user into a message, you need to embed a link to tg://user?id=123456789 in the Bot API. Bot API docs

      Buttons under messages (they are also inline keyboards / inline buttons) are basically of three types:

      • URL button - a button with a link.

      • Callback button. When you click on such a button, the bot will receive an update. With the creation of the button, you can specify the parameter that will be specified in this update (up to 64 bytes). Usually, after clicking on such buttons, bots change the original message or show a notification or alert.

      • Switch to inline button. Button to switch to inline mode (see below for inline mode). The button can open inline in the same chat or open a menu to select a chat. You can specify in the button a query that will appear next to the bot's nickname when you click on the button.

      Additional types of buttons
      • Login URL button — a special button for authorizing users on the site. It was used, for example, in the official @discussbot bot (before adding native comments to Telegram).

      • Callback game button — a button for opening an HTML game. See "HTML games".

      • Pay button - button for payments. See "Payments via bots".

      Keyboard buttons

      There is another type of button: keyboard buttons. They are displayed instead of the keyboard as hints. When you click on such a button, the user will simply send this text.

      At the same time, in private chats, using the button, you can:

      • Request the user's phone number,

      • Request the user's geolocation,

      • Open the poll creation menu for the user.

      There is an option resize_keyboard, which is responsible for whether to change the height of this "keyboard of buttons". By default, for some reason, it is turned off, and then the standard height of the keyboard is large. Buttons are obtained as in this picture:

      To show the keyboard buttons, the bot must send a message. You can send a keyboard that will collapse (but not disappear) after pressing the button.

      By default, if you show buttons in a group, they will be visible to all users. Instead, you can display the buttons simultaneously for these users:

      • For users whose usernames were in the body of the message,

      • If this is a response to another message: for the user who sent it.

      More about buttons

      Both types of buttons can be arranged in several rows, each with several buttons. Restrictions: there can be up to 8 buttons in a row, and up to 100 buttons in total with a message.

      When sending a message, you can choose one (but no more) of the following actions:

      • Add to the Inline Knopok message,

      • 2 Show keyboard buttons,

      • Remove all keyboard buttons,

      • Forope reply: Automatically force the user to reply to a message. So the same thing happens as when the user clicks the "Reply" button. This is necessary so that the bot can communicate with users in groups without violating Privacy mode.

      Thus, it is not possible to show both types of buttons at the same time.

      Interaction with the bot

      Links to the bot

      Bot usernames work just like any other usernames in Telegram: the bot @examplebot can be opened at t.me/examplebot.

      There is also a direct link: tg://resolve?domain=examplebot

      More about links tg://

      Such links can not only replace t.me links, but also set their own actions. For example, tg://settings opens settings.

      A list of known such links is in the @DeepLink channel.

      Link to add to the group

      The link t.me/examplebot?startgroup=true opens the menu for the user: select a group to add a bot.

      Direct link: tg://resolve?domain=examplebot&startgroup=true

      Deeplinks

      By the link t.me/examplebot?start= the user can start the bot with some start parameter ( ).

      What happens when the user follows this link:

      1. The bot opens as usual.

      2. The Run button is displayed even if the user has already started the bot.

      3. The user presses the button and sees the message /start (as usual).

      4. The bot instead receives the message /start

      So the bot can react to the launch not like the usual "/start", but in a different way.

      Visual GIF:

      Often deep links are used for referral programs (as a parameter, you can pass the id of the user who shared the link). There are other uses as well.

      Direct link: tg://resolve?domain=examplebot&start=

      About deep links in the Bot API documentation

      Inline mode

      with which the user can use the bot in all chats.

      It looks like this: the user enters the username of the bot in the field for entering a message. After the username, you can also write a request (text up to 256 characters).

      The results menu appears. By selecting a result, the user sends a message.

      Inline mode can be enabled in BotFather, where you can also select a placeholder instead of the standard "Search..."

      In a group, you can prohibit all or some members from using inline. In the official Telegram applications, this restriction is combined with the restriction on sending stickers and GIFs.

      Inline mode page on the Telegram website

      Inline mode results

      Results can be displayed in two ways:

      Two types can be combined, but this is displayed correctly only on Telegram Desktop.

      Inline privacy and geolocation

      When the user invokes inline mode, the bot cannot obtain any context information other than information about the user. Thus, the bot cannot recognize either the chat in which the inline was called, or the message to which the user is responding.

      But if you enable the "Inline Location Data" setting in BotFather, then the bot will be able to see the geolocation of users when they use inline (on mobile devices). Before that, users are shown a warning.

      Inline feedback

      Inline feedback are updates about selected inline results. Enabled via BotFather.

      Inline feedback is supposed to be used to collect statistics, but it is not always used that way. Inline feedback allows you to "load" not all the results at once, but only the selected one. For example, if a bot is used to search for music, then it may not download all the songs at once, but only one.

      An important point: if you received an update about sending an inline message, you can edit it only if inline buttons are attached to it. (If there are no buttons, then the update does not specify the id of the inline message that is being edited).

      Create sticker packs

      Bots (and only bots!) can create sticker packs. In addition, each set of stickers must belong to some user. Users can view their sticker packs using the @Stickers bot.

      Payments via bots

      Telegram allows bots to accept payments from users. This is done through the providers YuMoney, Sberbank, Stripe and 7 more.

      This feature is rarely used, because you need a legal entity to use the providers.

      Bot Payments API page

      UPD 04.2021. New update introduces more payment options for developers. Now bots can send payments not only to personal accounts, but also to groups and channels. This allows you to make a "showcase" from the channel, where you can immediately buy a product. You can see what it looks like in the official demo channel.

      HTML games in bots

      Bots can allow users to play HTML5 games in chats. The bot can send game messages or create them via inline mode. How it works can be seen on the example of the official @gamebot.

      Bot Gaming Platform page

      Telegram Login Widget

      You can add authorization to your site via Telegram. The authorization process will go like this:

      1. The user will have to enter their phone number.

      2. The Telegram bot will ask you to confirm the entry.

      3. The user logs in and clicks on "Accept" on the site.

      Telegram Login Widget is not related to the Login URL button (see the button section above), but is its alternative.

      About Telegram Login Widget on the Telegram website

      Development of bots

      What updates can be received

      The bot cannot get old messages from the chat. The bot cannot get a list of all its users. All the bot can receive is information about updates. This is the main difficulty in developing bots.

      You can receive information about new messages in the bot and other events, but only once. You will have to keep a list of chats, old messages (if you need it for some reason), and so on. If you accidentally erase/lose this information, you won't get it again.

      In the Telegram API, a bot can do a little more: it can receive messages by id, get a list of group members, and so on.

      Receiving updates: Bot API vs Telegram API

      If you received an update in the Bot API, then you won't get it a second time.

      This is not the case in the Telegram API: the user can use the messenger through several clients, each of which must receive updates.

      If you run several Telegram API programs for one bot, then each of them will receive all updates.

      Bot API restrictions do not allow the same.

      API updates

      Telegram API and Telegram Bot API are updated with new features in Telegram. All Bot API updates are described on a separate page in the documentation and in the official BotNews channel.

      Limits

      Of course, there are limits on requests to the server. The Bots FAQ on the Telegram website states the following:

      • No more than one message per second in one chat,

      • No more than 30 messages per second in general,

      • No more than 20 messages per minute in one group.

      These limits are not strict, but approximate. Limits can be increased for large bots through support.

      Other known limits in Telegram are collected at limits.tginfo.me - see the section about bots.

      Sending messages to users

      Below in the Bots FAQ, it says that the Bot API does not allow sending messages to all users at the same time and that in the future, maybe they will do something about this. And it's been written for years.

      They advise stretching out the mailing list for a long time (8-12 hours) and notice that the API will not allow sending messages to more than ~30 users per second.

      Bot owner change

      In the fall of 2020, it became possible to transfer bots to another person. This can be done in the bot settings in BotFather. To do this, two-factor authorization must be enabled on your account - at least 7 days before the transfer. You can transfer the bot only to the user who wrote something to him.

      Bot API local server

      Also in the fall of 2020, the Bot API sources were posted on GitHub. Now you can raise your own Bot API server. The following benefits are listed on GitHub:

      • Downloading files from the server without limitation (the limit on sending files by users in Telegram is 2 GB),

      • Uploading files to the server up to 2000 MB, using a local path and file URI,

      • Use HTTP URL for webhuk,

      • 22 Use of any local IP address for webhuk,

      • Using any port for webhuk,

      • The ability to increase the maximum number of connections to 100000,

      • 9000 local file path instead of downloading the file from the server.

      Userbots

      At the beginning of the article, I talked about what Telegram API and Telegram Bot API are.

      Telegram API is used not only for bots - then what's the problem with managing user accounts like bots? People do it. Someone automatically puts the current time on their profile picture, someone reacts to their messages as commands with a script, someone saves messages from public groups and channels. These are all called userbots.

      Userbots should be used carefully: an account can be restricted or banned for excessive suspicious activity.

      Conclusion

      I tried to collect and structure information about all the possibilities of Telegram bots in one place. Many thanks to vanutp, NToneE and Grinrill for helping with the facts. If we forgot something - write, I will correct it.

      I deliberately did not divide a large article into several posts so that you can quickly find the information you need. In addition, at the beginning of the article there is its content. So you can save it to yourself and use it as a reference :)

      In general, the bot interface (that is, the chat interface) has many limitations. But is it bad? It's really more convenient to use a tool when it's part of a familiar environment. I often find the right picture or information right in the correspondence with the help of inline bots. As an avid Telegram user, I love using bots.


      Learn more