Bot en Telegram para Wallet Hive / Telegram bot for Wallet Hive

avatar
(Edited)

Introducción - 800x460.png


Bienvenido a este post donde enseñare como desarrollar tu propio bot con Python, que te permitirá poder consultar desde tu Telegram un resumen de tu Wallet de Hive. Para poder realizar este Bot realizaremos y aprenderemos:

Welcome to this post where I will teach you how to develop your own bot with Python, which will allow you to consult from your Telegram a summary of your Hive Wallet. In order to make this Bot we will make and learn:

  1. Crear un Bot desde Telegram / Create a Bot from Telegram
  2. Obtener el token del Bot para poder conectarnos desde nuestro script en Python / Obtain the Bot token to be able to connect from our Python script.
  3. Hacer funciones en Python para controlar las acciones y retornar mensajes a Telegram / Make functions in Python to control actions and return messages to Telegram.

Para poder realizar lo necesitaremos / In order to be able to do so, we will need:

  1. Tener Telegram descargado / Have Telegram downloaded
  2. Contar con Python3 instalado / Have Python3 installed

Crear un nuevo bot con BotFather / Create a new bot with BotFather

Primero que nada, debemos hacer que Telegram sepa de nuestro Bot, para ellos en el buscador de Telegram buscamos BotFather. Se debe abrir el resultado llamado @BotFather macado con una verificación azul ya que es el único y oficial de Telegram.

First of all, we must let Telegram know about our Bot, for them in the Telegram search engine we search for BotFather. It should open the result called @BotFather macado with a blue check as it is the only and official Telegram.

botfather_1.png

Luego se iniciara un chat con el Bot en el cual con el comando /start o /help te aparecerán los comandos disponibles. El primer comando a ejecutar será /newbot donde te solicitara el nombre del Bot en este caso le colocamos My Hive Wallet Bot ustedes le pueden colocar el que deseen, luego para el username es requerido que el nombre finalice en bot, yo le he colocado my_hive_wallet_bot.

Then it will start a chat with the Bot in which with the command /start or /help will appear the available commands. The first command to execute will be /newbot where you will be asked for the name of the Bot in this case we put My Hive Wallet Bot you can put the one you want, then for the username is required that the name ends in bot, I have placed my_hive_wallet_bot.

botfather_2.png

Y listo ya tenemos nuestro token, recuerda que ese token no lo debes compartir con terceros ya que pueden modificar el comportamiento de tu bot. Al final le pueden agregar la imagen, una descripción, etc ya que son varios las opciones disponibles en el BotFather.

And ready we have our token, remember that this token should not be shared with third parties as they can modify the behavior of your bot. At the end you can add the image, a description, etc. since there are several options available in the BotFather.

Listo con esto ya tenemos nuestro primer bot en Telegram registrado.

With this we now have our first Telegram bot registered.

Programar el bot con Python / Programming the bot with Python

Instalación de módulos requeridos / Installation of required modules::

# Este lo usaremos para hacer el WebScraping
pip3 install bs4
# Para conectarnos con la url de Hive y obtener la data
pip3 install requests
# La librería de Python para conexión y uso de Telegram
pip3 install python-telegram-bot

Iniciamos a programar / We start programming

Primero que nada Creamos un archivo config.py en el cual registramos nuestro token, este archivo fue agregado al git ignore para no compartir el token del bot principal.

First of all we create a config.py file in which we register our token, this file was added to the git ignore in order not to share the token of the main bot.

Iniciamos la estructura de nuestro script para el bot creando un archivo llamado main.py en el cual procedemos a importar los módulos requeridos.

We start the structure of our bot script by creating a file called main.py in which we proceed to import the required modules.

# Import configuration
from config import Config
# Import logging
import logging
# Import telegram
from telegram.ext import (
    Updater,
    CommandHandler
)
# Enable logging
from telegram.utils import helpers
from bs4 import BeautifulSoup
import requests

Registramos las funciones principales que darán acción a nuestro bot

We register the main functions that will give action to our bot

# Iniciaremos el bot
def start(update, context):
    user = update.message.from_user
    bot_msg = "Saludos {}, bienvenido.\n\n"
    .......
    update.message.reply_text(bot_msg)
# Nos retornara los comandos disponibles
def help(update, context):
    """Enviar un mensaje cuando se emite el comando /help"""
    bot_msg = "Comandos disponibles:\n" \
              "/start Inicio del bot\n" \
    .......
    update.message.reply_text(bot_msg)
# Con este comando podremos obtener nuestro resumen
def summary(update, context):
    user = update.message.from_user
    is_valid = search_action(context,user.username)
    ......    
    update.message.reply_text(bot_msg)

Este método es muy importante ya que es quien da inicia al script, aquí procederemos a registrar los eventos registrados anteriormente.

This method is very important since it is the one that starts the script, here we will proceed to register the events previously registered.

def main():
    """Configuración inicial de bot."""

Web Scraping

Para este bot vamos a necesitar consultar la Wallet en Hive y sacar los datos, por ello recurrimos a Web Scraping para sacar los datos de la estructura de la web, registramos un método en el cual según el usuario vamos a obtener la información de la wallet. Si es la primera vez que escuchas el termino y quisieras aprender mas me lo puedes dejar en los comentarios y haré un post solamente de web scraping.

For this bot we will need to query the Wallet in Hive and get the data, so we resort to Web Scraping to get the data from the structure of the web, we register a method in which according to the user we will get the information from the wallet. If this is the first time you hear the term and would like to learn more you can leave it in the comments and I will make a post only about web scraping.

# Método para busqueda de la data con web scraping
def search_action(context,username):
    # Se realiza la busqueda de Data
    parse_url = f'https://wallet.hive.blog/@{username}/transfers'
    url = requests.get(parse_url)
    soup = BeautifulSoup(url.content, 'html.parser')
    results_account = soup.find('h1')
    results = soup.find('div', {'class': 'UserWallet'})

Y listo ya podemos iniciar nuestro bot con el comando python3 main.py vamos a Telegram y podemos interactuar con el.

And now we can start our bot with the command python3 main.py we go to Telegram and we can interact with it.

bot_02.png

bot_1.png

Como podemos ver es grande el potencial de Python como lenguaje de programación, pero esto es solo una pequeña parte de todas las grandes cosas que tiene para nosotros. Espero les allá gustado si tenían esa interrogante de como creaban los bots de Telegram pues aquí ya pueden aprender a crear el suyo.

As we can see the potential of Python as a programming language is great, but this is just a small part of all the great things it has for us. I hope you liked it there, if you were wondering how to create Telegram bots, here you can learn how to create your own.

Máximo Sojo - 800x460.png

Por ahora resta darle las gracias por haber llegado hasta aquí, seguimos siempre aprendiendo y buscando compartir todo cada día. Seguiré realizando publicaciones relacionadas a la programación con el fin de ayudar a muchos que deseen incursionar en este mundo y quizá sientan que es algo para súper genios o imposible, pues no, todo se puede, SI TE ATREVES PUEDES.

For now it remains to thank you for having come this far, we are always learning and looking to share everything every day. I will continue making publications related to programming in order to help many who wish to venture into this world and perhaps feel that it is something for super geniuses or impossible, because no, anything is possible, IF YOU DARE YOU CAN.

Si te ha gustado o tienes alguna pregunta me lo puedes dejar en los comentarios y así saber que voy ayudando, saludos.

If you liked it or have any questions you can leave it in the comments and let me know that I'm helping, greetings.

Los diseños de fotos fueron realizados con la aplicación de diseño Gimp en la distribución de linux debian, los diseños son de mi autoría y el svg utilizado fue descargado de la plataforma gratuita undraw.

The photo designs were made with the design application Gimp in the linux distribution debian, the designs are of my authorship and the svg used was downloaded from the free platform undraw.

Aquí el repositorio del proyecto, puedes descargarlo y crear a partir de allí su propio bot:

Here is the repository of the project, you can download it and create your own bot from there:

https://github.com/maximosojo/myhivewallet-bot



0
0
0.000
1 comments
avatar

Congratulations @maximosojo! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You received more than 300 upvotes.
Your next target is to reach 400 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out the last post from @hivebuzz:

Hive Tour Update - Account creation and Account Recovery steps
Support the HiveBuzz project. Vote for our proposal!
0
0
0.000