Добавить bash/bash-tg-bot.sh
This commit is contained in:
@@ -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 <telegram_token> <user_id>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
main_loop
|
||||
Reference in New Issue
Block a user