def demo(): url = "https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=at_t8PI3edTMfOr9Q2JkJbok5B300gr8" response = requests.get(url) x = response.json() temp, humidity = get_weather_data(x["location"]["lat"],x["location"]["lng"]) temp = (temp-273.15) * 9/5 + 32 return render_template('index.html',x = int(predict(temp,humidity,x["location"]["lat"],x["location"]["lng"])),noise=int(open('noise.txt','r').read()),tem = round(temp,2),hum = round(humidity,2),lat = x["location"]["lat"],long = x["location"]["lng"])
def process_request(request): response = request.get_json() chat_id = response['message']['chat']['id'] try: text = response['message']['text'] except KeyError: send_message(chat_id, 'Input is incorrect!') if text == '/start': send_message( chat_id, "This bot can send you weather data from any City.\nType '/help' to see how-to." ) elif text == '/help': send_message(chat_id, 'none') elif text == '/weather': send_message(chat_id, 'Type name of the city:') else: city = text.split()[0].capitalize() data = weather.get_weather_data(city) if data != None: send_message( chat_id, f""" City: {city} {data['weather']}, {data['temp']} °C, feels like {data["feels_like"]} °C Wind speed: {data["wind_sp"]} m/s """) else: send_message(chat_id, 'Incorrect input, please try again.')
def demo(): lat = 43.538797 lng = -79.666482 temp, humidity = get_weather_data(lat, lng) temp = (temp - 273.15) * 9 / 5 + 32 data = pd.DataFrame({ 'average_humidity': [17.58, humidity], 'type': ['average', 'actual'], 'average_temp': [19.76, temp], 'noise': [670.6984, int(open('noise.txt', 'r').read())] }) graph_humidity = px.bar(data, x="type", y="average_humidity") graph_temp = px.bar(data, x='type', y='average_temp') graph_noise = px.bar(data, x='type', y='noise') graph_humidity = json.dumps(graph_humidity, cls=plotly.utils.PlotlyJSONEncoder) graph_temp = json.dumps(graph_temp, cls=plotly.utils.PlotlyJSONEncoder) graph_noise = json.dumps(graph_noise, cls=plotly.utils.PlotlyJSONEncoder) return render_template('index.html', graph_temp=graph_temp, graph_noise=graph_noise, graph_humidity=graph_humidity, x=int(predict(temp, humidity, lat, lng)), noise=int(open('noise.txt', 'r').read()), tem=round(temp, 2), hum=round(humidity, 2), lat=lat, long=lng)
def index(): """Homepage/Shows user their lists of restaurants""" weather_info = weather.get_weather_data(37.7749, 122.4194) temp = weather_info['temp'] humidity = weather_info['humidity'] return render_template('home.html', temp=temp, humidity=humidity)
def return_weather_results(): """sends weather API call and sends weather results to client""" lat = float(request.form.get('userLat')) lng = float(request.form.get('userLng')) weather_info = weather.get_weather_data(lat, lng) print weather_info return jsonify(weather_info)
def show_zip_form(): """takes zip code info from user form and returns weather API call based on lat/long""" zipcode = int(request.form.get('zip')) zipcode = zcdb[zipcode] lat = zipcode.latitude lng = zipcode.longitude weather_info = weather.get_weather_data(lat, lng) return render_template('home.html', temp=weather_info['temp'], humidity=weather_info['humidity'])
def main(host, privateKeyPath, certificatePath, rootCAPath, useWebsocket, peoplecount): # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub", useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub") myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() TOPIC = "sdk/test/Python" # myAWSIoTMQTTClient.subscribe(TOPIC, 1, customCallback) # time.sleep(2) data = {} data['time'] = get_calendar_data() data['pi'] = get_pi_data(peoplecount) data['weather'] = weather.get_weather_data() data['traffic'] = traffic.get_traffic_data() myAWSIoTMQTTClient.publish(TOPIC, json.dumps(data), 1) myAWSIoTMQTTClient.disconnect()
def execute(): global last global URL try: req = requests.get(URL) except ConnectionError: print("Echec à l'ouverture de page - Mauvais URL") return while doitQuitter == False: if time.time() - last > 20: last = time.time() spoti.spotify() parser = argparse.ArgumentParser( description= "Quick Script for Extracting Weather data using Google Weather" ) parser.add_argument( "region", nargs="?", help="""Region to get weather for, must be available region. Default is your current location determined by your IP Address""", default="") # parse arguments args = parser.parse_args() region = args.region URL += region # get data data = weather.get_weather_data(URL) # print data print("Météo pour:", data["region"]) print("Maintenant:", data["dayhour"]) print(f"Température maintenant: {data['temp_now']}°C") print("Description:", data['weather_now']) print("Précipitations:", data["precipitation"]) print("Humidité:", data["humidity"]) print("Vent:", data["wind"]) print("Prochains jours:") for dayweather in data["next_days"]: print("=" * 40, dayweather["name"], "=" * 40) print("Description:", dayweather["weather"]) print(f"Température max: {dayweather['max_temp']}°C") print(f"Température min: {dayweather['min_temp']}°C")
def main(): TOKEN = "3d02e045e965c29c4c4a04606979e5c5b0aa3372fcd07a97d4fcfec0c799f52e46355eacac5affb5d9eb9" vk_session = vk_api.VkApi(token=TOKEN) vk = vk_session.get_api() longpoll = VkLongPoll(vk_session) hello = ''' Привет, я повелитель Ада - Люци, и я всегда готова тебе помочь^.^ Вот, что я умею: Я могу присылать различные мемы: -тм - мем из русского мультифандома -нм - научный мем -дм - добрый мем Так же я могу скинуть цитатку: -ц - цитата И интересные слэнговые слова: -р - слэнговые слова Ещё я умею узнавать погоду в твоём городе, курс валют и выдавать краткие справки о том, что тебя интересует: -с <объект> - краткая справка о интересующем тебя объекте -п <город> - погода в твоём городе -к - курс валют ''' gs = goslate.Goslate() ss = [ 'Ава — сокращённый вариант от слова "аватарка"; фотография пользователя в профиле соцсети. ', 'Агриться — злиться, ругаться на кого-то.', 'Бомбит — бесит, раздражает, напрягает. ', 'Баттхёрт, бугурт — состояние человека' ', который негодует, испытывает гнев; нередко используется как синоним слова "бугурт";' ' произошло от английского слова butthurt (попная боль). ', 'Бра, бро — уважительная и дружественная форма обращение от сокращённого английского слова brother (брат). ', 'Бабецл — взрослая женщина, которую мальчики-подростки не считают сексуально привлекательной. ', 'Варик — сокращённое от слова "вариант". ', 'Го — пойдём, начинай, давай; от английского глагола go (давай, пойдём).', 'Жиза — правда, жизненная ситуация, близкая читателю.', 'Зашквар — позор, недостойно, плохо, не модно.', 'ЛС — личные сообщения.', 'По дэхе — чуть-чуть, немного.', 'Абилка — способность, свойство человека или предмета. Например, "У нового "айфона" куча прикольных абилок".', 'Ганк, ганкнуть — добиться своих целей подлыми методами.', 'Грайнд (возм. гринд) — однообразная и нудная работа, необходимая для достижения какой-либо цели.' ] memes = { '-138383301': ['456742203', '456741173', '456740947'], '-147286578': ['456363035', '456362986', '456362982'], '-159146575': ['456295687', '456311973', '456311966'] } post = [ 'Если радуга долго держится, на нее перестают смотреть.', 'В нашей семье считалось, что любую беду можно исправить чашкой чая.', 'Лучшая маска, какую мы только можем надеть, — это наше собственное лицо.', 'Можно ехать в одном вагоне, но в разные стороны.', 'В шесть лет я хотел быть Колумбом, в семь – Наполеоном, а потом мои притязания постоянно росли.' ] for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me: msg_text = event.text.lower() query = msg_text[3:] message_id = random.randint(0, 200000) if msg_text == "начать" or msg_text == "?": vk.messages.send(user_id=event.user_id, random_id=message_id, message=hello) elif msg_text[0:2] == "-с": vk.messages.send(user_id=event.user_id, random_id=message_id, message=get_summary(query)) elif msg_text[0:2] == "-п": try: query = gs.translate(query, "en") response = get_weather_data(query) except Exception: response = ":( Сервис не доступен" vk.messages.send(user_id=event.user_id, random_id=message_id, message=response) elif msg_text[0:2] == "-к": response = "{0} рублей за 1 доллар \n {1} рублей за 1 евро \n {2} рублей за 10 юаней \n {3} рублей за фунт" response = response.format(get_сourse("R01235"), get_сourse("R01239"), get_сourse("R01375"), get_сourse("R01035")) vk.messages.send(user_id=event.user_id, random_id=message_id, message=response) elif msg_text[0:2] == '-ц': vk.messages.send(user_id=event.user_id, random_id=message_id, message=random.choice(post)) elif msg_text[0:3] == "-тм": vk.messages.send(user_id=event.user_id, random_id=message_id, message=":)", attachment='photo{0}_{1}'.format( '-138383301', random.choice(memes['-138383301']))) elif msg_text[0:3] == "-дм": vk.messages.send(user_id=event.user_id, random_id=message_id, message=":)", attachment='photo{0}_{1}'.format( '-147286578', random.choice(memes['-147286578']))) elif msg_text[0:3] == "-нм": vk.messages.send(user_id=event.user_id, random_id=message_id, message=":)", attachment='photo{0}_{1}'.format( '-159146575', random.choice(memes['-159146575']))) elif msg_text[0:3] == "-р": vk.messages.send(user_id=event.user_id, random_id=message_id, message=random.choice(ss)) else: vk.messages.send(user_id=event.user_id, random_id=message_id, message="Я вас не понимаю ;(")
import pyhdb import sys import configparser import datetime import random from os import path from pprint import pprint from datetime import timedelta import model_generator import weather import holiday import users import math_utils weather_year_data = [x for x in weather.get_weather_data() if x['date'].year == 2017] holidays = holiday.get_holiday_data() user_data = users.generate_data() today = datetime.date.today() dates = [datetime.date(today.year - 1, 1, 1) + datetime.timedelta(days=i) for i in range(365 * 2)] # Loop weather data weather_loop_data = [] for i, date in enumerate(dates): data = weather_year_data[i % len(weather_year_data)].copy() data['date'] = date weather_loop_data.append(data)
def action_wrapper(hermes, intentMessage, conf): """ Write the body of the function that will be executed once the intent is recognized. In your scope, you have the following objects : - intentMessage : an object that represents the recognized intent - hermes : an object with methods to communicate with the MQTT bus following the hermes protocol. - conf : a dictionary that holds the skills parameters you defined. To access global parameters use conf['global']['parameterName']. For end-user parameters use conf['secret']['parameterName'] Refer to the documentation for further details. """ import datetime import re import weather as wt import locale import random from conditioncodes import CONDITION_CODES locale.setlocale(locale.LC_TIME, '') api_key = conf['secret']['api_key'] locality = conf['secret']['default_location'] country = conf['secret']['default_countrycode'] geographical_poi = None region = None startdate = datetime.datetime.now() rightnow = startdate condition_name = None capital = None # Populate the parameters and sanitize them if len(intentMessage.slots['forecast_condition_name']) > 0: condition_name = intentMessage.slots['forecast_condition_name'].first( ).value if len(intentMessage.slots['forecast_start_datetime']) > 0: # This one is tricky, regarding the question it may be an InstantTimeValue or a TimeIntervalValue # In the last case, I take the start hour and add one hour to make a difference with 00:00 (see below how this is handled) # This should not affect the result, with the free API I can only get 3h-intervals startdate = intentMessage.slots['forecast_start_datetime'].first() is_interval = False if type(startdate ) == hermes_python.ontology.dialogue.slot.InstantTimeValue: startdate = startdate.value elif type(startdate ) == hermes_python.ontology.dialogue.slot.TimeIntervalValue: startdate = startdate.from_date is_interval = True startdate = re.sub( r'^([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} \+[0-9]{2}):([0-9]{2})$', r'\1\2', startdate) startdate = datetime.datetime.strptime(startdate, '%Y-%m-%d %H:%M:%S %z') rightnow = datetime.datetime.now(startdate.tzinfo) if is_interval: startdate += datetime.timedelta(hours=+1) # If only a day is asked, Snips will provide a time of 00:00:00 which is not interesting for weather. # So I offset that by 12 hours if startdate.time() == datetime.time(00, 00, 00): startdate += datetime.timedelta(hours=12) if len(intentMessage.slots['forecast_geographical_poi']) > 0: geographical_poi = intentMessage.slots[ 'forecast_geographical_poi'].first().value if len(intentMessage.slots['forecast_region']) > 0: region = intentMessage.slots['forecast_region'].first().value if len(intentMessage.slots['forecast_country']) > 0: # OpenWeatherMap requests 2-letters ISO-3166 country codes. This is for the mapping fr->ISO-3166 # Note that some countries may not work properly country = intentMessage.slots['forecast_country'].first().value f = open("iso_3166.csv", 'rt') for line in f: line_list = line.split("\t") if line_list[1].strip().lower() == country.split( " ")[-1].strip().lower(): country = line_list[2].lower().strip() if len(line_list) >= 6: capital = line_list[5].lower().strip() break f.close() if len(intentMessage.slots['forecast_locality']) > 0: locality = intentMessage.slots['forecast_locality'].first().value answer = "Je ne suis pas sûr de savoir quelle météo tu m'as demandée" # First of all, determine the location from which we want the weather if geographical_poi is not None: answer = "Désolé, je ne suis pas encore capable de récupérer un point d'intérêt" hermes.publish_end_session(intentMessage.session_id, answer) return elif region is not None: answer = "Je ne peux pas encore te donner la météo d'un région" hermes.publish_end_session(intentMessage.session_id, answer) return elif country != conf['secret']['default_countrycode'] and locality == conf[ 'secret']['default_location']: if capital is None: answer = "J'ai besoin d'une ville dans le pays dont tu souhaites la météo" hermes.publish_end_session(intentMessage.session_id, answer) return else: locality = capital weather = wt.get_weather_data(locality, country, api_key) if weather is None or weather['cod'] != "200" and weather['cod'] != "404": answer = "Il y a un problème avec la récupération des infos météo" hermes.publish_end_session(intentMessage.session_id, answer) return elif weather['cod'] == "404": answer = "Je n'ai pas trouvé la ville que tu as demandé" hermes.publish_end_session(intentMessage.session_id, answer) return i = 0 start_timestamp = startdate.timestamp() selected_forecast = None if startdate == rightnow or startdate - datetime.timedelta( hours=3) < rightnow: selected_forecast = 0 else: for forecast in weather['list']: #print(start_timestamp) #print(forecast['dt']) # We have to take in account that the next forecast is already in the future (3h in the worst case scenario) if start_timestamp > forecast['dt'] and start_timestamp < forecast[ 'dt'] + 10800: # 3-hour intervals selected_forecast = i i += 1 if selected_forecast is None: # Nope, the date given is beyond the forecast or on a past value answer = "Il semblerait que la date que tu m'as demandée ne permette pas de récupérer d'info." hermes.publish_end_session(intentMessage.session_id, answer) return answer = "" if startdate == rightnow: answer += "En ce moment, il y a " elif startdate.date() == rightnow.date( ) and startdate.time() >= datetime.time( 12, 0, 0) and startdate.time() < datetime.time(18, 0, 0): answer += "Cette après-midi il y aura " elif startdate.date() == rightnow.date() and startdate.time( ) < datetime.time(12, 0, 0) and startdate.time() >= datetime.time(6, 0, 0): answer += "Ce matin il y aura " elif startdate.date() == rightnow.date( ) and startdate.time() > datetime.time( 18, 0, 0) and startdate.time() <= datetime.time(23, 59, 59): answer += "Ce soir il y aura " elif startdate.date() == rightnow.date() + datetime.timedelta( days=1) and startdate.time() > datetime.time( 0, 0, 0) and startdate.time() < datetime.time(6, 0, 0): answer += "Cette nuit il y aura " elif startdate.date() == rightnow.date() + datetime.timedelta(days=1): if startdate.time() == datetime.time(12, 0, 0): answer += "Demain il y aura " elif startdate.time() >= datetime.time( 6, 0, 0) and startdate.time() < datetime.time(12, 0, 0): answer += "Demain matin il y aura " elif startdate.time() > datetime.time( 12, 0, 0) and startdate.time() < datetime.time(18, 0, 0): answer += "Demain après-midi il y aura " elif startdate.time() >= datetime.time( 18, 0, 0) and startdate.time() <= datetime.time(23, 59, 59): answer += "Demain soir il y aura " else: dayofweek = startdate.strftime("%A") if startdate.time() == datetime.time(12, 0, 0): answer += "%s il y aura " % dayofweek elif startdate.time() < datetime.time(12, 0, 0): answer += "%s matin il y aura " % dayofweek elif startdate.time() > datetime.time( 12, 0, 0) and startdate.time() < datetime.time(18, 0, 0): answer += "%s après-midi il y aura " % dayofweek elif startdate.time() >= datetime.time( 18, 0, 0) and startdate.time() <= datetime.time(23, 59, 59): answer += "%s soir il y aura " % dayofweek et = "" if len(weather['list'][selected_forecast]['weather']) > 1: et = " et " non_array = [ "Non. ", "Pas vraiment. ", "Il semblerait que non. ", ] oui_array = [ "Oui. ", "En effet, ", "Effectivement, ", ] oui = random.choice(non_array) for w in weather['list'][selected_forecast]['weather']: answer += CONDITION_CODES[w['id']]['snips'][0] + et if condition_name is not None and condition_name in CONDITION_CODES[ w['id']]['snips']: oui = random.choice(oui_array) if len(et) > 0: answer = answer[:-len(et)] answer += " " answer = oui + answer if locality != conf['secret']['default_location']: answer += "à %s" % locality hermes.publish_end_session(intentMessage.session_id, answer)
'dish_id': dish_id, 'date': date, 'weekday': date.weekday(), 'temperature': temperature, 'holiday': date in holidays, 'orders': round(max(0, x + random.gauss(0, 0.05)) * weight) } for (date, temperature, x) in zip(dates, temperatures, model)] return result if __name__ == '__main__': n = 365 base = datetime.date.today() dates = [base + datetime.timedelta(days=x) for x in range(n)] temperatures = [x['temperature'] for x in weather.get_weather_data()] holidays = [x['date'] for x in holiday.get_holiday_data()] data = generate_data(range(7), [100 for _ in range(7)], dates, temperatures, holidays) dish_id = 3 plotly.offline.plot([ *[ plotly.graph_objs.Scatter( x=list(range(n)), y=[x['orders'] for x in data if x['dish_id'] == dish_id], name='Dish {}'.format(dish_id)) for dish_id in range(7) ], plotly.graph_objs.Scatter( x=list(range(n)), y=temperatures, name='Temperature'), plotly.graph_objs.Scatter(x=list(range(n)),
def action_wrapper(hermes, intentMessage, conf): """ Write the body of the function that will be executed once the intent is recognized. In your scope, you have the following objects : - intentMessage : an object that represents the recognized intent - hermes : an object with methods to communicate with the MQTT bus following the hermes protocol. - conf : a dictionary that holds the skills parameters you defined. To access global parameters use conf['global']['parameterName']. For end-user parameters use conf['secret']['parameterName'] Refer to the documentation for further details. """ import datetime import re import weather as wt import locale import random from conditioncodes import CONDITION_CODES locale.setlocale(locale.LC_TIME, '') api_key = conf['secret']['api_key'] locality = conf['secret']['default_location'] country = conf['secret']['default_countrycode'] geographical_poi = None region = None startdate = datetime.datetime.now() rightnow = startdate item = None capital = None # Populate the parameters and sanitize them if len(intentMessage.slots['forecast_item']) > 0: item = intentMessage.slots['forecast_item'].first().value if len(intentMessage.slots['forecast_start_datetime']) > 0: # This one is tricky, regarding the question it may be an InstantTimeValue or a TimeIntervalValue # In the last case, I take the start hour and add one hour to make a difference with 00:00 (see below how this is handled) # This should not affect the result, with the free API I can only get 3h-intervals startdate = intentMessage.slots['forecast_start_datetime'].first() is_interval = False if type(startdate ) == hermes_python.ontology.dialogue.slot.InstantTimeValue: startdate = startdate.value elif type(startdate ) == hermes_python.ontology.dialogue.slot.TimeIntervalValue: startdate = startdate.from_date is_interval = True startdate = re.sub( r'^([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} \+[0-9]{2}):([0-9]{2})$', r'\1\2', startdate) startdate = datetime.datetime.strptime(startdate, '%Y-%m-%d %H:%M:%S %z') rightnow = datetime.datetime.now(startdate.tzinfo) if is_interval: startdate += datetime.timedelta(hours=+1) # If only a day is asked, Snips will provide a time of 00:00:00 which is not interesting for weather. # So I offset that by 12 hours if startdate.time() == datetime.time(00, 00, 00): startdate += datetime.timedelta(hours=12) if len(intentMessage.slots['forecast_geographical_poi']) > 0: geographical_poi = intentMessage.slots[ 'forecast_geographical_poi'].first().value if len(intentMessage.slots['forecast_region']) > 0: region = intentMessage.slots['forecast_region'].first().value if len(intentMessage.slots['forecast_country']) > 0: # OpenWeatherMap requests 2-letters ISO-3166 country codes. This is for the mapping fr->ISO-3166 # Note that some countries may not work properly country = intentMessage.slots['forecast_country'].first().value f = open("iso_3166.csv", 'rt') for line in f: line_list = line.split("\t") if line_list[1].strip().lower() == country.split( " ")[-1].strip().lower(): country = line_list[2].lower().strip() if len(line_list) >= 6: capital = line_list[5].lower().strip() break f.close() if len(intentMessage.slots['forecast_locality']) > 0: locality = intentMessage.slots['forecast_locality'].first().value answer = "Je ne suis pas sûr de savoir quelle météo tu m'as demandée" # First of all, determine the location from which we want the weather if geographical_poi is not None: answer = "Désolé, je ne suis pas encore capable de récupérer un point d'intérêt" hermes.publish_end_session(intentMessage.session_id, answer) return elif region is not None: answer = "Je ne peux pas encore te donner la météo d'une région" hermes.publish_end_session(intentMessage.session_id, answer) return elif country != conf['secret']['default_countrycode'] and locality == conf[ 'secret']['default_location']: if capital is None: answer = "J'ai besoin d'une ville dans le pays dont tu souhaites la météo" hermes.publish_end_session(intentMessage.session_id, answer) return else: locality = capital weather = wt.get_weather_data(locality, country, api_key) if weather is None or weather['cod'] != "200" and weather['cod'] != "404": answer = "Il y a un problème avec la récupération des infos météo" hermes.publish_end_session(intentMessage.session_id, answer) return elif weather['cod'] == "404": answer = "Je n'ai pas trouvé la ville que tu as demandé" hermes.publish_end_session(intentMessage.session_id, answer) return i = 0 start_timestamp = startdate.timestamp() selected_forecast = None if startdate == rightnow or startdate - datetime.timedelta( hours=3) < rightnow: selected_forecast = 0 else: for forecast in weather['list']: #print(start_timestamp) #print(forecast['dt']) # We have to take in account that the next forecast is already in the future (3h in the worst case scenario) if start_timestamp > forecast['dt'] and start_timestamp < forecast[ 'dt'] + 10800: # 3-hour intervals selected_forecast = i i += 1 if selected_forecast is None: # Nope, the date given is beyond the forecast or on a past value answer = "Il semblerait que la date que tu m'as demandée ne permette pas de récupérer d'info." hermes.publish_end_session(intentMessage.session_id, answer) return answer = "" if item in [ 'éventail', 'chapeau', 'couvre-chef', 'casquette', 'turban', 'chapeau chinois', 'robe sans manche', 'créme bronzante', 'crème solaire', 'short', 'jupe', 'nuds-pieds', 'espadrilles', 'tongues', 'lunettes de soleil', 'ombrelle', 'chapeau de paille', 'vêtements légers' ]: if weather['list'][selected_forecast]['weather'][0]['id'] in [ 800, 801 ]: answer += "ça peut être utile, du soleil est prévu" elif item in [ 'éventail', 'robe sans manche', 'short', 'jupe', 'nuds-pieds', 'espadrilles', 'tongues', 'vêtements légers' ]: if weather['list'][selected_forecast]['main']['temp'] > 25: answer += "Il va faire chaud, ça peut être utile" else: answer += "La température ne va pas non plus être étouffante, à toi de voir" else: answer += "Il semblerait que ce ne soit pas de première nécessité" elif item in [ 'bonneterie', 'écharpe', 'bonnet', 'cagoule', 'bottes fourrées', 'manteau', 'pull', 'doudoune', 'gros pull', 'bas de laine', 'chaussettes de laine', 'chaussettes en laine', 'chaussettes chaudes', 'pull chaud', 'mouffles' ]: if weather['list'][selected_forecast]['main']['temp'] < 8: answer += "Les températures promettent d'être basses, mieux vaut être prévoyant" elif weather['list'][selected_forecast]['main'][ 'temp'] >= 8 and weather['list'][selected_forecast]['main'][ 'temp'] < 12: answer += "Il ne va pas faire affreusement froid mais sait-on jamais" else: answer += "Tout l'attirail anti froid ne semble pas nécessaire" elif item in ['parapluie', 'capuche', 'imperméable', 'imper', 'k way']: if weather['list'][selected_forecast]['weather'][0]['id'] in [ 300, 301, 302, 310, 311, 312, 313, 314, 321, 500, 501, 502, 503, 504, 511, 521, 522, 531, 615, 616 ]: answer += "Il risque d'y avoir de la pluie, ça peut être intéressant de prendre ça avec" elif weather['list'][selected_forecast]['weather'][0]['id'] in [ 200, 201, 202, 210, 211, 212, 221, 230, 231, 232 ]: if item != "parapluie": answer += "Attention, de l'orage est prévu. Prends de quoi te couvrir" else: answer += "Un parapluie dans un orage, c'est pas vraiment conseillé" else: answer += "À priori non, pas de mauvais temps prévu" else: answer += "Je ne vois pas de quoi tu veux parler" hermes.publish_end_session(intentMessage.session_id, answer)
def getResponse(msg, ints, intents_json): tag = ints[0]['intent'] list_of_intents = intents_json['intents'] for i in list_of_intents: if (tag == "lyrics"): response = random.choice(i['responses']) ChatLog.insert(END, "Chatty: " + response + '\n\n') content = song_lyrics(msg) if type(content) == str: ChatLog.insert(END, "Chatty: " + content + '\n\n') return "here are you results." elif type(content) == tuple: for data in content: ChatLog.insert(END, "Chatty: " + data + '\n\n') return "here are you results." elif (tag == "music"): content = music(msg) if type(content) == str: ChatLog.insert(END, "Chatty: " + content + '\n\n') elif type(content) == tuple: title, flink, vlink = content def audio_link(): # import vlc # p = vlc.MediaPlayer(flink) # p.play() webbrowser.open_new(flink) def video_link(): webbrowser.open_new(vlink) ChatLog.insert(END, "Chatty: " + title + '\n\n') ChatLog.insert(END, "Audio link: " + flink + '\n\n', hyperlink.add(audio_link)) ChatLog.insert(END, "Video link: " + vlink + '\n\n', hyperlink.add(video_link)) return "here are you results." elif (tag == 'news'): title, description, short_link = get_news() for i in range(5): def news_link(): webbrowser.open_new(short_link[i]) ChatLog.insert(END, "News: " + title[i] + ' - \n' + description[i]) ChatLog.insert(END, "\nclick here for brief.\n\n", hyperlink.add(news_link)) return "here are your result." elif (tag == 'weather'): weather_report = get_weather_data(msg) ChatLog.insert(END, "Chatty: " + weather_report + '\n\n') return "here are your results" elif (tag == 'quotations'): quoto = get_quotations() ChatLog.insert(END, "Chatty: " + quoto + '\n\n') return "here are your result" elif (tag == 'search'): search(msg) return "open your browser if it's not opened automatically" elif (i['tag'] == tag): result = random.choice(i['responses']) return result
def index(): key = request.args.get("keyword") if key == "-- 선택 --" or key is None: return render_template("index.html") else: today_1 = date.today() today = today_1.strftime("%Y%m%d") yesterday_1 = today_1 - timedelta(days=1) yesterday = yesterday_1.strftime("%Y%m%d") time1 = time.strftime("%H%M") time2 = time.strftime("%H%M") w_1_time = "0000" w_2_time = "0000" time1 = int(time1) time2 = int(time2) if 0 <= time1 < 1000: if 0 <= time1 < 210: w_1_time = "2300" if 210 <= time1 < 510: w_1_time = "0200" if 510 <= time1 < 810: w_1_time = "0500" if 810 <= time1 <= 959: w_1_time = "0800" if 0 <= time2 < 40: w_2_time = "2300" if 40 <= time2 < 140: w_2_time = "0000" if 140 <= time2 < 240: w_2_time = "0100" if 240 <= time2 < 340: w_2_time = "0200" if 340 <= time2 < 440: w_2_time = "0300" if 440 <= time2 < 540: w_2_time = "0400" if 540 <= time2 < 640: w_2_time = "0500" if 640 <= time2 < 740: w_2_time = "0600" if 740 <= time2 < 840: w_2_time = "0700" if 840 <= time2 < 940: w_2_time = "0800" if 940 <= time2 < 959: w_2_time = "0900" elif 1000 <= time1 < 2400: if 1000 <= time1 < 1110: w_1_time = "0800" if 1110 <= time1 < 1410: w_1_time = "1100" if 1410 <= time1 < 1710: w_1_time = "1400" if 1710 <= time1 < 2010: w_1_time = "1700" if 2010 <= time1 < 2310: w_1_time = "2000" if 2310 <= time1 < 2400: w_1_time = "2300" if 1000 <= time2 < 1040: w_2_time = "0900" if 1040 <= time2 < 1140: w_2_time = "1000" if 1140 <= time2 < 1240: w_2_time = "1100" if 1240 <= time2 < 1340: w_2_time = "1200" if 1340 <= time2 < 1440: w_2_time = "1300" if 1440 <= time2 < 1540: w_2_time = "1400" if 1540 <= time2 < 1640: w_2_time = "1500" if 1640 <= time2 < 1740: w_2_time = "1600" if 1740 <= time2 < 1840: w_2_time = "1700" if 1840 <= time2 < 1940: w_2_time = "1800" if 1940 <= time2 < 2040: w_2_time = "1900" if 2040 <= time2 < 2140: w_2_time = "2000" if 2140 <= time2 < 2240: w_2_time = "2100" if 2240 <= time2 < 2340: w_2_time = "2200" if 2340 <= time2 < 2400: w_2_time = "2300" data1 = cv_19.get_cv_19_data(today, today) data2 = city_cv_19.get_city_cv_19_data(today, today) data3 = weather.get_weather_data(today, key, w_1_time) data4 = weather2.get_weather2_data(today, key, w_2_time) if not data3: data3 = weather.get_weather_data(yesterday, key, w_1_time) if not data4: data4 = weather2.get_weather2_data(yesterday, key, w_2_time) if not data1 or not data2: yesterday_1 = today_1 - timedelta(days=1) yesterday = yesterday_1.strftime("%Y%m%d") time1 = time.strftime("%H%M") time2 = time.strftime("%H%M") w_1_time = "0000" w_2_time = "0000" time1 = int(time1) time2 = int(time2) if 0 <= time1 < 1000: if 0 <= time1 < 210: w_1_time = "2300" if 210 <= time1 < 510: w_1_time = "0200" if 510 <= time1 < 810: w_1_time = "0500" if 810 <= time1 <= 959: w_1_time = "0800" if 0 <= time2 < 40: w_2_time = "2300" if 40 <= time2 < 140: w_2_time = "0000" if 140 <= time2 < 240: w_2_time = "0100" if 240 <= time2 < 340: w_2_time = "0200" if 340 <= time2 < 440: w_2_time = "0300" if 440 <= time2 < 540: w_2_time = "0400" if 540 <= time2 < 640: w_2_time = "0500" if 640 <= time2 < 740: w_2_time = "0600" if 740 <= time2 < 840: w_2_time = "0700" if 840 <= time2 < 940: w_2_time = "0800" if 940 <= time2 < 959: w_2_time = "0900" elif 1000 <= time1 < 2400: if 1000 <= time1 < 1110: w_1_time = "0800" if 1110 <= time1 < 1410: w_1_time = "1100" if 1410 <= time1 < 1710: w_1_time = "1400" if 1710 <= time1 < 2010: w_1_time = "1700" if 2010 <= time1 < 2310: w_1_time = "2000" if 2310 <= time1 < 2400: w_1_time = "2300" if 1000 <= time2 < 1040: w_2_time = "0900" if 1040 <= time2 < 1140: w_2_time = "1000" if 1140 <= time2 < 1240: w_2_time = "1100" if 1240 <= time2 < 1340: w_2_time = "1200" if 1340 <= time2 < 1440: w_2_time = "1300" if 1440 <= time2 < 1540: w_2_time = "1400" if 1540 <= time2 < 1640: w_2_time = "1500" if 1640 <= time2 < 1740: w_2_time = "1600" if 1740 <= time2 < 1840: w_2_time = "1700" if 1840 <= time2 < 1940: w_2_time = "1800" if 1940 <= time2 < 2040: w_2_time = "1900" if 2040 <= time2 < 2140: w_2_time = "2000" if 2140 <= time2 < 2240: w_2_time = "2100" if 2240 <= time2 < 2340: w_2_time = "2200" if 2340 <= time2 < 2400: w_2_time = "2300" data1 = cv_19.get_cv_19_data(yesterday, yesterday) data2 = city_cv_19.get_city_cv_19_data(yesterday, yesterday) data3 = weather.get_weather_data(today, key, w_1_time) data4 = weather2.get_weather2_data(today, key, w_2_time) if not data3: data3 = weather.get_weather_data(yesterday, key, w_1_time) if not data4: data4 = weather2.get_weather2_data(yesterday, key, w_2_time) return render_template("index.html", data1=data1, data2=data2, data3=data3, data4=data4, city=key)
def receive_data(): req_data = request.json get_weather_data(req_data) # print (req_data['queryResult']['parameters']['geo-city']) return 'data received'
import weather print(weather.get_weather_data("Sharon Center,OH"))