Exemplo n.º 1
0
def en_rastrear_paquete_guia(mensaje):
    bot.send_chat_action(mensaje.chat.id, 'typing')
    paquete = logic.get_paquete_numero_guia(mensaje.text)
    if paquete:
        informacion = ""
        informacion += f"*Número de guía:* {paquete.numero_guia} \n"
        informacion += f"*Remitente:* {paquete.nombre_remitente} \n"
        informacion += f"*Peso en kg:* {ayudadores.formato_decimal(paquete.peso_kg,2)} \n"
        informacion += f"*Dirección destino:* {paquete.direccion_destino} \n"
        informacion += f"*Dirección recogida:* {paquete.direccion_recogida} \n"
        informacion += f"*Estado actual:* {paquete.estado_actual_objeto.nombre} \n"
        informacion += f"*Fecha del estado actual:* {ayudadores.formato_fecha_bonita(paquete.fecha_estado_actual)} \n"
        informacion += f"*Fecha de creación:* {ayudadores.formato_fecha_bonita(paquete.creado_el)} \n\n"
        informacion += f"*Estados:* \n"
        eventos = paquete.eventos
        indice = len(eventos)
        for evento in eventos:
            informacion += f"{indice}. *{evento.estado.nombre}* el {ayudadores.formato_fecha_bonita(evento.fecha)} \n"
            indice -= 1
        bot.send_message(mensaje.chat.id, informacion, parse_mode="Markdown")
    else:
        bot.send_message(
            mensaje.chat.id,
            f"No existe un paquete para este número de guía *{mensaje.text}* \U00002639",
            parse_mode="Markdown")
Exemplo n.º 2
0
def on_fallback(message):
    bot.send_chat_action(message.chat.id, 'typing')
    sleep(1)

    response = GestorConversacion.get_fallback_message(
        message.text, message.from_user.first_name, config.COMPANIA_SIGNOS)
    bot.reply_to(message, response, parse_mode="Markdown")
Exemplo n.º 3
0
def on_command_help(message):
	bot.send_chat_action(message.chat.id, 'typing')

	bot.send_message(
		message.chat.id, 
		logic.get_help_message (), 
		parse_mode="Markdown") 
Exemplo n.º 4
0
def on_set_cancion(message):
    bot.send_chat_action(message.chat.id, 'typing')
    parts = re.match(r"^(agregar cancion|ag) ([a-zA-Z]{3,20}) ([0-9]{1,2})",
                     message.text, re.IGNORECASE)
    print(parts.groups())

    nombreCancion = (parts[2])
    idtipoMusica = int(parts[3])
    response = ''
    if idtipoMusica > 0:
        nombreUsuario = usuarios.register_usuario(message.from_user.id,
                                                  message.from_user.first_name)
        print(nombreUsuario)
        canciones.register_cancion(nombreCancion, "5", message.from_user.id,
                                   idtipoMusica)
        response = '¡Cancion almacenada con éxito!:'
    else:
        listatipoMusica = tipoMusica.get_tipoMusica()
        if listatipoMusica:
            response = 'Debe seleccionar el ID del tipo de música \n Los tipos de música son: \n'
            for tipomusica in listatipoMusica:
                response += str(
                    tipomusica.id) + ' ' + tipomusica.nombreTipoMusica + '\n'
        else:
            response = 'No existe Tipo de música, debe crearla con {agtm}'

    bot.reply_to(message, f"\U0001F4B0" + response)
Exemplo n.º 5
0
def on_remove_cancion(message):
    bot.send_chat_action(message.chat.id, 'typing')
    parts = re.match(r"^(agregar cancion|rc) ([a-zA-Z]{3,20}) ([0-9]{1,2})",
                     message.text, re.IGNORECASE)
    print(parts.groups())

    nombreCancion = (parts[2])
    idtipoMusica = int(parts[3])
    response = ''
    if idtipoMusica > 0:
        rowdelete = canciones.remover_cancion(nombreCancion,
                                              message.from_user.id,
                                              idtipoMusica)
        if rowdelete > 0:
            response = '¡Cancion removida con éxito!:'
        else:
            response = '¡No fue posible eliminar la cacion, favor verifica los datos!:'
    else:
        listatipoMusica = tipoMusica.get_tipoMusica()
        if listatipoMusica:
            response = 'Debe indicar el ID del tipo de música \n Los tipos de música son: \n'
            for tipomusica in listatipoMusica:
                response += str(
                    tipomusica.id) + ' ' + tipomusica.nombreTipoMusica + '\n'
        else:
            response = 'No existe Tipo de música, debe crearla con {agtm}'

    bot.reply_to(message, f"\U0001F4B0" + response)
Exemplo n.º 6
0
def on_list_earnings(message):
    bot.send_chat_action(message.chat.id, 'typing')
    parts = re.match(r"^(listar ganancias|lg) en ([0-9]{1,2}) de ([0-9]{4})$",
                     message.text,
                     re.IGNORECASE)
    
    #print(parts.groups())
    month = int(parts[2])
    year = int(parts[3])
    
    # Esta forma de validar es un ensayo, para sacar la validación aparte
    mensaje_error = logic.validate_date(month,year)
    if mensaje_error != None:
        bot.reply_to(message, mensaje_error)
        return
    
    earnings = logic.list_earnings (message.from_user.id, month, year)
    text = ""
    total = 0
    
    if not earnings:
        text = f"\U0001F633 No tienes ganancias registradas en {month}/{year}"
    else:
        text = " Listado de ganancias:\n\n"
        for e in earnings:
            total += e.amount
            text += f"| {e.id} | ${e.amount} | ({e.when.strftime('%d/%m/%Y - %H:%M')}) |\n"
        
        text += f"\nTOTAL = ${total}"
        text += "   "
    
    bot.reply_to(message, text, parse_mode="Markdown")
Exemplo n.º 7
0
def on_command_start(message):
    bot.send_chat_action(message.chat.id, 'typing')
    sleep(1)

    bot.send_message(message.chat.id,
                     "Hola, soy un \U0001F916, ¿cómo estás?",
                     parse_mode="Markdown")
Exemplo n.º 8
0
def get_id(m):
    bot.send_chat_action(m.chat.id, 'typing')  #тайпинг бота
    bot.send_message(
        m.chat.id, u"@" + str(m.from_user.username) + ", " +
        "ваш Telegram ID: " + str(m.from_user.id))
    bot.delete_message(m.chat.id,
                       m.message_id)  #Удалить сообщение, содержащее команду
Exemplo n.º 9
0
def on_get_signos(message):
    bot.send_chat_action(message.chat.id, 'typing')
    parts = re.match(
        r"^(consultar signos|cs) ([0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])) ([0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]))$",
        message.text,
        flags=re.IGNORECASE)
    fecha_inicial = parts[2]
    fecha_final = parts[5]

    id_usuario = int(message.from_user.id)
    nombre_user = message.chat.first_name

    if check_user(message, id_usuario):
        signos = GestorConsultas.get_signos(message.from_user.id,
                                            fecha_inicial, fecha_final)
        # En caso de que el usuario este registrado pero no tenga registros de signos vitales se le mostrara un mensaje
        if not signos:
            return bot.reply_to(
                message,
                "No existe registro de signos para el usuario " + nombre_user +
                "\n\n",
                parse_mode="Markdown")

        #si pasa todas las validaciones
        text = "``` Listado de los signos del usuario: " + nombre_user + "\n"
        text += f" Desde {fecha_inicial} hasta {fecha_final} \n"
        text += f"|ID|Sistolica|Diastolica|F.Cardiaca|Peso|Observación| \n"
        for sv in signos:
            text += f"| {sv.id}|   {sv.pas}   |   {sv.pad}     | {sv.fc}   | {sv.peso} |{sv.observacion}| \n"
        text += "```"
        return bot.reply_to(message, text, parse_mode="Markdown")
Exemplo n.º 10
0
def on_get_balance(message):
    bot.send_chat_action(message.chat.id, 'typing')
    balance = logic.get_balance (message.from_user.id)
    text = "\U0000274C Aún no tienes una cuenta asociada, ejecuta /start para arreglarlo."
    if balance != None:
        text = f"Tu saldo actual es ${balance}"
    bot.reply_to(message, text)
Exemplo n.º 11
0
def on_set_paciente(message):
    bot.send_chat_action(message.chat.id, 'typing')

    parts = re.match(r"^(registrar paciente|rp) ([0-9]*)$",
                     message.text,
                     flags=re.IGNORECASE)

    #Si es un Medico
    if GestorConsultas.validar_medico(message.from_user.id):
        return bot.reply_to(
            message,
            f"\U0001FA7A *Dr(a). {message.from_user.first_name}*, no puede implementar este comando, solo lo pueden usarlo pacientes.",
            parse_mode="Markdown")

    documento = int(parts[2])
    #si existe paciente
    paciente = GestorPacientes.get_paciente(documento)
    if paciente:
        return bot.reply_to(message,
                            f"Paciente ya registrado.",
                            parse_mode="Markdown")

    #si usuario ya registrado
    usuario = GestorConsultas.existencia_usuario(message.from_user.id)
    if usuario:
        return bot.reply_to(
            message,
            f"Este usuario ya está registrado con el documento *{usuario.documento}*",
            parse_mode="Markdown")

    #Usuario no existente se procede al registro
    GestorPacientes.set_paciente(
        message.from_user.id, documento,
        message.chat.first_name + " " + message.chat.last_name, 1)
    return bot.reply_to(message, f"Paciente registrado.")
Exemplo n.º 12
0
def on_set_signos(message):
    bot.send_chat_action(message.chat.id, 'typing')

    parts = re.match(
        r"^(registrar signos|rs) ([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*[.]?[0-9]*) ([0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))$",
        message.text,
        flags=re.IGNORECASE)

    pas = int(parts[2])
    pad = int(parts[3])
    fc = int(parts[4])
    peso = float(parts[5])
    fecha_toma = parts[6]

    id_usuario = message.from_user.id

    #Pasa todas las validaciones pruebas
    if check_user(message, id_usuario):
        bot.send_message(
            message.chat.id,
            GestorConversacion.get_registro_signos(
                message.chat.first_name + " " + message.chat.last_name, pas,
                pad, fc, peso, fecha_toma),
            parse_mode="Markdown")
        bot.register_next_step_handler(message,
                                       GestorMediciones.step_2_registro_signos,
                                       pas, pad, fc, peso, fecha_toma)
Exemplo n.º 13
0
def on_fallback(message):
    bot.send_chat_action(message.chat.id, 'typing')
    sleep(1)

    bot.reply_to(
        message,
        "\U0001F63F Ups, no entendí lo que me dijiste.")
Exemplo n.º 14
0
def on_command_about(message):
	bot.send_chat_action(message.chat.id, 'typing')

	bot.send_message(
		message.chat.id, 
		logic.get_about_this(config.VERSION), 
		parse_mode="Markdown")    
Exemplo n.º 15
0
def on_remove_record(message):
	bot.send_chat_action(message.chat.id, 'typing')

	parts = re.match(
		r"^(remover|r) (ganancia|g|gasto|gg) ([0-9]+)$", 
		message.text)

	record_type = parts[2]
	index = int(parts[3])
	
	if record_type not in ["ganancia", "g", "gasto", "gg"]:
		bot.reply_to(message, f"Error, tipo de registro inválido: {record_type}")
		return

	if index < 0:
		bot.reply_to(message, f"Error, índice inválido: {index}")
		return

	response = False

	if record_type == "ganancia" or record_type == "g":
		response = logic.remove_earning (message.from_user.id, index)
	elif record_type == "gasto" or record_type == "gg":
		response = logic.remove_spending (message.from_user.id, index)

	if response:
		bot.reply_to(message, f"Registro removido: {record_type}, {index}")
	else:
		bot.reply_to(message, f"No se pudo remover el registro: {index}")
Exemplo n.º 16
0
def on_list_earnings(message):
    bot.send_chat_action(message.chat.id, 'typing')
    parts = re.match(
        r"^(listar ganancias|lg) en ([0-9]{1,2}) de ([0-9]{4})$",
        message.text)
    month = int(parts[2])
    year = int(parts[3])
    if month < 1 or month > 12:
        bot.reply_to(message, f"Error, mes inválido: {month}")
        return
    if year < 1990 or year > 2050:
        bot.reply_to(message, f"Error, año inválido: {year}")
        return
    earnings = logic.list_earnings (message.from_user.id, month, year)
    text = ""
    total = 0
    if not earnings:
        text = f"\U0001F633 No tienes ganancias registradas en {month}/{year}"
    else:
        text = "``` Listado de ganancias:\n\n"
        for e in earnings:
            total += e.amount
            text += f"| {e.id} | ${e.amount} | ({e.when.strftime('%d/%m/%Y - %H:%M')}) |\n"
        text += f"\nTOTAL = ${total}"
        text += "```"
    bot.reply_to(message, text, parse_mode="Markdown")
Exemplo n.º 17
0
def on_in_vehiculo(message):
    bot.send_chat_action(message.chat.id, 'typing')

    parts = re.match(r"(^)registrar ingreso|ingreso|ring placa ([a-zA-Z0-9_ ]*) en la zona ([a-zA-Z0-9_ ]*)($)", message.text, re.IGNORECASE)

    #Ejemplo: ring placa UES070 en la zona ZN02

    try:
        placaVehiculo = parts.group(2)
        zonaVehiculo = parts.group(3)

        obtenerPlaca = logic.get_placa (placaVehiculo)
        
        if  not obtenerPlaca:  
            bot.reply_to(message, f"🚨 El vehículo con placa {placaVehiculo} no se encuentra registrado")
        else:
            disponibilidad = logic.get_disponibilidad_zona(zonaVehiculo)

            estado = float(0); 

            if disponibilidad == True:
                control = logic.ingresar_vehiculo(message.from_user.id, placaVehiculo, zonaVehiculo)
                logic.update_dispo_zona(zonaVehiculo, estado)
                bot.reply_to(
                message,
                f"🚗 Vehículo Ingrezado a la Zona:  {zonaVehiculo}" if control == True
                else "🙈 Tuve problemas ingresando el Vehiculo, ejecuta /start y vuelve a intentarlo") 
            else:    
                bot.reply_to(message, f"⚠️ Zona: {zonaVehiculo} no se encuentra disponible") 
    except:
            bot.reply_to(message, f"💩 Tuve problemas ingresando el Vehiculo, valida la zona y placa, ejecuta /start y vuelve a intentarlo")
Exemplo n.º 18
0
def send_meaning(message):
    """Priority to search for a word:
    dict. 1 -> dict. '3' -> in the exact place at the I-net.
    """
    chat_id = message.chat.id
    bot.send_chat_action(chat_id, 'typing')
    
    try:
        cmd_pattern = _cmd_pattern('meaning')
        text = message.text
        word = re.fullmatch(cmd_pattern + '\s*([-а-яё]+)', text).group(1)
    except:
        try:
            text = message.reply_to_message.text
            word = re.fullmatch(WORDS_GAME_PATTERN, text).group(1)
        except:
            msg = """Не распознано слово. Напиши либо в ответ на сообщение, \
где искомое слово, либо `/meaning слово`."""
            bot.send_message(chat_id, msg,
                             reply_to_message_id=message.message_id,
                             parse_mode='Markdown')
            return
    from functions import d as d0
    order = [1, '3']
    def by_rule(kid):
        if kid == 1:
            for a, q in d.items():
                a = a.replace(')', '')
                a = a.replace('(', ',')
                a = a.lower().split(',')
                a = map(lambda ph: ph.strip(), a)

                if word.lower() in a:
                    bot.send_message(chat_id, q,
                        reply_to_message_id=message.message_id)
                    return 0
        elif kid == '3':
            for k in d:
                if k.lower() == word.lower():
                    meaning = d[k]
                    bot.send_message(chat_id, meaning,
                        reply_to_message_id=message.message_id)
                    return 0
    for k in order:
        try:
            d = d0[k]
            if by_rule(k) != 0:
                continue
            return
        except:
            continue
        del d
    del d0, order, by_rule

    url = f"https://loopy.ru/?word={word}&def="
    
    if (sc := (r := requests.get(url)).status_code) == 404:
        msg = f"Слово {word!r} не найдено в словаре."
        bot.send_message(chat_id, msg)
Exemplo n.º 19
0
def en_registrar_paquete_direccion_envio(mensaje):
    bot.send_chat_action(mensaje.chat.id, 'typing')
    paquete = logic.obtener_paquete_creacion(mensaje.from_user.id)
    datos = {'direccion_destino': mensaje.text}
    logic.actualizar_datos_modelo(paquete, datos)
    pregunta = '¿En qué dirección quieres que recojamos el paquete?'
    markup = telebot.types.ForceReply(selective=False)
    bot.send_message(mensaje.chat.id, pregunta, reply_markup=markup)
Exemplo n.º 20
0
def comando_start(mensaje):
    bot.send_chat_action(mensaje.chat.id, 'typing')
    logic.registrar_cliente(mensaje.from_user.id, mensaje.from_user.first_name,
                            mensaje.from_user.last_name)
    markup = logic.construir_menu(mensaje.from_user.id)
    bot.send_message(mensaje.chat.id,
                     text="Estas son las opciones que te puedo ofrecer",
                     reply_markup=markup)
Exemplo n.º 21
0
def en_registrar_paquete_remitente(mensaje):
    bot.send_chat_action(mensaje.chat.id, 'typing')
    paquete = logic.obtener_paquete_creacion(mensaje.from_user.id)
    datos = {'nombre_remitente': mensaje.text}
    logic.actualizar_datos_modelo(paquete, datos)
    pregunta = '¿En kilogramos cuánto pesa tu paquete?'
    markup = telebot.types.ForceReply(selective=False)
    bot.send_message(mensaje.chat.id, pregunta, reply_markup=markup)
Exemplo n.º 22
0
def on_command_start(message):
    bot.send_chat_action(message.chat.id, 'typing')
    bot.send_message(message.chat.id,
                     logic.get_welcome_message(bot.get_me()),
                     parse_mode="Markdown")
    bot.send_message(message.chat.id,
                     logic.get_help_message(),
                     parse_mode="Markdown")
    logic.register_account(message.from_user.id)
Exemplo n.º 23
0
def on_command_start(message):
    bot.send_chat_action(message.chat.id, 'typing')
    bot.send_message(message.chat.id,
                     util.get_welcome_message(bot.get_me()),
                     parse_mode="Markdown")

    bot.send_message(message.chat.id,
                     util.get_help_message(),
                     parse_mode="Markdown")
Exemplo n.º 24
0
def on_earn_money(message):
    bot.send_chat_action(message.chat.id, 'typing')
    parts = re.match(r"^(gane|gané|g) ([+-]?([0-9]*[.])?[0-9]+)$",message.text,re.IGNORECASE)
    # print (parts.groups())
    amount = float(parts[2])
    control = logic.earn_money (message.from_user.id, amount)
    bot.reply_to(
        message,
        f"\U0001F4B0 ¡Dinero ganado!: {amount}" if control == True
        else "\U0001F4A9 Tuve problemas registrando la transacción, ejecuta /start y vuelve a intentarlo")
Exemplo n.º 25
0
def on_fallback(message):
    bot.send_chat_action(message.chat.id, 'typing')
    sleep(1)

    response = logic.get_fallback_message(message.text)
    bot.reply_to(message, response)

    bot.send_message(message.chat.id,
                     logic.get_help_message(),
                     parse_mode="Markdown")
Exemplo n.º 26
0
def on_spend_money(message):
    bot.send_chat_action(message.chat.id, 'typing')
    parts = re.match(
        r"^(gaste|gasté|gg) ([+-]?([0-9]*[.])?[0-9]+)$",
        message.text)
    amount = float(parts[2])
    control = logic.spend_money (message.from_user.id, amount)
    bot.reply_to(message,
        f"\U0001F4B8 ¡Dinero gastado!: {amount}" if control == True
        else "\U0001F4A9 Tuve problemas registrando la transacción, ejecuta /start y vuelve a intentarlo")
Exemplo n.º 27
0
def command_id(m):
    bot.delete_message(m.chat.id, m.message_id)
    try:
        bot.send_chat_action(m.chat.id, 'typing')  #тайпинг бота
        sent = bot.send_message(
            m.chat.id, u"@" + str(m.from_user.username) + ", " +
            "ваш Telegram ID: " + str(m.from_user.id))
        sleep(10)
        bot.delete_message(m.chat.id, sent.message_id)
    except Exception:
        Error(m, bot).error()
Exemplo n.º 28
0
def on_producto(message):
    bot.send_chat_action(message.chat.id, 'typing')
    sleep(1)
    parts = re.match(
        r"^multiplicar ([+-]?([0-9]*[.])?[0-9]+) y ([+-]?([0-9]*[.])?[0-9]+)$",
        message.text)
    # print (parts.groups())
    oper1 = float(parts[1])
    oper2 = float(parts[3])
    result = oper1 * oper2
    bot.reply_to(message, f"\U0001F522 Resultado: {result}")
Exemplo n.º 29
0
def es(message):
    bot.send_chat_action(message.chat.id, 'typing')
    listacanciones = canciones.get_canciones()
    response = ''
    if listacanciones:
        for cancion in listacanciones:
            response += str(cancion.id) + ' ' + cancion.nombreCancion + '\n'
    else:
        response = 'No tienes canciones almacenadas por el momento'

    bot.reply_to(message, f"\U0001F3BC ¡Tus canciones son: \n" + response)
Exemplo n.º 30
0
def comando_menu(mensaje):
    bot.send_chat_action(mensaje.chat.id, 'typing')
    logic.generar_numero_guia()
    markup = logic.construir_menu(mensaje.from_user.id)
    if (markup != None):
        bot.send_message(mensaje.chat.id,
                         text="Estas son las opciones que te puedo ofrecer",
                         reply_markup=markup)
    else:
        bot.send_message(
            mensaje.chat.id,
            text="Por favor ejecuta el comando /start para iniciar el bot")