-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram_claude_gateway.sh
More file actions
executable file
·575 lines (488 loc) · 14 KB
/
telegram_claude_gateway.sh
File metadata and controls
executable file
·575 lines (488 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${ENV_FILE:-$ROOT_DIR/.env}"
if [[ -f "$ENV_FILE" ]]; then
# shellcheck disable=SC1090
source "$ENV_FILE"
fi
: "${TELEGRAM_BOT_TOKEN:?Missing TELEGRAM_BOT_TOKEN in .env}"
: "${TELEGRAM_CHAT_ID:?Missing TELEGRAM_CHAT_ID in .env}"
API_BASE="https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}"
RAW_OUTPUT="${RAW_OUTPUT:-0}"
CLAUDE_SETTINGS_PATH="${CLAUDE_SETTINGS_PATH:-$HOME/.claude/settings.json}"
TELEGRAM_MAX_MESSAGE_LENGTH="${TELEGRAM_MAX_MESSAGE_LENGTH:-3500}"
CLAUDE_PENDING_MESSAGE="${CLAUDE_PENDING_MESSAGE:-Processing your request...}"
HEARTBEAT_KEYWORD="${HEARTBEAT_KEYWORD:-ping}"
HEARTBEAT_RESPONSE="${HEARTBEAT_RESPONSE:-pong}"
usage() {
cat <<'EOF'
Usage:
./telegram_claude_gateway.sh send "hello"
./telegram_claude_gateway.sh claude-send "hello"
./telegram_claude_gateway.sh receive
./telegram_claude_gateway.sh watch
./telegram_claude_gateway.sh watch-new
./telegram_claude_gateway.sh watch-reply
./telegram_claude_gateway.sh watch-claude-reply
./telegram_claude_gateway.sh webhook-info
./telegram_claude_gateway.sh delete-webhook
Commands:
send Send a text message to TELEGRAM_CHAT_ID
claude-send Run Claude with the prompt and send the reply to TELEGRAM_CHAT_ID
receive Fetch pending updates once
watch Long-poll for new messages continuously
watch-new Skip existing pending updates, then watch only new messages
watch-reply Watch messages and auto-reply to text messages
watch-claude-reply
Skip existing pending updates, then use Claude to auto-reply to new text messages
webhook-info Show current webhook status
delete-webhook Remove webhook so getUpdates can work
Debug:
RAW_OUTPUT=1 Print raw JSON responses instead of formatted output
Environment:
ENV_FILE Path to the env file (default: ./\.env next to the script)
CLAUDE_SETTINGS_PATH Claude settings path (default: ~/.claude/settings.json)
TELEGRAM_MAX_MESSAGE_LENGTH
Max Telegram message length before truncation (default: 3500)
CLAUDE_PENDING_MESSAGE Placeholder reply before Claude finishes
(default: Processing your request...)
HEARTBEAT_KEYWORD Direct reply keyword that skips Claude (default: ping)
HEARTBEAT_RESPONSE Direct reply text for heartbeat keyword (default: pong)
EOF
}
require_arg() {
local value="${1:-}"
local name="$2"
if [[ -z "$value" ]]; then
printf 'Missing %s\n' "$name" >&2
exit 1
fi
}
api_post() {
local method="$1"
shift
curl --silent --show-error --fail \
-X POST \
"$API_BASE/$method" \
"$@"
}
has_jq() {
command -v jq >/dev/null 2>&1
}
has_claude() {
command -v claude >/dev/null 2>&1
}
has_python() {
command -v python >/dev/null 2>&1 || command -v python3 >/dev/null 2>&1
}
python_cmd() {
if command -v python >/dev/null 2>&1; then
printf '%s\n' "python"
return
fi
printf '%s\n' "python3"
}
limit_message_length() {
local text="$1"
local limit="${TELEGRAM_MAX_MESSAGE_LENGTH}"
local suffix="\n\n[truncated]"
if (( ${#text} <= limit )); then
printf '%s' "$text"
return
fi
if (( limit <= ${#suffix} )); then
printf '%s' "${text:0:limit}"
return
fi
printf '%s%s' "${text:0:limit-${#suffix}}" "$suffix"
}
preview_text() {
local text="$1"
local preview_limit="${2:-120}"
local normalized=""
normalized="$(printf '%s' "$text" | tr '\n' ' ' | tr '\r' ' ')"
if (( ${#normalized} <= preview_limit )); then
printf '%s' "$normalized"
return
fi
printf '%s...' "${normalized:0:preview_limit}"
}
log_sent_message() {
local chat_id="$1"
local sender="$2"
local kind="$3"
local text="$4"
local target="$chat_id"
if [[ "$RAW_OUTPUT" == "1" ]]; then
return
fi
if [[ -n "$sender" ]]; then
target="${sender} (${chat_id})"
fi
printf -- '-> %s [%s]: %s\n' \
"$target" \
"$kind" \
"$(preview_text "$(limit_message_length "$text")")"
}
extract_next_offset() {
local response="$1"
local lines=""
lines="$(printf '%s\n' "$response" | grep -o '"update_id":[0-9]\+' || true)"
if [[ -n "$lines" ]]; then
printf '%s\n' "$(
printf '%s\n' "$lines" \
| sed 's/.*://g' \
| sort -n \
| tail -n 1
)"
fi
}
print_updates() {
local response="$1"
if [[ "$RAW_OUTPUT" == "1" ]]; then
printf '%s\n' "$response"
return
fi
if has_python; then
printf '%s\n' "$response" | "$(python_cmd)" -c '
import json
import sys
from datetime import datetime, timezone, timedelta
response = json.load(sys.stdin)
for item in response.get("result", []):
message = item.get("message")
if not message:
continue
dt = datetime.fromtimestamp(message["date"], tz=timezone.utc) + timedelta(hours=8)
sender = (
message.get("from", {}).get("username")
or message.get("from", {}).get("first_name")
or "unknown"
)
text = message.get("text") or message.get("caption") or "<non-text message>"
text = text.replace("\n", "\\n")
print(f"{dt:%Y-%m-%d %H:%M:%S} {sender}: {text}")
'
return
fi
if ! has_jq; then
printf '%s\n' "$response"
return
fi
printf '%s\n' "$response" | jq -r '
if (.result | length) == 0 then
empty
else
.result[]
| select(.message != null)
| ((.message.date + 28800) | strftime("%Y-%m-%d %H:%M:%S")) + " "
+ (.message.from.username // .message.from.first_name // "unknown")
+ ": "
+ ((.message.text // .message.caption // "<non-text message>") | gsub("\n"; "\\n"))
end
'
}
print_send_response() {
local response="$1"
if [[ "$RAW_OUTPUT" == "1" ]] || ! has_jq; then
printf '%s\n' "$response"
return
fi
printf '%s\n' "$response" | jq -r '
if .ok then
[
"sent",
"message_id=" + (.result.message_id | tostring),
"chat_id=" + (.result.chat.id | tostring),
"text=" + ((.result.text // "") | gsub("\n"; "\\n"))
] | join(" ")
else
.
end
'
}
print_webhook_info() {
local response="$1"
if [[ "$RAW_OUTPUT" == "1" ]] || ! has_jq; then
printf '%s\n' "$response"
return
fi
printf '%s\n' "$response" | jq -r '
if .ok then
[
"url=" + (.result.url // ""),
"pending_update_count=" + (.result.pending_update_count | tostring),
"has_custom_certificate=" + (.result.has_custom_certificate | tostring)
] | join(" ")
else
.
end
'
}
delete_webhook() {
api_post "deleteWebhook" \
--data-urlencode "drop_pending_updates=false"
}
get_webhook_info() {
api_post "getWebhookInfo"
}
send_message() {
local text="${1:-}"
local limited_text=""
local response=""
require_arg "$text" "message text"
limited_text="$(limit_message_length "$text")"
# Read message text from stdin so curl preserves UTF-8 on Windows/Git Bash.
response="$(printf '%s' "$limited_text" | api_post "sendMessage" \
--data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode text@-)"
print_send_response "$response"
}
send_message_to_chat() {
local chat_id="$1"
local text="$2"
local limited_text=""
limited_text="$(limit_message_length "$text")"
printf '%s' "$limited_text" | api_post "sendMessage" \
--data-urlencode "chat_id=${chat_id}" \
--data-urlencode text@- >/dev/null
}
run_claude_prompt() {
local prompt="$1"
local output=""
local status=0
require_arg "$prompt" "prompt"
if ! has_claude; then
printf 'Claude CLI not found in PATH'
return 0
fi
if [[ ! -f "$CLAUDE_SETTINGS_PATH" ]]; then
printf 'Claude settings file not found: %s' "$CLAUDE_SETTINGS_PATH"
return 0
fi
set +e
output="$(claude -p "$prompt" \
--settings "$CLAUDE_SETTINGS_PATH" \
--permission-mode bypassPermissions \
--dangerously-skip-permissions \
--add-dir "$ROOT_DIR" \
--no-session-persistence 2>&1)"
status=$?
set -e
output="$(printf '%s' "$output" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
if [[ $status -ne 0 ]]; then
if [[ -n "$output" ]]; then
printf 'Claude command failed (%s): %s' "$status" "$output"
else
printf 'Claude command failed with exit code %s' "$status"
fi
return 0
fi
if [[ -z "$output" ]]; then
printf 'Claude returned no output'
return 0
fi
printf '%s' "$output"
}
receive_once() {
local response=""
delete_webhook >/dev/null
response="$(api_post "getUpdates" \
--data-urlencode "allowed_updates=[\"message\"]" \
--data-urlencode "timeout=10")"
print_updates "$response"
}
watch_messages() {
local offset="${1:-}"
local auto_reply="${2:-0}"
local response=""
local next_offset=""
delete_webhook >/dev/null
while true; do
if [[ -n "$offset" ]]; then
response="$(api_post "getUpdates" \
--data-urlencode "allowed_updates=[\"message\"]" \
--data-urlencode "timeout=30" \
--data-urlencode "offset=${offset}")"
else
response="$(api_post "getUpdates" \
--data-urlencode "allowed_updates=[\"message\"]" \
--data-urlencode "timeout=30")"
fi
print_updates "$response"
if [[ "$auto_reply" == "1" ]]; then
auto_reply_to_updates "$response"
fi
next_offset="$(extract_next_offset "$response" || true)"
if [[ -n "$next_offset" ]]; then
offset=$((next_offset + 1))
fi
done
}
get_next_offset() {
local response=""
local offset=""
delete_webhook >/dev/null
response="$(api_post "getUpdates" \
--data-urlencode "allowed_updates=[\"message\"]" \
--data-urlencode "timeout=1")"
offset="$(extract_next_offset "$response" || true)"
if [[ -n "$offset" ]]; then
printf '%s\n' $((offset + 1))
fi
}
watch_new_messages() {
local next_offset=""
next_offset="$(get_next_offset || true)"
watch_messages "$next_offset" "${1:-0}"
}
auto_reply_to_updates() {
local response="$1"
local line=""
local chat_id=""
local sender=""
local text=""
local reply_text=""
if ! has_jq; then
printf 'jq is required for auto-reply commands\n' >&2
exit 1
fi
while IFS= read -r line; do
chat_id="$(printf '%s\n' "$line" | jq -r '.chat_id')"
sender="$(printf '%s\n' "$line" | jq -r '.sender')"
text="$(printf '%s\n' "$line" | jq -r '.text')"
if [[ -z "$chat_id" || -z "$text" ]]; then
continue
fi
reply_text="Rcvd msg from ${sender}"
send_message_to_chat "$chat_id" "$reply_text"
done < <(
printf '%s\n' "$response" | jq -c '
.result[]
| select(.message != null)
| select(.message.from.is_bot != true)
| select((.message.text // "") != "")
| {
chat_id: (.message.chat.id | tostring),
sender: (.message.from.username // .message.from.first_name // "unknown"),
text: .message.text
}
'
)
}
auto_claude_reply_to_updates() {
local response="$1"
local line=""
local chat_id=""
local sender=""
local text=""
local normalized_text=""
local normalized_heartbeat_keyword=""
local reply_text=""
if ! has_jq; then
printf 'jq is required for Claude auto-reply commands\n' >&2
exit 1
fi
while IFS= read -r line; do
chat_id="$(printf '%s\n' "$line" | jq -r '.chat_id')"
sender="$(printf '%s\n' "$line" | jq -r '.sender')"
text="$(printf '%s\n' "$line" | jq -r '.text')"
if [[ -z "$chat_id" || -z "$text" ]]; then
continue
fi
normalized_text="$(printf '%s' "$text" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')"
normalized_heartbeat_keyword="$(printf '%s' "$HEARTBEAT_KEYWORD" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')"
if [[ "$normalized_text" == "$normalized_heartbeat_keyword" ]]; then
send_message_to_chat "$chat_id" "$HEARTBEAT_RESPONSE"
log_sent_message "$chat_id" "$sender" "heartbeat" "$HEARTBEAT_RESPONSE"
continue
fi
send_message_to_chat "$chat_id" "$CLAUDE_PENDING_MESSAGE"
log_sent_message "$chat_id" "$sender" "placeholder" "$CLAUDE_PENDING_MESSAGE"
reply_text="$(run_claude_prompt "$text")"
send_message_to_chat "$chat_id" "$reply_text"
log_sent_message "$chat_id" "$sender" "claude" "$reply_text"
done < <(
printf '%s\n' "$response" | jq -c '
.result[]
| select(.message != null)
| select(.message.from.is_bot != true)
| select((.message.text // "") != "")
| {
chat_id: (.message.chat.id | tostring),
sender: (.message.from.username // .message.from.first_name // "unknown"),
text: .message.text
}
'
)
}
watch_claude_replies() {
local offset=""
local response=""
local next_offset=""
offset="$(get_next_offset || true)"
delete_webhook >/dev/null
while true; do
if [[ -n "$offset" ]]; then
response="$(api_post "getUpdates" \
--data-urlencode "allowed_updates=[\"message\"]" \
--data-urlencode "timeout=30" \
--data-urlencode "offset=${offset}")"
else
response="$(api_post "getUpdates" \
--data-urlencode "allowed_updates=[\"message\"]" \
--data-urlencode "timeout=30")"
fi
print_updates "$response"
auto_claude_reply_to_updates "$response"
next_offset="$(extract_next_offset "$response" || true)"
if [[ -n "$next_offset" ]]; then
offset=$((next_offset + 1))
fi
done
}
main() {
local command="${1:-}"
case "$command" in
send)
shift
send_message "${1:-}"
;;
claude-send)
shift
send_message "$(run_claude_prompt "${1:-}")"
;;
receive)
receive_once
;;
watch)
watch_messages
;;
watch-new)
watch_new_messages
;;
watch-reply)
watch_messages "" "1"
;;
watch-claude-reply)
watch_claude_replies
;;
webhook-info)
print_webhook_info "$(get_webhook_info)"
;;
delete-webhook)
delete_webhook
printf '\n'
;;
""|-h|--help|help)
usage
;;
*)
printf 'Unknown command: %s\n\n' "$command" >&2
usage
exit 1
;;
esac
}
main "$@"