forked from shellscriptx/shellbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShellBot.sh
3704 lines (3175 loc) · 104 KB
/
ShellBot.sh
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#-----------------------------------------------------------------------------------------------------------
# DATA: 07 de Março de 2017
# SCRIPT: ShellBot.sh
# VERSÃO: 4.7
# DESENVOLVIDO POR: Juliano Santos [SHAMAN]
# PÁGINA: http://www.shellscriptx.blogspot.com.br
# FANPAGE: https://www.facebook.com/shellscriptx
# GITHUB: https://github.com/shellscriptx
# CONTATO: [email protected]
#
# DESCRIÇÃO: ShellBot é uma API não-oficial desenvolvida para facilitar a criação de
# bots na plataforma TELEGRAM. Constituída por uma coleção de métodos
# e funções que permitem ao desenvolvedor:
#
# * Gerenciar grupos, canais e membros.
# * Enviar mensagens, documentos, músicas, contatos e etc.
# * Enviar teclados (KeyboardMarkup e InlineKeyboard).
# * Obter informações sobre membros, arquivos, grupos e canais.
# * Para mais informações consulte a documentação:
#
# https://github.com/shellscriptx/ShellBot/wiki
#
# O ShellBot mantém o padrão da nomenclatura dos métodos registrados da
# API original (Telegram), assim como seus campos e valores. Os métodos
# requerem parâmetros e argumentos para a chamada e execução. Parâmetros
# obrigatórios retornam uma mensagem de erro caso o argumento seja omitido.
#
# NOTAS: Desenvolvida na linguagem Shell Script, utilizando o interpretador de
# comandos BASH e explorando ao máximo os recursos built-in do mesmo,
# reduzindo o nível de dependências de pacotes externos.
#-----------------------------------------------------------------------------------------------------------
# Verifica se a API já foi instanciada.
[[ $_SHELLBOT_SH_ ]] && return 1
# Verifica se os pacotes necessários estão instalados.
for _pkg_ in curl jq getopt; do
# Se estiver ausente, trata o erro e finaliza o script.
if ! which $_pkg_ &>/dev/null; then
echo "ShellBot.sh: erro: '$_pkg_' O pacote requerido não está instalado." 1>&2
exit 1 # Status
fi
done
# Script que importou a API.
declare -r _BOT_SCRIPT_=$(basename "$0")
# Diretório temporário onde são gerados os arquivos json (JavaSCript Object Notation) sempre que um método é chamado.
_TMP_DIR_=$(mktemp -q -d --tmpdir=/tmp ${_BOT_SCRIPT_%%.*}-XXXXXXXXXX) || {
echo -e "ShellBot: erro: não foi possível criar o diretório JSON em '/tmp'." 1>&2
echo -e "Verifique se o diretório existe ou se possui permissões de escrita e tente novamente." 1>&2
exit 1
}
# API inicializada.
declare -r _SHELLBOT_SH_=1
# Desabilitar globbing
set -f
# Paleta de cores
declare -r _C_WHITE_='\033[0;37m'
declare -r _C_YELLOW_='\033[0;33m'
declare -r _C_GREEN_='\033[0;32m'
declare -r _C_CYAN_='\033[0;36m'
declare -r _C_DEF_='\033[0;m'
# diretório temporário
declare -r _TMP_DIR_
# curl parâmetros
declare -r _CURL_OPT_='--silent --request'
# Erros registrados da API (Parâmetros/Argumentos)
declare -r _ERR_TYPE_BOOL_='Tipo incompatível: Suporta somente "true" ou "false".'
declare -r _ERR_TYPE_PARSE_MODE_='Formação inválida: Suporta Somente "markdown" ou "html".'
declare -r _ERR_TYPE_INT_='Tipo incompatível: Suporta somente inteiro.'
declare -r _ERR_TYPE_FLOAT_='Tipo incompatível: Suporta somente float.'
declare -r _ERR_TYPE_POINT_='Máscara inválida: Deve ser “forehead”, “eyes”, “mouth” ou “chin”.'
declare -r _ERR_ACTION_MODE_='Ação inválida: A definição da ação não é suportada.'
declare -r _ERR_PARAM_REQUIRED_='Opção requerida: Verique se o(s) parâmetro(s) ou argumento(s) obrigatório(s) estão presente(s).'
declare -r _ERR_TOKEN_UNAUTHORIZED_='Não autorizado. Verifique se possui permissões para utilizar o token.'
declare -r _ERR_TOKEN_INVALID_='TOKEN inválido: Verique o número do token e tente novamente.'
declare -r _ERR_FUNCTION_NOT_FOUND_='Função inválida: Verique se o nome está correto ou se a função existe.'
declare -r _ERR_BOT_ALREADY_INIT_='Inicialização negada: O bot já foi inicializado.'
declare -r _ERR_FILE_NOT_FOUND_='Arquivo não encontrado: Não foi possível ler o arquivo especificado.'
declare -r _ERR_DIR_WRITE_DENIED_='Não é possível gravar no diretório: Permissão negada.'
declare -r _ERR_DIR_NOT_FOUND_='Não foi possível acessar: Diretório não encontrado.'
declare -r _ERR_FILE_DOWNLOAD_='Não foi possível realizar o download: Arquivo não encontrado.'
declare -r _ERR_FILE_INVALID_ID_='Arquivo não encontrado: ID inválido.'
declare -r _ERR_UNKNOWN_='Erro desconhecido: Ocorreu uma falha inesperada. Reporte o problema ao desenvolvedor.'
# Remove diretório JSON se o script for interrompido.
trap "rm -rf $_TMP_DIR_ &>/dev/null; exit 1" SIGQUIT SIGINT SIGKILL SIGTERM SIGSTOP SIGPWR
json() { jq -r "${*:2}" $1 2>/dev/null; }
json_status(){ [[ $(json $1 '.ok') != false ]] && return 0 || return 1; }
getFileJQ(){ echo $_TMP_DIR_/${1#*.}.json; return 0; } # Gera nomenclatura dos arquivos json.
getObjVal(){ sed -nr '/\s*"[a-z_]+":\s+(\[|\{)/!{s/,$//;s/^.*:\s+"?(.*[^",])*"?/\1/p}' | sed ':a;N;s/\n/|/;ta'; return 0; }
message_error()
{
# Variáveis locais
local err_message err_param assert jq_file err_line err_func
# A variável 'BASH_LINENO' é dinâmica e armazena o número da linha onde foi expandida.
# Quando chamada dentro de um subshell, passa ser instanciada como um array, armazenando diversos
# valores onde cada índice refere-se a um shell/subshell. As mesmas caracteristicas se aplicam a variável
# 'FUNCNAME', onde é armazenado o nome da função onde foi chamada.
err_line=${BASH_LINENO[1]} # Obtem o número da linha no shell pai.
err_func=${FUNCNAME[1]} # Obtem o nome da função no shell pai.
# Lê o tipo de ocorrência do erro.
# TG - Erro externo, retornado pelo core do telegram
# API - Erro interno, gerado pela API ShellBot.
case $1 in
TG)
# arquivo json
jq_file="${*: -1}"
err_param="$(json $jq_file '.error_code')"
err_message="$(json $jq_file '.description')"
;;
API)
err_param="${3:--}: ${4:--}"
err_message="$2"
assert=1
;;
esac
# Imprime erro
printf "%s: erro: linha %s: %s: %s: %s\n" "${_BOT_SCRIPT_}" \
"${err_line:--}" \
"${err_func:--}" \
"${err_param:--}" \
"${err_message:-$_ERR_UNKNOWN_}" 1>&2
# Finaliza script/thread em caso de erro interno, caso contrário retorna 1
[[ $assert ]] && exit 1 || return 1
}
# Inicializa o bot, definindo sua API e _TOKEN_.
ShellBot.init()
{
# Verifica se o bot já foi inicializado.
[[ $_SHELLBOT_INIT_ ]] && message_error API "$_ERR_BOT_ALREADY_INIT_"
# Variável local
local param=$(getopt --name "$FUNCNAME" \
--options 't:m' \
--longoptions 'token:,
monitor' \
-- "$@")
# Define os parâmetros posicionais
eval set -- "$param"
while :
do
case $1 in
-t|--token)
[[ $2 =~ ^[0-9]+:[a-zA-Z0-9_-]+$ ]] || message_error API "$_ERR_TOKEN_INVALID_" "$1" "$2"
declare -gr _TOKEN_="$2" # TOKEN
declare -gr _API_TELEGRAM_="https://api.telegram.org/bot$_TOKEN_" # API
shift 2
;;
-m|--monitor)
# Ativa modo monitor
declare -gr _BOT_MONITOR_=1
shift
;;
--)
shift
break
;;
esac
done
# Parâmetro obrigatório.
[[ $_TOKEN_ ]] || message_error API "$_ERR_PARAM_REQUIRED_" "[-t, --token]"
# Um método simples para testar o token de autenticação do seu bot.
# Não requer parâmetros. Retorna informações básicas sobre o bot em forma de um objeto Usuário.
ShellBot.getMe()
{
# Variável local
local jq_file=$(getFileJQ $FUNCNAME)
# Chama o método getMe passando o endereço da API, seguido do nome do método.
curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} > $jq_file
# Verifica o status de retorno do método
json_status $jq_file && {
# Retorna as informações armazenadas em "result".
json $jq_file '.result' | getObjVal
} || message_error TG $jq_file
return $?
}
_BOT_INFO_=$(ShellBot.getMe 2>/dev/null) || message_error API "$_ERR_TOKEN_UNAUTHORIZED_" '[-t, --token]'
# Define o delimitador entre os campos.
# Inicializa um array somente leitura contendo as informações do bot.
IFSbkp=$IFS; IFS='|'
declare -gr _BOT_INFO_=($_BOT_INFO_)
IFS=$IFSbkp
# Bot inicializado
declare -gr _SHELLBOT_INIT_=1
# SHELLBOT (FUNÇÕES)
# Inicializa as funções para chamadas aos métodos da API do telegram.
ShellBot.ListUpdates(){ echo ${!update_id[@]}; }
ShellBot.TotalUpdates(){ echo ${#update_id[@]}; }
ShellBot.OffsetEnd(){ local -i offset=${update_id[@]: -1}; echo $offset; }
ShellBot.OffsetNext(){ echo $(($(ShellBot.OffsetEnd)+1)); }
ShellBot.token() { echo "${_TOKEN_}"; }
ShellBot.id() { echo "${_BOT_INFO_[0]}"; }
ShellBot.first_name() { echo "${_BOT_INFO_[1]}"; }
ShellBot.username() { echo "${_BOT_INFO_[2]}"; }
ShellBot.regHandleFunction()
{
local function callback_data handle args
local param=$(getopt --name "$FUNCNAME" \
--options 'f:a:d:' \
--longoptions 'function:,
args:,
callback_data:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-f|--function)
# Verifica se a função especificada existe.
if ! declare -fp $2 &>/dev/null; then
message_error API "$_ERR_FUNCTION_NOT_FOUND_" "$1" "$2"
return 1
fi
function="$2"
shift 2
;;
-a|--args)
args="$2"
shift 2
;;
-d|--callback_data)
callback_data="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $function ]] || message_error API "$_ERR_PARAM_REQUIRED_" "[-f, --function]"
[[ $callback_data ]] || message_error API "$_ERR_PARAM_REQUIRED_" "[-d, --callback_data]"
# Testa se o indentificador armazenado em handle já existe. Caso já exista, repete
# o procedimento até que um handle válido seja gerado; Evitando sobreescrever handle's existentes.
until ! declare -fp $handle &>/dev/null; do
handle=handleid:$(tr -dc a-za-z0-9 < /dev/urandom | head -c15)
done
# Cria a função com o nome gerado e adiciona a chamada com os argumentos especificados.
# Anexa o novo handle a lista no índice associativo definindo em callback_data
function="$handle(){ $function $args; }"
eval "$function"
declare -Ag _reg_func_handle_list_
_reg_func_handle_list_[$callback_data]+="$handle "
return 0
}
ShellBot.watchHandle()
{
local callback_data func_handle \
param=$(getopt --name "$FUNCNAME" \
--options 'd' \
--longoptions 'callback_data' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-d|--callback_data)
shift 2
callback_data="$1"
;;
*)
shift
break
;;
esac
done
# O parâmetro callback_data é parcial, ou seja, Se o handle for válido, os elementos
# serão listados. Caso contrário a função é finalizada.
[[ $callback_data ]] || return 1
# Lista todos os handles no índice callback_data e executa-os
# consecutivamente. A ordem de execução das funções é determinada
# pela ordem de declaração.
for func_handle in ${_reg_func_handle_list_[$callback_data]}; do
$func_handle; done # executa
# retorno
return 0
}
ShellBot.getWebhookInfo()
{
# Variável local
local jq_file=$(getFileJQ $FUNCNAME)
# Chama o método getMe passando o endereço da API, seguido do nome do método.
curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} > $jq_file
# Verifica o status de retorno do método
json_status $jq_file && {
json $jq_file '.result' | getObjVal
} || message_error TG $jq_file
return $?
}
ShellBot.deleteWebhook()
{
# Variável local
local jq_file=$(getFileJQ $FUNCNAME)
# Chama o método getMe passando o endereço da API, seguido do nome do método.
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} > $jq_file
# Verifica o status de retorno do método
json_status $jq_file || message_error TG $jq_file
return $?
}
ShellBot.setWebhook()
{
local url certificate max_connections allowed_updates
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'u:c:m:a:' \
--longoptions 'url:,
certificate:,
max_connections:,
allowed_updates:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-u|--url)
url="$2"
shift 2
;;
-c|--certificate)
[[ $2 =~ ^@ && ! -f ${2#@} ]] && message_error API "$_ERR_FILE_NOT_FOUND_" "$1" "$2"
certificate="$2"
shift 2
;;
-m|--max_connections)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
max_connections="$2"
shift 2
;;
-a|--allowed_updates)
allowed_updates="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $url ]] || message_error API "$_ERR_PARAM_REQUIRED_" "[-u, --url]"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${url:+-d url="$url"} \
${certificate:+-d certificate="$certificate"} \
${max_connections:+-d max_connections="$max_connections"} \
${allowed_updates:+-d allowed_updates="$allowed_updates"} > $jq_file
# Testa o retorno do método.
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.setChatPhoto()
{
local chat_id photo
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:p:' \
--longoptions 'chat_id:,photo:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
-p|--photo)
[[ $2 =~ ^@ && ! -f ${2#@} ]] && message_error API "$_ERR_FILE_NOT_FOUND_" "$1" "$2"
photo="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
[[ $photo ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-p, --photo"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \
${photo:+-F photo="$photo"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.deleteChatPhoto()
{
local chat_id
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:' \
--longoptions 'chat_id:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.setChatTitle()
{
local chat_id title
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:t:' \
--longoptions 'chat_id:,title:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
-t|--title)
title="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
[[ $title ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-t, --title"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \
${title:+-d title="$title"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.setChatDescription()
{
local chat_id description
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:d:' \
--longoptions 'chat_id:,description:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
-d|--description)
description="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
[[ $description ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-d, --description"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \
${description:+-d description="$description"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.pinChatMessage()
{
local chat_id message_id disable_notification
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:m:n:' \
--longoptions 'chat_id:,
message_id:,
disable_notification:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
-m|--message_id)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
message_id="$2"
shift 2
;;
-n|--disable_notification)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
disable_notification="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
[[ $message_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-m, --message_id"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \
${message_id:+-d message_id="$message_id"} \
${disable_notification:+-d disable_notification="$disable_notification"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.unpinChatMessage()
{
local chat_id
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:' \
--longoptions 'chat_id:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.restrictChatMember()
{
local chat_id user_id until_date can_send_messages \
can_send_media_messages can_send_other_messages \
can_add_web_page_previews
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:u:d:s:m:o:w:' \
--longoptions 'chat_id:,
user_id:,
until_date:,
can_send_messages:,
can_send_media_messages:,
can_send_other_messages:,
can_add_web_page_previews:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
-u|--user_id)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
user_id="$2"
shift 2
;;
-d|--until_date)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
until_date="$2"
shift 2
;;
-s|--can_send_messages)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_send_messages="$2"
shift 2
;;
-m|--can_send_media_messages)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_send_media_messages="$2"
shift 2
;;
-o|--can_send_other_messages)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_send_other_messages="$2"
shift 2
;;
-w|--can_add_web_page_previews)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_add_web_page_previews="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
[[ $user_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --user_id"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \
${user_id:+-d user_id="$user_id"} \
${until_date_:+-d until_date="$until_date"} \
${can_send_messages:+-d can_send_messages="$can_send_messages"} \
${can_send_media_messages:+-d can_send_media_messages="$can_send_media_messages"} \
${can_send_other_messages:+-d can_send_other_messages="$can_send_other_messages"} \
${can_add_web_page_previews:+-d can_add_web_page_previews="$can_add_web_page_previews"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.promoteChatMember()
{
local chat_id user_id can_change_info can_post_messages \
can_edit_messages can_delete_messages can_invite_users \
can_restrict_members can_pin_messages can_promote_members
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:u:i:p:e:d:v:r:f:m:' \
--longoptions 'chat_id:,
user_id:,
can_change_info:,
can_post_messages:,
can_edit_messages:,
can_delete_messages:,
can_invite_users:,
can_restrict_members:,
can_pin_messages:,
can_promote_members:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
-u|--user_id)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
user_id="$2"
shift 2
;;
-i|--can_change_info)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_change_info="$2"
shift 2
;;
-p|--can_post_messages)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_post_messages="$2"
shift 2
;;
-e|--can_edit_messages)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_edit_messages="$2"
shift 2
;;
-d|--can_delete_messages)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_delete_messages="$2"
shift 2
;;
-v|--can_invite_users)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_invite_users="$2"
shift 2
;;
-r|--can_restrict_members)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_restrict_members="$2"
shift 2
;;
-f|--can_pin_messages)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_pin_messages="$2"
shift 2
;;
-m|--can_promote_members)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
can_promote_members="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
[[ $user_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --user_id"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \
${user_id:+-d user_id="$user_id"} \
${can_change_info:+-d can_change_info="$can_change_info"} \
${can_post_messages:+-d can_post_messages="$can_post_messages"} \
${can_edit_messages:+-d can_edit_messages="$can_edit_messages"} \
${can_delete_messages:+-d can_delete_messages="$can_delete_messages"} \
${can_invite_users:+-d can_invite_users="$can_invite_users"} \
${can_restrict_members:+-d can_restrict_members="$can_restrict_members"} \
${can_pin_messages:+-d can_pin_messages="$can_pin_messages"} \
${can_promote_members:+-d can_promote_members="$can_promote_members"} > $jq_file
json_status $jq_file || message_error TG $jq_file
# Status
return $?
}
ShellBot.exportChatInviteLink()
{
local chat_id
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:' \
--longoptions 'chat_id:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} > $jq_file
# Testa o retorno do método.
json_status $jq_file && {
json $jq_file '.result'
} || message_error TG $jq_file
# Status
return $?
}
ShellBot.sendVideoNote()
{
local chat_id video_note duration length disable_notification \
reply_to_message_id reply_markup
local jq_file=$(getFileJQ $FUNCNAME)
local param=$(getopt --name "$FUNCNAME" \
--options 'c:v:t:l:n:r:m:' \
--longoptions 'chat_id:,
video_note:,
duration:,
length:,
disable_notification:,
reply_to_message_id:,
reply_markup:' \
-- "$@")
# Define os parâmetros posicionais
eval set -- "$param"
while :
do
case $1 in
-c|--chat_id)
chat_id="$2"
shift 2
;;
-v|--video_note)
[[ $2 =~ ^@ && ! -f ${2#@} ]] && message_error API "$_ERR_FILE_NOT_FOUND_" "$1" "$2"
video_note="$2"
shift 2
;;
-t|--duration)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
duration="$2"
shift 2
;;
-l|--length)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
length="$2"
shift 2
;;
-n|--disable_notification)
[[ "$2" =~ ^(true|false)$ ]] || message_error API "$_ERR_TYPE_BOOL_" "$1" "$2"
disable_notification="$2"
shift 2
;;
-r|--reply_to_message_id)
[[ "$2" =~ ^[0-9]+$ ]] || message_error API "$_ERR_TYPE_INT_" "$1" "$2"
reply_to_message_id="$2"
shift 2
;;
-m|--reply_markup)
reply_markup="$2"
shift 2
;;
--)
shift
break
;;
esac
done
[[ $chat_id ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-c, --chat_id"
[[ $video_note ]] || message_error API "$_ERR_PARAM_REQUIRED_" "-v, --video_note"
curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \
${video_note:+-F video_note="$video_note"} \
${duration:+-F duration="$duration"} \
${length:+-F length="$length"} \
${disable_notification:+-F disable_notification="$disable_notification"} \
${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \
${reply_markup:+-F reply_markup="$reply_markup"} > $jq_file
# Testa o retorno do método.
json_status $jq_file && {
json $jq_file '.result' | getObjVal
} || message_error TG $jq_file
# Status
return $?
}
ShellBot.InlineKeyboardButton()
{
local button line text url callback_data \
switch_inline_query switch_inline_query_current_chat \
delm
local param=$(getopt --name "$FUNCNAME" \
--options 'b:l:t:u:c:q:s:' \
--longoptions 'button:,
line:,
text:,
url:,
callback_data:,
switch_inline_query:,
switch_inline_query_chat:' \
-- "$@")
eval set -- "$param"
while :
do
case $1 in
-b|--button)
# Ponteiro que recebe o endereço de "button" com as definições
# da configuração do botão inserido.