def cmd_alerts_brazil(update, context): """Fetch and send active high-risk alerts for Brazil.""" functionsLogger.debug("Getting alerts for Brazil...") try: cep = bot_utils.parse_CEP(update, context, cepRequired=False) if cep: return cmd_alerts_CEP(update, context) except: # No zip code provided pass # Ignore moderate alerts alerts = list( models.INMETBotDB.alertsCollection.find({"severity": {"$ne": "Moderate"}}) ) if list(alerts): return check_and_send_alerts_warning(update, context, alerts) else: alertMessage = bot_messages.noAlertsBrazil context.bot.send_message( chat_id=update.effective_chat.id, reply_to_message_id=update.message.message_id, text=alertMessage, parse_mode="markdown", disable_web_page_preview=True, )
def cmd_forecast(update, context): """Fetch and send weather forecast for the next 3 days for given CEP (zip code).""" functionsLogger.debug("Getting weather forecast by CEP (zip code)...") textArgs = update.message.text.split(" ") try: cep = bot_utils.parse_CEP(update, context) IBGECode = viacep.get_cep_IBGE(cep) APIBaseURL = f"https://apiprevmet3.inmet.gov.br" # Create headers for requests headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" } response = requests.get( f"{APIBaseURL}/previsao/{IBGECode}", headers=headers, allow_redirects=False, ) if response.status_code == 200: functionsLogger.info("Successful GET request to APIPREVMET3 endpoint!") # pprint.pprint(response.json()[IBGECode]) data = response.json()[IBGECode] for date in data.keys(): pprint.pprint(date) forecastMessage = bot_messages.createForecastMessage(date, data[date]) context.bot.send_message( chat_id=update.effective_chat.id, reply_to_message_id=update.message.message_id, text=forecastMessage, parse_mode="markdown", ) except ( pycep.excecoes.ExcecaoPyCEPCorreios, KeyError, Exception, ) as cepError: # Invalid zip code functionsLogger.warning( f'{cepError} on cmd_forecast. Message text: "{update.message.text}"' ) message = bot_messages.invalidZipCode.format(textArgs=textArgs[0]) context.bot.send_message( chat_id=update.effective_chat.id, reply_to_message_id=update.message.message_id, text=message, parse_mode="markdown", )
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", )
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)...") try: cep = bot_utils.parse_CEP(update, context) city = viacep.get_cep_city(cep) # 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 functionsLogger.warning( f'{cepError} on cmd_alerts_CEP. Message text: "{update.message.text}"' )
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", )
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, )