Skip to content

Instantly share code, notes, and snippets.

@renanpalmeira
Created March 14, 2016 20:40
Show Gist options
  • Save renanpalmeira/8566e127b472f4ffe718 to your computer and use it in GitHub Desktop.
Save renanpalmeira/8566e127b472f4ffe718 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
#
from xml.etree import ElementTree
import xml.etree.ElementTree as ET
from telegram import Updater
from telegram.dispatcher import run_async
import logging, telegram, json, requests, time, sys
from geopy.distance import vincenty
reload(sys)
sys.setdefaultencoding('utf8')
# Enable Logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
job_queue = None
# We use this var to save the last chat id, so we can reply to it
last_chat_id = 0
# Define a few (command) handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Olá, '+str(update.message.from_user.first_name)+' '+str(update.message.from_user.last_name)+'!')
keyboard = [["/Chuva"],["/Meteorologicas"],["/Ajuda"]]
reply_markup = telegram.ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=False, selective=False)
bot.sendMessage(update.message.chat_id, text='Bem Vindo!\nFizemos algumas atualizações no nosso robô.\nAgora, se você enviar a sua localização, nosso robô lhe enviará as condições meteorológicas mais próximas a você.\nEscolha uma das opções abaixo.', reply_markup=reply_markup)
def help(bot, update):
keyboard = [["/Chuva"],["/Meteorologicas"],["/Ajuda"]]
reply_markup = telegram.ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=False, selective=False)
bot.sendMessage(update.message.chat_id, text='Bom, vamos te ajudar!\nClicando no botão onde está escrito "Meteorologicas", você receberá as informações de todas as estações meteorológicas da cidade do Rio de Janeiro opearadas pelo AlertaRio.\nClicando no botão onde está escrito "Chuva", você receberá as informações de chuva nos últimos 15 minutos também de estações operadas pelo AlertaRio.\nCaso você deseje informações sobre sua localidade ou uma localidade específica, use a ferramenta de enviar a localização do seu Telegram e ele lhe retornará as informações meteorológicas mais próximas a você.', reply_markup=reply_markup)
def any_message(bot, update):
# Save last chat_id to use in reply handler
global last_chat_id
last_chat_id = update.message.chat_id
if update.message.location != None:
update.message.text = '/Local'
logger.info("New message\nFrom: %s\nchat_id: %d\nText: %s" %
(update.message.from_user,
update.message.chat_id,
update.message.text))
@run_async
def chuva(bot, update, **kwargs):
a = requests.get("http://alertario.rio.rj.gov.br/upload/xml/Chuvas.xml")
root = ElementTree.fromstring(a.content)
x = 0
sm = 0
while x != len(root):
if float(((root[x][1]).attrib).get('m15')) != 0:
nome = ((root[x]).attrib).get('nome')
data = ((root[x][1]).attrib).get('hora')
chuva = float(((root[x][1]).attrib).get('m15'))
bot.sendMessage(update.message.chat_id, text=''+str(nome)+'\n'+str(data)+'\n'+str(chuva)+'')
elif float(((root[x][1]).attrib).get('m15')) == 0:
sm += 1
x += 1
if sm == 33:
bot.sendMessage(update.message.chat_id, text='Neste momento, não chove em nenhum lugar da cidade do Rio de Janeiro')
def met(bot, update, args):
bot.sendMessage(update.message.chat_id, text='Vamos aos dados meteorológicos!')
a = requests.get("http://alertario.rio.rj.gov.br/upload/xml/Chuvas.xml")
root = ElementTree.fromstring(a.content)
x = 0
while x != len(root):
if ((root[x]).attrib).get('type') == 'met':
nome = ((root[x]).attrib).get('nome')
data = ((root[x][1]).attrib).get('hora')
data1 = str(data[8:9])+'/'+str(data[5:7])+'/'+str(data[0:4])+' '+str(data[11:16])
dirvento = ((root[x][2]).attrib).get('dirvento')
velvento = ((root[x][2]).attrib).get('velvento')
pressao = ((root[x][2]).attrib).get('pressao')
temperatura = ((root[x][2]).attrib).get('temperatura')
umidade = ((root[x][2]).attrib).get('umidade')
bot.sendMessage(update.message.chat_id, text='Nome da Estação: '+unicode(nome)+'\nData: '+str(data1)+'\nTemperatura: '+str(temperatura[0:4]).replace("None","Sem informações")+'\nUmidade: '+str(umidade[0:4]).replace("None","Sem informações")+'\nDireção do Vento: '+str(dirvento[0:4]).replace("None","Sem informações")+'\nVelocidade do Vento: '+str(velvento[0:4]).replace("None","Sem informações")+'\nPressão: '+str(pressao[0:6]).replace("None","Sem informações"))
x += 1
def local(bot, update, args):
dist = []
name = []
bot.sendMessage(update.message.chat_id, text='Segundo sua localização, as condições meteorológicos mais próximas de você são:')
a = requests.get("http://alertario.rio.rj.gov.br/upload/xml/Chuvas.xml")
root = ElementTree.fromstring(a.content)
x = 0
while x != len(root):
if ((root[x]).attrib).get('type') == 'met':
newport_ri = (((root[x][0]).attrib).get('latitude'),((root[x][0]).attrib).get('longitude'))
cleveland_oh = (float(update.message.location.latitude), float(update.message.location.longitude))
dist.append(vincenty(newport_ri, cleveland_oh).kilometers)
name.append(((root[x]).attrib).get('nome'))
x += 1
min_d = min(dist)
a = dist.index(min_d)
x = 0
while x != len(root):
if ((root[x]).attrib).get('type') == 'met' and ((root[x]).attrib).get('nome') == name[a]:
nome = ((root[x]).attrib).get('nome')
data = ((root[x][1]).attrib).get('hora')
data1 = str(data[8:9])+'/'+str(data[5:7])+'/'+str(data[0:4])+' '+str(data[11:16])
dirvento = ((root[x][2]).attrib).get('dirvento')
velvento = ((root[x][2]).attrib).get('velvento')
pressao = ((root[x][2]).attrib).get('pressao')
temperatura = ((root[x][2]).attrib).get('temperatura')
umidade = ((root[x][2]).attrib).get('umidade')
bot.sendMessage(update.message.chat_id, text='Nome da Estação: '+unicode(nome)+'\nData: '+str(data1)+'\nTemperatura: '+str(temperatura[0:4]).replace("None","Sem informações")+'\nUmidade: '+str(umidade[0:4]).replace("None","Sem informações")+'\nDireção do Vento: '+str(dirvento[0:4]).replace("None","Sem informações")+'\nVelocidade do Vento: '+str(velvento[0:4]).replace("None","Sem informações")+'\nPressão: '+str(pressao[0:6]).replace("None","Sem informações"))
x += 1
dist = []
name = []
x = 0
while x != len(root):
newport_ri = (((root[x][0]).attrib).get('latitude'),((root[x][0]).attrib).get('longitude'))
cleveland_oh = (float(update.message.location.latitude), float(update.message.location.longitude))
dist.append(vincenty(newport_ri, cleveland_oh).kilometers)
name.append(((root[x]).attrib).get('nome'))
x += 1
min_d = min(dist)
a = dist.index(min_d)
x = 0
while x != len(root):
if ((root[x]).attrib).get('nome') == name[a]:
if float(((root[x][1]).attrib).get('m15')) != 0:
nome = ((root[x]).attrib).get('nome')
data = ((root[x][1]).attrib).get('hora')
chuva = float(((root[x][1]).attrib).get('m15'))
bot.sendMessage(update.message.chat_id, text=''+str(nome)+'\n'+str(data)+'\n'+str(chuva)+'')
elif float(((root[x][1]).attrib).get('m15')) == 0:
bot.sendMessage(update.message.chat_id, text='Neste momento, não chove nas proximidades do local indicado.')
x += 1
# These handlers are for updates of type str. We use them to react to inputs
# on the command line interface
def main():
global job_queue
# Create the EventHandler and pass it your bot's token.
token = ''
updater = Updater(token, workers=10)
job_queue = updater.job_queue
# Get the dispatcher to register handlers
dp = updater.dispatcher
# This is how we add handlers for Telegram messages
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("Chuva", chuva)
dp.addTelegramCommandHandler("Meteorologicas", met)
dp.addTelegramCommandHandler("Local", local)
dp.addTelegramCommandHandler("Ajuda", help)
# Message handlers only receive updates that don't contain commands
dp.addTelegramRegexHandler('.*', any_message)
# String handlers work pretty much the same
# All TelegramErrors are caught for you and delivered to the error
# handler(s). Other types of Errors are not caught.
# Start the Bot and store the update Queue, so we can insert updates
update_queue = updater.start_polling(poll_interval=0.1, timeout=10)
j = updater.job_queue
telegram.replykeyboardhide.ReplyKeyboardHide(hide_keyboard=True)
# Start CLI-Loop
while True:
try:
text = raw_input()
except NameError:
text = input()
# Gracefully stop the event handler
if text == 'stop':
updater.stop()
break
# else, put the text into the update queue to be handled by our handlers
elif len(text) > 0:
update_queue.put(text)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment