From 4ae7e2651070305c8272b127fcfc967193ef52cd Mon Sep 17 00:00:00 2001 From: ekzyis Date: Sat, 9 Sep 2023 16:49:22 +0200 Subject: [PATCH] Add script for Telegram updates long polling --- telegram_poll.sh | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 telegram_poll.sh diff --git a/telegram_poll.sh b/telegram_poll.sh new file mode 100644 index 0000000..5f117ba --- /dev/null +++ b/telegram_poll.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash + +usage() { + echo "Usage: $(basename $0) offset" +} + +if [ ! $# -eq 1 ]; then + usage + exit 1 +fi + +OFFSET=$1 + +if [ -z $TELEGRAM_BOT_TOKEN ]; then + echo "TELEGRAM_BOT_TOKEN must be set with OpenAI authorization bearer token (without Bearer prefix)" + exit 1 +fi + +TIMEOUT=5 + +while true +do + echo "Long polling for telegram updates with offset $OFFSET ..." + R=$(curl --silent "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates?timeout=$TIMEOUT&offset=$OFFSET") + echo "$R" | jq + update_id="$(echo "$R" | jq -e '.result[0].update_id')" + if [ ! $? -eq 0 ]; then + echo "Timeout" + continue + fi + text=$(echo "$R" | jq -e '.result[0].message.text') + if [ $? -eq 0 ]; then + text=$(echo "$text" | sed -e 's/^"//' -e 's/"$//') + if [[ $text = /prompt* ]]; then + prompt="${text:8}" + chat_id="$(echo "$R" | jq -e '.result[0].message.chat.id')" + echo "Received prompt "$prompt" in chat $chat_id" + # TODO: send prompt to OpenAI and stream response back to chat + fi + fi + OFFSET=$(( update_id + 1)) +done