Como criar um Bot no Telegram com NodeJS
Nesse artigo abordarei de forma simples, clara e objetiva como um iniciante pode criar um Bot de Telegram 100% funcional, utilizando a linguagem javascript através do NodeJs.
Para quem não me conhece eu sou o Andre Muniz e escrevo para o Medium a pelo menos um ano. Sou especialista em Segurança da Informação e Ethical Hacking. Cheguei onde estou graças ao treinamento Guia Hacker, o qual recomendo para todos que desejam iniciar no mundo da computação, seja simplesmente para aprender a se tornar um programador ou até mesmo para virar um hacker profissional.
Sem mais delongas, vamos ao que interessa e por a mão na massa!
Para começar você vai precisar instalar o Telegram no seu celular e criar uma conta para utilizar o aplicativo. Também vai precisar instalar o NodeJS. Nesse tutorial estarei utilizar o Visual Studio Code como ambiente de desenvolvimento.
Abra o Visual Studio Code e crie uma pasta para o projeto com o nome de sua preferência.
Crie um arquivo chamado app.js, dentro da pasta do projeto, esse será nosso arquivo principal, onde ficará o código do nosso bot.
Abra o terminal pelo VS Code, através do menu superior.
Com o terminal aberto digite o comando “npm init” e de enter. Uma série de pergunta serão feitas, basta dar enter até que elas acabem.
Agora rode o comando “npm install node-telegram-bot-api”, esse comando instalará a biblioteca e as dependências referentes ao bot do telegram.
Agora dentro do arquivo “app.js” adicione o seguinte código:
const TelegramBot = require( `node-telegram-bot-api` )
const BOT_TOKEN = '{SEU_TOKEN_AQUI}'
const bot = new TelegramBot( BOT_TOKEN, { polling: true } )
Okay. Agora precisamos adquiri um token para ser inserido na segunda linha do código. Para isso vamos ao Telegram e procure por @BotFather (antecede ao símbolo azul que indica uma conta oficial)
Envie para o bot a seguinte mensagem:
/newbot
Ele pedira para que você dê nomes ao bot. E em seguida irá te entregar a chave do bot. Segue exemplo:
Volte no app.js e altere o {SEU_TOKEN_AQUI} pelo seu token, dado pelo BotFather.
Agora adicione o seguinte código no seu app.js. (esse é um script de exemplo que criei).
bot.on(/\/start/, (msg) => {
bot.sendMessage(msg.chat.id, `Olá ${msg.from.first_name}, seja muito bem vindo!\nMeus comandos são:\n/ping\n/pong`)
})bot.onText(/\/ping/, (msg) => {
bot.sendMessage(msg.chat.id, `pong`)
})bot.onText(/\/pong/, (msg) => {
bot.sendMessage(msg.chat.id, `ping`)
})
E então execute no terminal o comando:
node app.js
Esse comando colocará seu bot para rodar.
Agora procure pelo seu bot no telegram (o @BotFather terá deixado um link direto para ele. Você também pode procurar pelo nome que deu a ele)
Agora já pode brincar com o seu bot.
Para para-lo dê um ctrl+c no terminal. Você pode editar o código a vontade para criar seus próprios robos.
Segue o link da biblioteca utilizada, onde você poderá encontrar a documentação e mais exemplos: https://github.com/yagop/node-telegram-bot-api
Espero que tenha gostado.
Não deixe de conferir meus outros posts como por exemplo esse daqui -> Como virar um hacker profissional pelo celular
Dê bônus você pode aproveitar para pegar um pdf sobre como se tornar um Hacker, gratuitamente através deste link -> Pdf Hacker
Até a próxima!
Ten articles before and after
data-rh=”true”>Airdrop 20 WYD ($50) – ALVIN LAGONERO – Medium – Telegram Group
Telegram Bot in JAVA| by Naveen Kumar M N – Telegram Group
Improved node setup and monitoring for the validator of the Agoric testnet – Telegram Group
Cricket Score Alert Telegram Bot using EspnCricinfo – Telegram Group
Get Telegram Group Members with Python and Telethon – Telegram Group
.Net Core Console Uygulması İle Telegram Botu Geliştirmek – Telegram Group
Creating a Telegram Bot: Full Beginner’s Guide 2021 – Telegram Group
Sending a message from Python to a Telegram chat: the simplest way – Telegram Group
Create a telegram bot – Telegram Group
Bot Telegram Untuk Membantu Sekolah/Kuliah Kamu – Telegram Group