Monitoring a Server with the Telegram API
Some servers behind Podrover are just workers and do not run a web application, so I can’t use Pingdom and the like to monitor them.
I could use some library like Monit but honestly I didn’t want to install one more thing on the server and I like to exploit push notifications when possible.
I am already monitoring some behavior of my DB servers via Slack. When some key activity is performed a message is sent to a private Slack group, and I get a notification on my iPhone. I didn’t want to clutter that monitoring channel with more notifications about workers, plus I wanted to learn something new so I gave Telegram a shot. It turned out to be pretty easy.
I created a bot, then I created a new group (conversation) to which I added the bot and myself. A script on my servers tells the bot to post a message in that group. That’s it. To post to a group you need its id, which is a little tricky to find it. You need to fetch updates via the getUpdates
API, like this.
curl -s \
-X POST \
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
This returns something like
{
"result": [
{
...
"chat": {
"username": "funkyboy",
"first_name": "Cesare",
"id": 123 // <- this ID
},
...
]
}
That id
field within the chat
object is the one you need. Now you can post messages to that specific group:
curl -s \
-X POST \
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage \
-d text="This is a message from the bot" \
-d chat_id=123
You can schedule such a script on the server via Cron. On my servers I use a Rake task like this
task :dude_i_am_still_alive do
require 'socket'
require 'httparty'
host = Socket.gethostname
body = {:text => "#{host} is alive", :chat_id => 123}
response = HTTParty.post('https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage', :body => body)
end
scheduled via whenever.
It’s still not ideal to me, because essentially I should worry when I am NOT getting a notification but for now it will do. After all a dead machine can not tell you that it’s dead :)
If you are using a different tool to solve this problem, let me know on Twitter.