How to Build a Bot That Sends You Alerts (Telegram or Discord)
You have a thing you keep checking by hand: a service that sometimes goes down, a job that sometimes fails quietly, a page that changes now and then. Every manual check is a small interruption, and the one time you skip it is the time it mattered.
The fix is a small bot that does the checking and messages you only when something changes. It is a short script, not a platform. Here is how to set one up, how to keep its token safe, and how to confirm it actually works.
The short answer
Create a bot through Telegram’s bot-creation chat to get a token, send your bot a message, and read your chat ID from the bot API. Store the token and chat ID in environment variables, not in the code. Then write a loop that checks your condition, compares the result to the last result, and posts a message to the API only when the state changes. Discord works the same way with a channel webhook URL instead of a token and chat ID.
Step 1: Create the bot and protect the token
In Telegram, open a chat with the account called BotFather and send /newbot. It asks for a display name and a username, then replies with a token. The token is the bot’s password. Anyone who has it can send messages as your bot.
Put it in an environment variable straight away, before it ends up in a file you might share:
export TELEGRAM_BOT_TOKEN="paste-your-token-here"
export TELEGRAM_CHAT_ID="paste-your-chat-id-here"
Your script reads it with os.environ["TELEGRAM_BOT_TOKEN"]. The code never contains the secret, so you can paste the code into a ticket or a repository without leaking anything.
For a script that runs unattended, the variables need to exist in that environment too. Two common ways are an environment file that your process manager loads, or a .env file kept out of version control with its permissions limited to your user. If the token ever leaks, ask BotFather to revoke it and issue a new one. The old one stops working at once.
Step 2: Find your chat ID
A bot cannot message you first. Open your new bot in Telegram, press Start, and send it any text. Then ask the API what it received:
curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates"
In the JSON that comes back, look for "chat":{"id":...}. That number is your chat ID. If you want alerts in a group instead, add the bot to the group, post a message there, and run the same command. Group IDs are usually negative numbers, which is normal.
If getUpdates returns an empty list, you have not messaged the bot yet, or the message is old. Send a new one and run it again.
Step 3: Write the check-then-notify loop
The pattern has four parts: check, compare, notify, wait. The comparison is the part people skip, and skipping it is how you end up with a bot that sends a message every minute until you mute it.
Here is a small version that watches a URL you own and tells you when it stops responding and when it recovers:
import os
import time
import requests
TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
URL = "https://example.com/health"
def notify(text):
api = f"https://api.telegram.org/bot{TOKEN}/sendMessage"
requests.post(api, data={"chat_id": CHAT_ID, "text": text}, timeout=10)
def is_down():
try:
return requests.get(URL, timeout=10).status_code != 200
except requests.RequestException:
return True
was_down = False
while True:
down = is_down()
if down and not was_down:
notify("ALERT: " + URL + " is not responding")
elif was_down and not down:
notify("OK: " + URL + " is back")
was_down = down
time.sleep(60)
The was_down variable is the memory. The bot speaks only when the state flips, so one outage produces one alert and one recovery message. The sleep of an illustrative 60 seconds sets how quickly you hear about a change.
Swap is_down() for any check you can express as true or false: a file that has not been updated recently, a log line that appeared, a number that crossed a threshold you chose. The loop around it stays the same.
If you check someone else’s site rather than your own, follow that site’s terms and the law, and keep the interval gentle.
The Discord version
Discord is simpler because there is no bot account to create. In the channel settings, add a webhook under the integrations section and copy its URL. Treat that URL like a token, because anyone with it can post to your channel. Store it in an environment variable such as DISCORD_WEBHOOK_URL.
Then replace the notify function:
def notify(text):
requests.post(os.environ["DISCORD_WEBHOOK_URL"],
json={"content": text}, timeout=10)
The rest of the loop is unchanged. The tradeoff is that a webhook only sends. If you want the bot to read commands, such as replying to a message with a status report, you need a full bot account on either platform, and the script gets longer.
How to check that it works
Test the alert path and the check path separately.
- Run
notify("test")on its own. If the message does not arrive, the problem is the token, the chat ID or the network, not your logic. - Point the check at something you can break on purpose, such as a local test server you can stop. Confirm you get exactly one alert when it goes down and one when it comes back.
- Unplug the network or block the Telegram API for a minute. A failed send should not crash the loop. Wrap
notifyin atryblock and log the error, or the bot will die silently, which is the worst failure for an alert tool. - Restart the machine. If the bot does not come back by itself, run it under a process manager or a scheduled task so it starts at boot.
A bot that has never been seen to fail is a bot you have not tested. Do step 2 at least once.
When to do it yourself and when to hand it off
Do it yourself if you have one check, one destination, and you are comfortable reading a short Python script. The code above is most of the job. An afternoon of setup and testing is a fair price for something you will understand completely and can change whenever you like.
Handing it off makes more sense when the work around the loop grows. Examples are several checks with different rules, parsing messy pages or APIs, storing state between restarts, rate limits, formatted messages, or a setup that has to run cleanly on a server you do not want to babysit. It also makes sense when you simply do not have the time, or Python is not your language.
AutomateHive Custom Builds builds bots, scanners, alert systems, scripts and data pipelines to your spec. The price is fixed and agreed in writing before any work starts, from $300 per project. Payment is 50% to start and 50% before delivery, through Stripe, and qualifying projects are delivered in under 7 days.
You get one zip file with the source code, a README, an install guide for your operating system, a usage guide with troubleshooting, a one-command setup script and a sample config. It runs on your own computer or server. You own the setup and the API keys, and AutomateHive does not host or manage anything.
Everything is handled by email, with no calls or meetings. A request gets a fixed quote with a delivery date, or a clear “not a fit”, within 24 hours. You get 14 days of defect fixes against the agreed spec. New features or changed requirements are quoted as a new project. Once you have paid in full, you hold a perpetual license to use and modify the delivered code.
Custom Builds does not take on projects that need calls, that break a platform’s terms or the law, or that need ongoing hosting or management. Be clear about that in your request and you will save a round of email.
The takeaway
A useful alert bot is a token in an environment variable, a chat ID, and a loop that messages you only when the state changes. Build the smallest version, break it on purpose to prove it speaks up, and make sure it restarts on its own. Add complexity only when a real need shows up.
If you would rather have this built for you: Custom Builds delivers bots, scanners, alert systems and scripts to your spec, at a fixed price from $300, as one zip with source code, docs and a one-command setup script that runs on your own computer or server. Request a build at automatehive.net/custombuilds.
Custom Builds delivers software only. Nothing on this page is financial, investment or betting advice.
