
Python for automation, part 5: Telegram bot for alerts and simple commands
🌐 Machine-translated from Russian. Show original
In this part:
What we will do#
- Alerts: any script from previous parts sends a message to the chat—without a separate bot process.
- Bot with commands:
/statuschecks ports,/certs— certificate deadlines; the bot responds only to "its own." - Periodic checks inside the bot: once every 5 minutes — and a message only if something changes.
Creating a bot#
- In Telegram, open @BotFather, command
/newbot, enter the bot's name and login (ends withbot). - BotFather will issue a token — this is the bot's password. Immediately put it in the
.envasTG_BOT_TOKEN, don't send it anywhere. Leaked —/revoketo BotFather. - Add the bot to the workgroup or message them privately.
- Learn chat_id: temporarily launch the bot from the section below and send a
/start— it will show the chat ID.
Alerts from any script#
No bot library is needed to send a message — one HTTP request to the Bot API is enough.
# src/pyreports/notify.py
import html
import logging
import httpx
from pyreports.config import need
logging.getLogger("httpx").setLevel(logging.WARNING) # иначе httpx запишет в лог URL вместе с токеном
log = logging.getLogger(__name__)
def tg_send(text: str, chat_id: str | None = None) -> None:
token = need("TG_BOT_TOKEN")
r = httpx.post(
f"https://api.telegram.org/bot{token}/sendMessage",
data={
"chat_id": chat_id or need("TG_CHAT_ID"),
"text": text[:4000], # лимит сообщения — 4096 символов
"parse_mode": "HTML",
"link_preview_options": '{"is_disabled": true}', # без превью ссылок
},
timeout=15,
)
if r.status_code != 200:
# не печатаем r.request.url — в нем токен
log.error("Telegram: HTTP %s %s", r.status_code, r.text[:200])
def alert(title: str, details: str) -> None:
tg_send(f"🔴 <b>{html.escape(title)}</b>\n<pre>{html.escape(details)}</pre>")
html.escape mandatory: if the error text contains < or &, Telegram will reject the message with the markup error without shielding.
Use in the daily report from part 2:
except Exception as e:
log.exception("Отчет не сформирован")
alert("Отчет о продажах не сформирован", repr(e))
return 1
Bot with commands: python-telegram-bot 22#
Two popular libraries are python-telegram-bot (version 22.8 as of November 2026) and aiogram 3.x. Both are asynchronous and live. In the example — python-telegram-bot: it has detailed documentation with examples, and at the time of verification it already announces support for Python 3.15, while aiogram 3.31 restricts requires_python to versions below 3.15.
uv add "python-telegram-bot[job-queue]" # job-queue — для периодических задач
# src/pyreports/bot.py
import asyncio
import html
import logging
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, filters
from pyreports.checks import TARGETS, check_all
from pyreports.config import need
logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s", level=logging.INFO)
logging.getLogger("httpx").setLevel(logging.WARNING)
log = logging.getLogger("pyreports.bot")
# кому можно пользоваться ботом: id пользователей через запятую
ALLOWED_USERS = {int(x) for x in os.environ.get("TG_ALLOWED_USERS", "").split(",") if x.strip()}
ALERT_CHAT = int(need("TG_CHAT_ID"))
allowed = filters.User(user_id=ALLOWED_USERS)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# отвечает всем — чтобы новый админ мог узнать свой id и передать его вам
await update.message.reply_text(
f"Ваш user_id: {update.effective_user.id}\nchat_id: {update.effective_chat.id}"
)
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Проверяю…")
results = await asyncio.to_thread(check_all) # блокирующие проверки — в отдельном потоке
lines = [f"{'✅' if ok else '❌'} {html.escape(h)}:{p}" for h, p, ok in results]
await update.message.reply_html("\n".join(lines))
async def watch(context: ContextTypes.DEFAULT_TYPE) -> None:
"""Раз в 5 минут: пишем в чат только об изменениях состояния."""
results = await asyncio.to_thread(check_all)
prev: dict = context.bot_data.setdefault("state", {})
for host, port, ok in results:
key = f"{host}:{port}"
if key in prev and prev[key] != ok:
icon, word = ("✅", "снова доступен") if ok else ("🔴", "НЕДОСТУПЕН")
await context.bot.send_message(ALERT_CHAT, f"{icon} {key} {word}")
prev[key] = ok
def main() -> None:
app = Application.builder().token(need("TG_BOT_TOKEN")).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("status", status, filters=allowed))
app.job_queue.run_repeating(watch, interval=300, first=10)
log.info("Бот запущен, проверяю %d адресов", len(TARGETS))
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
# .env
TG_BOT_TOKEN=
TG_CHAT_ID=-1001234567890
TG_ALLOWED_USERS=111111111,222222222
uv run python -m pyreports.bot
How it works:
run_pollingpolls Telegram servers itself — there is no need to open incoming ports, the bot can live on an internal network with internet access only toapi.telegram.org.filters.User(user_id=...)— commands from other users are simply ignored. Do not use the login (@username) for verification: it can be changed, and user_id is permanent.asyncio.to_thread— port checks are blocking; without this, the bot will "freeze" during the check and will not respond.bot_datais stored in memory: after restarting, the bot will remember the state again and will not send false "recovery" alerts.- Set the list of commands for hints in Telegram from BotFather:
/setcommands→status - проверить серверы.
What a bot should not do#
- Execute arbitrary commands (
/run rm -rf ...). Only predefined safe actions, no parameters from the message or with strict whitelist parameter checking. - Restart services without confirmation or log. If such a command is needed — a separate handler, a separate allowed list, log entry: who, when, what.
- Send personal data and passwords to the general chat.
- Work under a domain administrator: bot accounting — with minimal permissions.
Example with aiogram for comparison#
If the team has already adopted aiogram, the logic is the same, the syntax changes:
import asyncio
import os
from aiogram import Bot, Dispatcher
from aiogram.filters import Command
from aiogram.types import Message
dp = Dispatcher()
@dp.message(Command("start"))
async def start(message: Message) -> None:
await message.answer(f"Ваш user_id: {message.from_user.id}")
async def main() -> None:
bot = Bot(os.environ["TG_BOT_TOKEN"])
await dp.start_polling(bot)
asyncio.run(main())
The final part is logging, testing, packaging, and launching the bot as a service: Python for automation, part 6: logging, testing, packaging, and secure launch as a service.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.