From ada78112f633fe66839eaf3c9129821da383fd13 Mon Sep 17 00:00:00 2001 From: CREATIVE_tg1 Date: Wed, 22 Apr 2026 10:49:34 +0000 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20bash/bash-tg-bot.sh?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bash/bash-tg-bot.sh | 90 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 bash/bash-tg-bot.sh diff --git a/bash/bash-tg-bot.sh b/bash/bash-tg-bot.sh new file mode 100644 index 0000000..f9adee0 --- /dev/null +++ b/bash/bash-tg-bot.sh @@ -0,0 +1,90 @@ +#!/bin/bash + +TG_TOKEN="$1" +USER_ID="$2" +API_URL="https://api.telegram.org/bot$TG_TOKEN" + +OFFSET_FILE="tg_bot_offset.dat" + +send_message() { + local chat_id="$1" + local text="$2" + curl -s -X POST "$API_URL/sendMessage" -d chat_id="$chat_id" -d text="$text" --max-time 10 > /dev/null +} + +get_system_status() { + { + echo "Hostname: $(hostname)" + echo "Uptime: $(uptime -p)" + echo "Memory:" + free -h + echo + echo "Disk:" + df -h / + echo + echo "Load average:" + cat /proc/loadavg + } | sed 's/\\n/\n/g' +} + +run_command() { + local cmd="$1" + output="$(bash -c "$cmd" 2>&1)" + echo "\$ $cmd" + echo "$output" +} + +get_updates() { + local offset="$1" + curl -s "$API_URL/getUpdates?timeout=30&offset=$offset" --max-time 35 +} + +main_loop() { + local offset=0 + if [ -f "$OFFSET_FILE" ]; then + offset=$(cat "$OFFSET_FILE") + fi + + while true; do + updates=$(get_updates "$offset") + [ -z "$updates" ] && sleep 2 && continue + + new_offset="$offset" + + echo "$updates" | jq -c '.result[]' | while read -r update; do + update_id=$(echo "$update" | jq '.update_id') + [ "$update_id" -ge "$new_offset" ] && new_offset=$((update_id + 1)) + + chat_id=$(echo "$update" | jq '.message.chat.id') + from_id=$(echo "$update" | jq '.message.from.id') + text=$(echo "$update" | jq -r '.message.text // empty') + + [ "$from_id" != "$USER_ID" ] && continue + + if [[ "$text" =~ ^/status ]]; then + status="$(get_system_status)" + send_message "$chat_id" "$status" + elif [[ "$text" =~ ^/c[[:space:]]+(.+) ]]; then + cmd="${text:3}" + result="$(run_command "$cmd")" + [ -z "$result" ] && result="(no output)" + # Truncate if message is too long for Telegram + result=$(echo "$result" | head -c 4000) + send_message "$chat_id" "\`\`\` +$result +\`\`\`" + fi + done + + echo "$new_offset" > "$OFFSET_FILE" + offset="$new_offset" + done +} + +# Entrypoint +if [[ -z "$TG_TOKEN" || -z "$USER_ID" ]]; then + echo "Usage: $0 " + exit 1 +fi + +main_loop \ No newline at end of file