aboutsummaryrefslogtreecommitdiff
path: root/bot.zsh
blob: 66a85cd3bd4b59029be81b293c835632c9f02f13 (plain)
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
#!/usr/bin/env zsh
#
# Copyright (C) 2024-2025 Maria Lisina
# Copyright (C) 2024-2025 Danil Lisin
# SPDX-License-Identifier: Apache-2.0

if [[ "${__bot_noenv}" != "0" ]]
then
    trap 'wait && exit 0' INT TERM
    env -i PATH="${PATH}" __bot_noenv=0 "${0}" ${@}
    exit ${?}
fi

set -e
umask 77
exec 2> /dev/null

version="5.0.9"
useragent="Sekoohaka/${version} Telegram Bot"

local_address="127.0.0.1:8081"
default_address="https://api.telegram.org"

dir="${0%/*}"
auth="${dir}/auth"
cache="${dir}/cache/${$}"
config="${dir}/config"
dumps="${dir}/dumps/${$}"
files="${dir}/files"
mods="${dir}/modules"
submods="${dir}/submodules"
units="${dir}/units"
users="${dir}/users"
offset=-1

zmods=(
    zsh/datetime
    zsh/files
    zsh/stat
    zsh/zutil
)

reqs=(
    busybox
    curl
    jq
    recode
    xq
)

busybox=(
    base64
    cut
    find
    grep
    ls
    sed
    sort
    sha1sum
    sleep
    tr
)

if [[ -n "${1}" ]]
then
    while getopts ha:lg:r:m:t:s:cjqui:e:d:f:n:x: opts
    do
        case "${opts}" in
            (h)
                help=0
            ;;
            (a)
                api_address="${OPTARG}"
            ;;
            (l)
                api_address="${local_address}"
            ;;
            (g)
                shorts_limit=${OPTARG}
            ;;
            (r)
                inline_limit=${OPTARG}
            ;;
            (m)
                cache_mode=${OPTARG}
            ;;
            (t)
                cache_time=${OPTARG}
            ;;
            (s)
                sleep_time=${OPTARG}
            ;;
            (c)
                clear_cache=0
            ;;
            (j)
                threaded_hash=0
            ;;
            (q)
                no_logs=0
            ;;
            (u)
                collect_dumps=0
            ;;
            (i)
                internal_timeout=${OPTARG}
            ;;
            (e)
                external_timeout=${OPTARG}
            ;;
            (d)
                head_timeout=${OPTARG}
            ;;
            (f)
                connrefused_timeout=${OPTARG}
            ;;
            (n)
                internal_proxy="${OPTARG}"
            ;;
            (x)
                external_proxy="${OPTARG}"
            ;;
            (*)
                echo "Unrecognized options" \
                    "\nSee '${0} -h'"
                exit 1
            ;;
        esac
    done

    shift $((OPTIND - 1))
else
    help=0
fi

if [[ -n "${help}" ]]
then
    echo "Sekoohaka Bot v${version}" \
        "\n\nUsage: ${0} [options] [token]" \
        "\n\nOptions:" \
        "\n  -h\t\tShow help information" \
        "\n  -a <addr>\tTelegram Bot API address, default: api.telegram.org" \
        "\n  -l\t\tUse local Telegram Bot API, address: 127.0.0.1:8081" \
        "\n  -r <num>\tInline results limit, max: 50, default: 10" \
        "\n  -g <num>\tShortcuts storage limit, max: 10000, default: 100" \
        "\n  -m <mode>\tCache mode, default: normal" \
        "\n  -t <secs>\tCache expiration time, max: 1000, default: 300 secs" \
        "\n  -s <secs>\tSleep duration time, max: 100, default: 10 secs" \
        "\n  -c\t\tClear cache automatically" \
        "\n  -j\t\tUse threaded MD5 hash lookup" \
        "\n  -q\t\tDo not print logs" \
        "\n  -u\t\tCollect debug dumps" \
        "\n  -i <secs>\tTelegram Bot API connetion timeout, max: 10, default: 10 secs" \
        "\n  -e <secs>\tImage Boards API connetion timeout, max: 10, default: 5 secs" \
        "\n  -d <secs>\tHead request connetion timeout, max: 10, default: 2 secs" \
        "\n  -f <secs>\tConnrefused timeout, max: 2, default: none" \
        "\n  -n <addr>\tProxy server for Telegram Bot API" \
        "\n  -x <addr>\tProxy server for Image Boards API" \
        "\n\nCache modes:" \
        "\n  none\t\tNo cache reuse" \
        "\n  normal\tReuse inline results and posts cache" \
        "\n  advanced\tExtract posts cache from inline results" \
        "\n\nSupported Image Boards:" \
        "\n  Safebooru\t\t(https://safebooru.donmai.us/)" \
        "\n  Danbooru\t\t(https://danbooru.donmai.us/)" \
        "\n  Gelbooru\t\t(https://gelbooru.com/)" \
        "\n  Idol Complex\t\t(https://idol.sankakucomplex.com/)" \
        "\n  Konachan.com\t\t(https://konachan.com/)" \
        "\n  Sankaku Channel\t(https://chan.sankakucomplex.com/)" \
        "\n  yande.re\t\t(https://yande.re/)"
    exit 0
fi

for zmod in ${zmods[@]}
do
    if ! zmodload ${zmod}
    then
        failed="${failed} ${zmod}"
    fi
done

if [[ -n "${failed}" ]]
then
    echo "Failed to load Z Shell modules:${failed}" \
        "\nUpdate your Z Shell or get a version with all the required modules"
    exit 1
fi

for req in ${reqs[@]}
do
    if ! command -v ${req} > /dev/null
    then
        missing="${missing} ${req}"
    fi
done

if [[ -n "${missing}" ]]
then
    echo "Missing dependencies:${missing}" \
        "\nFor more information follow: https://command-not-found.com/"
    exit 1
fi

for function in ${busybox[@]}
do
    if busybox ${function} --help > /dev/null
    then
        alias ${function}="busybox ${function}"
    else
        missing="${missing} ${function}"
    fi
done

if [[ -n "${missing}" ]]
then
    echo "Missing BusyBox functions:${missing}" \
        "\nUpdate your BusyBox or get a version with all the required functions"
    exit 1
fi

if [[ -z "${api_address}" ]]
then
    api_address="${default_address}"
fi

if [[ -n "${shorts_limit}" ]]
then
    if ! test ${shorts_limit} -gt 0
    then
        echo "Illegal shortcuts limit number" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${shorts_limit} -gt 10000 ]]
    then
        shorts_limit=10000
    fi
else
    shorts_limit=100
fi

if [[ -n "${inline_limit}" ]]
then
    if ! test ${inline_limit} -gt 0
    then
        echo "Illegal inline results limit number" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${inline_limit} -gt 50 ]]
    then
        inline_limit=50
    fi
else
    inline_limit=10
fi

if [[ -n "${cache_mode}" ]]
then
    case "${cache_mode}" in
        (none | normal | advanced)
        ;;
        (*)
            echo "Unrecognized caching mode ${cache_mode}" \
                "\nSee '${0} -h'"
            exit 1
        ;;
    esac
else
    cache_mode=normal
fi

if [[ -n "${cache_time}" ]]
then
    if ! test ${cache_time} -gt 0
    then
        echo "Illegal caching time" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${cache_time} -gt 1000 ]]
    then
        cache_time=1000
    fi
else
    cache_time=300
fi

if [[ -n "${sleep_time}" ]]
then
    if ! test ${sleep_time} -gt 0
    then
        echo "Illegal sleeping time" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${sleep_time} -gt 100 ]]
    then
        sleep_time=100
    fi
else
    sleep_time=10
fi

if [[ -n "${internal_timeout}" ]]
then
    if ! test ${internal_timeout} -gt 0
    then
        echo "Illegal Telegram Bot API timeout" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${internal_timeout} -gt 10 ]]
    then
        internal_timeout=10
    fi
else
    internal_timeout=10
fi

if [[ -n "${external_timeout}" ]]
then
    if ! test ${external_timeout} -gt 0
    then
        echo "Illegal Image Boards API timeout" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${external_timeout} -gt 10 ]]
    then
        external_timeout=10
    fi
else
    external_timeout=5
fi

if [[ -n "${head_timeout}" ]]
then
    if ! test ${head_timeout} -gt 0
    then
        echo "Illegal head request timeout" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${head_timeout} -gt 10 ]]
    then
        head_timeout=10
    fi
else
    head_timeout=2
fi

if [[ -n "${connrefused_timeout}" ]]
then
    if ! test ${connrefused_timeout} -gt 0
    then
        echo "Illegal connrefused timeout" \
            "\nSee '${0} -h'"
        exit 1
    fi

    if [[ ${connrefused_timeout} -gt 2 ]]
    then
        connrefused_timeout=2
    fi
else
    connrefused_timeout=0
fi

if [[ -n "${1}" ]]
then
    api_token="${1}"
    shift
fi

if [[ -n "${1}" ]]
then
    echo "Unrecognized action ${1}" \
        "\nSee '${0} -h'"
    exit 1
fi

until [[ -n "${api_token}" ]]
do
    read -p "Telegram Bot API Token: " -r api_token
done

alias parameter="cut -d ' ' -f"
alias enhash="sha1sum | parameter 1"
alias htmlescape="sed -e 's/</\&#60;/g' -e 's/>/\&#62;/g'"
alias urlencode="jq -Rr @uri"

rm -fr "${cache}"
mkdir -p "${cache}"
mkdir -p "${users}"

for file in aliases blacklist donate help whitelist
do
    if [[ -f "${files}/${file}.txt" ]]
    then
        if [[ "${files}/${file}.txt" -ot "${files}/${file}.txt.default" ]]
        then
            log_text="Warning: File ${file}.txt is older than ${file}.txt.default"
            . "${units}/log.zsh"
        fi
    else
        < "${files}/${file}.txt.default" > "${files}/${file}.txt"
    fi
done

if ! [[ -s "${files}/donate.txt" ]]
then
    nocommand_donate=0
    log_text="Warning: File donate.txt is empty, donate command is disabled"

    . "${units}/log.zsh"
fi

if [[ "${api_address}" != "${local_address}" && "${api_address}" != "${default_address}" ]]
then
    nocommand_source=0
    log_text="Warning: You are running bot with unknown Telegram Bot API instance, SauceNAO is disabled"

    . "${units}/log.zsh"
elif [[ "${api_address}" == "${local_address}" ]]
then
    if ! curl --connect-timeout ${connrefused_timeout} \
        --data "user_id=${api_token%:*}" \
        --get \
        --max-time ${internal_timeout} \
        --output "${cache}/getUserProfilePhotos.json" \
        --proxy "${internal_proxy}" \
        --retry 1 \
        --retry-connrefused \
        --retry-max-time $((internal_timeout - connrefused_timeout)) \
        --silent \
        --user-agent "${useragent}" \
        "${api_address}/bot${api_token}/getUserProfilePhotos"
    then
        log_text="getUserProfilePhotos: Failed to access Telegram Bot API"
        . "${units}/log.zsh"

        exit 1
    fi

    if ! jq -e '.' "${cache}/getUserProfilePhotos.json" > /dev/null
    then
        log_text="getUserProfilePhotos: An unknown error occurred"
        . "${units}/log.zsh"

        exit 1
    fi

    if [[ "$(jq -r '.ok' "${cache}/getUserProfilePhotos.json")" != "true" ]]
    then
        error_description="$(jq -r '.description' "${cache}/getUserProfilePhotos.json")"

        if [[ "${error_description}" != "null" ]]
        then
            log_text="getUserProfilePhotos: ${error_description}"
        else
            log_text="getUserProfilePhotos: An unknown error occurred"
        fi

        . "${units}/log.zsh"
        exit 1
    fi

    profilephoto="$(jq -r '.result.photos[].[0].file_id' "${cache}/getUserProfilePhotos.json")"

    if [[ -z "${profilephoto}" || "${profilephoto}" == "null" ]]
    then
        log_text="Error: Bot must have profile photo to run SauceNAO check"

        . "${units}/log.zsh"
        exit 1
    fi

    if ! curl --connect-timeout ${connrefused_timeout} \
        --data-urlencode "file_id=${profilephoto}" \
        --get \
        --max-time ${internal_timeout} \
        --output "${cache}/getFile.json" \
        --proxy "${internal_proxy}" \
        --retry 1 \
        --retry-connrefused \
        --retry-max-time $((internal_timeout - connrefused_timeout)) \
        --silent \
        --user-agent "${useragent}" \
        "${api_address}/bot${api_token}/getFile"
    then
        log_text="getFile: Failed to access Telegram Bot API"
        . "${units}/log.zsh"

        exit 1
    fi

    if ! jq -e '.' "${cache}/getFile.json" > /dev/null
    then
        log_text="getFile: An unknown error occurred"

        . "${units}/log.zsh"
        exit 1
    fi

    if [[ "$(jq -r '.ok' "${cache}/getFile.json")" != "true" ]]
    then
        error_description="$(jq -r '.description' "${cache}/getFile.json")"

        if [[ "${error_description}" != "null" ]]
        then
            log_text="getFile: ${error_description}"
        else
            log_text="getFile: An unknown error occurred"
        fi

        . "${units}/log.zsh"
        exit 1
    fi

    profilephoto_path="$(jq -r '.result.file_path' "${cache}/getFile.json")"

    if ! ls "${profilephoto_path}" > /dev/null
    then
        nocommand_source=0
        log_text="Error: Cannot access Telegram Bot API working directory, SauceNAO is disabled"

        . "${units}/log.zsh"
        exit 1
    fi
fi

log_text="PID: ${$}"
. "${units}/log.zsh"

if ! curl --connect-timeout ${connrefused_timeout} \
    --get \
    --max-time ${internal_timeout} \
    --output "${cache}/getMe.json" \
    --proxy "${internal_proxy}" \
    --retry 1 \
    --retry-connrefused \
    --retry-max-time $((internal_timeout - connrefused_timeout)) \
    --silent \
    --user-agent "${useragent}" \
    "${api_address}/bot${api_token}/getMe"
then
    log_text="getMe: Failed to access Telegram Bot API"
    . "${units}/log.zsh"

    exit 1
fi

if ! jq -e '.' "${cache}/getMe.json" > /dev/null
then
    log_text="getMe: An unknown error occurred"
    . "${units}/log.zsh"

    exit 1
fi

if [[ "$(jq -r '.ok' "${cache}/getMe.json")" != "true" ]]
then
    error_description="$(jq -r '.description' "${cache}/getMe.json")"

    if [[ "${error_description}" != "null" ]]
    then
        log_text="getMe: ${error_description}"
    else
        log_text="getMe: An unknown error occurred"
    fi

    . "${units}/log.zsh"
    exit 1
fi

username="$(jq -r '.result.username' "${cache}/getMe.json")"
log_text="Bot: ${username}"
. "${units}/log.zsh"

strftime %s > "${cache}.timer"

while trap 'wait && exit 0' INT TERM
do
    . "${mods}/timer.zsh" &

    if ! curl --connect-timeout ${connrefused_timeout} \
        --data "offset=${offset}" \
        --get \
        --output "${cache}/getUpdates.json" \
        --proxy "${internal_proxy}" \
        --retry 1 \
        --retry-connrefused \
        --retry-max-time $((internal_timeout - connrefused_timeout)) \
        --silent \
        --user-agent "${useragent}" \
        "${api_address}/bot${api_token}/getUpdates"
    then
        log_text="getUpdates: Failed to access Telegram Bot API, sleeping for ${sleep_time} seconds"
        . "${units}/log.zsh"

        sleep ${sleep_time}
        continue
    fi

    if ! jq -e '.' "${cache}/getUpdates.json" > /dev/null
    then
        log_text="getUpdates: An unknown error occurred, sleeping for ${sleep_time} seconds"
        . "${units}/log.zsh"

        sleep ${sleep_time}
        continue
    fi

    if [[ "$(jq -r '.ok' "${cache}/getUpdates.json")" != "true" ]]
    then
        error_description="$(jq -r '.description' "${cache}/getUpdates.json")"

        if [[ "${error_description}" != "null" ]]
        then
            log_text="getUpdates: ${error_description}, sleeping for ${sleep_time} seconds"
        else
            log_text="getUpdates: An unknown error occurred, sleeping for ${sleep_time} seconds"
        fi

        . "${units}/log.zsh"

        sleep ${sleep_time}
        continue
    fi

    update_id="$(jq -r '.result.[0].update_id' "${cache}/getUpdates.json")"

    if [[ "${update_id}" == "null" ]]
    then
        continue
    fi

    update="${cache}/${update_id}.json"
    dump=(${update##*/})

    if ! jq -c '.result.[0]' "${cache}/getUpdates.json" > "${update}"
    then
        log_text="Failed to write update file ${update_id}.json"

        . "${units}/log.zsh"
        continue
    fi

    for module in callback commands inline
    do
        . "${mods}/${module}.zsh" &
    done

    offset=$((update_id + 1))
done