Este sitio web usa cookies, puedes ver la política de cookies, aquí
Política de cookies +
Como crear un bot para Telegram en Python

Como crear un bot para Telegram en Python


Autor: n1g1channel 2022-02-10 19:38


En el presente tutorial vamos a aprender a realizar un bot en telegram de forma fácil y sencilla, para el desarrollo utilizaremos Google Colab, y de igual forma necesitamos tener una cuenta cualquiera en telegram.

De igual forma necesitamos contar con Pip3 en nuestro servidor. Para ello te recomiendo leer lo siguiente:

Pip, instalación y conceptos básicos de esta herramienta en Ubuntu 20.04 | Ubunlog

Y ejecutar este comando:
pip3 install pyTelegramBotAPI

Vamos a necesitar las siguientes librerías:
import telebot # Importamos las librería
import requests
import json
De igual forma necesitamos obtener un token en Telegram, para ello le debemos de dar clic a la lupita en Telegram y posteriormente buscar ¨BotFather¨ sin comillas, y crear un bot, una vez lo tengamos creado nos dará un token.

Para ello vamos a crear una variable para almacenarlo en nuestro código de python:
TOKEN = "TU_TOKEN" 

De igual forma vamos a utilizar los siguientes comandos
def getError():
  respuesta = "Algo salió mal con la API"
  return respuesta

# Método para dar un error cuando falla

def getBtc():
    try:
      response = requests.get("https://www.bitstamp.net/api/v2/ticker/btcusd")
      response = response.json()
      return str("{:,.2f}".format(float(response["last"])))
    except:
      return getError()
Para publicar mensajes se utilizara comandos similares al siguiente:
@bot.message_handler(commands=['panas', 'help'])
def send_welcome(message):
    try:
      mensaje = 'Hola @'+getUsuario(message)+ u', '+'El precio del BTC es de: $' + getBtc()
    except:
      mensaje = 'Estoy agarrando señal carnal...'
    bot.reply_to(message, mensaje)
   Video tutorial: 
Código fuente:
!pip3 install pyTelegramBotAPI
import telebot # Importamos las librería
import requests
import json

TOKEN = "TU_TOKEN" 
bot = telebot.TeleBot(TOKEN)

def getError():
  respuesta = "Algo salió mal con la API"
  return respuesta

def getBtc():
    try:
      response = requests.get("https://www.bitstamp.net/api/v2/ticker/btcusd")
      response = response.json()
      return str("{:,.2f}".format(float(response["last"])))
    except:
      return getError()

@bot.message_handler(commands=['panas'])
def sentMessage(message):
    try:
      mensaje = 'Hola, '+'El precio del BTC es de: $' + getBtc()
    except:
      mensaje = 'Estoy agarrando señal carnal...'
    bot.reply_to(message, mensaje)

@bot.message_handler(commands=['panas2'])
def sentMessage(message):
    try:
      mensaje = 'Esta es una prueba'
    except:
      mensaje = 'Estoy agarrando señal carnal...'
    bot.reply_to(message, mensaje)



bot.infinity_polling(timeout=10, long_polling_timeout = 5)
user = bot.get_me()
updates = bot.get_updates()