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.
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.
Bot developers can also make use of our Payments API to accept payments from Telegram users around the world.
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.
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.
How to get your application identifier and create a new Telegram app.
How to register a user’s phone to start using the API.
How to login to a user’s account if they have enabled 2FA, how to change password.
How to handle API return errors correctly.
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.
How to subscribe to updates and handle them properly.
How to subscribe and handle them properly.
How to handle channels, supergroups, groups, and what’s the difference between them.
Telegram offers detailed channel statistics for channels and supergroups.
Additional options for calling methods.
How to transfer large data batches correctly.
How to fetch results from large lists of objects.
The MTProto API has multiple client configuration parameters that can be fetched with the appropriate methods.
Important checks required in your client application.
Binding temporary authorization key to permanent ones.
Ways to boost API interactions.
A list of available high-level methods.
Text and JSON-presentation of types and methods used in API.
A list of available schema versions.
How to work with bots using the MTProto API.
Bots offer a set of commands that can be used by users in private, or in a chat.
Users can interact with your bot via buttons or even inline buttons, straight from inline messages in any chat.
Users can interact with your bot via inline queries, straight from the text input field in any chat.
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.
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.
Telegram allows sending polls and quizes, that can be voted on by thousands, if not milions of users in chats and channels.
How to handle admin permissions, granular bans and global permissions in channels, groups and supergroups.
Groups can be associated to a channel as a discussion group, to allow users to discuss about posts.
Telegram allows commenting on a channel post or on a generic group message, thanks to message threads.
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.
Telegram allows pinning multiple messages on top of a specific chat.
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.
Telegram allows scheduling messages.
Telegram allows sending the live geolocation of a user in a chat, optionally setting a proximity alert.
Sometimes, user and channel constructors met in group chat updates may not contain full info about the user: how to handle such constructors.
How to reset an account if the 2FA password was forgotten.
Telegram allows importing messages and media from foreign chat apps.
How to work with Telegram Passport directly using the MTProto API.
How to work with Telegram Payments directly using the MTProto API.
How to create styled text with message entities
Graphical telegram clients should transform emojis into their respective animated version.
Telegram supports sending animated dice emojis.
How to handle message drafts
Working with folders
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).
How to handle file references.
Handle Seamless Telegram Login URL authorization requests.
When interacting with HTML5 games and the websites of payment gateways, Telegram apps should expose the following JS APIs.
Источник
Запускаем Telegram-бота на Android устройстве (Remote Bot for Telegram)
Четыре месяца назад у меня появилась идея написать Telegram-бота, который будет запускаться не на внешнем сервере, как большинство ботов, а на мобильном телефоне.
Идея родилась не на пустом месте: я часто пропускал входящие звонки и СМС, когда телефон был в куртке или в кармане, поэтому мне нужен был дополнительный способ уведомлений. А так как я активно использую Telegram на компьютере, то подумал, что было бы не плохо, если бы входящие СМС и пропущенные звонки приходили в Telegram. Немного покопавшись, я решил написать бота.
Разработка прототипа
Я стал изучать тему создания Telegram ботов по официальной документации и по примерам. В основном все примеры были написаны на Python. Поэтому не долго думая, стал искать способы запуска Python сервера на Android. Но оценив время на изучение Python и не найдя ничего подходящего для запуска сервера, занялся поиском альтернатив и наткнулся на несколько библиотек на Java для написания Telegram ботов. В итоге остановился на проекте от Pengrad: java-telegram-bot-api.
Данная библиотека позволяла, на тот момент, инициализировать бота и получать-отправлять сообщения, что мне было и нужно. Добавив библиотеку в свой проект, я реализовал простой сервис, который запускал в фоновом потоке цикл по получению сообщений из Telegram и их обработке. Предварительно необходимо было зарегистрировать нового бота через родительский бот @Botfather и получить его токен. Подробнее о создании бота по ссылке.
Для того, чтобы сервис не убивался системой, когда устройство находится с выключенным экраном, при запуске сервиса, устанавливался WakeLock.
Приведу в пример функцию, позволяющую получать последние сообщения и отправлять их на обработку:
Позже, в целях безопасности, я добавил возможность привязки бота к разрешенным Telegram-аккаунтам и возможность запрета выполнения определенных команд для заданных пользователей.
Добавив несколько команд для бота, такие как: отправка, чтение СМС, просмотр пропущенных звонков, информация о батарее, определение местоположения и др., я опубликовал приложение в Google Play, создал темы на нескольких форумах, стал ждать комментарии и отзывы.
В основном отзывы были хорошие, но вскрылась проблема большого расхода батареи, что, как вы могли догадаться, было связано с WakeLock и постоянной активностью сервиса.Немного погуглив, решил периодически запускать сервис через AlarmManager, затем после получения сообщений и ответа на них сервис останавливать.
Это немного помогло, но появилась другая проблема, AlarmManager некорректно работал на некоторых китайских устройствах. И поэтому бот иногда не просыпался после нескольких часов, проведенных в состоянии сна. Изучая официальную документацию, я читал о том, что Long Polling это не единственная возможность получения сообщений, сообщения еще можно было получать используя Webhook.
Получение сообщений через Webhook
Я зарегистрировался на Digital Ocean, создал VPS на Ubuntu, затем реализовал простейший http сервер на Java, использующий Spark Framework. На сервер можно делать запросы 2 типов: push (отправка пуш-уведомления через webhook) и ping.
Пуш-нотификации отправлялись с помощью Google Firebase.
Генерация SSL сертификата
Протестировав отправку пуш-уведомлений, я стал разбираться с тем, как настроить и запустить сервер с HTTPS, так как это одно из требований при получении сообщений из Telegram через webhook.
Бесплатный сертификат можно сгенерировать с помощью сервиса letsencrypt.org, но одним из ограничений является то, что указываемый хост при генерации сертификата не может быть ip адресом. Регистрировать доменное имя я пока не хотел, тем более официальная документация Telegram Bot API разрешает использование самоподписанных сертификатов, поэтому я стал разбираться, как создать свой сертификат.
После нескольких часов, проведенных в попытках и поисках, получился скрипт, позволяющий сгенерировать нужный сертификат.
После запуска скрипта, на выходе получаем два файла: keystore.jks — используется на сервере, public_cert.pem — используется при установке webhook в Android приложении.
Для того, чтобы запустить HTTPS на Spark Framework достаточно добавить 2 строки, одну указывающую порт (разрешенные порты для webhook: 443, 80, 88, 8443), другую, указывающую сгенерированный сертификат и пароль к нему:
Чтобы установить webhook для бота, необходимо добавить в андроид-приложение следующие строки:
При регистрации webhook, в качестве URL указывается адрес webhook, затем передается пуш-токен, необходимый для отправки пуш-уведомлений и секретный ключ, генерируемый на устройстве, который я добавил для дополнительной проверки входящих уведомлений.
Функция чтения публичного сертификата из RAW ресурса:
После модификации сервиса по обработке сообщений в Android приложении, бот стал расходовать батарею намного меньше, но и добавилась зависимость работы приложения от сервера пуш-нотификаций, что было необходимостью для стабильной работы приложения.
Автоматическое создание бота
После обновления механизма получения сообщений, осталась еще одна проблема, которая не позволяла пользоваться приложением некоторому проценту пользователей из-за сложности создания бота через BotFather. Поэтому я решил автоматизировать этот процесс.
В этом мне помогла библиотека tdlib от создателей Telegram. К сожалению, я нашел очень мало примеров использования этой библиотеки, но разобравшись в API, оказалось, что не так все сложно. В итоге удалось реализовать авторизацию в Telegram по номеру телефона, добавление @Botfather в список контактов и отправку и получение сообщений заданному контакту, а в конкретном случае, боту @Botfather.
Добавление новых возможностей
После решения первостепенных проблем с автономностью, я занялся добавлением новых команд.
В итоге были добавлены такие команды как: фото, запись видео, диктофон, скриншот экрана, управление плеером, запуск избранных приложений и т.д. Для удобного запуска команд, добавил Telegram-клавиатуру и разбил команды по категориям.
По просьбам пользователей, я также добавил возможность вызова команд Tasker и отправки сообщений из Tasker в Telegram.
После этого я задумался о том, что неплохо бы добавить внешний доступ из сторонних приложений для оправки сообщений в Telegram. Сообщения могут быть как текстовыми, так и включать в себя аудио, видео, местоположение по координатам. В итоге, я написал библиотеку, которую можно добавить в свой проект.
Заключение
В этой статье я постарался поделиться краткой историей работы над проектом по созданию бота, работающего на Android устройстве и трудностями, с которыми я столкнулся. Сейчас я занимаюсь проектом в свободное от работы время, добавляю новые команды и исправляю возникающие ошибки.
Большое спасибо за внимание. Буду рад услышать от Вас полезные замечания и предложения.
Источник
Telegram api android studio
iMe Messenger — is an unofficial client developed on the Telegram open source and working on Telegram API.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
iMe Messenger is an unofficial Telegram client
The development of the main functionality is made by the Telegram team which creates the most advanced and sophisticated messenger in the world. Telegram provides the opportunity to use its open code and API to implement brand-new solutions. The iMe team develops and adds new features in the messenger without breaking user privacy and violating security principles, enjoying the benefits provided by Telegram.
In-house developments and integrations:
- iMe Wallet and internal AiCoin
- Neurobots assistants for chatting
- Neurobots Store
- Telegram channels, groups, and chatbots’ collection
- Animated stickers with the addition of a text
- Integrated Google Translator
- Text from a Photo
- Photo Description
- Transcribing voice messages to text
- Fast forwarding messages to WhatsApp, WA Business, and Viber
Features based on the Telegram functionality:
- Efficient Cloud based on the Saved Messages chat
- Multi-panel in chats
- Automatic sorting of chats’ lists by types: Unread; Personal; Groups; Channels; Bots
- Customized Telegram folders
- Management. Includes tabs: Owner; Administrator; Undelivered; Drafts
- Forward messages without quotes
- Compact view of a chat list
- Set of iMe app icons
Additional Telegram configurations:
- Going to the first message in a chat
- Opportunity to pin chats’ previews to view their content without opening them
- Hiding a pinned message
- Display accounts on the home screen for quick switching between them
- Opportunity to choose what account data to display in the sidebar
- “Move to archive” option in the chat’s setting of the hamburger menu
- Disable/enable the lower panel in channels
- Disable/enable rounding the number of users in chats
- Confirmation before a call
- Sending GIFs and stickers without sound
- Clickable links in profile description
- User ID in profile
- Stickers, GIF, voice and video messages preview before sending
Download iMe from the App Store or Google Play!
Creating your Telegram Application
We welcome all developers to use our API and source code to create applications on our platform. There are several things we require from all developers for the moment.
- Obtain your own api_id for your application.
- Please do not use the name Telegram for your app — or make sure your users understand that it is unofficial.
- Kindly do not use our standard logo (white paper plane in a blue circle) as your app’s logo.
- Please study our security guidelines and take good care of your users’ data and privacy.
- Please remember to publish your code too in order to comply with the licences.
API, Protocol documentation
You will require Android Studio 3.4, Android NDK rev. 20 and Android SDK 8.1
Источник