def send_forecast(message): try: get_forecast(message.text) except pyowm.exceptions.api_response_error.NotFoundError: MyBot.send_message( message.chat.id, "❌ Tempat yang anda pilih salah, Silahkan coba lagi!") forecast = get_forecast(message.text) MyBot.send_message(message.chat.id, forecast)
def handle_weather(self, text): if re.search(r"今日天气", text): try: city_name = re.search(r"(今日天气)(\+)(.*)", text).group(3) reply = get_forecast('今日天气', city_name) except: reply = '查询今日天气请输入今日天气 + 城市名,如: 今日天气 + 西安.' elif re.search(r"七日天气", text): try: city_name = re.search(r"(七日天气)(\+)(.*)", text).group(3) reply = get_forecast('七日天气', city_name) except: reply = '查询七日天气请输入七日天气+城市名,如:七日天气+西安' else: reply = '''查询今日天气请输入今日天气+城市名,如:今日天气+西安.\n查询七日天气请输入七日天气+城市名,如:七日天气+西安。''' send_msg(reply, self.user)
async def me(ctx): is_from_server = not isinstance(ctx.message.server, type(None)) logger_text = '{} -' + 'User: {0} User ID: {1} Server Name: {2} Server ID: {3}'.format( ctx.message.author.name, ctx.message.author.id, ctx.message.server.name if is_from_server else 'N/A', ctx.message.server.id if is_from_server else 'N/A') await bot.send_typing(ctx.message.channel) try: location, is_metric = get_preference(ctx.message.author.id) weather_msg = get_forecast(location, is_metric) logger.info( logger_text.format('Me Request') + ' Location: {0} Units: {1}'.format( location, 'Metric' if is_metric else 'Imperial')) except (DatabaseException, WeatherException): weather_msg = sys.exc_info()[1] logger.info( logger_text.format('Me Request Failed ({})'.format(weather_msg))) if (not isinstance(ctx.message.server, type(None))): await bot.say( 'Hey {}, weather information is being sent to your PMs.'.format( ctx.message.author.mention)) await bot.whisper(weather_msg)
def location(bot, update): lat = update.message.location.latitude lon = update.message.location.longitude forecasts = get_forecast(lat, lon) bot.send_message(chat_id=update.message.chat_id, text=forecasts, reply_markup=ReplyKeyboardRemove())
def outdoor(): """ Shows outdoor conditions """ return render_template('outdoor.html', today=get_weather(), forecast=get_forecast(1))
def index(): address = request.values.get('address') forecast = None map_src = None if address: forecast = get_forecast(address) map_src = get_map(address) return render_template('index.html', forecast=forecast, map_src=map_src)
def index(): address = request.values.get('address') forecast = None print(address) if address: forecast = get_forecast(address) print(forecast) return render_template('index.html', forecast=forecast)
def search(): city = ui.get_city() restaurants = rest.get_restaurants(city) news_articles = news.get_articles(city) weather_forecast = weather.get_forecast(city) ui.display(restaurants, news_articles, weather_forecast) # figure out if user wants to save if user_wants_to_save: db.save(restaurants, news_articles, weather_forecast)
def send_forecast(message): """Take city name and returns forecast.""" try: forecast = get_forecast(message.text) bot.send_message(message.chat.id, forecast) except pyowm.commons.exceptions.NotFoundError as e: logging.error( "No city found for user and error handled. User asked to enter city again" ) bot.send_message( message.chat.id, """❌ Нажаль я не можу знайти таке місто! \nБудь ласка, перевірь ще раз та спробуй знову!""" ) default_menu(message)
def main(): city = None name = None #pass no args to use the ip of the machine running this pass extra args and it will # default to Brentwood if len(sys.argv) == 3: loc = sys.argv[1] if loc == 'local': name = 'local_test.html' city = location.get_location_by_ip() elif loc == 'default': city = location.get_location() name = 'brentwood_test.html' else: print( 'usage:\n python htmlgen.py local newsapikey\n python htmlgen.py default newsapikey\n' ) sys.exit(0) newsapi = sys.argv[2] try: news_data = news.build_url_call(None, newsapi) except: print('bad key try again') sys.exit(1) else: print( 'usage:\n python htmlgen.py local newsapikey\n python htmlgen.py default newsapikey\n' ) sys.exit(0) current_weather = weather.get_current_weather(city=city) forecast = weather.get_forecast(city=city) x, y = weather.get_coord(current_weather) weather_url = weather.get_map_url(y, x) # get the top headline news url = news.build_url_call(None, newsapi) news_data = news.get_data(url) html = html_header1 + builder_header(city) + build_news_section( news_data) + build_current_weather(current_weather) + build_forecast( forecast) + build_weather_map(weather_url) save_file(html, name)
def process_automation(self): # Get season of today self.season = sun.get_season(datetime.date.today()) # Get all info (sensor, actuator, rule) by room self.get_room() # Get automation rule auto_rule_status, self.automation_rule = self.get_automation_rule() if auto_rule_status: # Get last weather measures and forecast self.weather_forecast = weather.get_forecast( self.__client, self.automation_log, False) self.weather_current = weather.get_current_weather( self.__client, self.automation_log, False) if self.weather_forecast and self.weather_current: # Check if we have room to process automation # Useless check if len(self.rooms) > 0: # Walk through all room for room in self.rooms: # Process blind rule self.process_blinds(room) # If True => we can process the room multisensor_status, temp, measures = multisensor.check_multisensor( self.__client, self.automation_log, self.automation_rule, room.sensors) if multisensor_status: # Process valve rule self.process_valves(room, temp) #self.process_valves(room, 26) else: self.automation_log.log_error( f"In function (process_automation), could not get weather or forecast" )
def test_get_forecast(self, get_weather_from_weather_com): get_weather_from_weather_com.return_value = WEATHER_MOCK days_from_today = 1 # Only testing one day from today forecast = get_forecast(days_from_today) expected = WEATHER_MOCK['forecasts'][days_from_today] assert forecast['date'] == expected['date'] assert forecast['high'] == expected['high'] assert forecast['low'] == expected['low'] assert forecast['sunrise'] == expected['sunrise'] assert forecast['sunset'] == expected['sunset'] assert forecast['day_text'] == expected['day']['text'] assert forecast['day_humidity'] == expected['day']['humidity'] assert forecast['day_precip'] == expected['day']['chance_precip'] assert forecast['day_wind'] == expected['day']['wind']['gust'] assert forecast['night_text'] == expected['night']['text'] assert forecast['night_humidity'] == expected['night']['humidity'] assert forecast['night_precip'] == expected['night']['chance_precip'] assert forecast['night_wind'] == expected['night']['wind']['gust']
def do_weather(display): display.reset() while True: try: forecasts = weather.get_forecast("Ingolstadt", "de", "de") forecasts = [ [ datetime.fromtimestamp(item["dt"]), __SCROLL_SEP + " {}\xF8C {} ".format(item["main"]["temp"], item["weather"][0]["description"]), ] for item in forecasts ] before = datetime.now() while (datetime.now() - before).seconds < WEATHER_REFRESH_TIMEOUT: display.position_cursor(0, 0) display.write("\r\n".join(["{:%H:%M} {}".format(*item)[:20] for item in forecasts])) for item in forecasts: item[1] = item[1][1:] + item[1][:1] time.sleep(0.25) except: display.reset() display.write("Keine Daten od. Feh-\r\nler.") time.sleep(WEATHER_REFRESH_TIMEOUT)
def generate_svg(filename): now = now_cet() # adding one minute to account for some delays # and make me reach the buses in time now += timedelta(minutes=1) date_str, time_str = get_date_strings(now) departures_ms = get_departures(ID_BF_MOOSACHER_STR, now) departure_texts_ms = [dep.get_text(now) for dep in departures_ms[:6]] departures_ffr = get_departures(ID_BF_FF_RING, now, ubahn_express_bus_only=True) departure_texts_ffr = [dep.get_text(now) for dep in departures_ffr[:6]] weather_forecast = get_forecast(ID_WEATHER_MILBERTSHOFEN) # gets the current weather and that for the next two days at 6:00, 12:00 and 18:00 weather_info_current = weather_forecast.weather_infos[0] anchor_idx = (now.hour / 3) future_idx = [x - anchor_idx for x in [10, 12, 14, 18, 20, 22]] weather_infos_tomorrow = [ weather_forecast.weather_infos[i] for i in future_idx[:3] ] weather_infos_day_after_tomorrow = [ weather_forecast.weather_infos[i] for i in future_idx[3:] ] gen_svg(date_str=date_str, time_str=time_str, departure_texts_ms=departure_texts_ms, departure_texts_ffr=departure_texts_ffr, weather_info_current=weather_info_current, weather_infos_tomorrow=weather_infos_tomorrow, weather_infos_day_after_tomorrow=weather_infos_day_after_tomorrow, filename=filename)
def display_weather(): """ Update weather conditions and display on the tkinter window. :return: None """ global root # Size screen width = root.winfo_screenwidth() height = round(root.winfo_screenheight() * 1) print(width, height) num_rows = 6 for i in range(num_rows): root.grid_rowconfigure(i, minsize=height // num_rows) num_columns = 12 for i in range(num_columns): root.grid_columnconfigure(i, minsize=width // num_columns) # Get and display prog chart prog_chart = ImageTk.PhotoImage(Image.open(io.BytesIO(weather.get_prog()))) canvas = tk.Canvas(root, bg='white', width=width // 2, height=height) canvas.grid(row=0, column=0, rowspan=num_rows - 2, columnspan=num_columns // 2) canvas.create_image(width // 2, 0, image=prog_chart, anchor='ne') PHOTOS.append(prog_chart) # Get and display weather data tk.Label(root, text="Today's Weather. Last Updated: {}".format( datetime.now().strftime("%I:%M:%S %p")), font=("Helvetica", 20)).grid(row=0, column=6, columnspan=5) current, outlook, forecast = weather.get_forecast() # GET WEATHER DATA curr_image = resize_img(get_image(current['icon']), 100, 100) curr_photo = ImageTk.PhotoImage(curr_image) PHOTOS.append(curr_photo) # Current weather frame current_frame = tk.Frame(root) tk.Label(current_frame, text="Current Weather", font=("Helvetica", LARGE_FONT)).pack() tk.Label(current_frame, text=current['summary'], font=("Helvetica", MEDIUM_FONT)).pack() cv1 = tk.Canvas(current_frame, bg='#d1d1d1', width=curr_photo.width(), height=curr_photo.height()) cv1.pack() cv1.create_image(0, 0, image=curr_photo, anchor='nw') tk.Label(current_frame, text=current['time'], font=("Helvetica", MEDIUM_FONT)).pack() tk.Label(current_frame, text="{:.0%} - {}\u00B0".format(current['precipProbability'], current['temperature']), font=("Helvetica", SMALL_FONT)).pack() current_frame.grid(row=1, column=6, rowspan=1, columnspan=2, sticky='NE') out_image = resize_img(get_image(outlook['icon']), 100, 100) out_photo = ImageTk.PhotoImage(out_image) PHOTOS.append(out_photo) # Outlook weather frame out_frame = tk.Frame(root) tk.Label(out_frame, text="Weather Outlook", font=("Helvetica", LARGE_FONT)).pack() tk.Label(out_frame, text=outlook['summary'], font=("Helvetica", MEDIUM_FONT)).pack() cv1 = tk.Canvas(out_frame, bg='#d1d1d1', width=out_photo.width(), height=out_photo.height()) cv1.pack() cv1.create_image(0, 0, image=out_photo, anchor='nw') tk.Label(out_frame, text=current['date'], font=("Helvetica", MEDIUM_FONT)).pack() out_frame.grid(row=1, column=8, rowspan=1, columnspan=2, sticky='NE') for_itr = 0 for i in range(2): for j in range(num_columns // 2, num_columns - 1): hour_data = forecast[for_itr] for_itr += 1 for_frame = tk.Frame(root) for_image = resize_img(get_image(hour_data['icon']), 100, 100) for_photo = ImageTk.PhotoImage(for_image) PHOTOS.append(for_photo) tk.Label(for_frame, text=hour_data['summary'], font=("Helvetica", MEDIUM_FONT)).pack() cv = tk.Canvas(for_frame, bg='#d1d1d1', width=for_photo.width(), height=for_photo.height()) cv.pack() cv.create_image(0, 0, image=for_photo, anchor='nw') tk.Label(for_frame, text=hour_data['time'], font=("Helvetica", MEDIUM_FONT)).pack() tk.Label(for_frame, text="{:.0%} - {}\u00B0".format( hour_data['precipProbability'], hour_data['temperature']), font=("Helvetica", SMALL_FONT)).pack() for_frame.grid(row=i + 2, column=j, padx=(15, 0), sticky='NW', pady=(0, 7))
async def forecast(*location: str): output = weathermodule.get_forecast('%2C'.join(location)) await bot.say(output)
async def forecast(ctx, *location:str): if 'bot' in str(ctx.message.channel): output = weathermodule.get_forecast('%2C'.join(location)) await bot.say(output) else: await bot.say("this command is only allowed in the bot channel")
def test_get_forecast_raises_exception(self, days): with pytest.raises(ValueError) as exc: get_forecast(days) assert exc.message == 'Days must be 1, 2 or 3'
def pull_forecast(self): self.future_forecast = weather.get_forecast(self.coords[0], self.coords[1])
def main(): logging.basicConfig(filename='ei_cal.log') #print('Getting Work Schedule') creds = g_cal.get_creds() ''' if len(g_cal.get_events(creds)) == 0: print('No Work!') else: print(g_cal.get_events(creds)) ''' logging.info('Getting work events') try: all_events = g_cal.get_events(creds) except socket.timeout as e: all_events = [] logging.exception(e) logging.info('Getting weather') API_KEY = weather.get_API_KEY('darksky.json') latitude, longitude = weather.get_lat_long('darksky.json') forecast = weather.get_forecast(API_KEY, latitude, longitude) weather_now = weather.get_weather_now(forecast) weather_tmrw = weather.get_weather_tmrw(forecast) epd = epd7in5.EPD() epd.init() epd.Clear() screen_w = epd.width screen_h = epd.height image = Image.new('1', (screen_w, screen_h), 255) logging.info('Drawing calendar') draw = ImageDraw.Draw(image) #center divider line day_view_divider = screen_w*5/9 draw.line([(day_view_divider,0),(day_view_divider,screen_h)], fill=0, width=2) #draw calendar divider line cal_divider = screen_h/2 draw.line([(0,cal_divider),(day_view_divider,cal_divider)], fill=0, width=2) #draw weather divider line title_divider = (screen_h - cal_divider)/5 weather_divider = day_view_divider/2 draw.line([(weather_divider, title_divider), (weather_divider, cal_divider)], fill=0, width=2) #draw weather icons icon_divider = title_divider + (cal_divider-title_divider)*3/4 draw_weather_icons(draw, weather_now, 0, title_divider, weather_divider, icon_divider) draw_weather_icons(draw, weather_tmrw, weather_divider, title_divider, day_view_divider, icon_divider) #draw.line([(0, icon_divider),(day_view_divider, icon_divider)], fill=0, width=2) #write weather info today_weather_info(draw, weather_now, 0, icon_divider, weather_divider, cal_divider) tmrw_weather_info(draw, weather_tmrw, weather_divider, icon_divider, day_view_divider, cal_divider) #get today as a datetime object today = datetime.date.today() #draw the date title font24 = ImageFont.truetype('./fonts/mononoki-Regular.ttf', 24) title(draw, today, font24, day_view_divider, title_divider) #draw the calendar in the lower left draw_cal.draw_cal(draw, screen_w, screen_h, day_view_divider, cal_divider, today) #draw the two day view on the right draw_cal.draw_two_day_view(draw, screen_w, screen_h, day_view_divider, 7, 17, today, all_events) logging.info('Send to e-ink screen') epd.display(epd.getbuffer(image)) logging.info('Go to sleep') epd.sleep()
skipDatas = True engine.say("quitting") engine.runAndWait() skipDatas = False break elif tmp == "weather forecast" or tmp == "weather": skipDatas = True if constants.DEBUG: engine.say( "Debug mode, reading weather from a local file") else: engine.say( "Fetching weather from internet, this may take a while" ) engine.runAndWait() forecast = weather.get_forecast() if forecast != "": engine.say(forecast) else: engine.say( "Enable to fetch the weather forecast from internet" ) engine.runAndWait() skipDatas = False elif tmp == "play music" or tmp == "play some music": musicplayer.launch(gui=True) elif tmp == "next music" or tmp == "music next": musicplayer.next_track() elif tmp == "previous music" or tmp == "music previous": musicplayer.previous_track() elif tmp == "stop music" or tmp == "music stop":
def get_bot_response(self): """ Process the user input and return a string response from the bot :return: the bot response """ try: user_input = request.args.get("msg") # get data from input, we write js too index.html response = str(self.bot.get_response(user_input)) current_app.logger.debug("You:" + user_input) current_app.logger.debug("Bot:" + response) if self.trip_forecast != "": # If we already collected the forecast if self.conversation.is_affirmative(user_input): response = suggest_clothes(self.trip_forecast) self.trip_forecast = '' else: response = "Ok. Take care and enjoy your trip." self.trip_forecast = '' if self.trip_date != "": # If we already collected the date if is_location(user_input): user_location = user_input self.trip_forecast = get_forecast(self.trip_date, user_location) response = self.trip_forecast.get('text') + " Can I sugest you something to wear? "; self.trip_date = '' else: current_app.logger.warning("Error while getting user location.") response = "You entered an invalid location. Please, try again." if self.check_date: current_app.logger.debug("1") if not is_date(user_input, current_app): current_app.logger.debug("2") response = "You entered an invalid date. The date should be within the next 5 days and in the format dd/mm/yyyy. Please, try again." if self.conversation.is_negative(user_input): current_app.logger.debug("2") response = "Ok. Understood." self.check_date = False if self.conversation.is_question(user_input): current_app.logger.debug("3") response = "I will help you. Please enter the date for your next trip?" else: current_app.logger.debug("4") self.trip_date = is_date(user_input, current_app) self.check_date = False response = "Thank you. Please provide the location that you will go. Format: City, Country" if self.other_trip: if self.conversation.is_affirmative(user_input): response = "Ok! Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy" self.check_date = True self.other_trip = False else: response = "Ok. Take care and enjoy your trip." self.other_trip = False if "next trip" in response: current_app.logger.info("Bot waiting for the date.") self.check_date = True if "anything else" in response: current_app.logger.info("Bot waiting for the other trip info.") self.other_trip = True if self.conversation.is_goodbye(user_input): return "Bye." current_app.logger.debug("Variables monitoring:") current_app.logger.debug("trip_date:") current_app.logger.debug(self.trip_date) current_app.logger.debug("trip_forecast:") current_app.logger.debug(self.trip_forecast) current_app.logger.debug("check_date:") current_app.logger.debug(self.check_date) return response except(KeyboardInterrupt, EOFError, SystemExit): current_app.logger.info("End of conversation.")
def test_get_forecast(self): result = weather.get_forecast() self.assertFalse(result, True)
async def forecast(ctx, *input_string): location = '' weather_msg = '' notifications = [] forecast.channel = ctx.message.channel forecast.is_metric = False forecast.is_pm = False forecast.invalid_flag = False forecast.is_saving = False forecast.flag_string = '' def save(): if not forecast.is_saving: forecast.flag_string += 's' forecast.is_saving = True def metric(): if not forecast.is_metric: forecast.flag_string += 'm' forecast.is_metric = True def private_message(): if not forecast.is_pm: forecast.flag_string += 'p' forecast.is_pm = True def invalid_flag(): if not forecast.invalid_flag: forecast.flag_string += 'i' forecast.invalid_flag = True flags = {'-save': save, '-metric': metric, '-pm': private_message} for i in input_string: word = ''.join(i) try: flags[word]() except KeyError: if word[0] == '-': invalid_flag() else: location += '{} '.format(word) location = location.rstrip() is_from_server = not isinstance(ctx.message.server, type(None)) logger_text = '{}'+' - User: {0} User ID: {1} Server Name: {2} ' \ 'Server ID: {3} Location: {4} Flags: {5}'.format(ctx.message.author.name, ctx.message.author.id, ctx.message.server.name if is_from_server else 'N/A', ctx.message.server.id if is_from_server else 'N/A', location if location != '' else 'N/A', forecast.flag_string if not forecast.flag_string == '' else 'N/A') logger.info(logger_text.format('Forecast Request')) await bot.send_typing(forecast.channel) try: weather_msg += get_forecast(location, forecast.is_metric) logger.info(logger_text.format('Forecast Retrieved')) if forecast.is_pm: if is_from_server: forecast.channel = ctx.message.author await bot.say( 'Hey {}, weather information is being sent to your PMs.'. format(ctx.message.author.mention)) if forecast.is_saving: # only saves if no WeatherException caught, preventing useless saves notifications.append( ':warning:' + make_shortcut(ctx.message.author, ctx.message.server, location, forecast.is_metric)) if forecast.invalid_flag: notifications.append( ':warning:Flag(s) identified but not resolved. for all flags view github.com/lluisrojass/discord-weather-bot' ) for m in notifications: weather_msg += m + '\n' except WeatherException: weather_msg += ':warning: {}'.format(sys.exc_info()[1]) logger.info( logger_text.format('Error Retrieving Weather ({})'.format( sys.exc_info()[1]))) await bot.send_message(forecast.channel, weather_msg)
print(choice(jokes)) elif intent == 'thanks': print(choice(youre_welcome)) elif intent in ['weather_get', 'temperature_get', 'is_condition']: if not location: print(choice(error_no_location)) continue request_condition = data['conditions'] date_diff = (request_date - date.today()).days if request_date else 0 if date_diff == 0: weather_conditions = weather.get_current_weather(location) elif 0 < date_diff < 3: weather_conditions = weather.get_forecast(location, date_diff) elif date_diff > 3: print(choice(error_date_too_late)) continue else: print(choice(error_past_date)) continue if intent == 'weather_get': print( f'In {location[0]} it {"will be" if date_diff else "is"} {weather_conditions["condition"]}' f' and the temperature {"will be" if date_diff else "is"} {weather_conditions["temperature"]} ' f'degrees Celsius') elif intent == 'temperature_get': print( f'In {location[0]} the temperature {"will be" if date_diff else "is"} ' f'{weather_conditions["temperature"]} degrees Celsius')
def getweather(city='Rochester',state='NY'): try: forecast = weather.get_forecast(city, state).split('\n') except SystemExit: return {} forecastdict = {} today = time.localtime()[6] lowtempcarry = False hightempcarry = False popcarry = False dayconditionscarry = False nightconditionscarry = False for i in forecast: firstword = i.strip().split(' ')[0].strip('.') if firstword in daysofweek: forecastdayindex = daysofweek.index(firstword) dayoffset = forecastdayindex - today if dayoffset < 0: # damn sundays dayoffset += 7 forecastdatetime = datetime.date.today() + datetime.timedelta(dayoffset) hightempnext = lowtempnext = False hightemp = lowtemp = pop = False dayconditions = nightconditions = False conditions = i.strip().split('...')[1].split(',')[0].strip() if conditions.split(' ')[0] in ['high', 'High', 'low', 'Low']: conditions = False for j in i.strip().split(' '): if hightempnext: hightempnext = False hightemp = int(j.strip(',.')) elif lowtempnext: lowtempnext = False lowtemp = int(j.strip(',.')) elif j in ['high', 'High']: hightempnext = True dayconditions = conditions elif j in ['low', 'Low']: lowtempnext = True nightconditions = conditions elif j[-1] == '%': pop = int(j[:-1]) if hightemp and lowtemp: forecastdict[dayoffset] = (hightemp, lowtemp, pop, dayconditions, nightconditions) elif hightemp and lowtempcarry: if popcarry: pop = max(pop, popcarry) if nightconditionscarry: nightconditions = nightconditionscarry nightconditionscarry = False forecastdict[dayoffset] = (hightemp, lowtempcarry, pop, dayconditions, nightconditions) lowtempcarry = False elif lowtemp and hightempcarry: if popcarry: pop = max(pop, popcarry) if dayconditionscarry: dayconditions = dayconditionscarry dayconditionscarry = False forecastdict[dayoffset] = (hightempcarry, lowtemp, pop, dayconditions, nightconditions) hightempcarry = False elif lowtemp: if dayoffset == 0: forecastdict[dayoffset] = (False, lowtemp, pop, False, nightconditions) else: lowtempcarry = lowtemp popcarry = pop nightconditionscarry = nightconditions elif hightemp: hightempcarry = hightemp dayconditionscarry = dayconditions popcarry = pop if hightempcarry: # handle the "last day" of the forecast, which seems # to only show a high temp. experimental forecastdict[dayoffset] = (hightempcarry, False, False, dayconditionscarry, nightconditions) return forecastdict