示例#1
0
文件: utility.py 项目: my-rep/kala
 async def weather(self, ctx, *, city: str):
     settings = {"APPID": os.environ['OWM']}
     data = weather.get_current('{}'.format(city), units='metric', **settings)
     data2 = weather.get_current(city, units='standard', **settings)
     keys = ['main.temp', 'main.humidity', 'coord.lon', 'coord.lat']
     x = data.get_many(keys)
     loc = data('name')
     country = data('sys.country')
     lon = data('coord.lon')
     lat = data('coord.lat')
     temp = data('main.temp')
     temp2 = temp * 9/5 + 32
     high = data('main.temp_max')
     low = data('main.temp_min')
     high2 = high * 9/5 + 32
     low2 = low * 9/5 + 32
     embed = discord.Embed(title='{}, {}'.format(loc, country), color=ctx.author.color)
     embed.add_field(name='Absolute Location', value='Longitude, Latitude\n{}, {}'.format(lon, lat))
     embed.add_field(name='Temperature', value=f'{temp2 * 1.01:.4f}F, {temp}C')
     embed.add_field(name='Humidity', value='{}%'.format(data('main.humidity')))
     embed.add_field(name='Wind Speed', value='{}m/s'.format(data('wind.speed')))       
     embed.add_field(name='Low Temperature', value='**{}** F\n**{}** C'.format(low2, low))
     embed.add_field(name='High Temperature', value='**{}** F\n**{}** C'.format(high2, high))
     embed.set_footer(text='Weather Data from OpenWeatherMap.org')
     embed.set_thumbnail(url='https://cdn2.iconfinder.com/data/icons/weather-icons-8/512/day-clear-256.png')
     await ctx.send(embed=embed)
示例#2
0
def WeatherBot():

    #auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    #auth.set_access_token(access_token, access_token_secret)
    #api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())

    data = []
    cities = ['Yekaterinburg', 'Washington']
    settings = {"units": "metric", "appid": weather_api_key}
    curtime = datetime.datetime.now().strftime('%H:%M:%S %d-%m-%y ')

    for city in cities:
        data.append(owm.get_current(city, **settings))

    search = [
        'name', 'sys.country', 'main.temp', 'main.humidity', 'clouds.all',
        'wind.speed'
    ]

    ext_data = [city(*search) for city in data]

    tweet = [f'On {curtime} ']

    for x in range(len(cities)):
        tweet.append(
            f'Temperature in {ext_data[x][0]}, {ext_data[x][1]}: {ext_data[x][2]}C°, Humidity: \
{ext_data[x][3]}, Cloudiness: {ext_data[x][4]}, Wind Speed: {ext_data[x][5]}KmH.'
        )

    ans = '\n'.join((tweet))

    api.update_status(f'{ans}')

    print('done')
def _theweather(city):
    # self.city = input("in what city are you located?")

    settings = {'units': 'metric', 'appid': api_key}
    cities_weather = []
    # city = input("in what city are you located?")

    try:
        cities_weather.append(owm.get_current(city, **settings))
        print(f"Processing record | {city}")
    except:
        #         if err.code == 404:
        print(f'City {city} not found... Skipping')

    # this is the information we are looking for, we will create a summery list that we are going to use with the wrapper
    summary = [
        'name', 'clouds.all', 'sys.country', 'main.humidity', 'coord.lat',
        'coord.lon', 'main.temp_max', 'wind.speed'
    ]
    data = [cities_weather[0](*summary)]

    data_dict = {
        "City": data[0][0],
        "Cloudiness": data[0][1],
        "Country": data[0][2],
        "Humidity": data[0][3],
        "Lat": data[0][4],
        "Lon": data[0][5],
        "Max": data[0][6],
        "Min": data[0][7]
    }
    # print (data)
    # print (data_dict)

    return data_dict
示例#4
0
 def getRainStatus(self):
       data = owm.get_current(zip=self.location,**self.settings)
       if not data('weather')[0]['id'] in conditions:
             self.jobstatus="False"
       else:
             print("skipping the job")
             self.jobstatus="True"
       return self.jobstatus
示例#5
0
def current_temperature(location):
    """
    Checks outdoor temperature in the specified location.

    See https://pypi.python.org/pypi/openweathermapy/0.6.6

    :param location: zip code or city to check for current conditions.
    :return: current humidity in the specified location.
    """
    data = owm.get_current(location, **settings)
    return data["main"]["temp"]
示例#6
0
def get_weather(zip_code):
    """
    gets all current weather data from a zip code

    Arguments:
        zip_code {int} -- zip code of interest

    Returns:
        dict -- weather data
    """

    settings = {"units": "imperial", "appid": weather_api_key}
    zip_weather = owm.get_current(zip=zip_code, **settings)
    return zip_weather
示例#7
0
def WeatherTweet(tweet):

    # Construct a Query URL for the OpenWeatherMap
    url = "http://api.openweathermap.org/data/2.5/weather?"
    city = "Washington, D.C."
    units = "imperial"
    settings = {"units": "imperial", "appid": weather_api_key}
    # Perform the API call to get the weather
    washington = owm.get_current(city, **settings)
    washingtonweather = washington["main"]["temp"]
    # Twitter credentials
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())

    # Tweet the weather
    currenttime = datetime.datetime.now().strftime("%I:%M %p")
    api.update_status(
        f"The weather in DC RIGHT NOW is {washingtonweather}F timestamp: {currenttime}"
    )

    # Print success message
    print("This was successful")
示例#8
0
 def execute(self, bot, update, args):
     try:
         if len(args) != 1:
             bot.send_message(
                 chat_id=update.message.chat_id,
                 text="This doesn't seem like correct usage of /weather.",
                 disable_notification=True)
             return
         data = owm.get_current(args[0], **self.settings)
         temp, tmin, tmax = data('main.temp', 'main.temp_min',
                                 'main.temp_max')
         form = "<b>Weather for {}, {}:</b>\n".format(
             data['name'], data['sys']['country'])
         form += " - {} {}\n".format(
             data['weather'][0]['description'].capitalize(),
             emoji.emojize(emojify(data['weather'][0]['id']),
                           use_aliases=True))
         form += " - Current {:.1f}°C / High {:.1f}°C / Low {:.1f}°C\n".format(
             temp, tmax, tmin)
         form += " - Wind: {:.1f} km/h".format(data['wind']['speed'])
         if 'deg' in data['wind']:
             form += " {}".format(self.card(data['wind']['deg']))
         if 'gust' in data['wind']:
             form += " (Gust: {:.1f} km/h)".format(data['wind']['gust'])
         bot.send_message(chat_id=update.message.chat_id,
                          parse_mode=ParseMode.HTML,
                          text=form,
                          disable_notification=True)
         self.logger.info("Command /weather executed successfully.")
     except urllib.error.HTTPError:
         bot.send_message(
             chat_id=update.message.chat_id,
             text="The location you chose seems to be invalid.",
             disable_notification=True)
     except Exception as e:
         raise (e)
示例#9
0
 async def weather(self, ctx, *, city: str):
     """Get the weather for a select city."""
     settings = {"APPID": self.weather_api}
     data = weather.get_current('{}'.format(city), units='metric', **settings)
     loc = data('name')
     country = data('sys.country')
     lon = data('coord.lon')
     lat = data('coord.lat')
     temp = data('main.temp')
     temp2 = temp * 9 / 5 + 32
     high = data('main.temp_max')
     low = data('main.temp_min')
     high2 = high * 9 / 5 + 32
     low2 = low * 9 / 5 + 32
     embed = discord.Embed(title='{}, {}'.format(loc, country), color=ctx.author.color)
     embed.add_field(name='Absolute Location :map:', value='Longitude, Latitude\n{}, {}'.format(lon, lat))
     embed.add_field(name='Temperature :thermometer:', value='{}F, {}C'.format(temp2, temp))
     embed.add_field(name='Humidity :potable_water:', value='{}%'.format(data('main.humidity')))
     embed.add_field(name='Wind Speed :wind_blowing_face: ', value='{}m/s'.format(data('wind.speed')))
     embed.add_field(name='Lowest Temperature :low_brightness: ', value='**{}** F\n**{}** C'.format(low2, low))
     embed.add_field(name='Highest Temperature :high_brightness: ', value='**{}** F\n**{}** C'.format(high2, high))
     embed.set_footer(text='Weather Data from OpenWeatherMap.org')
     embed.set_thumbnail(url='https://cdn2.iconfinder.com/data/icons/weather-icons-8/512/day-clear-256.png')
     await ctx.send(embed=embed)
示例#10
0
import openweathermapy.core as ow

#create settings dictionary
api_key = "15383539ac6ad7827e835523385021b3"
settings = {"units" : "metric", "appid" : api_key}

#parsing is neat
current_weather_paris = ow.get_current("Paris", **settings)
summary = ["main.temp"]

data = current_weather_paris(*summary)
print("The current weather summary for Paris is:" + " " + str(data)) + "degrees celcius"
示例#11
0
 def weatherDetails(self):
         data = owm.get_current(zip=self.location,**self.settings)
         self.wsdetails ={}
         self.wsdetails = {"Condition":data('weather')[0]['main'],"Description":data('weather')[0]['description'],"temp":data('main.temp'),"temp_min":data('main.temp_min'),"temp_max":data('main.temp_max')}
         return self.wsdetails
def ride_share_calcs(start, stop, t):
    import openweathermapy.core as owm
    import requests
    import geopip
    #import os
    import datetime as dt
    from model import prediction_model

    # Weather API
    from config import ow_api_key

    # MapQuest API
    from config import mq_api_key

    # Set geopip to look at geojson file
    #os.environ['REVERSE_GEOCODE_DATA'] = 'Resources/Data/community_areas.geojson'

    # Form Inputs
    start_address = start  #'405 N Wabash Avenue, Chicago, IL'
    end_address = stop  #'938 W Webster Ave, Chicago, IL 60614'
    time = '2019-12-11 00:00:00'
    # make default app time the current time

    # format time to default

    time = t
    noncoded_time = dt.datetime.today()

    # if error then use 'dt.datetime.today()'

    def coded_week(date_input):
        weekdays = 7

        coded_week = []
        for i in range(weekdays):
            if i == date_input - 1:
                coded_week.append(1)
            else:
                coded_week.append(0)

        return coded_week

    # List of Coded Weekday Values
    start_date = dt.datetime.today().weekday()
    coded_week = coded_week(start_date)

    def coded_date(list, type):
        if type == 'months':
            time_frame = 12
            list_var = 0

        elif type == 'days':
            if list[0] in [1, 3, 5, 7, 8, 10, 12]:
                time_frame = 31
                list_var = 1

            if list[0] in [4, 6, 9, 11]:
                time_frame = 30
                list_var = 1

            if list[0] in [2]:
                time_frame = 28
                list_var = 1

        elif type == 'hr-mins':
            time_frame = 96
            hours = 24
            hour = list[2]
            minute = list[3]
            quarter_hour = []

            for j in range(hours):
                if j == hour:
                    if minute >= 45:
                        quarter_hour += [0, 0, 0, 1]
                    elif minute >= 30:
                        quarter_hour += [0, 0, 1, 0]
                    elif minute >= 15:
                        quarter_hour += [0, 1, 0, 0]
                    else:
                        quarter_hour += [1, 0, 0, 0]
                else:
                    quarter_hour += [0, 0, 0, 0]

        if type in ['months', 'days']:
            coded_time = []
            for i in range(time_frame):
                if i == list[list_var] - 1:
                    coded_time.append(1)
                else:
                    coded_time.append(0)
            return coded_time
        else:
            return quarter_hour

    # List of Coded Months and Days (96 Quarter Hour Periods)
    noncoded_month = noncoded_time.month
    noncoded_day = noncoded_time.day
    noncoded_hour = noncoded_time.hour
    noncoded_minute = noncoded_time.minute
    date_list = [noncoded_month, noncoded_day, noncoded_hour, noncoded_minute]
    coded_dates = coded_date(date_list, 'months') + coded_date(
        date_list, 'days') + coded_date(date_list, 'hr-mins')

    # Extract Map Information - variables added to model
    url = f'https://www.mapquestapi.com/directions/v2/optimizedRoute?json={{"locations":["{start_address}","{end_address}"]}}&outFormat=json&key={mq_api_key}'
    format = "json"

    street_directions = requests.get(f"{url}").json()
    distance = street_directions["route"]['distance']
    duration = street_directions["route"]["time"]
    start_longitude = street_directions["route"]["boundingBox"]["lr"]['lng']
    start_latitude = street_directions["route"]["boundingBox"]["lr"]['lat']
    end_longitude = street_directions["route"]["boundingBox"]["ul"]['lng']
    end_latitude = street_directions["route"]["boundingBox"]["ul"]['lat']

    def coded_community(community):
        number_communities = 77

        coded_location = []
        for i in range(number_communities):
            if i == community - 1:
                coded_location.append(1)
            else:
                coded_location.append(0)

        return coded_location

    # List of Coded Start Community
    #start_geo = int(geopip.search(start_longitude, start_latitude)['area_num_1'])
    #coded_start_community = coded_community(start_geo)

    # List of Coded End Community
    #end_geo = int(geopip.search(end_longitude, end_latitude)['area_num_1'])
    #coded_end_community = coded_community(end_geo)

    # Retrieve Weather Data
    settings = {"units": "imperial", "appid": ow_api_key}
    location = (start_latitude, start_longitude)
    current_weather_chicago = owm.get_current(location, **settings)
    actual_temp = current_weather_chicago('main.temp')
    feels_temp = current_weather_chicago('main.feels_like')
    pressure = current_weather_chicago('main.pressure')
    humidity = current_weather_chicago('main.humidity')

    # Precipitation calc
    # https://openweathermap.org/weather-conditions
    # https://openweathermap.org/weather-data

    # weather code converted into average precipitation value
    rain_light_precipitation = [200, 230, 231, 300, 301, 310, 311, 500, 520]
    rain_moderate_precipitation = [201, 232, 302, 312, 313, 321, 501, 521]
    rain_intense_precipitation = [202, 314, 502, 503, 504, 531]

    weather_code = current_weather_chicago('cod')

    if weather_code in rain_light_precipitation:
        rain = 0.1
    elif weather_code in rain_moderate_precipitation:
        rain = 1.0
    elif weather_code in rain_intense_precipitation:
        rain = 2.0
    else:
        rain = 0.0

    snow_light_precipitation = [600, 620]
    snow_moderate_precipitation = [601, 612, 613, 615, 616, 621]
    snow_intense_precipitation = [602, 611, 622]

    if weather_code in snow_light_precipitation:
        snow = 0.1
    elif weather_code in snow_moderate_precipitation:
        snow = 1.0
    elif weather_code in snow_intense_precipitation:
        snow = 2.0
    else:
        snow = 0.0

    weather = [actual_temp, feels_temp, pressure, humidity, rain, snow]

    # Need Variables:  duration, distance, rain_1h, PCA_76, DCA_76, temp, November, PCA_56, DCA_56, snow_1h
    # Variables Translated:  duration, distance, rain, start_geo[75], end_geo[75], actual_temp, coded_date[10], start_geo[55], end_geo[55], snow
    #ML_input_original = [duration, distance, start_geo, end_geo, start_longitude, start_latitude, end_longitude, end_latitude] + coded_week + coded_date + coded_start_community + coded_end_community + weather

    #ML_input_values = [duration, distance, rain, coded_start_community[75], coded_end_community[75], actual_temp, coded_dates[10], coded_start_community[55], coded_end_community[55], snow]
    ML_input_values = [
        duration, distance, rain, 0, 0, actual_temp, coded_dates[10], 0, 0,
        snow
    ]
    ML_input = prediction_model(ML_input_values)
    return ML_input
示例#13
0
import logging
import time
import datetime
import openweathermapy.core as owm

units = 'imperial'
settings = {
    "APPID": "5aead618eb034cfd535ab9331ee4ec05",
    "units": units,
    "lang": "US"
}
data = owm.get_current("Denver,US", **settings)
fahrenheit_degrees = u'\N{DEGREE SIGN}' + "F"
celcius_degrees = u'\N{DEGREE SIGN}' + "C"
doIteration = False


def convertDegreesToCompassDirection(deg):
    compass = [
        "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW",
        "WSW", "W", "WNW", "NW", "NNW", "N"
    ]
    ndx = int(round(deg / 22.5) + 1)
    return compass[ndx]


print(data)
views = {
    "summary": [
        "main.temp", "main.pressure", "main.humidity", "main.temp_min",
        "main.temp_max", "main.humidity"