Posting Minecraft login events to Telegram

Me and my friends wanted to be notified every time someone logins or logouts from the Minecraft server I host.

I studied lot of overly complicated solutions, until I thought of the easiest way to implement it: continuously read the log, search for the ‘logged in’ or ‘logged out’ keywords and make an API call when there’s a result.

Translated in simplified Unix commands:

tail -F logfile | grep ‘login’ | curl api.telegram.org

The API call is made to a Telegram bot that sends the message to a group chat.

I started working from the script from this blog post and edited it a bit:

#!/bin/bash

tail -n0 -F /home/dzamir/minecraft-docker/logs/latest.log | while read LINE; do
  (echo "$LINE" | grep -e "logged in" -e "left the game") && curl -X POST \
  https://api.telegram.org/bot<insert-your-bot-token>/sendMessage \
  -H 'Accept: */*' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Host: api.telegram.org' \
  -F chat_id=<insert-chat-id> \
  -F text="$LINE";
done

The script can be improved by filtering only the useful data from the log messages or posting to other platforms (eg Slack).