gpt2tg/telegram_sender.sh

42 lines
1.3 KiB
Bash

#!/usr/bin/env bash
# This script sends a message to Telegram.
# Every single line will be interpreted as a message update thus the message will be edited with the new content.
# exit if any command fails
usage() {
echo "Usage: $(basename $0) <chat_id>"
}
if [ ! $# -eq 1 ]; then
usage
exit 1
fi
if [ -z $TELEGRAM_BOT_TOKEN ]; then
echo "TELEGRAM_BOT_TOKEN must be set"
exit 1
fi
TELEGRAM_CHAT_ID="$1"
mid=
retry_after=
while read -r line
do
if [ -z $mid ]; then
R=$(curl --silent "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage?disable_web_page_preview=true&chat_id=$TELEGRAM_CHAT_ID" --data-urlencode "text=$line")
mid=$(echo "$R" | jq -e '.result.message_id')
else
R=$(curl --silent "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/editMessageText?disable_web_page_preview=true&chat_id=$TELEGRAM_CHAT_ID&message_id=$mid" --data-urlencode "text=$line")
# check for 429 Too Many Requests
retry_after=$(echo "$R" | jq -e '.parameters.retry_after')
if [ $? -eq 0 ]; then
echo "Received 429 Too Many Requests. Waiting for $retry_after seconds ..."
sleep $retry_after
fi
fi
# https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
sleep 1
done < "${2:-/dev/stdin}"