Your bot runs 24/5 on a VPS, but you don't stare at the screen all day. How to know it executed an order, hit the target, or — importantly — crashed with an error? The elegant answer: a Telegram bot that alerts you on your phone for each event. Simple to build, free, and transforms Telegram into a real tool (very different from signal groups). Let's get to the code.
Why this is the "good Telegram": unlike signal groups (where you depend on third parties), here Telegram is just a notification channel for your bot, with your rules. Transparent, under your control, nobody earning commissions. Pure technical use.
01Criar o bot no BotFather
Telegram has an official bot to create bots — BotFather. The process takes 1 minute:
On Telegram, search for @BotFather (the official one, with badge). Start the conversation.
Send /newbot, choose a name and username (must end in "bot"). BotFather returns a token — something like 123456:ABC-DEF....
This token gives full control of the bot. Treat it like a password — put it in a .env, never in versioned code.
Segurança do token: quem tem o token controla o bot. Never cole em código público, GitHub, ou compartilhe. Use variável de ambiente. Se vazar, revogue no BotFather (/revoke) e gere outro.
02Pegar o seu chat ID
The bot needs to know where to send. You need your chat ID. The simple way: send any message to your bot, then query:
# pegar_chat_id.py — rode uma vez import requests, os TOKEN = os.getenv("TELEGRAM_TOKEN") url = f"https://api.telegram.org/bot{TOKEN}/getUpdates" resp = requests.get(url).json() # envie uma msg for the bot ANTES de rodar isto for r in resp.get("result", []): chat = r["message"]["chat"] print(f"Chat ID: {chat['id']} ({chat.get('first_name')})")
Note the number that appears — that's your chat ID, which also goes in the .env.
03Enviar mensagem (a função-base)
The heart of everything — a function that sends a message. Two ways: with requests (simpler, no dependency) or with the python-telegram-bot library (more complete). For alerts, requests is enough:
# telegram_alerta.py import requests, os TOKEN = os.getenv("TELEGRAM_TOKEN") CHAT_ID = os.getenv("TELEGRAM_CHAT_ID") def enviar_alerta(mensagem: str): url = f"https://api.telegram.org/bot{TOKEN}/sendMessage" dados = { "chat_id": CHAT_ID, "text": mensagem, "parse_mode": "HTML", # permite negrito etc. } try: requests.post(url, data=dados, timeout=10) except Exception as e: print(f"Falha ao enviar Telegram: {e}") # teste enviar_alerta("✅ Bot de alerta conectado!")
Ready to use: with this function, sending an alert becomes one line. Note the try/except — you never want a Telegram send failure to crash your bot. The alert is secondary; the trade is primary.
04Integrar ao seu bot
Now the good part: calling send_alert() on your bot's important events. Taking the loop from our bot MT5 ou Binance:
from telegram_alerta import enviar_alerta while True: try: df = puxar_candles(...) sinal = calcular_sinal(df) if sinal == "COMPRA" and not tem_posicao(): resultado = comprar(...) enviar_alerta(f"🟢 COMPRA executada\n" f"Ativo: WIN | Preço: {resultado.price}\n" f"Stop: {stop} | Alvo: {alvo}") time.sleep(60) except Exception as e: # alerta de ERRO — o mais importante de todos enviar_alerta(f"🔴 ERRO no bot!\n{str(e)}") time.sleep(30)
The most important events to alert: (1) error/crash — the most critical, you need to know immediately; (2) order executed (entry and exit); (3) target or stop hit; (4) daily summary (how many trades, result). The error alert alone justifies building this — knowing your bot crashed at 3am prevents losses.
Ainda doesn't have o bot for alertar?
Start with the Binance bot or MT5-Python API tutorials, then plug in Telegram.
05Indo além: comandos (com cuidado)
The bot can go beyond just alerting — it can receive commands from you (e.g., /status to check positions, /stop to shut down the bot). This uses the python-telegram-bot library and update reading logic. But here comes a serious caution:
If the bot controls the bot, protect it: a bot that only sends alerts is read-only — safe. But if you give it power to send commands to the bot (stop, change parameter), you need authentication: validate that the chat ID is yours and nobody else's. An exposed control bot is a door for someone to mess with your bot. For alerts, stay read-only; for control, lock down rigorously.
06Preguntas frecuentes
Como criar um bot no Telegram?
Conversando com o @BotFather (bot oficial). Envie /newbot, escolha nome e username terminado em "bot", e ele gera um token de API that you usa no código. Leva cerca de 1 minuto.
Pra que serve um bot de alerta no trading?
Receber notificações em tempo real do seu bot: ordem executada, preço atingindo nível, erro, bot parado. Permite monitorar a operação by the celular without ficar na tela. O alerta de erro é o mais valioso.
Is it safe usar bot do Telegram no bot?
Pra enviar alertas (leitura), é seguro e útil. Cuidados: never expor o token publicamente; e se o bot enviar comandos ao bot, proteger com autenticação for que só você possa controlá-lo.
Preciso de servidor for rodar o bot de alerta?
O envio de alerta roda inside do seu próprio bot — where ele estiver (VPS, PC). Não precisa de servidor separado for só enviar. Se quiser que o bot receba comandos continuamente, there precisa de algo always rodando (a mesma VPS do bot serve).
requests ou python-telegram-bot?
Pra só enviar alertas, requests basta (simples, without dependência extra). Pra receber comandos e interações mais ricas, a biblioteca python-telegram-bot é mais completa. Comece com requests pros alertas.