I needed a way to keep myself updated with what happens on the server (new user signup, daily stats with visitors, new user send a message to me thru contact form etc.).
You can do that with just email, but you can also do it with the help of Telegram Bot API.
Install telegram on your phone. Once installed, search for BotFather
- click start and then type /newbot
(follow the steps there, save safely the private bot token for the api). After the new bot is created search it and start a conversation with it (this will help you get chat_id which we will need later).
After your first conversation with the bot get the chat_id
:
curl -X GET 'https://api.telegram.org/botTOKEN:FROM-BOTFATHER/getUpdates'
The response will look similar to this:
{
"ok": true,
"result": [
{
"update_id": 123123123123,
"message": {
"message_id": 124,
"from": {
"id": CHAT_ID,
"is_bot": false,
"first_name": "NAME",
"last_name": "NAME",
"language_code": "en"
},
"chat": {
"id": "HERE-IS-CHAT_ID-YOU-NEED",
"first_name": "NAME",
"last_name": "NAME",
"type": "private"
},
"date": 1718539209,
"text": "/start",
"entities": [
{
"offset": 0,
"length": 6,
"type": "bot_command"
}
]
}
}
]
}
Take chat_id value from: HERE-IS-CHAT_ID-YOU-NEED
(see up).
Nice, now save CHAT_ID and TELEGRAM_API_TOKEN in .env
file (or somewhere else just don't push it to a public repo).
Here is the code to send push notifications (messages from the server to your phone) at each 10 seconds.
import time
import requests
from config import cfg
def server_push_notifications():
try:
while True:
url = f"https://api.telegram.org/bot{cfg.TELEGRAM_API_TOKEN}/sendMessage"
response = requests.post(
url=url,
params={'chat_id': cfg.CHAT_ID, 'text': 'All system are ok.', 'parse_mode': 'Markdown'}
)
print(url, response.json())
time.sleep(10)
except KeyboardInterrupt:
return
if __name__ == "__main__":
server_push_notifications()
As you can see the base is just a POST request to telegram api with chat_id and text as body. What you send as a message is up to you.
For something more serious I would recommend using scheduler, but I don't see why a barebones while loop with a time.sleep won't do the same thing.
Top comments (4)
Interesting… A couple of questions (if you will of course — sorry in advance if that’s inappropriate):
No worries.
Checkout this project: ntfy.sh/ (can do the same thing better and easier - I have not played with it yet.)
Good luck!
I had a similar script running and since last week isn't working.. getting a connection error coming from the request module.. my guess is something changed on Telegram side (URL maybe..), by any chance are you having the same issue and/or do you know what changed?
My script has now about 2 months since is running, no issues yet. I don't think something changed. Maybe your script was more complex than mine. Feel free to use it if it fits your needs: github.com/ClimenteA/telegram-push...