ZipBot: Telegram Bot que Compacta Arquivos
Nos posts anteriores sobre bots para o Telegram, eu demonstrei a implementação de diversas funcionalidades presentes na API do Telegram que podem ser usadas no desenvolvimento de bots. Dentre essas funcionalidades está o envio e recebimento de imagens pelo bot. Contudo, apesar do exemplo descrito ter sido bastante direto e conciso, acho que ainda faltou um exemplo “mais real” da aplicação desse tipo de recurso.
Com o objetivo de mostrar um exemplo mais claro de envio e recebimento de arquivos e aplicar a API do Telegram para a criação de novos recursos para bots, neste post iremos implementar um bot que recebe uma imagem, compacta em formato ZIP e envia o arquivo gerado ao usuário.
Gostou da ideia que vamos implementar? Vamos lá! kkkk
Basicamente, na implementação do bot serão utilizados três métodos da API do Telegram, são eles: sendMessage, e sendDocument. O sendMessage já foi muito explorado em diversos posts aqui do blog, dessa forma não será preciso entrar em detalhes (Caso seja sua primeira visita aqui no blog, dá uma olhada nesse post). Do mesmo modo, o método sendPhoto já foi analisado no post sobre envio de imagens no Telegram. Portanto, neste post, iremos focar em entender como o sendDocument pode ser usado para atender as necessidades do nosso exemplo.
A tabela abaixo descreve alguns dos parâmetros que fazem parte da chamada ao método sendDocument da API do Telegram. Nessa tabela só estão descritos os parâmetros que iremos fazer uso, mas esse método possui muitos outros que são opcionais.
Agora que já conhecemos o sendDocument, podemos partir para a implementação do bot. Essa implementação será baseada no código-fonte dos exemplos de bot aqui do blog (Você pode encontrar os fontes no nosso repositório no GitHub), porém com algumas modificações.
A fim de iniciar a implementação do comportamento do nosso bot, criaremos um arquivo chamado bot.php
. Esse arquivo, o qual o fonte pode ser visto abaixo, processa as mensagens enviadas pelo usuário e responde de acordo com o comando que foi entendido.
Resumidamente, de acordo com o código acima, o nosso bot só responderá às mensagens que contenham imagem, qualquer outro tipo de mensagem será respondida como “Não entendida”.
Na linha 21, caso a mensagem enviada pelo usuário possua o atributo photo
, o bot dará início ao processamento da imagem recebida. Como tratar o recebimento da mensagem que inclui uma imagem já foi explicado em , vamos focar apenas em compactar esta imagem e responder ao usuário.
Ao receber a imagem, ela será processada através dos métodos saveFile
e zipFile
, presentes nas linhas 26 e 29 do fonte, respectivamente. Esses dois métodos foram implementados em um arquivo à parte chamado zipfile.php
, o qual será disponibilizado no final do post.
O método saveFile
salva a imagem recebida numa pasta do nosso servidor. Porém, para realizar o armazenamento dessa imagem, é preciso baixá-la do servidor do Telegram, uma vez que na mensagem é fornecido apenas o seu ID, no caso, o file_id
. Para isso, precisamos utilizar a URL abaixo para obter o JSON que informa o endereço da imagem no servidor do Telegram:
Após obter o JSON, o qual pode ser visto abaixo, é possível notar que o endereço se encontra no atributo file_path
do objeto result
.
Agora que já sabemos o caminho para acessar a imagem no servidor do Telegram, basta acessar o link abaixo para obter a imagem e salvá-la no servidor.
O código-fonte do método saveFile
pode ser visto a seguir:
Como a imagem já armazenada, podemos iniciar a implementação da compactação no formato ZIP. Utilizaremos a classe ZipArchive
do PHP para isso. Por meio dessa classe, no método zipFile
, é criado um arquivo ZIP que, por sua vez, recebe a imagem salva. Após a criação desse arquivo ZIP, ele fica disponível no servidor para ser enviado ao usuário.
Para responder ao usuário com o arquivo Zip recém-criado, é necessário implementar o sendDocument da API do Telegram. Na linha 35 do bot.php
é possível visualizar essa implementação, passando como parâmetro a URL com o caminho para o arquivo ZIP em nosso servidor. Após esse arquivo ter sido enviado ao usuário, tanto ele quanto a imagem são deletados do servidor.
Feito isso, já podemos testar o bot! Lembrando que já estou supondo que você já configurou seu bot junto ao Telegram através do Webhook.
Bom, é isso! =)
Para testar o bot desenvolvido neste post, procure por “zip_brasil_bot” no app do Telegram ou acesse o seguinte link: https://telegram.me/zip_brasil_bot. Ao iniciar uma conversa com o bot, basta enviar uma imagem.
Para visualizar o código-fonte do bot que foi desenvolvido neste tutorial, acesse: Zip Bot.
O bot desenvolvido neste tutorial foi hospedado na Umbler.
Ficou com alguma dúvida? Então, deixa um comentário.
Originally published at https://luizmarcus.com on October 29, 2021.
Ten articles before and after
What is telegram messenger?. Telegram is a messenger application… – Telegram Group
The Indra Capital Ecosystem — Part II— IndraX, YieldWallet.io and Airavat – Telegram Group
Telegram HTTP API With Python — Sending Messages Programatically – Telegram Group
CryptoChat: Un chatbot hecho con rasa sobre criptomonedas – Telegram Group
TRX1 Dev Blog #9 (September 2021) – Telegram Group
PyCryptoBot Telegram Bot. This really is a very exciting new… – Telegram Group
Building a Covid-19 Fact-Check Tele Bot Using Machine Learning – Telegram Group
Python and Telegram bot, how to collaborate them to make processes simplified? – Telegram Group
How to Bulk Invite Members in your Telegram Group or Channel – Telegram Group