Skip to content

Instantly share code, notes, and snippets.

@gourytch
Created July 6, 2015 20:13
Show Gist options
  • Select an option

  • Save gourytch/a5fb9c2fe7b0b4331f63 to your computer and use it in GitHub Desktop.

Select an option

Save gourytch/a5fb9c2fe7b0b4331f63 to your computer and use it in GitHub Desktop.
#! /bin/bash
die() {
echo "EDIT YOUR ~/telegram_bot.rc AND RE-RUN!" 1>&2
exit 1
}
if [ ! -f $HOME/telegram_bot.rc ]; then
cat >$HOME/telegram_bot.rc <<_EOF_
#
# BOT_KEY='123456:enterYourTelegramBotAPIKeyHere'
#
BOT_KEY=''
#
# BOT_MASTER=your telegram id (ID! not your telephone!)
#
BOT_MASTER=
# REMOVE THIS LINE AND BELOW AFTER EDITING AND CHECKING
echo "YOU ARE LAZY! CHECK YOUR CONFIG!"
exit 1
_EOF_
die
fi
source $HOME/telegram_bot.rc
[ "x$BOT_KEY" = "x" -o "x$BOT_MASTER" = "x" ] && die
rawurlencode() {
# see
# http://stackoverflow.com/questions/296536/how-to-urlencode-data-for-curl-command
#
local string="${*}"
local strlen=${#string}
local encoded=""
for (( pos=0 ; pos<strlen ; pos++ )); do
c=${string:$pos:1}
case "$c" in
[-_.~a-zA-Z0-9] ) o="${c}" ;;
* ) printf -v o '%%%02x' "'$c"
esac
encoded+="${o}"
done
REPLY="${encoded}" #+or echo the result (EASIER)... or both... :p
}
message_wget() {
rawurlencode "$*"
wget "https://api.telegram.org/bot${BOT_KEY}/sendMessage?chat_id=${BOT_MASTER}&text=${REPLY}" -O /dev/null &>/dev/null
}
message_curl() {
curl -X POST \
--data-urlencode "chat_id=${BOT_MASTER}" \
--data-urlencode "text=${*}" \
"https://api.telegram.org/bot${BOT_KEY}/sendMessage" &>/dev/null
}
message_null() {
echo "<<<MESSAGE>>>
$*
--- --- ---
"
}
if [ "x$*" = "x" ]; then
message "hello from $(hostname)"
else
hdr="$(date +'%Y/%m/%d_%H:%M:%S') @ #$(hostname)"
case "$1" in
"error"|"ERROR")
shift
hdr="$hdr #error"
;;
"warn"|"WARN"|"warning"|"WARNING")
shift
hdr="$hdr #warning"
;;
"info"|"INFO")
shift
hdr="$hdr #info"
;;
*)
;;
esac
if [ "x$*" = "x-" ]; then
IFS="2p3o48u y2;lhqwe rfo8q23y@$#$Q#@%$25"
body=''
while read -s L
do
body="$body
$L"
done
else
body="$*"
fi
msg="::: $hdr :::
$body
"
if which curl >/dev/null
then
message_curl "$msg"
elif which wget >/dev/null
then
message_wget "$msg"
else
message_null "$msg"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment