#!/bin/bash DEFAULT_TOKENFILE=${HOME}/.telegram/bottoken DEFAULT_CHATFILE=${HOME}/.telegram/chatid TOKENFILE=${DEFAULT_TOKENFILE} CHATFILE=${DEFAULT_CHATFILE} function die() { echo "FATAL: $*" >&2 exit 1 } function usage() { echo "usage: $0 [OPTIONS] \"text to send\"" echo echo "Instructs telegram bot to send the supplied message to a chat." echo echo "OPTIONS" echo " -b filename Override default bot token file (${DEFAULT_TOKENFILE})" echo " -c filename Override default chat id token file (${DEFAULT_CHATFILE})" echo echo "Needs these files to work:" echo " File with telegram bot token: ${DEFAULT_TOKENFILE}" echo " File with telegram chat id: ${DEFAULT_CHATFILE}" } ARGS="b:c:h" while getopts "$ARGS" i; do case "$i" in b) TOKENFILE=$OPTARG ;; c) CHATFILE=$OPTARG ;; h) usage; exit 1; ;; *) usage; exit 1; ;; esac done shift $((OPTIND - 1)) if [[ $# -ne 1 ]]; then usage exit 1 fi [[ ! -e ${TOKENFILE} ]] && die "bot token file '${TOKENFILE}' doesn't exist"; [[ ! -e ${CHATFILE} ]] && die "chat id file '${CHATFILE}' doesn't exist"; TOKEN=$(egrep -v '^#' "$TOKENFILE") CHAT=$(egrep -v '^#' "$CHATFILE") [[ -z ${TOKEN} ]] && die "bot token file '${TOKENFILE}' appears empty"; [[ -z ${CHAT} ]] && die "chat id file '${CHATFILE}' appears empty"; msg="$*" res=$(curl -s --data "text=$msg" --data "chat_id=$CHAT" 'https://api.telegram.org/bot'$TOKEN'/sendMessage' 2>&1) rv=$? [[ $rv -ne 0 ]] && fatal "curl failed" status=$(jq -r .ok <<<"${res}") [[ $status != "true" ]] && die "telegram API returned failure: ${res}" exit 0