Exemplo n.º 1
0
def catch_all_if_private(update, context):
    """Reply to any message not handled (if not sent to a group/channel)."""

    chat = models.create_chat_obj(update)

    if chat.type == "private":
        functionsLogger.debug(
            f"catch_all: {update.message.chat.type} to @{update.message.chat.username}"
        )
        return send_instructions_message(update, context)
Exemplo n.º 2
0
def cmd_chat_activate(update, context):
    """Set chat's activated status to True."""

    chat = models.create_chat_obj(update=update)
    activateMessage = chat.toggle_subscription_callback(chat.activate)

    context.bot.send_message(
        chat_id=update.effective_chat.id,
        reply_to_message_id=update.message.message_id,
        text=activateMessage,
        parse_mode="markdown",
    )
Exemplo n.º 3
0
def cmd_chat_subscription_status(update, context):
    """Send chat's subscription status."""

    chat = models.create_chat_obj(update=update)

    subscriptionStatus = chat.check_subscription_status()
    subscriptionStatusMessage = chat.get_subscription_status_message(subscriptionStatus)

    context.bot.send_message(
        chat_id=update.effective_chat.id,
        reply_to_message_id=update.message.message_id,
        text=subscriptionStatusMessage,
        parse_mode="markdown",
    )
Exemplo n.º 4
0
def cmd_chat_toggle_activated(update, context):
    """Toggle chat's activated status"""

    chat = models.create_chat_obj(update=update)
    toggleMessage = chat.toggle_subscription_callback(chat.toggle_activated)

    try:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            reply_to_message_id=update.message.message_id,
            text=toggleMessage,
            parse_mode="markdown",
        )
    except Exception as error:
        functionsLogger.error(f"Unexpected error: {error})")
Exemplo n.º 5
0
def cmd_chat_unsubscribe_alerts(update, context):
    """Unsubscribe chat and/or CEP."""

    textArgs = update.message.text.split(" ")

    try:
        cep = textArgs[1]
    except:
        cep = None

    chat = models.create_chat_obj(update)
    unsubscribeResult = chat.unsubscribe_chat(cep)
    unsubscribeMessage = chat.get_unsubscribe_message(unsubscribeResult, cep=cep)

    context.bot.send_message(
        chat_id=update.effective_chat.id,
        reply_to_message_id=update.message.message_id,
        text=unsubscribeMessage,
        parse_mode="markdown",
    )
Exemplo n.º 6
0
def cmd_chat_subscribe_alerts(update, context):
    """Subscribe chat and/or CEP."""

    textArgs = update.message.text.split(" ")

    try:
        cep = bot_utils.parse_CEP(update, context, cepRequired=False)
    except Exception:
        subscribeMessage = bot_messages.invalidZipCode.format(textArgs=textArgs[0])
    else:
        chat = models.create_chat_obj(update)
        subscribeResult = chat.subscribe_chat(cep)
        subscribeMessage = chat.get_subscribe_message(subscribeResult, textArgs, cep)

    context.bot.send_message(
        chat_id=update.effective_chat.id,
        reply_to_message_id=update.message.message_id,
        text=subscribeMessage,
        parse_mode="markdown",
    )
Exemplo n.º 7
0
def cmd_chat_unsubscribe_alerts(update, context):
    """Unsubscribe chat and/or CEP."""

    textArgs = update.message.text.split(" ")

    try:
        cep = bot_utils.parse_CEP(update, context, cepRequired=False)
    except Exception as error:
        functionsLogger.error(
            f"Unknown error when parsing CEP for subscribed chat: {error}."
        )
        unsubscribeMessage = bot_messages.invalidZipCode.format(textArgs=textArgs[0])
    else:
        chat = models.create_chat_obj(update)
        unsubscribeResult = chat.unsubscribe_chat(cep)
        unsubscribeMessage = chat.get_unsubscribe_message(unsubscribeResult, cep)

    context.bot.send_message(
        chat_id=update.effective_chat.id,
        reply_to_message_id=update.message.message_id,
        text=unsubscribeMessage,
        parse_mode="markdown",
    )
Exemplo n.º 8
0
def cmd_alerts_CEP(update, context):
    """Fetch and send active high-risk alerts for given CEP (zip code)."""

    functionsLogger.debug("Getting alerts by CEP (zip code)...")

    textArgs = update.message.text.split(" ")

    try:
        cep = bot_utils.parse_CEP(update, context, cepRequired=False)
        city = viacep.get_cep_city(cep)
        if not (cep or city):
            raise pycep.excecoes.ExcecaoPyCEPCorreios

        # Include moderate alerts
        alerts = list(models.INMETBotDB.alertsCollection.find({"cities": city}))
        check_and_send_alerts_warning(update, context, alerts, city)
    except (
        pycep.excecoes.ExcecaoPyCEPCorreios,
        KeyError,
        Exception,
    ) as cepError:  # Invalid zip code
        message = bot_messages.invalidZipCode.format(textArgs=textArgs[0])
        functionsLogger.warning(
            f'{cepError} on cmd_alerts_CEP. Message text: "{update.message.text}"'
        )
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            reply_to_message_id=update.message.message_id,
            text=message,
            parse_mode="markdown",
        )

        chat = models.create_chat_obj(update=update)
        if chat.subscribed:
            checkingForSubscribed = context.bot.send_message(
                chat_id=update.effective_chat.id,
                reply_to_message_id=update.message.message_id,
                text="*[🛠 BETA]* Irei checar os CEPs cadastrados no chat:",
                parse_mode="markdown",
            )

            # STUB:
            for cep in chat.CEPs:
                try:
                    city = viacep.get_cep_city(cep)
                    functionsLogger.debug(f"- Checking {city}...")
                except Exception as error:
                    functionsLogger.warning(f"Viacep error: {error}")
                    continue

                # Get alerts, by city, that weren't notified to this chat
                alerts = list(models.INMETBotDB.alertsCollection.find({"cities": city}))
                if alerts:
                    print("tem alerta o carai")
                    # Any alerts here are to be sent to the chat,
                    # since they affect a zip code and the chat hasn't been notified yet
                    alertCounter = 1
                    alertMessage = ""
                    functionsLogger.info(f"-- Existing alert for {city}. --")
                    for alert in alerts:
                        if alertCounter >= bot_messages.MAX_ALERTS_PER_MESSAGE:
                            try:
                                print(
                                    chat.id,
                                )
                                context.bot.send_message(
                                    chat_id=chat.id,
                                    text=alertMessage,
                                    parse_mode="markdown",
                                    disable_web_page_preview=True,
                                )
                            except Exception as error:
                                functionsLogger.error(
                                    f"ERRO: não foi possível enviar mensagem para {chat.id} ({chat.title}): {error}. Removendo chat do BD..."
                                )
                                models.INMETBotDB.subscribedChatsCollection.delete_one(
                                    {"chatID": chat.id}
                                )

                                alertMessage = ""
                                alertCounter = 1

                        alertObj = models.Alert(alertDict=alert)
                        alertMessage += alertObj.get_alert_message(city)
                        functionsLogger.info(
                            f"-- Notifying chat {chat.id} about alert {alert['alertID']}... --"
                        )

                        models.INMETBotDB.alertsCollection.update_one(
                            {"alertID": alert["alertID"]},
                            {"$addToSet": {"notifiedChats": chat.id}},
                        )
                        alertCounter += 1

                    # "Footer" message after all alerts
                    alertMessage += f"\nMais informações em {bot_messages.ALERTAS_URL}."

                    try:
                        context.bot.send_message(
                            chat_id=chat.id,
                            text=alertMessage,
                            parse_mode="markdown",
                            disable_web_page_preview=True,
                        )
                    except Exception as error:
                        functionsLogger.error(
                            f"ERRO: não foi possível enviar mensagem para {chat.id} ({chat.title}). Removendo chat do BD..."
                        )
                        models.INMETBotDB.subscribedChatsCollection.delete_one(
                            {"chatID": chat.id}
                        )

            context.bot.delete_message(
                chat_id=checkingForSubscribed.chat.id,
                message_id=checkingForSubscribed.message_id,
            )