Skip to content

Instantly share code, notes, and snippets.

@josegomezr
Last active March 20, 2019 17:13
Show Gist options
  • Save josegomezr/d1f7ad5d19c56e7fcded21c249e3d45f to your computer and use it in GitHub Desktop.
Save josegomezr/d1f7ad5d19c56e7fcded21c249e3d45f to your computer and use it in GitHub Desktop.
tg_send

tg_send

Send telegram messages from your shell.

Install

Add the content of tg_send.sh to your .bashrc/profile/bash_alias (the one you like the most).

# to send a message use
tg_send_msg $TG_USER_ID $MESSAGE
# to send a file use
tg_send_file $TG_USER_ID $FILE_LOCATION $OPTIONAL_CAPTION
# you can get your user id from @userinfobot

# you can use pipes
echo "lololol" | tg_send_msg $TG_USER_ID
# with files too
echo "my contents!" | tg_send_file $TG_USER_ID $FILE_NAME $OPTIONAL_CAPTION

Limitations

  1. Messages: Telegram has a fixed message width limit of 4096 UTF-8 characters, and you can clearly see that there is no segmentation if message is too long. So beware.
  2. Files: Telegram has a limit for photo size of 10MB, and 50MB of other types. Keep it in mind when using this script.
export TG_BOT_TOKEN='' # get your token with @botfather
function tg_send_msg {
TARGET=$1
if test -t 0; then
MSG=$2
else
MSG="$(cat -)"
fi
TG_BOT_URL="https://api.telegram.org/bot$TG_BOT_TOKEN"
curl "$TG_BOT_URL/sendMessage" \
--form-string "chat_id=$TARGET" \
-F "text=$MSG" \
-F parse_mode=markdown \
-F disable_web_page_preview=1 \
-s -o /dev/null
if [[ $? -ne 0 ]]; then
echo "Couldn't send your message";
fi
}
function tg_send_file {
TARGET="$1"
FILE="$2"
CAPTION="${3:-sent from server}"
if test -t 0; then
FILENAME="$(basename $FILE)"
else
FILE="-"
FILENAME="${2:-unamed_file}"
fi
TG_BOT_URL="https://api.telegram.org/bot$TG_BOT_TOKEN"
curl "$TG_BOT_URL/sendDocument" \
--form-string "chat_id=$TARGET" \
-F "document=@$FILE;filename=$FILENAME" \
-F "caption=$CAPTION" \
-F parse_mode=markdown \
-s -o /dev/null
if [[ $? -ne 0 ]]; then
echo "Couldn't send your message";
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment