¡Hola, Hivers!
Durante las últimas semanas he estado creando aplicaciones que tenía en pendientes como el bot de Telegram para delegar RC sugerido por , así que procedí a crearlo.
La función básica que tiene el bot es delegar RC a otros usuarios de Hive y quisimos añadir más cosas tales como:
- Estadísticas de las cuentas de Hive
- Precios de las monedas Hive y HBD
Así que procedí crear el bot en Telegram usando Python y la libreria de Python para conectarnos a las API de Telegram Ver librería
Para conectarme a la blockchain Hive utilicé Beem la librería de Python para conectarme a Hive:
Aquí muestro la función principal para conectarme a Hive y extraer los datos de un usuario de Hive:
def get_user_info(username):
try:
account = Account(username, blockchain_instance=hive)
reputation = account.get_reputation()
reputation = round(reputation)
hive_power = account.get_steem_power(onlyOwnSP=True)
delegated_power_resta = account.get_steem_power(onlyOwnSP=False)
delegated_power = delegated_power_resta - hive_power
VP = account.get_voting_power()
VP = round(VP, 2)
vp_value = account.get_voting_value()
vp_value = round(vp_value, 2)
recharge_time = account.get_recharge_timedelta(voting_power_goal=100, starting_voting_power=VP)
rc_percentage = account.get_rc_manabar()['current_pct']
recharge_arrow = arrow.utcnow().shift(seconds=recharge_time.total_seconds())
formatted_time = recharge_arrow.humanize(locale='es', only_distance=True)
voting_power_time = formatted_time
print ("tiempo")
print (voting_power_time)
blog_posts = account.get_blog(limit=10)
blog_posts_by_username = [post for post in blog_posts if post['author'] == username and Comment(post['authorperm']).is_main_post()]
last_post = Comment(blog_posts_by_username[0]['authorperm'])['created'] if blog_posts_by_username else None
created_date = account['created']
created_datetime = arrow.get(created_date).to('local')
now = arrow.utcnow().to('local')
age = created_datetime.humanize(locale='es', only_distance=True)
age_str = age
post_datetime = arrow.get(last_post).to('local')
age_post = post_datetime.humanize(locale='es', only_distance=True)
peakd_url = f"https://peakd.com/@{username}"
hive_links = f"{peakd_url}"
comment_capacity, vote_capacity = get_comment_capacity(username)
return {
'username': username,
'reputation': reputation,
'hive_power': hive_power,
'delegated_power': delegated_power,
'last_post': age_post,
'hive_total': delegated_power_resta,
'created_date': age_str,
'hive_links': hive_links,
'VP': VP,
'vp_value': vp_value,
'voting_power_time': voting_power_time,
"rc_percentage": rc_percentage,
"comment_capacity": comment_capacity, # Agregar capacidad de comentarios
"vote_capacity": vote_capacity # Agregar capacidad de votos
}
except Exception as e:
print(f"Error getting user info: {e}")
return None
Aquí el resultado:
Ahora quiero mostrar la función de ..coin
Que me arroja el resultado del precio actual del Hive:
Este precio se actualiza cada 5 min, así que añadir la función caché para evitar hacer tantas peticiones a las API de Coingeko:
Solo agregué esto:
if time.time() - cache["timestamp"] <= CACHE_DURATION:
return cache["hive_price"], cache["hive_change"], cache["hbd_price"], cache["hbd_change"], cache["btc_price"], cache["btc_change"]
El archivo caché guarda la información de la siguiente manera:
{"hive_price": 0.415301, "hive_change": -0.68981, "hbd_price": 1.008, "hbd_change": -0.22975, "btc_price": 28312, "btc_change": 0.79663, "timestamp": 1681097302.0855346}
También hay una limitación de tiempo para solicitar precio por usuario, así evito que un usuario puede hacer muchas solicitudes en periodo corto de tiempo.
Por último quiero mostrar como ejecuta el comando de delegar RC y esta función no la puede ejecutar cualquiera por ahora, solo tenemos acceso Eddie y yo.
Actualmente, está en fase prueba en el canal de Hive en español y la idea es probarla allí para luego corregir los errores y pasarla a un canal de Telegram diferente para evitar el spam.
En los próximos días estaré actualizando las funciones y visualizando que otra función añadir.
¿Qué función te gustaría tener con este bot?