What are telegram bots and how to use them?
From playing games to checking Gmail, Telegram bots add a lot of functionalities to the messaging platform. Here are some useful Telegram bots you can try right now.
By: Tech Desk New Delhi | November 9, 2022 18:43 IST
Similar to usernames, every Telegram bot has a unique handle.
Telegram is one of the most popular instant messaging apps on the internet. Unlike WhatsApp, the platform is open-sourced and doesn’t require users to share their phone numbers.
Just like Discord, Telegram supports third-party bots that offer additional functionality. These bots can be used to perform various tasks like converting files, checking emails and even letting users play games with others.
Every bot has a unique handle, similar to Telegram user names. To add a bot, simply search for it, click on the bot handle and you will be able to interact with it in the chat window. Here, we will take a look at some of the most popular and useful bots on Telegram.
Advertisement
Check emails on Gmail (@Gmailbot)
If you are someone who wants to check emails on Gmail but hate opening the app, then this bot might come in handy. The Gmail bot (@Gmailbot) lets you check your emails without having to leave Telegram.
Once you set up the bot and authorise your Gmail account, you can reply to an email using Telegram’s reply feature. It even lets you compose new emails, customise notification settings and turn off email notifications.
You can also forward emails, mark them as read, hide messages from the sender and delete them from the chat window.
Convert files on the go (@newfileconverterbot)
The File Converter bot is one of the most useful Telegrams bots ever. If you want to convert files from one format to another on the fly, this is one of the easiest ways to do so.
Advertisement
The bot works with videos and audio files and even lets you convert images. To convert a file from one format to another, all you need to do is upload the file you want to convert to the bot’s Telegram chat and it will automatically detect the file format.
Once done, it shows a list of formats the file can be converted to. Just click on the type of file you want to convert to and the bot will send you the converted file in the chat window.
Use temporary email (@DropMailBot)
If you are looking for a Telegram bot that gives you access to a temporary disposable email, then this might help.
Advertisement
The DropMail bot is pretty simple and straightforward to use. Just type in ‘/get’ in the chat window and the bot will assign you a temporary email address that you can use to receive emails.
Play games with friends (@gamebot)
The Game bot is helpful for those who want to play some games with their friends on Telegram. Developed for Telegram’s gaming platform, the bot currently has three games to choose from.
Once you find the bot, tap on the ‘Play with friends’ button. Now, choose the person or group you want to play with and the bot will show you the available games. After you select the game you want to play, you will see the play button in the chat window.
Translate text or messages (@BabelgramBot)
The Babelgram bot lets users easily translate messages from one language to another. It works in both private as well as group chats and even has the ability to translate the text you type, similar to how Google Translate works.
It supports more than 100 languages and can even auto-translate messages in private or group chats. However, to enable auto-translation to group chats, you will have to add the bot to the group you want to translate messages from.
Telegram Bots: What Are the Most Popular Ones?
If you are looking for info about telegram bots, you’ve come to the right place! Find out all about their functions!
Last Updated: August 24, 2023

Telegram bots are AI-inspired apps that can serve many functions: send relevant information about the weather or useful news articles, schedule reminders, play tunes, create to-do lists, and so much more. If you want to learn how to program telegram bots, head to edX, and look for courses!
Such bots work in Telegram, a popular instant messaging application used by millions of people worldwide.
The security of Telegram is tight: users can enable end-to-end encryption and communicate through Secret Chats. This feature is not the only attractive aspect: bots are becoming increasingly popular as the third-party applications to run in the Telegram environment.
Furthermore, thanks to the Telegram bot API, you can easily create bots, promote them or generate them to make your instant messaging more convenient. This course on making a Telegram bot in Python is a perfect place to start learning how to make bots come alive.
Table of Contents
- 1. What is a Telegram bot?
- 2. Security of Telegram Bots: They Compromise Encryption?
- 3. Gamee
- 4. Spotybot
- 5. Bots for setting reminders and alerts
- 6. Gif Bot
- 7. Yandex.Translate
- 8. MoviesTracker bot
- 9. GitHub bot
- 10. Otouto
- 11. LittleGuardian Bot
- 12. VoteBot
- 13. MetricsBot
- 14. invokeGeekBot
- 15. Voicy Bot
- 16. Shieldy bot
- 17. Conclusion
What is a Telegram bot?
Bots started to emerge after Telegram announced a new Telegram bot API in 2015. It allows third parties to create bots that will use this messaging application as their main interface. The Telegram bots list is long: many developers have experimented with the provided API to generate unique bots for various purposes.
Latest DataCamp Coupon Found:
Verified Staff Pick
50% DISCOUNT
DataCamp Black Friday Sale
During this DataCamp Black Friday, you can access the top-rated courses with a huge 50% discount. Get the annual subscription plan & redevelop yourself!
Expiration date : 22/11/2023
4,834 People Used
Only 74 Left
Verified Staff Pick
Have you ever wondered which online learning platforms are the best for your career?
50% DISCOUNT
DataCamp Black Friday Sale
During this DataCamp Black Friday, you can access the top-rated courses with a huge 50% discount. Get the annual subscription plan & redevelop yourself!
Pros
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
Main Features
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
Pros
- High-quality courses
- Nanodegree programs
- Student Career services
Main Features
- Nanodegree programs
- Suitable for enterprises
- Paid certificates of completion
Pros
- A huge variety of courses
- Easy-to-navigate interface
- Over 600 free courses
Main Features
- A huge variety of courses
- 30-day refund policy
- Free certificates of completion
Your Discount is activated!
Expiration date : 22/11/2023
4,834 People Used
Only 74 Left
Verified Staff Pick
Have you ever wondered which online learning platforms are the best for your career?
50% DISCOUNT
DataCamp Black Friday Sale
During this DataCamp Black Friday, you can access the top-rated courses with a huge 50% discount. Get the annual subscription plan & redevelop yourself!
Pros
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
Main Features
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
Pros
- High-quality courses
- Nanodegree programs
- Student Career services
Main Features
- Nanodegree programs
- Suitable for enterprises
- Paid certificates of completion
Pros
- A huge variety of courses
- Easy-to-navigate interface
- Over 600 free courses
Main Features
- A huge variety of courses
- 30-day refund policy
- Free certificates of completion
Your Discount is activated!
Expiration date : 22/11/2023
4,834 People Used
Only 74 Left

In short, Telegram bots are applications set to perform specific functions, follow instructions, and interact with users. Bots run inside the Telegram environment and do not require an additional installation procedure.
By using bots, people can enhance the functionality of Telegram. For instance, you can send daily notifications to your friends, set reminders for yourself, translate messages, receive weather alerts, play games, and so much more.
All you need to do is embed a bot into your chat or channel. How can you do this? The procedure is very similar to adding a friend to your conversation and takes only a few seconds.
You can easily find bots by clicking the Telegram Search and typing in a specific name of a bot. Usually, creators of bots introduce their products and how they work.
The Most Liked Findings
Looking for more in-depth information on related topics? We have gathered similar articles for you to spare your time. Take a look!

What is Data Literacy, and Why is It Important for Your Business?
What is data literacy: definition, importance, best data literacy training programs, and much more.

How to Learn AI From Scratch: Top 5 AI Courses
Find out how to learn AI efficiently and why you should do so.

Where to Learn ChatGPT: A Simple Guide to AI
Find out where to learn ChatGPT and how this tool took the internet by a storm.
Security of Telegram Bots: They Compromise Encryption?
While Telegram provides flexibility and high-security measures, including the steel-like encryption, specialists worry whether Telegram bots follow the same pattern.
As it turns out, they do not. When you add a bot, it does not use the standard encryption that this instant messaging app follows. Therefore, chats and channels that embed bots become easier to intercept.
Specialists revealed that bots do not follow the standard MTProto protocol, which is the standard for encrypting messages in Telegram. Instead, they use TLS (Transport Layer Security) protocol applied in HTTPS web encryption.
Therefore, when you add bots into chats, you are unknowingly weakening the encryption of your messages.
Therefore, it might be best to steer clear of Telegram bots if you need to guarantee 100% security in your chats. However, if you still feel like adding a bot to use new functions while messaging, you are free to consider the following options.
Gamee
Gamee is one of the best Telegram bots, letting people play games, challenge their friends, and compare scores. Users can start playing by directly interacting with the bot or by activating it in a chat. Simply type in @gamee or @gamebot and start browsing to find a game to play.

One of the best features is that you will be able to compete with your friends and review high scores. Additionally, owners of Telegram insists that creating games for their instant messaging app is extremely easy and fast. For instance, creating some arcade or puzzle games can take only several hours.
Spotybot

Spotybot is one of the Telegram bots that let you listen to music available in this instant messaging application. You can share songs and lyrics with your friends as well.
There are many similar bots that you can choose from, but this bot is one of the most popular music-related applications.
Bots for setting reminders and alerts
Alert bot is a program for setting alerts or notifications to your Telegram account, a specific chat, or a group. Users praise it for being a quick and easy solution for setting reminders.

Skeddy bot is an excellent option for setting reminders and keeping your notes organized. You can indicate the purpose of the reminder: for instance, text Ashley in 30 minutes.

For forgetful people, this bot can guarantee that they will always be on top of their schedules.
Gif Bot
The Telegram gif bot lets you use the inline method to add gifs to chats. For instance, you can type @gif this is fine and pick one from the generated selection of gifs.

Tap on the gif you want to send, and the gif will immediately appear in the chat.
Yandex.Translate
Yandex.Translate is one of the best Telegram chat bots for translating messages to other languages. If you are chatting with people from different countries and find it challenging to communicate with them, you can ask Yandex.Translate to translate it instead.

Of course, the quality might not always be top-notch, but machine translation has greatly improved over the years.
MoviesTracker bot
The MoviesTracker bot is an application for finding information about movies directly from IMDB.
![]()
All you will need to do is type in the title of the film, and the related content will be presented to you in the Telegram interface.
GitHub bot
The GitHub bot is an application designed for managing notifications from Github directly from the interface of Telegram. You can post comments on issues as well.

However, our brief investigation of this bot concluded that it still has many bugs and make unnecessary complications to the way you handle GitHub content. However, it is a decent bot, but new features could improve it significantly.
Otouto
The Otouto is one of the Telegram bots with many functions. The program lets you search for content such as images, videos, articles, and maps.

Furthermore, it contains features that let you translate text.
LittleGuardian Bot
The LittleGuardian bot is a program that protects Telegram users from getting inappropriate or malware-ridden content through this messaging app. Therefore, this bot guarantees that you won’t receive spam or dangerous files aiming to infect you with viruses.

Additionally, the creators of LittleGuardian bot are actively fixing issues and releasing new updates to improve their product.
VoteBot

The VoteBot is one of the Telegram bots that let you create polls and use them in channels or chats.
You will create the survey by communicating with the bot through a sequence of prepared questions. Then, you will need to open the conversation, type @vote, and select the poll you want to insert.
MetricsBot
The MetricsBot is an application for receiving information from Google Analytics directly into the Telegram environment.

This bot is great for keeping track of your website or when you want to share information with your colleagues.
invokeGeekBot
For IT specialists, it is important to receive the latest job offerings to increase their chances of ending the job hunt. invokeGeekBot is here to serve information about the latest IT job offers. Additionally, the app provides frequent and daily career tips.

So, if career tips are what you’re interested in, this bot is for you!
Voicy Bot
The Voicy bot is an application that converts audio messages to texts. Therefore, you can easily send messages that would take too long to write.

Additionally, since Telegram prevents bots from downloading files bigger than 20 megabytes, the creators of Voicy added voice-recognition to their main website.
Shieldy bot
The Shieldy bot is one of the Telegram bots that aim to protect users from spammers. When a new person joins a group, the Shieldy bot will require him/her to perform an action.

If they cannot prove their legitimacy, the bot automatically kicks them out.
The Most Trending Findings
Browse our collection of the most thorough Online Learning Platform related articles, guides & tutorials. Always be in the know & make informed decisions!

What Is the Best Python IDE: Comparing Your Choices
What is the best Python IDE? See all the options presented and compared in a comprehensive guide. Find out what is the best Python IDE for you!

Columbia University Online Courses: Top-Rated Ones
Looking for the most popular Columbia University online courses to enhance your life and become a better version of yourself? Check out the top 7 courses to help you!

SQL Database Management System: Which One Should You Choose?
Choosing the right database management system can be a pickle. Start with getting to know the most popular SQL database management systems now!
Conclusion
All in all, Telegram bots help you implement many tasks without ever leaving the environment of this messaging app. The integration of a multitude of functions is an excellent feature, but we cannot ignore the potential security risks arising from the use of bots.
The suggested security issues in the way Telegram embeds bots can compromise the encryption of your messages. There are times in life when you need to set your priorities straight: should I guarantee proper encryption or send many gifs of cats rolling around?
However, creators of Telegram indicate the potential danger from bots as a one-time-thing. The bot in question had some flaws on its own.
Nevertheless, this left the online community baffled whether using Telegram chat bots is as safe as they make it out to be. After all, Telegram does not create bots (with some exceptions, of course), third-parties do. Therefore, it is better to be more critical when it comes to downloading applications from unknown sources.
If these bots don’t satisfy your needs, you can become a bot creator yourself. To do that, you have to learn programming languages. Now, head to edX and start learning and you’ll be creating telegram bots in no time!
Leave your honest feedback
Leave your genuine opinion & help thousands of people to choose the best online learning platform. All feedback, either positive or negative, are accepted as long as they’re honest. We do not publish biased feedback or spam. So if you want to share your experience, opinion or give advice — the scene is yours!
Знакомство с aiogram¶
Автор этой книги убеждён, что помимо теории должна быть и практика. Чтобы максимально упростить повторение приведённого далее кода, пришлось пойти на использование подходов, пригодных только для локальной разработки и обучения.
Так, например, во всех или почти во всех главах токен бота будет указываться прямо в исходных текстах. Это плохой подход, поскольку может привести к раскрытию токена, если вы забудете его удалить перед заливкой кода в публичный репозиторий (например, GitHub).
Или иногда в качестве хранилищ данных будут использоваться структуры, расположенные исключительно в оперативной памяти (словари, списки. ). В действительности такие объекты нежелательны, поскольку остановка бота приведёт безвозвратной потере данных.
Также механизмом получения апдейтов от Telegram выбран поллинг, поскольку он гарантированно работает в подавляющем большинстве окружений и подходит практически всем разработчикам.
Важно помнить, что автор ставит перед собой цель объяснить именно работу с Telegram Bot API при помощи aiogram, а не вообще весь Computer Science во всём его многообразии.
Терминология¶
Чтобы разговаривать в одних и тех же понятиях, введём некоторые термины, дабы в дальнейшем не путаться:
- ЛС — личные сообщения, в контексте бота это диалог один-на-один с пользователем, а не группа/канал.
- Чат — общее название для ЛС, групп, супергрупп и каналов.
- Апдейт — любое событие из этого списка: сообщение, редактирование сообщения, колбэк, инлайн-запрос, платёж, добавление бота в группу и т.д.
- Хэндлер — асинхронная функция, которая получает от диспетчера/роутера очередной апдейт и обрабатывает его.
- Диспетчер — объект, занимающийся получением апдейтов от Telegram с последующим выбором хэндлера для обработки принятого апдейта.
- Роутер — аналогично диспетчеру, но отвечает за подмножество множества хэндлеров. Можно сказать, что диспетчер — это корневой роутер.
- Фильтр — выражение, которое обычно возвращает True или False и влияет на то, будет вызван хэндлер или нет.
- Мидлварь — прослойка, которая вклинивается в обработку апдейтов.
Установка¶
Для начала давайте создадим каталог для бота, организуем там virtual environment (далее venv) и установим библиотеку aiogram.
Проверим, что установлен Python версии 3.9 (если вы знаете, что установлен 3.9 и выше, можете пропустить этот раздел):
[groosha@main lesson_01]$ python3.9 Python 3.9.9 (main, Jan 11 2022, 16:35:07) [GCC 11.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit() [groosha@main lesson_01]$
Теперь создадим файл requirements.txt , в котором укажем используемую нами версию aiogram. Также нам понадобится библиотека python-dotenv для файлов конфигурации.
О версиях aiogram
В этой главе используется aiogram 3.x, перед началом работы рекомендую заглянуть в канал релизов библиотеки и проверить наличие более новой версии. Подойдёт любая более новая, начинающаяся с цифры 3, поскольку aiogram 2.x более рассматриваться не будет и считается устаревшим.
[groosha@main 01_quickstart]$ python3.9 -m venv venv [groosha@main 01_quickstart]$ echo "aiogram requirements.txt [groosha@main 01_quickstart]$ echo "python-dotenv==1.0.0" >> requirements.txt [groosha@main 01_quickstart]$ source venv/bin/activate (venv) [groosha@main 01_quickstart]$ pip install -r requirements.txt # . здесь куча строк про установку. Successfully installed . тут длинный список. [groosha@main 01_quickstart]$
Обратите внимание на префикс «venv» в терминале. Он указывает, что мы находимся в виртуальном окружении с именем «venv». Проверим, что внутри venv вызов команды python указывает на всё тот же Python 3.9:
(venv) [groosha@main 01_quickstart]$ python Python 3.9.9 (main, Jan 11 2022, 16:35:07) [GCC 11.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit() (venv) [groosha@main 01_quickstart]$ deactivate [groosha@main 01_quickstart]$
Последней командой deactivate мы вышли из venv, чтобы он нам не мешал.
Если для написания ботов вы используете PyCharm, рекомендую также установить сторонний плагин Pydantic для поддержки автодополнения кода в телеграмных объектах.
Первый бот¶
Давайте создадим файл bot.py с базовым шаблоном бота на aiogram:
import asyncio import logging from aiogram import Bot, Dispatcher, types from aiogram.filters.command import Command # Включаем логирование, чтобы не пропустить важные сообщения logging.basicConfig(level=logging.INFO) # Объект бота bot = Bot(token="12345678:AaBbCcDdEeFfGgHh") # Диспетчер dp = Dispatcher() # Хэндлер на команду /start @dp.message(Command("start")) async def cmd_start(message: types.Message): await message.answer("Hello!") # Запуск процесса поллинга новых апдейтов async def main(): await dp.start_polling(bot) if __name__ == "__main__": asyncio.run(main())
Первое, на что нужно обратить внимание: aiogram — асинхронная библиотека, поэтому ваши хэндлеры тоже должны быть асинхронными, а перед вызовами методов API нужно ставить ключевое слово await, т.к. эти вызовы возвращают корутины.
Асинхронное программирование в Python
Не стоит пренебрегать официальной документацией!
Прекрасный туториал по asyncio доступен на сайте Python.
Если вы в прошлом работали с какой-то другой библиотекой для Telegram, например, pyTelegramBotAPI, то концепция хэндлеров (обработчиков событий) вам сразу станет понятна, разница лишь в том, что в aiogram хэндлерами управляет диспетчер.
Диспетчер регистрирует функции-обработчики, дополнительно ограничивая перечень вызывающих их событий через фильтры. После получения очередного апдейта (события от Telegram), диспетчер выберет нужную функцию обработки, подходящую по всем фильтрам, например, «обработка сообщений, являющихся изображениями, в чате с ID икс и с длиной подписи игрек». Если две функции имеют одинаковые по логике фильтры, то будет вызвана та, что зарегистрирована раньше.
Чтобы зарегистрировать функцию как обработчик сообщений, нужно сделать одно из двух действий:
1. Навесить на неё декоратор, как в примере выше. С различными типами декораторов мы познакомимся позднее.
2. Напрямую вызвать метод регистрации у диспетчера или роутера.
Рассмотрим следующий код:
# Хэндлер на команду /test1 @dp.message(Command("test1")) async def cmd_test1(message: types.Message): await message.reply("Test 1") # Хэндлер на команду /test2 async def cmd_test2(message: types.Message): await message.reply("Test 2")

Давайте запустим с ним бота:
Хэндлер cmd_test2 не сработает, т.к. диспетчер о нём не знает. Исправим эту ошибку и отдельно зарегистрируем функцию:
# Хэндлер на команду /test2 async def cmd_test2(message: types.Message): await message.reply("Test 2") # Где-то в другом месте, например, в функции main(): dp.message.register(cmd_test2, Command("test2"))

Снова запустим бота:
Синтаксический сахар¶
Для того чтобы сделать код чище и читабельнее, aiogram расширяет возможности стандартных объектов Telegram. Например, вместо bot.send_message(. ) можно написать message.answer(. ) или message.reply(. ) . В последних двух случаях не нужно подставлять chat_id , подразумевается, что он такой же, как и в исходном сообщении.
Разница между answer и reply простая: первый метод просто отправляет сообщение в тот же чат, второй делает «ответ» на сообщение из message :
@dp.message(Command("answer")) async def cmd_answer(message: types.Message): await message.answer("Это простой ответ") @dp.message(Command("reply")) async def cmd_reply(message: types.Message): await message.reply('Это ответ с "ответом"')

Более того, для большинства типов сообщений есть вспомогательные методы вида «answer_» или «reply_», например:
@dp.message(Command("dice")) async def cmd_dice(message: types.Message): await message.answer_dice(emoji="")
что значит ‘message: types.Message’ ?
Python является интерпретируемым языком с сильной, но динамической типизацией, поэтому встроенная проверка типов, как, например, в C++ или Java, отсутствует. Однако начиная с версии 3.5 в языке появилась поддержка подсказок типов, благодаря которой различные чекеры и IDE вроде PyCharm анализируют типы используемых значений и подсказывают программисту, если он передаёт что-то не то. В данном случае подсказка types.Message соообщает PyCharm-у, что переменная message имеет тип Message , описанный в модуле types библиотеки aiogram (см. импорты в начале кода). Благодаря этому IDE может на лету подсказывать атрибуты и функции.
При вызове команды /dice бот отправит в тот же чат игральный кубик. Разумеется, если его надо отправить в какой-то другой чат, то придётся по-старинке вызывать await bot.send_dice(. ) . Но объект bot (экземпляр класса Bot) может быть недоступен в области видимости конкретной функции. В aiogram 3.x объект бота, которому пришёл апдейт, неявно прокидывается в хэндлер и его можно достать как аргумент bot . Предположим, вы хотите по команде /dice отправлять кубик не в тот же чат, а в канал с ID -100123456789. Перепишем предыдущую функцию:
# не забудьте про импорт from aiogram.enums.dice_emoji import DiceEmoji @dp.message(Command("dice")) async def cmd_dice(message: types.Message, bot: Bot): await bot.send_dice(-100123456789, emoji=DiceEmoji.DICE)
Передача доп. параметров¶
Иногда при запуске бота может потребоваться передать одно или несколько дополнительных значений. Это может быть какая-нибудь переменная, объект конфигурации, список чего-то, отметка времени и что угодно ещё. Для этого достаточно передать эти данные как именованные (kwargs) аргументы в диспетчер, либо присвоить значения, как если бы вы работали со словарём.
Такая возможность лучше всего подходит для передачи объектов, которые должны жить в единственном экземпляре и не меняться в ходе работы бота (т.е. быть только для чтения). Если предполагается, что значение должно изменяться со временем, то помните, что это сработает только с мутабельными объектами. Чтобы получить значения в хэндлерах, просто укажите их как аргументы. Рассмотрим на примере:
# Где-то в другом месте # Например, в точке входа в приложение from datetime import datetime # bot = . dp = Dispatcher() dp["started_at"] = datetime.now().strftime("%Y-%m-%d %H:%M") await dp.start_polling(bot, mylist=[1, 2, 3]) @dp.message(Command("add_to_list")) async def cmd_add_to_list(message: types.Message, mylist: list[int]): mylist.append(7) await message.answer("Добавлено число 7") @dp.message(Command("show_list")) async def cmd_show_list(message: types.Message, mylist: list[int]): await message.answer(f"Ваш список: mylist>") @dp.message(Command("info")) async def cmd_info(message: types.Message, started_at: str): await message.answer(f"Бот запущен started_at>")
Теперь переменную started_at и список mylist можно читать и писать в разных хэндлерах. А если вам нужно пробрасывать уникальные для каждого апдейта значения (например, объект сессии СУБД), то ознакомьтесь с мидлварями.

Файлы конфигурации¶
Чтобы не хранить токен прямо в коде (вдруг вы захотите залить своего бота в публичный репозиторий?) можно вынести подобные данные в отдельный конфигурационный файл. Существует хорошее и адекватное мнение, что для прода достаточно переменных окружения, однако в рамках этой книги мы будем пользоваться отдельными файлами .env , чтобы немного упростить себе жизнь и сэкономить читателям время на разворачивание демонстрационного проекта.
Итак, создадим рядом с bot.py отдельный файл config_reader.py со следующим содержимым
config_reader.py
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic import SecretStr class Settings(BaseSettings): # Желательно вместо str использовать SecretStr # для конфиденциальных данных, например, токена бота bot_token: SecretStr # Начиная со второй версии pydantic, настройки класса настроек задаются # через model_config # В данном случае будет использоваться файла .env, который будет прочитан # с кодировкой UTF-8 model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8') # При импорте файла сразу создастся # и провалидируется объект конфига, # который можно далее импортировать из разных мест config = Settings()
Теперь немного отредактируем наш bot.py :
# импорты from config_reader import config # Для записей с типом Secret* необходимо # вызывать метод get_secret_value(), # чтобы получить настоящее содержимое вместо '*******' bot = Bot(token=config.bot_token.get_secret_value())
Наконец, создадим файл .env (с точкой в начале), где опишем токен бота:
BOT_TOKEN = 0000000000:AaBbCcDdEeFfGgHhIiJjKkLlMmNn
Если всё сделано правильно, то при запуске python-dotenv подгрузит переменные из файла .env , pydantic их провалидирует и объект бота успешно создастся с нужным токеном.
На этом мы закончим знакомство с библиотекой, а в следующих главах рассмотрим другие «фишки» aiogram и Telegram Bot API.
Пишем Telegram бот текущей погоды по IP адресу на Python aiogram
Штош. В этой статье я расскажу вам, как создать Telegram бота, который получает текущую погоду по IP адресу. Мы будем использовать язык Python и асинхронную библиотеку для взаимодействия с Telegram Bot API — aiogram.
Итак, как же вы можете создать такого бота?
Склонируйте репозиторий shtosh-weather-bot и пройдите по инструкции в README.
Выбираем погодный сервис с бесплатным API
Данные о текущей погоде нам нужно откуда-то брать. Еще желательно, чтобы это было бесплатно. У сайта OpenWeatherMap есть нужный нам API текущей погоды. Бесплатно можно посылать 1000 запросов в день.
Кстати, если вы ищете какой-то application user interface для своего проекта, рекомендую репозиторий public-apis.
Итак, для запроса нужны координаты и специальный ключ, который можно получить, зарегистрировав аккаунт. Ну это вообще не проблема, можно зарегать на временную почту. Конечно, если вы собираетесь серьезно использовать API и покупать больше 1000 запросов в день, лучше регистрировать аккаунт на свою почту. Капитан очевидность.
Заходим в My API keys и видим здесь тот самый ключ. Можете взять мой, мне не жалко.

Итак, давайте сформируем запрос. Я выбрал координаты Нью-Йорка, просто потому что хочу и могу. Не забудем добавить флаг units со значением metric , чтобы температура показывалась в градусах Цельсия. По умолчанию дается в Кельвинах.
Вот такой json мы получаем.
< "coord": < "lon": -74.006, "lat": 40.7128 >, "weather": [ < "id": 802, "main": "Clouds", "description": "scattered clouds", "icon": "03d" >], "base": "stations", "main": < "temp": 31.36, "feels_like": 31.23, "temp_min": 28.86, "temp_max": 33.94, "pressure": 1013, "humidity": 39 >, "visibility": 10000, "wind": < "speed": 5.14, "deg": 290 >, "clouds": < "all": 40 >, "dt": 1661375748, "sys": < "type": 2, "id": 2039034, "country": "US", "sunrise": 1661336121, "sunset": 1661384510 >, "timezone": -14400, "id": 5128581, "name": "New York", "cod": 200 >
Создаем бота и устанавливаем все необходимое
Создайте Telegram бота с помощью BotFather и возьмите его токен.
Из названия видео вы могли догадаться, что мы будем использовать язык Python и библиотеку aiogram. Я надеюсь, с установкой Python у вас не возникнет проблем. С aiogram тоже.
pip install aiogram
Лирическое отступление
Я много позаимствовал у проекта Алексея Голобурдина — автора YouTube канала «Диджитализируй!» Проблема в том, что его проект предназначен только для macOS устройств, потому что координаты берутся с помощью инструмента командной строки whereami. Пример вывода:
Latitude: 45.424807, Longitude: -75.699234 Accuracy (m): 65.000000 Timestamp: 2019-09-28, 12:40:20 PM EDT
Также его скрипт просто выводит всю форматированную информацию в терминал, хотелось бы иметь интерфейс поприятнее и удобнее.

Я решил, что можно доработать идею и охватить максимальное количество пользователей, пренебрегая точностью информации.
Пишем код. Файл конфигурации
Итак, файл config.py содержит константы:
- Токен бота BOT_API_TOKEN
- Ключ OpenWeather WEATHER_API_KEY
- Запрос текущей погоды CURRENT_WEATHER_API_CALL
BOT_API_TOKEN = '' WEATHER_API_KEY = '' CURRENT_WEATHER_API_CALL = ( 'https://api.openweathermap.org/data/2.5/weather?' 'lat=&lon=&' 'appid=' + WEATHER_API_KEY + '&units=metric' )
Конечно, такие данные, как токены и ключи нужно хранить в переменных окружения, но это пет-проект, деплоить я его не буду, поэтому особо не заморачиваюсь.
Получаем координаты
Для получения координат я создал отдельный модуль. Датакласс Coordinates содержит широту и долготу с типами float.
from dataclasses import dataclass @dataclass(slots=True, frozen=True) class Coordinates: latitude: float longitude: float
По IP адресу их можно найти с помощью ipinfo.io/json. Получается вот такой ответ.
Нас интересует ключ «loc» сокращенно от location. Опять капитан очевидность. Делаем запрос с помощью функции urlopen модуля request библиотеки urllib. Возвращаем словарь с помощью json.load()
from urllib.request import urlopen import json def _get_ip_data() -> dict: url = 'http://ipinfo.io/json' response = urlopen(url) return json.load(response)
В функции получения координат парсим этот словарь и возвращаем датакласс координат.
def get_coordinates() -> Coordinates: """Returns current coordinates using IP address""" data = _get_ip_data() latitude = data['loc'].split(',')[0] longitude = data['loc'].split(',')[1] return Coordinates(latitude=latitude, longitude=longitude)
coordinates.py
from urllib.request import urlopen from dataclasses import dataclass import json @dataclass(slots=True, frozen=True) class Coordinates: latitude: float longitude: float def get_coordinates() -> Coordinates: """Returns current coordinates using IP address""" data = _get_ip_data() latitude = data['loc'].split(',')[0] longitude = data['loc'].split(',')[1] return Coordinates(latitude=latitude, longitude=longitude) def _get_ip_data() -> dict: url = 'http://ipinfo.io/json' response = urlopen(url) return json.load(response)
Парсим ответ OpenWeather API
Далее рассмотрим модуль api_service. В нем происходит вся суета с погодой. Температура измеряется в градусах Цельсия, чему соответствует псевдоним float числа.
from typing import TypeAlias Celsius: TypeAlias = float
Как известно, градусы Фаренгейта были созданы только для того, чтобы Рэй Брэдбери смог красиво назвать свою антиутопию.

В ответе API направление ветра дается в градусах. Я решил привести их в более удобный формат. Для этого я создал перечисление основных направлений ветра.
from enum import IntEnum class WindDirection(IntEnum): North = 0 Northeast = 45 East = 90 Southeast = 135 South = 180 Southwest = 225 West = 270 Northwest = 315
В функции парсинга округление по 45 градусов выглядит таким образом: делим градусы на 45, округляем и умножаем обратно на 45. Результат может округлиться до 360 градусов, поэтому обрабатываем этот случай.
def _parse_wind_direction(openweather_dict: dict) -> str: degrees = openweather_dict['wind']['deg'] degrees = round(degrees / 45) * 45 if degrees == 360: degrees = 0 return WindDirection(degrees).name
Все данные о погоде будут храниться в датаклассе. При желании вы можете добавить сюда остальную информацию из ответа OpenWeather, например атмосферное давление, часовой пояс, минимальную и максимальную зафиксированную в данный момент температуру.
@dataclass(slots=True, frozen=True) class Weather: location: str temperature: Celsius temperature_feeling: Celsius description: str wind_speed: float wind_direction: str sunrise: datetime sunset: datetime
В остальном ничего интересного в модуле не происходит, просто парсинг json.
from typing import Literal, TypeAlias from urllib.request import urlopen from dataclasses import dataclass from datetime import datetime from enum import IntEnum import json from coordinates import Coordinates import config Celsius: TypeAlias = float class WindDirection(IntEnum): North = 0 Northeast = 45 East = 90 Southeast = 135 South = 180 Southwest = 225 West = 270 Northwest = 315 @dataclass(slots=True, frozen=True) class Weather: location: str temperature: Celsius temperature_feeling: Celsius description: str wind_speed: float wind_direction: str sunrise: datetime sunset: datetime def get_weather(coordinates=Coordinates) -> Weather: """Requests the weather in OpenWeather API and returns it""" openweather_response = _get_openweather_response( longitude=coordinates.longitude, latitude=coordinates.latitude ) weather = _parse_openweather_response(openweather_response) return weather def _get_openweather_response(latitude: float, longitude: float) -> str: url = config.CURRENT_WEATHER_API_CALL.format(latitude=latitude, longitude=longitude) return urlopen(url).read() def _parse_openweather_response(openweather_response: str) -> Weather: openweather_dict = json.loads(openweather_response) return Weather( location=_parse_location(openweather_dict), temperature=_parse_temperature(openweather_dict), temperature_feeling=_parse_temperature_feeling(openweather_dict), description=_parse_description(openweather_dict), sunrise=_parse_sun_time(openweather_dict, 'sunrise'), sunset=_parse_sun_time(openweather_dict, 'sunset'), wind_speed=_parse_wind_speed(openweather_dict), wind_direction=_parse_wind_direction(openweather_dict) ) def _parse_location(openweather_dict: dict) -> str: return openweather_dict['name'] def _parse_temperature(openweather_dict: dict) -> Celsius: return openweather_dict['main']['temp'] def _parse_temperature_feeling(openweather_dict: dict) -> Celsius: return openweather_dict['main']['feels_like'] def _parse_description(openweather_dict) -> str: return str(openweather_dict['weather'][0]['description']).capitalize() def _parse_sun_time(openweather_dict: dict, time: Literal["sunrise", "sunset"]) -> datetime: return datetime.fromtimestamp(openweather_dict['sys'][time]) def _parse_wind_speed(openweather_dict: dict) -> float: return openweather_dict['wind']['speed'] def _parse_wind_direction(openweather_dict: dict) -> str: degrees = openweather_dict['wind']['deg'] degrees = round(degrees / 45) * 45 if degrees == 360: degrees = 0 return WindDirection(degrees).name
Делаем сообщения для бота
В модуле messages собраны сообщения для бота по командам. Сообщение о погоде /weather содержит локацию, описание погоды, температуру и ее ощущение.
from coordinates import get_coordinates from api_service import get_weather def weather() -> str: """Returns a message about the temperature and weather description""" wthr = get_weather(get_coordinates()) return f', \n' \ f'Temperature is °C, feels like °C'
Сообщение о ветре /wind показывает его направление и скорость в метрах в секунду.
def wind() -> str: """Returns a message about wind direction and speed""" wthr = get_weather(get_coordinates()) return f' wind m/s'
Ну и сообщение о времени восхода и заката солнца /sun_time . Здесь datetime объект форматируется в часы и минуты, остальное в данном случае неважно.
def sun_time() -> str: """Returns a message about the time of sunrise and sunset""" wthr = get_weather(get_coordinates()) return f'Sunrise: \n' \ f'Sunset: \n'
Нужно заметить, что при каждом вызове функции создается новый API запрос. Почему это нужно заметить? Потому что сначала я сделал бота с одним запросом и недоумевал, почему информация не меняется через время. Потому что в идеале делать один запрос в 5 или 10 минут, за это время погода не особо меняется, да и данные OpenWeather тоже не обновляются каждую секунду.
from coordinates import get_coordinates from api_service import get_weather def weather() -> str: """Returns a message about the temperature and weather description""" wthr = get_weather(get_coordinates()) return f', \n' \ f'Temperature is °C, feels like °C' def wind() -> str: """Returns a message about wind direction and speed""" wthr = get_weather(get_coordinates()) return f' wind m/s' def sun_time() -> str: """Returns a message about the time of sunrise and sunset""" wthr = get_weather(get_coordinates()) return f'Sunrise: \n' \ f'Sunset: \n'
Inline клавиатура
Можно было сделать reply клавиатуру, но мне больше по душе Inline. 3 кнопки для 3 команд.
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup BTN_WEATHER = InlineKeyboardButton('Weather', callback_data='weather') BTN_WIND = InlineKeyboardButton('Wind', callback_data='wind') BTN_SUN_TIME = InlineKeyboardButton('Sunrise and sunset', callback_data='sun_time')
4 клавиатуры для 4 команд, добавляется команда помощи. В чем суть? После сообщения погоды нам не нужно показывать ее кнопку. Такая же логика для всех других команд, кроме помощи. Для нее выводятся кнопки всех 3 команд.
WEATHER = InlineKeyboardMarkup().add(BTN_WIND, BTN_SUN_TIME) WIND = InlineKeyboardMarkup().add(BTN_WEATHER).add(BTN_SUN_TIME) SUN_TIME = InlineKeyboardMarkup().add(BTN_WEATHER, BTN_WIND) HELP = InlineKeyboardMarkup().add(BTN_WEATHER, BTN_WIND).add(BTN_SUN_TIME)
inline_keyboard.py
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup BTN_WEATHER = InlineKeyboardButton('Weather', callback_data='weather') BTN_WIND = InlineKeyboardButton('Wind', callback_data='wind') BTN_SUN_TIME = InlineKeyboardButton('Sunrise and sunset', callback_data='sun_time') WEATHER = InlineKeyboardMarkup().add(BTN_WIND, BTN_SUN_TIME) WIND = InlineKeyboardMarkup().add(BTN_WEATHER).add(BTN_SUN_TIME) SUN_TIME = InlineKeyboardMarkup().add(BTN_WEATHER, BTN_WIND) HELP = InlineKeyboardMarkup().add(BTN_WEATHER, BTN_WIND).add(BTN_SUN_TIME)
Главный модуль бота
Ну и в главном модуле бота присутствует стандартная настройка, хэндлеры сообщений и коллбэков для inline кнопок, ничего сверхъестественного.
Нужно хоть что-нибудь рассказать. Под стандартной настройкой aiogram подразумевается следующий блок кода:
import logging from aiogram import Bot, Dispatcher, executor, types import config logging.basicConfig(level=logging.INFO) bot = Bot(token=config.BOT_API_TOKEN) dp = Dispatcher(bot)
Хэндлер для сообщений /start и /weather выглядит следующим образом. Все работает с помощью магии декораторов aiogram.
@dp.message_handler(commands=['start', 'weather']) async def show_weather(message: types.Message): await message.answer(text=messages.weather(), reply_markup=inline_keyboard.WEATHER)
Хэндлер коллбэка для инлайн-кнопки погоды:
@dp.callback_query_handler(text='weather') async def process_callback_weather(callback_query: types.CallbackQuery): await bot.answer_callback_query(callback_query.id) await bot.send_message( callback_query.from_user.id, text=messages.weather(), reply_markup=inline_keyboard.WEATHER)
Запускаем скрипт с помощью такой конструкции:
if __name__ == '__main__': executor.start_polling(dp, skip_updates=True)
import logging from aiogram import Bot, Dispatcher, executor, types import inline_keyboard import messages import config logging.basicConfig(level=logging.INFO) bot = Bot(token=config.BOT_API_TOKEN) dp = Dispatcher(bot) @dp.message_handler(commands=['start', 'weather']) async def show_weather(message: types.Message): await message.answer(text=messages.weather(), reply_markup=inline_keyboard.WEATHER) @dp.message_handler(commands='help') async def show_help_message(message: types.Message): await message.answer( text=f'This bot can get the current weather from your IP address.', reply_markup=inline_keyboard.HELP) @dp.message_handler(commands='wind') async def show_wind(message: types.Message): await message.answer(text=messages.wind(), reply_markup=inline_keyboard.WIND) @dp.message_handler(commands='sun_time') async def show_sun_time(message: types.Message): await message.answer(text=messages.sun_time(), reply_markup=inline_keyboard.SUN_TIME) @dp.callback_query_handler(text='weather') async def process_callback_weather(callback_query: types.CallbackQuery): await bot.answer_callback_query(callback_query.id) await bot.send_message( callback_query.from_user.id, text=messages.weather(), reply_markup=inline_keyboard.WEATHER ) @dp.callback_query_handler(text='wind') async def process_callback_wind(callback_query: types.CallbackQuery): await bot.answer_callback_query(callback_query.id) await bot.send_message( callback_query.from_user.id, text=messages.wind(), reply_markup=inline_keyboard.WIND ) @dp.callback_query_handler(text='sun_time') async def process_callback_sun_time(callback_query: types.CallbackQuery): await bot.answer_callback_query(callback_query.id) await bot.send_message( callback_query.from_user.id, text=messages.sun_time(), reply_markup=inline_keyboard.SUN_TIME ) if __name__ == '__main__': executor.start_polling(dp, skip_updates=True)
Запускаем бота
Смотрим логирование, вы должны увидеть 3 сообщения:
INFO:aiogram:Bot: superultramegaweatherbot [@superultramegaweatherbot] WARNING:aiogram:Updates were skipped successfully. INFO:aiogram.dispatcher.dispatcher:Start polling.

Пока что все работает, давайте посмотрим по IP из Германии.

Бывают такие случаи, когда запрос долго обрабатывается. Я не обрабатывал ошибки и не делал для них сообщений, бот просто ничего не делает в таких случаях. Я посчитал, что уже и так хорошо. Как говорится:

- Лучшее — враг хорошего
- Работает — не трогай
- Еще сотня фраз для оправдания лени
- Еще тысяча успокаивающих фраз для перфекционистов
Также можно реализовать получение координат через отправление геолокации боту, тогда получится в разы точнее.


Штош. Спасибо за прочтение. Надеюсь на отзывы, комментарии и критику.
