### ShellBot Keyboard Structure Examples Source: https://github.com/shellscriptx/shellbot/wiki/Funções Illustrates different ways to define the structure for a custom keyboard using string assignments. These examples show how to create arrays of arrays for button layouts, with or without explicit line indexing. ```shell teclado='["botao1"],["botao2"]' ``` ```shell teclado=‘[“botao1”],[”botao2”,“botao3”]’ ``` ```shell teclado=' ["1","2","3"], ["4","5","6"], ["7","8","9"], ["0"] ' ``` ```shell teclado[0]='["1","2"]' # linha 1 teclado[1]='["3","4"]' # linha 2 ``` ```shell teclado[1]='["1","2"]' # linha 2 teclado[0]='["3","4"]' # linha 1 ``` -------------------------------- ### Send Message Example Source: https://github.com/shellscriptx/shellbot/wiki/Funções Example of sending a message using ShellBot. The return type can be 'value' (default), 'json', or 'map'. Monitor mode can be enabled to display chat events. ```bash ShellBot.sendMessage --chat_id 999999999 --text "mensagem de teste" ``` -------------------------------- ### Run bot as a systemd service Source: https://context7.com/shellscriptx/shellbot/llms.txt Initialize the bot with --service and --user flags to create and register a systemd service. This ensures the bot starts automatically with the system and restarts on failure. Manage the service using systemctl commands. ```bash #!/bin/bash # meubot.sh — executar como root na primeira vez para criar o serviço source ShellBot.sh # O parâmetro --service cria o arquivo .service e o registra no systemd. # O parâmetro --user define o usuário sob o qual o serviço irá executar. # ATENÇÃO: execute como root APENAS uma vez; após criado, use systemctl. ShellBot.init \ --token '123456789:ABCDefGhIJKlmNOPqrSTUvwXYZ' \ --service \ --user 'botuser' # Após a execução inicial como root: # sudo ./meubot.sh # # O systemd criará e habilitará o serviço automaticamente: # meubot.service foi criado com sucesso !! # Habilitando...[OK] | Iniciando...[OK] # # Gerenciar o serviço depois: # sudo systemctl status meubot.service # sudo systemctl stop meubot.service # sudo systemctl start meubot.service # sudo systemctl restart meubot.service # sudo systemctl disable meubot.service while :; do ShellBot.getUpdates --limit 100 --offset "$(ShellBot.OffsetNext)" --timeout 30 for id in $(ShellBot.ListUpdates); do ( case "${message_text[$id]}" in '/start') ShellBot.sendMessage --chat_id "${message_chat_id[$id]}" --text "Bot ativo!" ;; esac ) done done ``` -------------------------------- ### Initialize ShellBot API Source: https://context7.com/shellscriptx/shellbot/llms.txt This is a mandatory function to authenticate the bot with a TOKEN and configure global settings like return type, delimiter, log file, and monitor mode. Without this, no other methods will be available. The example shows initialization with map return, enabled logging, and monitor mode. ```bash #!/bin/bash # Importar a API source ShellBot.sh # Inicializar com retorno map, log habilitado e modo monitor ShellBot.init \ --token '123456789:ABCDefGhIJKlmNOPqrSTUvwXYZ' \ --return map \ --monitor \ --flush \ --log_file '/var/log/meubot.log' \ --log_format '%(%d/%m/%Y %H:%M:%S)T: {BOT_USERNAME}: {FROM_USERNAME}: {OBJECT_TYPE}: {RETURN}' # Verificar se o bot foi inicializado corretamente if ShellBot.getMe; then echo "Bot: $(ShellBot.username) | ID: $(ShellBot.id)" else echo "Falha na inicialização!" >&2 exit 1 fi # Retorno esperado (modo map): # return[ok]='true' # return[id]='111111111' # return[username]='meubot_bot' # return[first_name]='MeuBot' ``` -------------------------------- ### Getting Bot Information Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Verify bot initialization by calling `ShellBot.getMe`. This method returns basic bot information: id, username, and first_name, separated by the specified delimiter. ```APIDOC ## Getting Bot Information Verify bot initialization using `ShellBot.getMe`. This method returns basic bot information. ```bash $ ShellBot.getMe ``` **Output format (default delimiter '|'):** ``` status|id|username|first_name ``` ``` -------------------------------- ### Manage ShellBot Service with systemctl Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Common systemctl commands to manage the ShellBot service, including status, stop, start, restart, enable, and disable. ```bash Uso: sudo systemctl bot_script.service {start|stop|restart|reload|status} ``` ```bash $ sudo systemctl ``` -------------------------------- ### Get File Information using ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Fetches basic file information, including ID, size, and directory. Requires the file ID as a parameter. ```shell ShellBot.getFile --file_id identificador ``` -------------------------------- ### ShellBot Service Creation Success Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Output indicating successful creation, enabling, and starting of the bot_script.service. This output also shows the active service details and a systemd log entry. ```bash $ sudo ./bot_script.sh bot_script.service foi criado com sucesso !! Habilitando...[OK] Iniciando...[OK] ● bot_script.service - bot_script.sh - (SHELLBOT) Loaded: loaded (/lib/systemd/system/bot_script.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2017-09-28 23:53:17 -03; 21ms ago Main PID: 8816 (bash) Tasks: 7 (limit: 4915) CGroup: /system.slice/bot_script.service ├─8816 /bin/bash bot_script.sh └─8827 curl --silent --request GET https://api.telegram.org/bot123456789:XXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXX set 28 23:53:17 doom systemd[1]: Started bot_script.sh - (SHELLBOT). ``` -------------------------------- ### Initializing the Bot Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API After importing the API, initialize your bot using `ShellBot.init` with your unique token obtained from BotFather. This makes all other methods available. ```APIDOC ## Initializing Bot Initialize the bot using the `ShellBot.init` method with your token. This makes all other methods available. ```bash $ ShellBot.init --token ``` Optionally, you can set a custom delimiter for method returns using `-d` or `--delimiter` (version 5.5+). ```bash $ ShellBot.init --token --delimiter '|' ``` You can also specify the return type (`json`, `map`, or `value`) using `-r` or `--return` (version 5.5+). ```bash $ ShellBot.init --token --return ``` ``` -------------------------------- ### ShellBot.getStickerSet Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Use this method to get a Sticker Set. On success, a StickerSet object is returned. ```APIDOC ## ShellBot.getStickerSet ### Description Use this method to get a Sticker Set. On success, a StickerSet object is returned. ### Method GET ### Endpoint /getStickerSet ### Parameters #### Query Parameters - **name** (String) - Required - Name of the Sticker Set ``` -------------------------------- ### Inicializar bot com serviço systemd Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Para gerenciar o bot via systemd, adicione o parâmetro `-s` ou `--service` ao método `ShellBot.init`. ```bash #!/bin/bash ``` -------------------------------- ### Get Bot Username - ShellBot.username Source: https://github.com/shellscriptx/shellbot/wiki/Funções Retrieves the username of the bot. This function requires no parameters. ```shell ShellBot.username ``` -------------------------------- ### ShellBot.getMyCommands Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Use this method to get the current list of the bot's commands. Does not require parameters. ```APIDOC ## ShellBot.getMyCommands ### Description Use this method to get the current list of the bot's commands. Does not require parameters. ### Method GET ### Endpoint /getMyCommands ### Parameters No parameters required. ``` -------------------------------- ### ShellBot.init Source: https://context7.com/shellscriptx/shellbot/llms.txt Initializes and configures the bot, authenticating with a TOKEN and setting global configurations like return type, delimiter, log file, and monitor mode. This function must be called before any other method. ```APIDOC ## ShellBot.init — Inicialização e configuração do bot Função obrigatória que autentica o bot via TOKEN, declara todos os métodos disponíveis e define configurações globais como tipo de retorno, delimitador, arquivo de log e modo monitor. Sem chamá-la, nenhum outro método estará disponível. ```bash #!/bin/bash # Importar a API source ShellBot.sh # Inicializar com retorno map, log habilitado e modo monitor ShellBot.init \ --token '123456789:ABCDefGhIJKlmNOPqrSTUvwXYZ' \ --return map \ --monitor \ --flush \ --log_file '/var/log/meubot.log' \ --log_format '%(%d/%m/%Y %H:%M:%S)T: {BOT_USERNAME}: {FROM_USERNAME}: {OBJECT_TYPE}: {RETURN}' # Verificar se o bot foi inicializado corretamente if ShellBot.getMe; then echo "Bot: $(ShellBot.username) | ID: $(ShellBot.id)" else echo "Falha na inicialização!" >&2 exit 1 fi # Retorno esperado (modo map): # return[ok]='true' # return[id]='111111111' # return[username]='meubot_bot' # return[first_name]='MeuBot' ``` ``` -------------------------------- ### Get ShellBot Configuration Source: https://github.com/shellscriptx/shellbot/wiki/Funções Retrieves the bot's configuration settings. This function does not require any parameters. ```shell ShellBot.getConfig ``` -------------------------------- ### ShellBot: Executar comandos com argumentos posicionais (Exemplo Didático) Source: https://github.com/shellscriptx/shellbot/wiki/Funções Exemplo didático para criar um shell que executa comandos enviados pelo usuário, utilizando argumentos posicionais. Aplicar com cautela devido a riscos de segurança. ```bash # Aceita a requisição no privado e executa o comando somente # para o usuário especificado. # ``` -------------------------------- ### Inicializar bot e processar atualizações em threads Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Este script demonstra a inicialização do bot, a obtenção contínua de atualizações e o processamento de cada atualização em uma thread separada usando o operador '&'. Remova o '&' para processar em fila. ```bash #!/bin/bash # Importando API source ShellBot.sh # Token do bot bot_token='' # Inicializando o bot ShellBot.init --token "$bot_token" while : do # Obtem as atualizações ShellBot.getUpdates --limit 100 --offset $(ShellBot.OffsetNext) --timeout 30 # Lista as atualizações. for id in $(ShellBot.ListUpdates) do # bloco de instruções ( ... ) & # Criando thread done done ``` -------------------------------- ### Get Bot ID - ShellBot.id Source: https://github.com/shellscriptx/shellbot/wiki/Funções Retrieves the unique identifier for the bot. This function requires no parameters. ```shell ShellBot.id ``` -------------------------------- ### Get Bot First Name - ShellBot.first_name Source: https://github.com/shellscriptx/shellbot/wiki/Funções Retrieves the first name of the bot. This function requires no parameters. ```shell ShellBot.first_name ``` -------------------------------- ### ShellBot.init Source: https://github.com/shellscriptx/shellbot/wiki/Funções Initializes and sets the bot's configuration using a valid TOKEN. It returns a bot object upon success. This function must be called to access other bot methods. ```APIDOC ## ShellBot.init ### Description Use this function to initialize and set the bot's configuration from a valid TOKEN. A bot object is returned on success. It is necessary to initialize the bot (ShellBot.init) to gain access to its methods. ### Method ShellBot.init ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Command Line Arguments - **-t, --token <_token_>** (String) - Required - Specifies the unique authentication key (TOKEN). - **-m, --monitor** (None) - Optional - Activates the bot's monitor mode. This parameter displays chat events like commands, messages, and variable initializations in the prompt. For messages, the bot must be a chat administrator. - **-f, --flush** (None) - Optional - Clears the bot's update offset list. If records exist, `flush_first_id` and `flush_last_id` are returned; otherwise, their values are 0. Any calls, events, or requests made during initialization are ignored. Records can be recovered by providing a negative offset code. - **-s, --service** (None) - Optional - Creates a Bot Unit Service in the `systemd` process management system (requires root privileges). Performs a background call and enables the bot on system startup. This parameter is only mandatory if the `-u, --user` option is provided. - **-u, --user <_usuario_>** (string) - Optional - Defines the user under which the service instance will run. If omitted, the current system user is used. - **-r, --return <_tipo_>** (String) - Optional - Specifies the data type returned by methods (except `ShellBot.getUpdates`). Supported types: `json`, `map`, or `value` (default). - **-l, --log_file <_arquivo_>** (string) - Optional - The full path to the log file to be generated. - **-o, --log_format <_formato_>** (String) - Optional - The default log output format. - **-d, --delimiter <_delimitador_>** (String) - Optional - Defines the default delimiter used by the API for separating values (default: '|'). ### Return Types Methods return values in a collection of objects formatted in a specific data type. - **json**: JavaScript Object Notation. - **value**: A collection of values separated by a delimiter '|' (default). See the `-d, --delimiter` parameter. - **map**: Maps values into an associative array (non-verbose). Initializes the array with the unique identifier `return`, accessed via a key using the syntax: `${return[key]}`. If a key contains multiple elements, values are separated by the default delimiter, e.g., `return[key]='element1|element2|element3'`. ### Example ```bash ShellBot.init --token YOUR_TOKEN --monitor ``` ### Response #### Success Response Returns a bot object upon successful initialization. #### Response Example (Conceptual) ``` [Bot Object Representation] ``` ``` -------------------------------- ### Get Bot Token - ShellBot.token Source: https://github.com/shellscriptx/shellbot/wiki/Funções Retrieves the unique authentication token for the bot. This function requires no parameters. ```shell ShellBot.token ``` -------------------------------- ### Create and Send Media Album Source: https://context7.com/shellscriptx/shellbot/llms.txt Use `inputMedia` to build an album of photos and videos, then send it with `sendMediaGroup`. Media can be added via URL or existing `file_id`. Captions can be set for each item. ```shell #!/bin/bash source ShellBot.sh ShellBot.init --token '' # Inicializar variável do álbum album="" # Adicionar fotos por URL ShellBot.inputMedia \ --input album \ --type photo \ --media 'https://example.com/foto1.jpg' \ --caption "Foto 1 - Paisagem" ShellBot.inputMedia \ --input album \ --type photo \ --media 'https://example.com/foto2.jpg' \ --caption "Foto 2 - Cidade" # Adicionar vídeo por file_id existente no Telegram ShellBot.inputMedia \ --input album \ --type video \ --media 'BAADAQADEgADHXSRRgkpayiIdrXjAg' \ --caption 'Vídeo do evento' # Enviar o álbum completo ShellBot.sendChatAction --chat_id 999999999 --action upload_video ShellBot.sendMediaGroup \ --chat_id 999999999 \ --media "$album" ``` -------------------------------- ### Get Current Bot Commands with ShellBot.getMyCommands Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Retrieve the current list of bot commands. This method does not require any parameters. ```shell ShellBot.getMyCommands ``` -------------------------------- ### Get Chat Members Count Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Retrieves the total number of members in a chat. Requires a valid chat identifier. ```shell ShellBot.getChatMembersCount --chat_id identificador ``` -------------------------------- ### Initialize ShellBot Script Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Initialize the ShellBot script with a token and optional user. The `--user` parameter is optional. ```bash ShellBot.init --token --service --user ``` -------------------------------- ### Get Chat Member Information Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Fetches information about a specific member within a chat. Requires both chat and user identifiers. ```shell ShellBot.getChatMember --chat_id identificador --user_id identificador ``` -------------------------------- ### Inicializar Bot com Tipo de Retorno Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Inicializa o bot especificando o tipo de retorno (json, map, ou value) usando o parâmetro -r ou --return. Funciona a partir da versão 5.5. ```bash source ShellBot.sh # Inicializando # TIPO: json, value ou map ShellBot.init --token --return # Enviando mensagem ShellBot.sendMessage --chat_id 999999 --text 'mensagem de teste' ``` -------------------------------- ### Get Bot Information using ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Retrieves information about the bot, useful for token validation. This function does not require any parameters. ```shell ShellBot.getMe ``` -------------------------------- ### Initialize ShellBot with Token Source: https://github.com/shellscriptx/shellbot/wiki/Funções Use this function to initialize the bot with a valid TOKEN. It returns a bot object upon success. This is a required step before accessing other bot methods. ```bash ShellBot.init --token token ``` -------------------------------- ### Get Next Update ID - ShellBot.OffsetNext Source: https://github.com/shellscriptx/shellbot/wiki/Funções Returns the ID of the next update (offset + 1). This function requires no parameters. ```shell ShellBot.OffsetNext ``` -------------------------------- ### Inicializar Bot com Token Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Inicializa o bot com seu token. A inicialização é necessária para que os outros métodos funcionem. ```shell $ ShellBot.init --token ``` -------------------------------- ### ShellBot.getChat / getChatAdministrators / getChatMembersCount Source: https://context7.com/shellscriptx/shellbot/llms.txt Query methods to get information about a chat, list its administrators, and check the total number of members. ```APIDOC ## ShellBot.getChat / getChatAdministrators / getChatMembersCount — Consultar informações do chat Métodos de consulta para obter informações sobre um chat, listar seus administradores e verificar o total de membros. ```bash #!/bin/bash source ShellBot.sh ShellBot.init --token '' --return map chat_alvo='@meugrupo' # Informações gerais do chat ShellBot.getChat --chat_id "$chat_alvo" echo "Título : ${return[title]}" echo "Tipo : ${return[type]}" echo "Username: ${return[username]}" # Total de membros ShellBot.getChatMembersCount --chat_id "$chat_alvo" echo "Membros : ${return[result]}" # Listar administradores ShellBot.getChatAdministrators --chat_id "$chat_alvo" # Retorno value: id|usuario|nome|sobrenome|status (um por linha separado por |) # Informações de um membro específico ShellBot.getChatMember \ --chat_id "$chat_alvo" \ --user_id 123456789 echo "Status do membro: ${return[status]}" ``` ``` -------------------------------- ### Get Last Update ID - ShellBot.OffsetEnd Source: https://github.com/shellscriptx/shellbot/wiki/Funções Returns the ID of the last update. Returns 0 if no updates are available. This function requires no parameters. ```shell ShellBot.OffsetEnd ``` -------------------------------- ### ShellBot: Simular comando egrep com argumentos posicionais Source: https://github.com/shellscriptx/shellbot/wiki/Funções Implementa uma regra que simula o comando `egrep` usando argumentos posicionais para o padrão e o nome do arquivo. Permite a execução de comandos com múltiplos argumentos. ```bash ShellBot.setMessageRules --name 'cmd_egrep' --entitie_type bot_command --chat_type private --username 'admin' --command '/egrep' --num_args 3 --exec 'grep -E "$2" $3' ``` -------------------------------- ### Get Total Updates - ShellBot.TotalUpdates Source: https://github.com/shellscriptx/shellbot/wiki/Funções Retrieves the total number of available updates. The maximum results are determined by ShellBot.getUpdates. This function requires no parameters. ```shell ShellBot.TotalUpdates ``` -------------------------------- ### ShellBot.init Method Updates Source: https://github.com/shellscriptx/shellbot/wiki/Atualizações-recentes Details on parameter additions and return value changes for the ShellBot.init method. ```APIDOC ## ShellBot.init ### Description Initializes the ShellBot with optional parameters for flushing records and monitoring events. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Added in Version 4.8 - `-f, --flush`: Clears all records from the offset list during initialization. ### Parameters Added in Version 4.5 - `-m, --monitor`: When activated, displays bot events in the prompt. ### Return Value - Returns a collection of objects: `bot_id|bot_username|bot_first_name|flush_first_id|flush_last_id` ``` -------------------------------- ### Get Webhook Info - ShellBot.getWebhookInfo Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Retrieves the current webhook status. Returns an empty URL field if the bot is using getUpdates. No parameters are required. ```shell ShellBot.getWebhookInfo ``` -------------------------------- ### Importing the API Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API To use the ShellBot API, you need to import it into your script using the 'source' or '.' command. If the script is in a different directory, provide the full path. ```APIDOC ## Importing the API To use the ShellBot API, import it into your script using the `source` or `.` command. ```bash $ source ShellBot.sh ``` If the script is in a different directory, provide the full path. Execution permissions are not required. ``` -------------------------------- ### Create InputMedia Object with ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Funções Use this method to create an InputMedia object. Specify the input variable, media type, and the media file. Optional parameters include caption, parse mode, thumbnail, dimensions, duration, streaming support, performer, and title. ```shell ShellBot.inputMedia --input --type ... ``` -------------------------------- ### Simular Array de Array para Propriedades de Imagem Source: https://github.com/shellscriptx/shellbot/wiki/Variáveis O Bash não suporta arrays multidimensionais nativamente. O ShellBot armazena múltiplos valores para propriedades de imagem (como ID, tamanho, altura, largura) em strings separadas por espaço, onde a posição do elemento corresponde ao índice. ```bash # Os ID's das imagens disponíveis message_photo_file_id = 'AgADAQAD4KcxG0_l6UU3aWyr8yZ5KhcT9y8ABLF5dSD8IsvVgMgAAgI AgADAQAD4KcxG0_l6UU3aZyr8ym5KhcT9y8ABIQ7q5EOmrnYgcgAAgI AgADAQAD4KcxG0_l6UU3aWyr8ym5KhcT9y8ABE86mx5aXfQwgsgAAgI AgADAQAD4KcxG0_l6UU3aUyr8ym5KhcT9y8ABPte4YhC8Fzwf8gAAgI' # Os Tamanhos dos arquivos message_photo_file_size = '1478 21417 100945 222230' # Dimensões message_photo_height = '51 180 450 720' message_photo_width = '90 320 800 1280' ``` -------------------------------- ### ShellBot.sendVideoNote Method Source: https://github.com/shellscriptx/shellbot/wiki/Atualizações-recentes Method for sending video notes. ```APIDOC ## ShellBot.sendVideoNote ### Description Sends a video note (a short video message) within a chat. ### Method (Not specified, assumed to be a method call within the ShellBot library) ### Endpoint N/A ### Parameters (Not specified in the source text) ### Request Example (Not specified in the source text) ### Response (Not specified in the source text) ``` -------------------------------- ### Get Sticker Set using ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Use this method to retrieve a sticker set. On success, a StickerSet object is returned. Requires the sticker set name. ```shell ShellBot.getStickerSet --name ``` -------------------------------- ### Get Chat Information using ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Retrieves updated information about a chat, such as the user's current username or chat title. Requires the chat ID. ```shell ShellBot.getChat --chat_id identificador ``` -------------------------------- ### Send Video with Streaming Support Source: https://context7.com/shellscriptx/shellbot/llms.txt Use `sendVideo` for sending video files. Supports streaming and requires chat ID, video path, and caption. You can also specify width, height, and `supports_streaming`. ```shell ShellBot.sendVideo \ --chat_id "$chat" \ --video '@/home/user/video.mp4' \ --caption 'Vídeo de demonstração' \ --supports_streaming true \ --width 1280 \ --height 720 ``` -------------------------------- ### Define and get bot commands Source: https://context7.com/shellscriptx/shellbot/llms.txt Use ShellBot.setMyCommands to define the list of commands displayed in the Telegram suggestion menu. ShellBot.getMyCommands retrieves the currently registered commands. ```bash #!/bin/bash source ShellBot.sh ShellBot.init --token '' # Definir lista de comandos cmds='' ShellBot.BotCommand --command 'start' --description 'Iniciar o bot' cmds+="$(ShellBot.BotCommand --command 'ajuda' --description 'Exibir ajuda e lista de comandos')" cmds+="$(ShellBot.BotCommand --command 'ping' --description 'Verificar latência de um host')" cmds+="$(ShellBot.BotCommand --command 'info' --description 'Informações do chat atual')" cmds+="$(ShellBot.BotCommand --command 'enquete' --description 'Criar uma enquete interativa')" ShellBot.setMyCommands --commands "$cmds" # Consultar os comandos registrados if ShellBot.getMyCommands; then echo "Comandos registrados com sucesso." fi ``` -------------------------------- ### ShellBot.inputMedia Source: https://context7.com/shellscriptx/shellbot/llms.txt Constructs media objects for use with `sendMediaGroup`. ```APIDOC ## ShellBot.inputMedia ### Description Constructs media objects for use with `sendMediaGroup`. ### Method N/A (Helper function) ### Parameters #### Path Parameters - **input** (string) - Required - The variable to accumulate the media objects into. - **type** (string) - Required - The type of media ('photo' or 'video'). - **media** (string) - Required - The media file path, URL, or `file_id`. - **caption** (string) - Optional - The caption for the media. ``` -------------------------------- ### Parâmetros Longos e Curtos Source: https://github.com/shellscriptx/shellbot/wiki/Introdução-a-API Os métodos suportam parâmetros longos (--nome) e curtos (-n). É possível mesclar ambos os tipos de parâmetros. ```shell ShellBot.metodo --param1 arg1 --param2 arg2 ... ``` ```shell ShellBot.metodo -p arg1 -p arg2 ... ``` ```shell ShellBot.metodo -p1 arg1 --param2 arg2 ``` -------------------------------- ### Ativar Modo Monitor ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Variáveis Use o parâmetro --monitor ou -m ao inicializar o ShellBot para exibir variáveis e seus valores na saída padrão. Isso é útil para depuração e monitoramento de eventos. ```bash ShellBot.init --token --monitor ``` -------------------------------- ### Get Chat Administrators using ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Fetches a list of administrators for a given chat. Returns an array of ChatMember objects. If no administrators are set in a group or supergroup, only the creator is returned. Requires the chat ID. ```shell ShellBot.getChatAdministrators --chat_id identificador ``` -------------------------------- ### ShellBot.getFile Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Returns basic file information. ```APIDOC ## ShellBot.getFile ### Description Returns basic file information. ### Method (Not specified, likely a GET request based on context) ### Endpoint (Not specified) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) - **-f, --file_id** (Integer) - Required - Identifier of the file. > * The information returned has its fields separated by the delimiter `|` PIPE with the following pattern: `id|size|directory` ### Request Example ``` ShellBot.getFile --file_id identificador ``` ### Response #### Success Response (200) (Response details not specified) #### Response Example (Response example not specified) ``` -------------------------------- ### Get User Profile Photos with ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Retrieves a list of a user's profile photos. Accepts optional offset and limit parameters to control pagination and the number of photos returned. Requires the user ID. ```shell ShellBot.getUserProfilePhotos --user_id identificador ... ``` -------------------------------- ### Date and Time Formatting - %(FMT)T Source: https://github.com/shellscriptx/shellbot/wiki/Funções Generates a date and time string using the provided format string (FMT) compatible with strftime. Example: "Hora atual: %(%H:%M)T" results in "Hora atual: 12:30". ```shell %(FMT)T ``` -------------------------------- ### ShellBot.uploadStickerFile Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Use this method to upload a .png file with a sticker for later use in the createNewStickerSet and addStickerToSet methods. Returns the uploaded file on success. ```APIDOC ## ShellBot.uploadStickerFile ### Description Use this method to upload a .png file with a sticker for later use in the createNewStickerSet and addStickerToSet methods. Returns the uploaded file on success. ### Method POST ### Endpoint /uploadStickerFile ### Parameters #### Request Body - **user_id** (Integer) - Required - User identifier of the file owner. - **png_sticker** (File) - Required - The Png sticker image must be up to 512 kilobytes in size, dimensions must not exceed 512px, and width or height must be exactly 512px. ``` -------------------------------- ### Upload Sticker File using ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Métodos Use this method to upload a PNG sticker file for later use. The file must be up to 512KB, with dimensions not exceeding 512px, and either width or height must be exactly 512px. Returns the uploaded file information on success. ```shell ShellBot.uploadStickerFile --user_id --png_sticker ``` -------------------------------- ### Define ReplyKeyboardMarkup in ShellBot Source: https://github.com/shellscriptx/shellbot/wiki/Funções Creates a custom keyboard markup from a specified variable structure. It returns a ReplyKeyboardMarkup object. Optional parameters like resize_keyboard, one_time_keyboard, and selective can be used to customize keyboard behavior. ```shell ShellBot.ReplyKeyboardMarkup --button ``` -------------------------------- ### Define Message Rules with ShellBot Source: https://context7.com/shellscriptx/shellbot/llms.txt Implements a declarative system for message filtering and automatic actions. Rules are processed sequentially, and actions are executed when criteria are met. This example shows rules for welcoming new members, deleting group links, responding to a specific command, and enforcing business hours. ```bash #!/bin/bash source ShellBot.sh ShellBot.init --token '' --monitor --flush # ── Funções de ação ────────────────────────────────────────────── boas_vindas() { ShellBot.sendMessage \ --chat_id "${message_chat_id[$id]}" \ --text "👋 Bem-vindo(a), *${message_new_chat_member_first_name[$id]}*!" \ --parse_mode markdown } apagar_links() { ShellBot.deleteMessage \ --chat_id "${message_chat_id[$id]}" \ --message_id "${message_message_id[$id]}" ShellBot.sendMessage \ --chat_id "${message_chat_id[$id]}" \ --text "⛔ [@${message_from_username[$id]}] links de grupos não são permitidos." \ --parse_mode markdown } # ── Regras ─────────────────────────────────────────────────────── # 1. Mensagem de boas-vindas para novos membros ShellBot.setMessageRules \ --name 'boas_vindas' \ --action boas_vindas \ --chat_member new # 2. Bloquear links de grupos (t.me/...) em supergrupos ShellBot.setMessageRules \ --name 'bloquear_links_grupo' \ --action apagar_links \ --entitie_type url \ --chat_type 'supergroup,group' \ --text 't\.me/[a-zA-Z0-9_]+' # 3. Comando /id restrito ao chat privado — responde com ID do usuário ShellBot.setMessageRules \ --name 'cmd_meuid' \ --command '/id' \ --chat_type private \ --bot_send_message 'Seu ID é: `${message_from_id}`' \ --bot_parse_mode markdown # 4. Ignorar mensagens fora do horário comercial (segunda a sexta) ShellBot.setMessageRules \ --name 'fora_horario' \ --weekday '1,2,3,4,5' \ --time '00:00-08:00,18:01-23:59' \ --bot_reply_message 'Atendemos das 08:00 às 18:00, de seg. a sex.' ``` -------------------------------- ### Send Text Messages with Formatting Source: https://context7.com/shellscriptx/shellbot/llms.txt This method sends text messages to users, groups, or channels. It supports Markdown/HTML formatting, disabling notifications, replying to specific messages, and attaching custom keyboards. The example shows a simple message, a message with Markdown formatting and disabled web page preview, and a silent message. ```bash #!/bin/bash source ShellBot.sh ShellBot.init --token '' --return value # Mensagem simples ShellBot.sendMessage \ --chat_id 999999999 \ --text 'Olá! Sou um bot ShellBot.' # Mensagem com formatação Markdown ShellBot.sendMessage \ --chat_id 999999999 \ --text '*Bem-vindo!* Seu ID é: `' ``` ```bash ${message_from_id[$id]} ``` ```bash ' \ --parse_mode markdown \ --disable_web_page_preview true # Verificar se o envio teve sucesso if ShellBot.sendMessage \ --chat_id 999999999 \ --text "_Mensagem silenciosa_" \ --parse_mode markdown \ --disable_notification true; then echo "Mensagem enviada com sucesso!" # Retorno value: true|36050|111111111|true|BotExemplo|botext_bot|999999999|... else echo "Falha ao enviar mensagem." >&2 fi ``` -------------------------------- ### Bot Unit Service (systemd) Source: https://context7.com/shellscriptx/shellbot/llms.txt Register the bot as a managed systemd service for automatic startup and fault tolerance. ```APIDOC ## Bot Unit Service (systemd) — Executar bot como serviço do sistema Permite registrar o bot como um serviço systemd gerenciado, garantindo que ele seja iniciado automaticamente com o sistema e reiniciado em caso de falha. ```bash #!/bin/bash # meubot.sh — executar como root na primeira vez para criar o serviço source ShellBot.sh # O parâmetro --service cria o arquivo .service e o registra no systemd. # O parâmetro --user define o usuário sob o qual o serviço irá executar. # ATENÇÃO: execute como root APENAS uma vez; após criado, use systemctl. ShellBot.init \ --token '123456789:ABCDefGhIJKlmNOPqrSTUvwXYZ' \ --service \ --user 'botuser' # Após a execução inicial como root: # sudo ./meubot.sh # # O systemd criará e habilitará o serviço automaticamente: # meubot.service foi criado com sucesso !! # Habilitando...[OK] | Iniciando...[OK] # # Gerenciar o serviço depois: # sudo systemctl status meubot.service # sudo systemctl stop meubot.service # sudo systemctl start meubot.service # sudo systemctl restart meubot.service # sudo systemctl disable meubot.service while :; do ShellBot.getUpdates --limit 100 --offset "$(ShellBot.OffsetNext)" --timeout 30 for id in $(ShellBot.ListUpdates); do ( case "${message_text[$id]}" in '/start') ShellBot.sendMessage --chat_id "${message_chat_id[$id]}" --text "Bot ativo!" ;; esac ) done done ``` ``` -------------------------------- ### Send Media Files Source: https://context7.com/shellscriptx/shellbot/llms.txt Methods for sending various media types like photos, audio, documents, and videos. These methods accept either a 'file_id' (for files already hosted on Telegram) or a direct HTTP URL. Local files can be specified with a '@' prefix. Captions, formatting, and keyboards are also supported. The example demonstrates sending a photo from a local file with a Markdown caption. ```bash #!/bin/bash source ShellBot.sh ShellBot.init --token '' chat="999999999" # Enviar foto por arquivo local ShellBot.sendPhoto \ --chat_id "$chat" \ --photo '@/home/user/imagem.jpg' \ --caption '*Foto enviada via ShellBot!' \ --parse_mode markdown ``` -------------------------------- ### Receive Telegram Updates with Long Polling Source: https://context7.com/shellscriptx/shellbot/llms.txt This method queries the Telegram server for available updates and loads them into indexed Bash variables. It's the core of the bot's event loop. After each call, variables like 'message_*', 'message_chat_id', and 'message_from_id' become available. The example demonstrates fetching up to 100 updates with a 30-second long polling timeout and iterating through each received update. ```bash #!/bin/bash source ShellBot.sh ShellBot.init --token '' while :; do # Buscar até 100 atualizações com long polling de 30s ShellBot.getUpdates \ --limit 100 \ --offset "$(ShellBot.OffsetNext)" \ --timeout 30 # Iterar sobre cada atualização recebida for id in $(ShellBot.ListUpdates); do ( echo "Atualização [$id]:" echo " Chat ID : ${message_chat_id[$id]}" echo " Usuário : ${message_from_username[$id]}" echo " Texto : ${message_text[$id]}" echo " Tipo obj : ${message_document_file_id[$id]:+documento}" ) & done done ``` -------------------------------- ### Download Files from Telegram Source: https://context7.com/shellscriptx/shellbot/llms.txt Use getFile to obtain the remote file path and downloadFile to download it to a local directory. Ensure the bot is initialized and the destination directory exists. ```bash #!/bin/bash source ShellBot.sh ShellBot.init --token '' --return map destino="$HOME/downloads_bot" mkdir -p "$destino" ``` ```bash while :; do ShellBot.getUpdates --limit 100 --offset "$(ShellBot.OffsetNext)" --timeout 30 for id in $(ShellBot.ListUpdates); do ( # Identificar o file_id do objeto recebido (foto, doc, áudio, sticker, voz) if [[ ${message_photo_file_id[$id]} ]]; then # Foto: pegar a versão de maior resolução (último id separado por |) file_id="${message_photo_file_id[$id]}##*|" else file_id="${message_document_file_id[$id]}${message_audio_file_id[$id]}${message_sticker_file_id[$id]}${message_voice_file_id[$id]}" fi if [[ "$file_id" ]]; then # Obter localização no servidor ShellBot.getFile --file_id "$file_id" # Fazer download usando o caminho retornado no array associativo if ShellBot.downloadFile \ --file_path "${return[file_path]}" \ --dir "$destino"; then ShellBot.sendMessage \ --chat_id "${message_chat_id[$id]}" \ --reply_to_message_id "${message_message_id[$id]}" \ --text "✅ Arquivo salvo em: \" ${return[file_path]}\" --parse_mode markdown fi fi ) & done done ``` -------------------------------- ### Define BotCommands Array Source: https://github.com/shellscriptx/shellbot/wiki/Funções Use this function to define an array of BotCommands. Each command requires a name (1-32 chars) and a description (3-256 chars). ```shell ShellBot.BotCommand --command --description ``` -------------------------------- ### ShellBot: Criar comando para retornar o ID do usuário Source: https://github.com/shellscriptx/shellbot/wiki/Funções Cria um comando que responde com o ID do usuário que o invocou, utilizando a expansão de variáveis para inserir dinamicamente o ID da mensagem. Útil para comandos de identificação. ```bash ShellBot.setMessageRules --name 'retornar_id' --entitie_type bot_command --num_args 1 --command '/meuid' --bot_send_message '*O seu id é:* ${message_from_id}'   --bot_parse_mode markdown ```