Exemple #1
0
def get_weather():
    global w, sunrise, sunset, sun_duration, moonrise, moonset, moon_duration, URL, URL_HOURLY, URL_DAILY, city_name, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain, t_today_low, t_tomorrow_low
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    show_block_tomorrow = gw_vars.get('show_block_tomorrow')
    show_block_today = gw_vars.get('show_block_today')
    show_block_add_info = gw_vars.get('show_block_add_info')
    weather_lang = gw_vars.get('weather_lang')
    icons_name = gw_vars.get('icons_name')
    if city_id.split(',')[0]==city_id.split(',')[-1]:
        city_number = city_id.split('/')[-1]
    else:
        city_number = city_id.split(',')[-1].strip()
        city_id = city_id.split(',')[0].strip()
    URL_CURRENT = 'http://www.accuweather.com/%s/%s/current-weather/%s'%(weather_lang, city_id, city_number)
    URL_ADD_INFO = 'http://www.accuweather.com/en/%s/current-weather/%s'%(city_id, city_number)
    URL_SEVERAL_DAYS = 'http://www.accuweather.com/%s/%s/month/%s?view=table'%(weather_lang, city_id, city_number)

    URL = URL_CURRENT
    URL_HOURLY = 'http://www.accuweather.com/%s/%s/hourly-weather-forecast/%s'%(weather_lang, city_id, city_number)
    URL_DAILY = 'http://www.accuweather.com/%s/%s/daily-weather-forecast/%s?day='%(weather_lang, city_id, city_number)

    print ('\033[34m>\033[0m '+_('Getting weather for')+' '+str(n)+' '+_('days'))

    source = urlopener(URL_CURRENT, 5)
    if not source:
        return False
    # time.sleep(1)

    # sun/moon
    sun_moon = re.findall('<span>(.*)</span></li>', source)

    if sun_moon:
        sunrise = sun_moon[1]
        sunset = sun_moon[2]
        sun_duration = sun_moon[3][:-3]
        moonrise = sun_moon[4]
        moonset = sun_moon[5]
        moon_duration = sun_moon[6][:-3]

    #### current weather ####
    # city
    city_name = re.findall('"current-city"><h1>(.*),', source)

    celsius = re.findall('\d\&deg;C', source)

    # temperature
    w_now = re.findall('detail-now.*', source, re.DOTALL)
    t_now = re.findall('<span class="large-temp">(.?\d+)', w_now[0])
    t_now_f = re.findall('<em>RealFeel&#174;</em>\s?(.?\d+)', w_now[0])
    if not celsius:
        t_now[0] = F_to_C(t_now[0])
        t_now_f[0] = F_to_C(t_now_f[0])
    t_now[0] = convert_from_C(t_now[0], t_now_f[0])

    # wind
    wind_speed_now = re.findall('<li class="wind"><strong>(\d*)', source)
    if wind_speed_now:
        wind_speed_now[0] = convert_from_kmh(wind_speed_now[0])
    wind_direct_now = re.findall('<div class="wind-point (.*)"', w_now[0])

    # icon
    icon_now = re.findall('<div class="icon (.*)xl"', w_now[0])
    icon_now[0] = convert(icon_now[0], icons_name)

    # wind icon
    icon_wind_now = ['']
    try:
        icon_wind_now[0] = wind_degree(wind_direct_now[0])
    except:
        icon_wind_now[0] = 'None'
    try:
        if wind_direct_now[0]=='CLM':
            wind_direct_now[0]=_('Calm')
        else:
            a=''
            for i in range(len(wind_direct_now[0])):
                a=a+_(wind_direct_now[0][i])
            wind_direct_now[0]=a
    except:
        wind_direct_now = []

    # weather text now
    text_now = re.findall('<span class="cond">(.*)<', w_now[0])
    text_now[0]=text_now[0].split('<')[0]
    
    # if show_block_add_info:
    source = urlopener(URL_ADD_INFO, 5)
    if not source:
        return False
    # time.sleep(1)

    # pressure now
    press = re.findall('Pressure.*>(.+?)<', source)
    if press:
        press_now = [press[0].split()[0]]
        press_scale = press[0].split()[1]
        if press_scale == 'mb':
            press_now[0] = convert_from_hPa(press_now[0])
        if press_scale == 'in':
            press_now[0] = convert_from_inHg(press_now[0])
    else:
        press_now = ['n/a mmHg;n/a inHg;n/a hPa']
    # humidity now
    hum_now = re.findall('Humidity.*>(\d+)', source)
    if not hum_now:
        hum_now=['n/a']

    #### weather to several days ####
    source = urlopener(URL_SEVERAL_DAYS, 5)
    if not source:
        return False

    # all days
    w_all = re.findall('<tr class="today lo calendar.*</table>', source, re.DOTALL)

    # day temperature
    t_day = re.findall('<td>(.*)&#176;/', w_all[0])
    t_day = t_day[::2]
    for i in range(len(t_day)):
        if not celsius:
            t_day[i] = F_to_C(t_day[i])
        t_day[i] = convert_from_C(t_day[i])

    # night temperature
    t_night = re.findall('<td>.*/(.*)&#176;', w_all[0])
    t_night = t_night[::2]
    for i in range(len(t_night)):
        if not celsius:
            t_night[i] = F_to_C(t_night[i])
        t_night[i] = convert_from_C(t_night[i])


    # day of week, date
    day = re.findall('<a.*>(.*)[.| ]*<time>', w_all[0])
    date = re.findall('<time>(.*)</time>', w_all[0])
    # try:
    #     int(date[0][:4])
    #     for i in range(len(date)):
    #         date[i]=date[i][5:]
    # except:
    #     for i in range(len(date)):
    #         date[i]=date[i][:-5]

    # weather icon day
    icon = re.findall('<div class="icon (.*)s"', w_all[0])
    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)


    # weather text
    text = re.findall('<p>(.*)</p>', w_all[0])

    chance_of_rain = re.findall('<td>(.*?)\s*<span class="small">(.*?)<', w_all[0])
    for i in range(len(chance_of_rain)):
        chance_of_rain[i] = ' '.join(chance_of_rain[i])
    chance_of_rain = chance_of_rain[::2]


    # if end of month, get days from next month
    if len(t_day)-1<n:
        try:
            next_month = re.findall('href="(.*)&amp;.*next-month', source)
            next_month[0] = next_month[0]+'&view=table'
            source = urlopener(next_month[0], 5)
            if not source:
                return False

            # all days
            w_all = re.findall('<tr class="lo calendar-list-cl-tr.*</table>', source, re.DOTALL)

            # day temperature
            t_day2 = re.findall('<td>(.*)&#176;/', w_all[0])
            t_day2 = t_day2[::2]
            for i in range(len(t_day2)):
                if not celsius:
                    t_day2[i] = F_to_C(t_day2[i])
                t_day2[i] = convert_from_C(t_day2[i])
            t_day.extend(t_day2)

            # night temperature
            t_night2 = re.findall('<td>.*/(.*)&#176;', w_all[0])
            t_night2 = t_night2[::2]
            for i in range(len(t_night2)):
                if not celsius:
                    t_night2[i] = F_to_C(t_night2[i])
                t_night2[i] = convert_from_C(t_night2[i])
            t_night.extend(t_night2)


            # day of week, date
            day2 = re.findall('<a.*>(.*)[.| ]*<time>', w_all[0])
            date2 = re.findall('<time>(.*)</time>', w_all[0])
            # try:
            #     int(date2[0][:4])
            #     for i in range(len(date2)):
            #         date2[i]=date2[i][5:]
            # except:
            #     for i in range(len(date2)):
            #         date2[i]=date2[i][:-5]
            day.extend(day2)
            date.extend(date2)


            # weather icon day
            icon2 = re.findall('<div class="icon (.*)s"', w_all[0])
            for i in range(len(icon2)):
                icon2[i] = convert(icon2[i], icons_name)
            icon.extend(icon2)


            # weather text
            text2 = re.findall('<p>(.*)</p>', w_all[0])
            # if text[-1] == '': # Need or not?
            #     del text[-1]
            text.extend(text2)


            chance_of_rain2 = re.findall('<td>(\d+)\s*<span class="small">(.*)</td>', w_all[0])
            for i in range(len(chance_of_rain2)):
                chance_of_rain2[i] = ' '.join(chance_of_rain2[i])
            if chance_of_rain2[1][-1] == '>':
                chance_of_rain2 = chance_of_rain2[::2]
            chance_of_rain.extend(chance_of_rain2)

        except:
            print('Can\'t get weather for next month')
            pass

    if show_block_tomorrow:
        #### weather tomorrow ####
        source = ['', '', '', '']
        for i, w_time in zip(range(4), ['morning', 'afternoon', 'evening', 'overnight']):
            source[i] = urlopener('http://www.accuweather.com/en/%s/%s-weather-forecast/%s?day=2'%(city_id, w_time, city_number), 5)
            if not source[i]:
                return False

        t_tomorrow=[]
        t_tomorrow_low = []
        icon_tomorrow = []
        
        for s in source:
            w_now = re.findall('detail-now.*', s, re.DOTALL)
            
            t = re.findall('<span class="large-temp">(.?\d+)', w_now[0])
            t_feel = re.findall('<em>RealFeel&#174;</em>\s?(.?\d+).*;/(.?\d+)', w_now[0])
            t_f = ['', '']
            if not celsius:
                t[0] = F_to_C(t[0])
                t_f[0] = F_to_C(t_feel[0][0])
                t_f[1] = F_to_C(t_feel[0][1])
            t[0] = convert_from_C(t[0], t_f[0])
            t_tomorrow.append(t[0])
            
            t = re.findall('<span class="small-temp">/(.?\d+)', w_now[0])
            if not celsius:
                t[0] = F_to_C(t[0])
            t[0] = convert_from_C(t[0], t_f[1])
            t_tomorrow_low.append(t[0])
            
            i = re.findall('<div class="icon (.*)xl"', w_now[0])
            i[0] = convert(i[0], icons_name)
            icon_tomorrow.append(i[0])
        

    if show_block_today:
        #### weather today ####
        source = ['', '', '', '']
        for i, w_time in zip(range(4), ['morning', 'afternoon', 'evening', 'overnight']):
            source[i] = urlopener('http://www.accuweather.com/en/%s/%s-weather-forecast/%s?day=1'%(city_id, w_time, city_number), 5)
            if not source[i]:
                return False

        t_today=[]
        t_today_low = []
        icon_today = []
        
        for s in source:
            w_now = re.findall('detail-now.*', s, re.DOTALL)
            
            t = re.findall('<span class="large-temp">(.?\d+)', w_now[0])
            t_feel = re.findall('<em>RealFeel&#174;</em>\s?(.?\d+).*;/(.?\d+)', w_now[0])
            t_f = ['', '']
            if not celsius:
                t[0] = F_to_C(t[0])
                t_f[0] = F_to_C(t_feel[0][0])
                t_f[1] = F_to_C(t_feel[0][1])
            t[0] = convert_from_C(t[0], t_f[0])
            t_today.append(t[0])
            
            t = re.findall('<span class="small-temp">/(.?\d+)', w_now[0])
            if not celsius:
                t[0] = F_to_C(t[0])
            t[0] = convert_from_C(t[0], t_f[1])
            t_today_low.append(t[0])
            
            i = re.findall('<div class="icon (.*)xl"', w_now[0])
            i[0] = convert(i[0], icons_name)
            icon_today.append(i[0])


    if time_update:
        print ('\033[34m>\033[0m '+_('updated on server')+' '+time_update[0]) 
    print ('\033[34m>\033[0m '+_('weather received')+' '+time.strftime('%H:%M', time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
def get_weather():
    global city_name, URL, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    APPID = gw_vars.get('appid')
    if not APPID:
        print('\033[1;31m[!]\033[0m Empty API key. Please enter API key')
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    show_block_tomorrow = gw_vars.get('show_block_tomorrow')
    show_block_today = gw_vars.get('show_block_today')
    show_block_add_info = gw_vars.get('show_block_add_info')
    weather_lang = gw_vars.get('weather_lang')
    icons_name = gw_vars.get('icons_name')
    URL = ''
    URL_CURRENT = 'http://api.openweathermap.org/data/2.5/weather?id=%s&lang=%s&units=metric&appid=%s' % (
        str(city_id), weather_lang, APPID)
    URL_SEVERAL_DAYS = 'http://api.openweathermap.org/data/2.5/forecast/daily?id=%s&lang=%s&units=metric&cnt=%s&appid=%s' % (
        str(city_id), weather_lang, n + 1, APPID)
    URL_TODAY_TOMORROW = 'http://api.openweathermap.org/data/2.5/forecast?id=%s&lang=%s&units=metric&appid=%s' % (
        str(city_id), weather_lang, APPID)
    print('\033[34m>\033[0m ' + _('Getting weather for') + ' ' + str(n) + ' ' +
          _('days'))

    source = urlopener(URL_CURRENT, 5)
    if not source:
        return False
    source = json.loads(source)

    #### current weather ####
    # city
    city_name = [source['name']]

    # temperature
    t_now = [add_plus(str(round(source['main']['temp'])))]
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = [str(round(source['wind']['speed']))]
    if wind_speed_now:
        wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    try:
        wind_direct_now = [wind_direct_convert.convert(source['wind']['deg'])]
        a = ''
        for i in range(len(wind_direct_now[0])):
            a = a + _(wind_direct_now[0][i])
        wind_direct_now[0] = a
    except:
        wind_direct_now = []

    # icon
    icon_now = [
        'http://openweathermap.org/img/w/' + source['weather'][0]['icon'] +
        '.png'
    ]
    icon_now[0] = convert(icon_now[0], icons_name)

    # wind icon
    try:
        icon_wind_now = [round(source['wind']['deg']) + 90]
        if icon_wind_now[0] == '0':
            icon_wind_now[0] = 'None'
    except:
        icon_wind_now = ['None']

    # update time
    dt = datetime.fromtimestamp(source['dt'])
    time_update = [dt.strftime('%H:%M')]

    # weather text now
    text_now = [source['weather'][0]['description']]

    # pressure now
    press_now = [str(round(source['main']['pressure']))]
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    # humidity now
    hum_now = [str(source['main']['humidity'])]

    #### weather to several days ####
    source = urlopener(URL_SEVERAL_DAYS, 5)
    if not source:
        return False
    source = json.loads(source)

    t_day = []
    t_night = []
    day = []
    date = []
    icon = []
    text = []
    wind_speed = []
    wind_direct = []
    chance_of_rain = []

    for data in source['list']:
        t_day.append(add_plus(str(round(data['temp']['day']))))
        t_night.append(add_plus(str(round(data['temp']['night']))))
        dt = datetime.fromtimestamp(data['dt'])
        day.append(dt.strftime('%a'))
        date.append(dt.strftime('%d.%m'))
        icon.append('http://openweathermap.org/img/w/' +
                    data['weather'][0]['icon'] + '.png')
        text.append(data['weather'][0]['description'])
        wind_speed.append(str(round(data['speed'])))
        wind_direct.append(wind_direct_convert.convert(data['deg']))
        chance_of_rain.append(
            str(data['rain']) if 'rain' in data.keys() else '')

    for j in range(len(wind_direct)):
        a = ''
        for i in range(len(wind_direct[j])):
            a = a + _(wind_direct[j][i])
        wind_direct[j] = a

    for i in range(len(t_day)):
        t_day[i] = convert_from_C(t_day[i])

    for i in range(len(t_night)):
        t_night[i] = convert_from_C(t_night[i])

    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)

    if wind_speed:
        for i in range(len(wind_speed)):
            wind_speed[i] = convert_from_ms(wind_speed[i])

    if show_block_tomorrow or show_block_today:
        source = urlopener(URL_TODAY_TOMORROW, 5)
        if not source:
            return False
        source = json.loads(source)

        t_tomorrow = ['', '', '', '']
        t_today = ['', '', '', '']
        icon_today = ['', '', '', '']
        icon_tomorrow = ['', '', '', '']
        wind_speed_tod = ['', '', '', '']
        wind_direct_tod = ['', '', '', '']
        wind_speed_tom = ['', '', '', '']
        wind_direct_tom = ['', '', '', '']

        day_today = get_day(source['list'][0])

        for data in source['list']:
            day_tommorow = get_day(data)
            if day_tommorow != day_today:
                break

        for data in source['list']:
            day_after_tommorow = get_day(data)
            if day_after_tommorow != day_today and day_after_tommorow != day_tommorow:
                break

        a_dict = {'00:00': 3, '06:00': 0, '12:00': 1, '18:00': 2}

        for data in source['list']:
            if get_time(data) in a_dict.keys():
                if get_day(data) == day_today:
                    t_today[a_dict[get_time(data)]] = add_plus(
                        str(round(data['main']['temp'])))
                    icon_today[a_dict[get_time(
                        data)]] = 'http://openweathermap.org/img/w/' + data[
                            'weather'][0]['icon'] + '.png'
                    wind_speed_tod[a_dict[get_time(data)]] = str(
                        round(data['wind']['speed']))
                    wind_direct_tod[a_dict[get_time(
                        data)]] = wind_direct_convert.convert(
                            data['wind']['deg'])
                if get_day(data) == day_tommorow:
                    t_tomorrow[a_dict[get_time(data)]] = add_plus(
                        str(round(data['main']['temp'])))
                    icon_tomorrow[a_dict[get_time(
                        data)]] = 'http://openweathermap.org/img/w/' + data[
                            'weather'][0]['icon'] + '.png'
                    wind_speed_tom[a_dict[get_time(data)]] = str(
                        round(data['wind']['speed']))
                    wind_direct_tom[a_dict[get_time(
                        data)]] = wind_direct_convert.convert(
                            data['wind']['deg'])
                    if get_time(data) == '00:00':
                        t_today[3] = add_plus(str(round(data['main']['temp'])))
                        icon_today[
                            3] = 'http://openweathermap.org/img/w/' + data[
                                'weather'][0]['icon'] + '.png'
                        wind_speed_tod[3] = str(round(data['wind']['speed']))
                        wind_direct_tod[3] = wind_direct_convert.convert(
                            data['wind']['deg'])
                if get_day(data) == day_after_tommorow and get_time(
                        data) == '00:00':
                    t_tomorrow[3] = add_plus(str(round(data['main']['temp'])))
                    icon_tomorrow[
                        3] = 'http://openweathermap.org/img/w/' + data[
                            'weather'][0]['icon'] + '.png'
                    wind_speed_tom[3] = str(round(data['wind']['speed']))
                    wind_direct_tom[3] = wind_direct_convert.convert(
                        data['wind']['deg'])

        for i in range(len(t_today)):
            if t_today[i] != '':
                t_today[i] = t_today[i] + '°;' + t_today[i] + '°;' + C_to_F(
                    t_today[i]) + '°;' + C_to_F(t_today[i]) + '°;' + C_to_K(
                        t_today[i]) + ';' + C_to_K(t_today[i])
            else:
                t_today[i] = ';;;;;'

        for i in range(len(t_tomorrow)):
            if t_tomorrow[i] != '':
                t_tomorrow[i] = t_tomorrow[i] + '°;' + t_tomorrow[
                    i] + '°;' + C_to_F(t_tomorrow[i]) + '°;' + C_to_F(
                        t_tomorrow[i]) + '°;' + C_to_K(
                            t_tomorrow[i]) + ';' + C_to_K(t_tomorrow[i])
            else:
                t_tomorrow[i] = ';;;;;'
        for i in range(len(icon_today)):
            if icon_today[i] != '':
                icon_today[i] = convert(icon_today[i], icons_name)
            else:
                icon_today[i] = 'na.png;na.png'
        for i in range(len(icon_tomorrow)):
            if icon_tomorrow[i] != '':
                icon_tomorrow[i] = convert(icon_tomorrow[i], icons_name)
            else:
                icon_tomorrow[i] = 'na.png;na.png'
        for i in range(len(wind_speed_tod)):
            if wind_speed_tod[i] != '':
                wind_speed_tod[i] = convert_from_ms(wind_speed_tod[i])
            else:
                wind_speed_tod[i] = ';;'
        for i in range(len(wind_speed_tom)):
            if wind_speed_tom[i] != '':
                wind_speed_tom[i] = convert_from_ms(wind_speed_tom[i])
        for j in range(len(wind_direct_tod)):
            a = ''
            for i in range(len(wind_direct_tod[j])):
                a = a + _(wind_direct_tod[j][i])
            wind_direct_tod[j] = a
        for j in range(len(wind_direct_tom)):
            a = ''
            for i in range(len(wind_direct_tom[j])):
                a = a + _(wind_direct_tom[j][i])
            wind_direct_tom[j] = a

    if time_update:
        print('\033[34m>\033[0m ' + _('updated on server') + ' ' +
              time_update[0])
    print('\033[34m>\033[0m ' + _('weather received') + ' ' +
          time.strftime('%H:%M', time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
Exemple #3
0
def get_weather():
    global time_of_day_list, URL, city_name, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    icons_name = gw_vars.get('icons_name')
    URL = 'http://www.yr.no/sted/%s/forecast.xml' % str(city_id)
    print ('\033[34m>\033[0m '+_('Getting weather for')+' '+str(n)+' '+_('days'))

    source = urlopener(URL, 5)
    if not source:
        return False

    URL = 'http://www.yr.no/sted/%s' % str(city_id)

    latitude = re.findall('<location.*latitude="(.+?)"', source)
    longitude = re.findall('<location.*longitude="(.+?)"', source)
    URL_CURRENT = "http://api.yr.no/weatherapi/locationforecast/1.9/?lat=%s;lon=%s" %(latitude[0], longitude[0])

    # city
    city_name = re.findall('<name>(.+?)</name>', source)

    # temperature
    temp = re.findall('<temperature unit="celsius" value="(.+?)"', source)
    for i in range(len(temp)):
        temp[i] = convert_from_C(temp[i])
    t_now = [temp[0]]

    # wind
    wind_speed_now = re.findall('<windSpeed mps="(.+?)"', source)
    if wind_speed_now:
        for i in range(len(wind_speed_now)):
            wind_speed_now[i] = convert_from_ms(wind_speed_now[i])

    wind_direct_now = re.findall('<windDirection.*code="(.*?)"', source)

    # icon
    icons = re.findall('<symbol.*var="([mf/]*.+?)"', source)
    for i in range(len(icons)):
        icons[i] = convert(icons[i], icons_name)
    icon_now = [icons[0]]

    # weather text now
    text_now = re.findall('<symbol.*name="(.+?)"', source)

    #### weather to several days ####
    # all days
    dates = re.findall('<time from="\d\d\d\d-(.+?)T', source)

    t_night = ['']
    t_day = ['']
    icon = []
    text = []
    date = [dates[0]]
    wind_speed = ['']
    wind_direct = ['']
    all_periods = re.findall('<time.*period="(\d)"', source)
    for i in range(1, len(all_periods)):
        if all_periods[i] == '0':
            # night
            t_night.append(temp[i])
            pass
        if all_periods[i] == '2':
            # day
            t_day.append(temp[i])
            icon.append(icons[i])
            text.append(text_now[i])
            date.append(dates[i])
            wind_speed.append(wind_speed_now[i])
            wind_direct.append(wind_direct_now[i])
            pass

    #### today tomorrow weather ####
    t_today = ['', '', '', '']
    t_tomorrow = []
    icon_today = ['', '', '', '']
    icon_tomorrow = []
    wind_speed_tod = ['', '', '', '']
    wind_speed_tom = []
    wind_direct_tod = ['', '', '', '']
    wind_direct_tom = []
    time_of_day_list = ( _('Night'), _('Morning'), _('Day'), _('Evening'))
    a1 = ['0', '1', '2', '3']
    a2 = ['0', '1', '2', '3']
    for i in range(len(all_periods)):
        if all_periods[i] in a1:
            t_today[int(all_periods[i])] = temp[i]
            icon_today[int(all_periods[i])] = icons[i]
            wind_speed_tod[int(all_periods[i])] = wind_speed_now[i]
            wind_direct_tod[int(all_periods[i])] = wind_direct_now[i]
            if all_periods[i] == '3':
                a1 = []
        else:
            if all_periods[i] in a2:
                t_tomorrow.append(temp[i])
                icon_tomorrow.append(icons[i])
                wind_speed_tom.append(wind_speed_now[i])
                wind_direct_tom.append(wind_direct_now[i])
                if all_periods[i] == '3':
                    break

    #### current weather ####
    source = urlopener(URL_CURRENT, 5)
    if not source:
        return False

    # pressure now
    press_now = re.findall('<pressure.*value="(.+?)"', source)
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    hum_now = re.findall('<humidity value="(.+?)"', source)
    hum_now[0] = str(round(float(hum_now[0])))

    t_now = re.findall('<temperature.*unit="celsius" value="(.+?)"', source)
    t_now[0] = convert_from_C(t_now[0])

    wind_speed_now = re.findall('<windSpeed.*mps="(.+?)"', source)
    wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    wind_direct_now = re.findall('<windDirection.*name="(.+?)"', source)

    icon_wind_now = re.findall('<windDirection.*deg="(.+?)"', source)
    if icon_wind_now[0] == '0':
        icon_wind_now[0] = 'None'
    else:
        icon_wind_now[0] = round(float(icon_wind_now[0]))+90

    print ('\033[34m>\033[0m '+_('weather received')+' '+time.strftime('%H:%M', time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
Exemple #4
0
def get_weather():
    global time_of_day_list, URL, city_name, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    icons_name = gw_vars.get('icons_name')
    URL = 'http://www.yr.no/place/%s/forecast.xml' % str(city_id)
    print ('\033[34m>\033[0m '+_('Getting weather for')+' '+str(n)+' '+_('days'))

    source = urlopener(URL, 2)
    if not source:
        return False

    URL = 'http://www.yr.no/sted/%s' % str(city_id)

    latitude = re.findall('<location.*latitude="(.+?)"', source)
    longitude = re.findall('<location.*longitude="(.+?)"', source)
    URL_CURRENT = "http://api.met.no/weatherapi/locationforecast/1.9/?lat=%s;lon=%s" %(latitude[0], longitude[0])

    # city
    city_name = re.findall('<name>(.+?)</name>', source)

    # temperature
    temp = re.findall('<temperature unit="celsius" value="(.+?)"', source)
    for i in range(len(temp)):
        temp[i] = convert_from_C(temp[i])
    t_now = [temp[0]]

    # wind
    wind_speed_now = re.findall('<windSpeed mps="(.+?)"', source)
    if wind_speed_now:
        for i in range(len(wind_speed_now)):
            wind_speed_now[i] = convert_from_ms(wind_speed_now[i])

    wind_direct_now = re.findall('<windDirection.*code="(.*?)"', source)

    # icon
    icons = re.findall('<symbol.*var="([mf/]*.+?)"', source)
    for i in range(len(icons)):
        icons[i] = convert(icons[i], icons_name)
    icon_now = [icons[0]]

    # weather text now
    text_now = re.findall('<symbol.*name="(.+?)"', source)

    #### weather to several days ####
    # all days
    dates = re.findall('<time from="\d\d\d\d-(.+?)T', source)

    t_night = ['']
    t_day = ['']
    icon = []
    text = []
    date = [dates[0]]
    wind_speed = ['']
    wind_direct = ['']
    all_periods = re.findall('<time.*period="(\d)"', source)
    for i in range(1, len(all_periods)):
        if all_periods[i] == '0':
            # night
            t_night.append(temp[i])
            pass
        if all_periods[i] == '2':
            # day
            t_day.append(temp[i])
            icon.append(icons[i])
            text.append(text_now[i])
            date.append(dates[i])
            wind_speed.append(wind_speed_now[i])
            wind_direct.append(wind_direct_now[i])
            pass

    #### today tomorrow weather ####
    t_today = [';;;;;', ';;;;;', ';;;;;', ';;;;;']
    t_tomorrow = []
    icon_today = ['clear.png;clear.png', 'clear.png;clear.png', 'clear.png;clear.png', 'clear.png;clear.png']
    icon_tomorrow = []
    wind_speed_tod = ['', '', '', '']
    wind_speed_tom = []
    wind_direct_tod = ['', '', '', '']
    wind_direct_tom = []
    time_of_day_list = ( _('Night'), _('Morning'), _('Day'), _('Evening'))
    a1 = ['0', '1', '2', '3']
    a2 = ['0', '1', '2', '3']
    for i in range(len(all_periods)):
        if all_periods[i] in a1:
            t_today[int(all_periods[i])] = temp[i]
            icon_today[int(all_periods[i])] = icons[i]
            wind_speed_tod[int(all_periods[i])] = wind_speed_now[i]
            wind_direct_tod[int(all_periods[i])] = wind_direct_now[i]
            if all_periods[i] == '3':
                a1 = []
        else:
            if all_periods[i] in a2:
                t_tomorrow.append(temp[i])
                icon_tomorrow.append(icons[i])
                wind_speed_tom.append(wind_speed_now[i])
                wind_direct_tom.append(wind_direct_now[i])
                if all_periods[i] == '3':
                    break

    #### current weather ####
    source = urlopener(URL_CURRENT, 2)
    if not source:
        return False

    # pressure now
    press_now = re.findall('<pressure.*value="(.+?)"', source)
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    hum_now = re.findall('<humidity value="(.+?)"', source)
    hum_now[0] = str(round(float(hum_now[0])))

    t_now = re.findall('<temperature.*unit="celsius" value="(.+?)"', source)
    t_now[0] = convert_from_C(t_now[0])

    wind_speed_now = re.findall('<windSpeed.*mps="(.+?)"', source)
    wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    wind_direct_now = re.findall('<windDirection.*name="(.+?)"', source)

    icon_wind_now = re.findall('<windDirection.*deg="(.+?)"', source)
    if icon_wind_now[0] == '0':
        icon_wind_now[0] = 'None'
    else:
        icon_wind_now[0] = round(float(icon_wind_now[0]))+90

    print ('\033[34m>\033[0m '+_('weather received')+' '+time.strftime('%H:%M', time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
Exemple #5
0
def get_weather():
    global city_name, URL, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain, time_of_day_list, sunrise, sunset, sun_duration
    APPID = gw_vars.get('appid')
    if not APPID:
        print('\033[1;31m[!]\033[0m Empty API key. Please enter API key')
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    if city_id[0] != 'l':
        city_id = 'id='+city_id
    show_block_tomorrow = gw_vars.get('show_block_tomorrow')
    show_block_today = gw_vars.get('show_block_today')
    show_block_add_info = gw_vars.get('show_block_add_info')
    weather_lang = gw_vars.get('weather_lang')
    URL = 'https://openweathermap.org/city/%s'%str(city_id)
    URL_CURRENT = 'http://api.openweathermap.org/data/2.5/weather?%s&lang=%s&units=metric&appid=%s'%(str(city_id), weather_lang, APPID)
    URL_SEVERAL_DAYS = 'http://api.openweathermap.org/data/2.5/forecast?%s&lang=%s&units=metric&appid=%s'%(str(city_id), weather_lang, APPID)

    print ('\033[34m>\033[0m '+_('Getting weather for')+' '+str(n)+' '+_('days'))

    source = urlopener(URL_CURRENT, 2)
    if not source:
        return False
    source = json.loads(source)

    #### current weather ####
    # city
    city_name = [source['name']]

    # temperature
    t_now = [add_plus(str(round(source['main']['temp'])))]
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = [str(round(source['wind']['speed']))]
    if wind_speed_now:
        wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    try:
        wind_direct_now = [wind_direct_convert.convert(source['wind']['deg'])]
    except:
        wind_direct_now = []

    # icon
    icon_now = ['http://openweathermap.org/img/w/'+source['weather'][0]['icon']+'.png']
    icon_now[0] = convert(icon_now[0])

    # wind icon
    try:
        icon_wind_now = [round(source['wind']['deg'])+90]
        if icon_wind_now[0] == '0':
            icon_wind_now[0] = 'None'
    except:
        icon_wind_now = ['None']

    # update time
    dt = datetime.utcfromtimestamp(source['dt']+source['timezone'])
    time_update = [dt.strftime('%H:%M')]
    day = [dt.strftime('%a')]
    date = [dt.strftime('%d.%m')]

    # weather text now
    text_now = [source['weather'][0]['description']]

    # pressure now
    press_now = [str(round(source['main']['pressure']))]
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    # humidity now
    hum_now = [str(source['main']['humidity'])]

    dt1 = datetime.utcfromtimestamp(source['sys']['sunrise']+source['timezone'])
    dt2 = datetime.utcfromtimestamp(source['sys']['sunset']+source['timezone'])
    dt3 = dt2-dt1
    sunrise = dt1.strftime('%H:%M')
    sunset = dt2.strftime('%H:%M')
    sun_duration = ':'.join(str(dt3).split(':')[:2])

    #### weather to several days ####
    source = urlopener(URL_SEVERAL_DAYS, 2)
    if not source:
        return False
    source = json.loads(source)

    wt2 = []
    for data in source['list']:
        t=str(round(data['main']['temp']))
        dt = datetime.utcfromtimestamp(data['dt']+source['city']['timezone'])
        _day=dt.strftime('%a')
        _date=dt.strftime('%d.%m')
        _time=dt.strftime('%H:%M')
        icon='http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
        text=data['weather'][0]['description']
        wind_speed=str(round(data['wind']['speed']))
        wind_direct=wind_direct_convert.convert(data['wind']['deg'])
        wt2.append({
            't':t,
            'day': _day,
            'date': _date,
            'time': _time,
            'icon': icon,
            'text': text,
            'wind_speed': wind_speed,
            'wind_direct': wind_direct
            })

    wt = [[]]
    i = 0
    _date = date[0]
    # true sort by date for local time
    for item in wt2:
        if _date != item['date']:
            i+=1
            wt.append([])
            _date = item['date']
        wt[i].append(item)

    t_day = ['']
    t_night = ['']
    icon = ['']
    text = ['']
    wind_speed = ['']
    wind_direct = ['']

    for i in range(1, len(wt)):
        max_t = None
        min_t = None
        w_s = 0
        # find max min temp
        for item in wt[i]:
            if max_t == None:
                max_t = item['t']
                min_t = item['t']
            if int(item['t']) > int(max_t):
                max_t = item['t']
            if int(item['t']) < int(min_t):
                min_t = item['t']
            w_s += int(item['wind_speed'])
        t_day.append(convert_from_C(max_t))
        t_night.append(convert_from_C(min_t))
        day.append(wt[i][0]['day'])
        date.append(wt[i][0]['date'])
        index = -1 if len(wt[i])<5 else 4
        icon.append(convert(wt[i][index]['icon']))
        text.append(wt[i][index]['text'])
        # avg wind_speed, may be best max-min
        wind_speed.append(convert_from_ms(str(round(w_s/len(wt[i])))))
        wind_direct.append(wt[i][index]['wind_direct'])

    if show_block_tomorrow or show_block_today:
        t_today = [';;;;;', ';;;;;', ';;;;;', ';;;;;']
        icon_today = ['clear.png;clear.png', 'clear.png;clear.png', 'clear.png;clear.png', 'clear.png;clear.png']
        wind_speed_tod = [';;', ';;', ';;', ';;']
        wind_direct_tod = ['', '', '', '']
        
        t_tomorrow = []
        icon_tomorrow = []
        wind_speed_tom = []
        wind_direct_tom = []

        time_of_day_list = (_('Night'), _('Morning'), _('Day'), _('Evening'))

        # today weather
        w_tod = []
        j = 0
        for i in (-7, -5, -3, -1):
            try:
                t_today[j] = convert_from_C(wt[0][i]['t'])
                icon_today[j] = convert(wt[0][i]['icon'])
                wind_speed_tod[j] = convert_from_ms(wt[0][i]['wind_speed'])
                wind_direct_tod[j] = wt[0][i]['wind_direct']
            except:
                pass
            j+=1

        # tomorrow weather
        for i in (1, 3, 5, 7):
            t_tomorrow.append(convert_from_C(wt[1][i]['t']))
            icon_tomorrow.append(convert(wt[1][i]['icon']))
            wind_speed_tom.append(convert_from_ms(wt[1][i]['wind_speed']))
            wind_direct_tom.append(wt[1][i]['wind_direct'])

    if time_update:
        print ('\033[34m>\033[0m '+_('updated on server')+' '+time_update[0]) 
    print ('\033[34m>\033[0m '+_('weather received')+' '+time.strftime('%H:%M', time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
    
Exemple #6
0
def get_weather():
    global time_of_day_list, URL, city_name, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    n = gw_vars.get("n")
    city_id = gw_vars.get("city_id")
    icons_name = gw_vars.get("icons_name")
    URL = "http://www.yr.no/place/%s/forecast.xml" % str(city_id)
    print("\033[34m>\033[0m " + _("Getting weather for") + " " + str(n) + " " + _("days"))

    source = urlopener(URL, 5)
    if not source:
        return False

    URL = "http://www.yr.no/sted/%s" % str(city_id)

    latitude = re.findall('<location.*latitude="(.+?)"', source)
    longitude = re.findall('<location.*longitude="(.+?)"', source)
    URL_CURRENT = "http://api.yr.no/weatherapi/locationforecast/1.9/?lat=%s;lon=%s" % (latitude[0], longitude[0])

    # city
    city_name = re.findall("<name>(.+?)</name>", source)

    # temperature
    temp = re.findall('<temperature unit="celsius" value="(.+?)"', source)
    for i in range(len(temp)):
        temp[i] = convert_from_C(temp[i])
    t_now = [temp[0]]

    # wind
    wind_speed_now = re.findall('<windSpeed mps="(.+?)"', source)
    if wind_speed_now:
        for i in range(len(wind_speed_now)):
            wind_speed_now[i] = convert_from_ms(wind_speed_now[i])

    wind_direct_now = re.findall('<windDirection.*code="(.*?)"', source)

    # icon
    icons = re.findall('<symbol.*var="([mf/]*.+?)"', source)
    for i in range(len(icons)):
        icons[i] = convert(icons[i], icons_name)
    icon_now = [icons[0]]

    # weather text now
    text_now = re.findall('<symbol.*name="(.+?)"', source)

    #### weather to several days ####
    # all days
    dates = re.findall('<time from="\d\d\d\d-(.+?)T', source)

    t_night = [""]
    t_day = [""]
    icon = []
    text = []
    date = [dates[0]]
    wind_speed = [""]
    wind_direct = [""]
    all_periods = re.findall('<time.*period="(\d)"', source)
    for i in range(1, len(all_periods)):
        if all_periods[i] == "0":
            # night
            t_night.append(temp[i])
            pass
        if all_periods[i] == "2":
            # day
            t_day.append(temp[i])
            icon.append(icons[i])
            text.append(text_now[i])
            date.append(dates[i])
            wind_speed.append(wind_speed_now[i])
            wind_direct.append(wind_direct_now[i])
            pass

    #### today tomorrow weather ####
    t_today = ["", "", "", ""]
    t_tomorrow = []
    icon_today = ["", "", "", ""]
    icon_tomorrow = []
    wind_speed_tod = ["", "", "", ""]
    wind_speed_tom = []
    wind_direct_tod = ["", "", "", ""]
    wind_direct_tom = []
    time_of_day_list = (_("Night"), _("Morning"), _("Day"), _("Evening"))
    a1 = ["0", "1", "2", "3"]
    a2 = ["0", "1", "2", "3"]
    for i in range(len(all_periods)):
        if all_periods[i] in a1:
            t_today[int(all_periods[i])] = temp[i]
            icon_today[int(all_periods[i])] = icons[i]
            wind_speed_tod[int(all_periods[i])] = wind_speed_now[i]
            wind_direct_tod[int(all_periods[i])] = wind_direct_now[i]
            if all_periods[i] == "3":
                a1 = []
        else:
            if all_periods[i] in a2:
                t_tomorrow.append(temp[i])
                icon_tomorrow.append(icons[i])
                wind_speed_tom.append(wind_speed_now[i])
                wind_direct_tom.append(wind_direct_now[i])
                if all_periods[i] == "3":
                    break

    #### current weather ####
    source = urlopener(URL_CURRENT, 5)
    if not source:
        return False

    # pressure now
    press_now = re.findall('<pressure.*value="(.+?)"', source)
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    hum_now = re.findall('<humidity value="(.+?)"', source)
    hum_now[0] = str(round(float(hum_now[0])))

    t_now = re.findall('<temperature.*unit="celsius" value="(.+?)"', source)
    t_now[0] = convert_from_C(t_now[0])

    wind_speed_now = re.findall('<windSpeed.*mps="(.+?)"', source)
    wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    wind_direct_now = re.findall('<windDirection.*name="(.+?)"', source)

    icon_wind_now = re.findall('<windDirection.*deg="(.+?)"', source)
    if icon_wind_now[0] == "0":
        icon_wind_now[0] = "None"
    else:
        icon_wind_now[0] = round(float(icon_wind_now[0])) + 90

    print("\033[34m>\033[0m " + _("weather received") + " " + time.strftime("%H:%M", time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
Exemple #7
0
def get_weather():
    global city_name, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    n = gw_vars.get("n")
    city_id = gw_vars.get("city_id")
    icons_name = gw_vars.get("icons_name")
    URL = "http://www.yr.no/place/%s/forecast.xml" % str(city_id)
    print("\033[34m>\033[0m " + _("Getting weather for") + " " + str(n) + " " + _("days"))

    source = urlopener(URL, 5)
    if not source:
        return False

    #### current weather ####
    # city
    city_name = re.findall("<name>(.+?)</name>", source)

    # temperature
    temp = re.findall('<temperature unit="celsius" value="(.+?)"', source)
    for i in range(len(temp)):
        temp[i] = convert_from_C(temp[i])
    t_now = [temp[0]]

    # wind
    wind_speed_now = re.findall('<windSpeed mps="(.+?)"', source)
    if wind_speed_now:
        for i in range(len(wind_speed_now)):
            wind_speed_now[i] = convert_from_ms(wind_speed_now[i])

    wind_direct_now = re.findall('<windDirection.*code="(.*?)"', source)

    # icon
    icons = re.findall('<symbol.*var="([mf/]*.+?)"', source)
    for i in range(len(icons)):
        icons[i] = convert(icons[i], icons_name)
    icon_now = [icons[0]]

    # wind icon
    icon_wind_now = re.findall('<windDirection.*deg="(.+?)"', source)
    if icon_wind_now[0] == "0":
        icon_wind_now[0] = "None"
    else:
        icon_wind_now[0] = round(float(icon_wind_now[0])) + 90

    # update time
    time_update = re.findall("<lastupdate>.*T(.+?)</lastupdate>", source)

    # weather text now
    text_now = re.findall('<symbol.*name="(.+?)"', source)

    # pressure now
    press_now = re.findall('<pressure unit="hPa" value="(.+?)"', source)
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    #### weather to several days ####
    # all days
    dates = re.findall('<time from="\d\d\d\d-(.+?)T', source)

    t_night = [""]
    t_day = [""]
    icon = []
    text = []
    date = [dates[0]]
    wind_speed = [""]
    wind_direct = [""]
    all_periods = re.findall('<time.*period="(\d)"', source)
    for i in range(1, len(all_periods)):
        if all_periods[i] == "0":
            # night
            t_night.append(temp[i])
            pass
        if all_periods[i] == "2":
            # day
            t_day.append(temp[i])
            icon.append(icons[i])
            text.append(text_now[i])
            date.append(dates[i])
            wind_speed.append(wind_speed_now[i])
            wind_direct.append(wind_direct_now[i])
            pass

    if time_update:
        print("\033[34m>\033[0m " + _("updated on server") + " " + time_update[0])
    print("\033[34m>\033[0m " + _("weather received") + " " + time.strftime("%H:%M", time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
Exemple #8
0
def get_weather():
    global city_name, URL, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    APPID = gw_vars.get('appid')
    if not APPID:
        print('\033[1;31m[!]\033[0m Empty API key. Please enter API key')
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    show_block_tomorrow = gw_vars.get('show_block_tomorrow')
    show_block_today = gw_vars.get('show_block_today')
    show_block_add_info = gw_vars.get('show_block_add_info')
    weather_lang = gw_vars.get('weather_lang')
    icons_name = gw_vars.get('icons_name')
    URL = ''
    URL_CURRENT = 'http://api.openweathermap.org/data/2.5/weather?id=%s&lang=%s&units=metric&appid=%s'%(str(city_id), weather_lang, APPID)
    URL_SEVERAL_DAYS = 'http://api.openweathermap.org/data/2.5/forecast/daily?id=%s&lang=%s&units=metric&cnt=%s&appid=%s'%(str(city_id), weather_lang, n+1, APPID)
    URL_TODAY_TOMORROW = 'http://api.openweathermap.org/data/2.5/forecast?id=%s&lang=%s&units=metric&appid=%s'%(str(city_id), weather_lang, APPID)
    print ('\033[34m>\033[0m '+_('Getting weather for')+' '+str(n)+' '+_('days'))

    source = urlopener(URL_CURRENT, 5)
    if not source:
        return False
    source = json.loads(source)

    #### current weather ####
    # city
    city_name = [source['name']]

    # temperature
    t_now = [add_plus(str(round(source['main']['temp'])))]
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = [str(round(source['wind']['speed']))]
    if wind_speed_now:
        wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    try:
        wind_direct_now = [wind_direct_convert.convert(source['wind']['deg'])]
        a = ''
        for i in range(len(wind_direct_now[0])):
            a = a + _(wind_direct_now[0][i])
        wind_direct_now[0] = a
    except:
        wind_direct_now = []

    # icon
    icon_now = ['http://openweathermap.org/img/w/'+source['weather'][0]['icon']+'.png']
    icon_now[0] = convert(icon_now[0], icons_name)

    # wind icon
    try:
        icon_wind_now = [round(source['wind']['deg'])+90]
        if icon_wind_now[0] == '0':
            icon_wind_now[0] = 'None'
    except:
        icon_wind_now = ['None']

    # update time
    dt = datetime.fromtimestamp(source['dt'])
    time_update = [dt.strftime('%H:%M')]

    # weather text now
    text_now = [source['weather'][0]['description']]

    # pressure now
    press_now = [str(round(source['main']['pressure']))]
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    # humidity now
    hum_now = [str(source['main']['humidity'])]

    #### weather to several days ####
    source = urlopener(URL_SEVERAL_DAYS, 5)
    if not source:
        return False
    source = json.loads(source)

    t_day = []
    t_night = []
    day = []
    date = []
    icon = []
    text = []
    wind_speed = []
    wind_direct = []
    chance_of_rain = []

    for data in source['list']:
        t_day.append(add_plus(str(round(data['temp']['day']))))
        t_night.append(add_plus(str(round(data['temp']['night']))))
        dt = datetime.fromtimestamp(data['dt'])
        day.append(dt.strftime('%a'))
        date.append(dt.strftime('%d.%m'))
        icon.append('http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png')
        text.append(data['weather'][0]['description'])
        wind_speed.append(str(round(data['speed'])))
        wind_direct.append(wind_direct_convert.convert(data['deg']))
        chance_of_rain.append(str(data['rain']) if 'rain' in data.keys() else '')

    for j in range(len(wind_direct)):
        a = ''
        for i in range(len(wind_direct[j])):
            a = a + _(wind_direct[j][i])
        wind_direct[j] = a

    for i in range(len(t_day)):
        t_day[i] = convert_from_C(t_day[i])

    for i in range(len(t_night)):
        t_night[i] = convert_from_C(t_night[i])

    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)

    if wind_speed:
        for i in range(len(wind_speed)):
            wind_speed[i] = convert_from_ms(wind_speed[i])

    if show_block_tomorrow or show_block_today:
        source = urlopener(URL_TODAY_TOMORROW, 5)
        if not source:
            return False
        source = json.loads(source)

        t_tomorrow = ['', '', '', '']
        t_today = ['', '', '', '']
        icon_today = ['', '', '', '']
        icon_tomorrow = ['', '', '', '']
        wind_speed_tod = ['', '', '', '']
        wind_direct_tod = ['', '', '', '']
        wind_speed_tom = ['', '', '', '']
        wind_direct_tom = ['', '', '', '']

        day_today = get_day(source['list'][0])

        for data in source['list']:
            day_tommorow = get_day(data)
            if day_tommorow != day_today:
                break

        for data in source['list']:
            day_after_tommorow = get_day(data)
            if day_after_tommorow != day_today and day_after_tommorow != day_tommorow:
                break

        a_dict = {'00:00':3, '06:00':0, '12:00':1, '18:00':2}

        for data in source['list']:
            if get_time(data) in a_dict.keys():
                if get_day(data) == day_today:
                    t_today[a_dict[get_time(data)]] = add_plus(str(round(data['main']['temp'])))
                    icon_today[a_dict[get_time(data)]] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                    wind_speed_tod[a_dict[get_time(data)]] = str(round(data['wind']['speed']))
                    wind_direct_tod[a_dict[get_time(data)]] = wind_direct_convert.convert(data['wind']['deg'])
                if get_day(data) == day_tommorow:
                    t_tomorrow[a_dict[get_time(data)]] = add_plus(str(round(data['main']['temp'])))
                    icon_tomorrow[a_dict[get_time(data)]] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                    wind_speed_tom[a_dict[get_time(data)]] = str(round(data['wind']['speed']))
                    wind_direct_tom[a_dict[get_time(data)]] = wind_direct_convert.convert(data['wind']['deg'])
                    if get_time(data) == '00:00':
                        t_today[3] = add_plus(str(round(data['main']['temp'])))
                        icon_today[3] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                        wind_speed_tod[3] = str(round(data['wind']['speed']))
                        wind_direct_tod[3] = wind_direct_convert.convert(data['wind']['deg'])
                if get_day(data) == day_after_tommorow and get_time(data) == '00:00':
                    t_tomorrow[3] = add_plus(str(round(data['main']['temp'])))
                    icon_tomorrow[3] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                    wind_speed_tom[3] = str(round(data['wind']['speed']))
                    wind_direct_tom[3] = wind_direct_convert.convert(data['wind']['deg'])

        for i in range(len(t_today)):
            if t_today[i] != '':
                t_today[i] = t_today[i]+'°;'+t_today[i]+'°;'+C_to_F(t_today[i])+'°;'+C_to_F(t_today[i])+'°;'+C_to_K(t_today[i])+';'+C_to_K(t_today[i])
            else:
                t_today[i] = ';;;;;'

        for i in range(len(t_tomorrow)):
            if t_tomorrow[i] != '':
                t_tomorrow[i] = t_tomorrow[i]+'°;'+t_tomorrow[i]+'°;'+C_to_F(t_tomorrow[i])+'°;'+C_to_F(t_tomorrow[i])+'°;'+C_to_K(t_tomorrow[i])+';'+C_to_K(t_tomorrow[i])
            else:
                t_tomorrow[i] = ';;;;;'
        for i in range(len(icon_today)):
            if icon_today[i] != '':
                icon_today[i] = convert(icon_today[i], icons_name)
            else:
                icon_today[i] = 'na.png;na.png'
        for i in range(len(icon_tomorrow)):
            if icon_tomorrow[i] != '':
                icon_tomorrow[i] = convert(icon_tomorrow[i], icons_name)
            else:
                icon_tomorrow[i] = 'na.png;na.png'
        for i in range(len(wind_speed_tod)):
            if wind_speed_tod[i] != '':
                wind_speed_tod[i] = convert_from_ms(wind_speed_tod[i])
            else:
                wind_speed_tod[i] = ';;'
        for i in range(len(wind_speed_tom)):
            if wind_speed_tom[i] != '':
                wind_speed_tom[i] = convert_from_ms(wind_speed_tom[i])
        for j in range(len(wind_direct_tod)):
            a=''
            for i in range(len(wind_direct_tod[j])):
                a=a+_(wind_direct_tod[j][i])
            wind_direct_tod[j]=a
        for j in range(len(wind_direct_tom)):
            a=''
            for i in range(len(wind_direct_tom[j])):
                a=a+_(wind_direct_tom[j][i])
            wind_direct_tom[j]=a
    
    if time_update:
        print ('\033[34m>\033[0m '+_('updated on server')+' '+time_update[0]) 
    print ('\033[34m>\033[0m '+_('weather received')+' '+time.strftime('%H:%M', time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
    
Exemple #9
0
def get_weather():
    global city_name, URL, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain, time_of_day_list, sunrise, sunset, sun_duration
    APPID = gw_vars.get('appid')
    if not APPID:
        print('\033[1;31m[!]\033[0m Empty API key. Please enter API key')
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    show_block_tomorrow = gw_vars.get('show_block_tomorrow')
    show_block_today = gw_vars.get('show_block_today')
    show_block_add_info = gw_vars.get('show_block_add_info')
    weather_lang = gw_vars.get('weather_lang')
    icons_name = gw_vars.get('icons_name')
    URL = ''
    URL_CURRENT = 'http://api.openweathermap.org/data/2.5/weather?id=%s&lang=%s&units=metric&appid=%s'%(str(city_id), weather_lang, APPID)
    URL_SEVERAL_DAYS = 'http://api.openweathermap.org/data/2.5/forecast?id=%s&lang=%s&units=metric&appid=%s'%(str(city_id), weather_lang, APPID)
    # URL_SEVERAL_DAYS2 = 'http://api.openweathermap.org/data/2.5/forecast/daily?id=%s&lang=%s&units=metric&cnt=%s&appid=%s'%(str(city_id), weather_lang, n+1, APPID)
    
    # URL_TODAY_TOMORROW = 'http://api.openweathermap.org/data/2.5/forecast?id=%s&lang=%s&units=metric&appid=%s'%(str(city_id), weather_lang, APPID)
    print ('\033[34m>\033[0m '+_('Getting weather for')+' '+str(n)+' '+_('days'))

    source = urlopener(URL_CURRENT, 2)
    if not source:
        return False
    source = json.loads(source)

    #### current weather ####
    # city
    city_name = [source['name']]

    # temperature
    t_now = [add_plus(str(round(source['main']['temp'])))]
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = [str(round(source['wind']['speed']))]
    if wind_speed_now:
        wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    try:
        wind_direct_now = [wind_direct_convert.convert(source['wind']['deg'])]
    except:
        wind_direct_now = []

    # icon
    icon_now = ['http://openweathermap.org/img/w/'+source['weather'][0]['icon']+'.png']
    icon_now[0] = convert(icon_now[0], icons_name)

    # wind icon
    try:
        icon_wind_now = [round(source['wind']['deg'])+90]
        if icon_wind_now[0] == '0':
            icon_wind_now[0] = 'None'
    except:
        icon_wind_now = ['None']

    # update time
    dt = datetime.fromtimestamp(source['dt'])
    time_update = [dt.strftime('%H:%M')]

    # weather text now
    text_now = [source['weather'][0]['description']]

    # pressure now
    press_now = [str(round(source['main']['pressure']))]
    if press_now:
        press_now[0] = convert_from_hPa(press_now[0])

    # humidity now
    hum_now = [str(source['main']['humidity'])]

    dt1 = datetime.fromtimestamp(source['sys']['sunrise'])
    dt2 = datetime.fromtimestamp(source['sys']['sunset'])
    dt3 = dt2-dt1
    sunrise = dt1.strftime('%H:%M')
    sunset = dt2.strftime('%H:%M')
    sun_duration = ':'.join(str(dt3).split(':')[:2])

    #### weather to several days ####
    source = urlopener(URL_SEVERAL_DAYS, 2)
    if not source:
        return False
    source = json.loads(source)

    wt = [[]]
    i = 0
    for data in source['list']:
        t=add_plus(str(round(data['main']['temp'])))
        dt = datetime.fromtimestamp(data['dt']-10)
        day=dt.strftime('%a')
        date=dt.strftime('%d.%m')
        icon='http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
        text=data['weather'][0]['description']
        wind_speed=str(round(data['wind']['speed']))
        wind_direct=wind_direct_convert.convert(data['wind']['deg'])
        if get_time(data) == '00:00' and wt[0] != []:
            i+=1
            wt.append([])
        wt[i].append([t, day, date, icon, text, wind_speed, wind_direct])

    t_day = ['']
    t_night = ['']
    day = [wt[0][0][1]]
    date = [wt[0][0][2]]
    icon = ['']
    text = ['']
    wind_speed = ['']
    wind_direct = ['']

    for i in range(1, len(wt)):
        t_d = None
        t_n = None
        w_s = 0
        for item in wt[i]:
            if t_d == None:
                t_d = item[0]
                t_n = item[0]
            if int(item[0]) > int(t_d):
                t_d = item[0]
            if int(item[0]) < int(t_n):
                t_n = item[0]
            w_s += int(item[5])
        t_day.append(convert_from_C(t_d))
        t_night.append(convert_from_C(t_n))
        day.append(wt[i][0][1])
        date.append(wt[i][0][2])
        index = -1 if len(wt[i])<5 else 4
        icon.append(convert(wt[i][index][3],icons_name))
        text.append(wt[i][index][4])
        wind_speed.append(convert_from_ms(str(round(w_s/len(wt[i])))))
        wind_direct.append(wt[i][index][6])

    if show_block_tomorrow or show_block_today:
        t_tomorrow = ['', '', '', '']
        t_today = ['', '', '', '']
        icon_today = ['', '', '', '']
        icon_tomorrow = ['', '', '', '']
        wind_speed_tod = ['', '', '', '']
        wind_direct_tod = ['', '', '', '']
        wind_speed_tom = ['', '', '', '']
        wind_direct_tom = ['', '', '', '']

        day_today = get_day(source['list'][0])

        for data in source['list']:
            day_tommorow = get_day(data)
            if day_tommorow != day_today:
                break

        for data in source['list']:
            day_after_tommorow = get_day(data)
            if day_after_tommorow != day_today and day_after_tommorow != day_tommorow:
                break

        a_dict = {'03:00':0, '09:00':1, '15:00':2, '21:00':3}

        for data in source['list']:
            if get_time(data) in a_dict.keys():
                if get_day(data) == day_today:
                    t_today[a_dict[get_time(data)]] = add_plus(str(round(data['main']['temp'])))
                    icon_today[a_dict[get_time(data)]] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                    wind_speed_tod[a_dict[get_time(data)]] = str(round(data['wind']['speed']))
                    wind_direct_tod[a_dict[get_time(data)]] = wind_direct_convert.convert(data['wind']['deg'])
                if get_day(data) == day_tommorow:
                    t_tomorrow[a_dict[get_time(data)]] = add_plus(str(round(data['main']['temp'])))
                    icon_tomorrow[a_dict[get_time(data)]] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                    wind_speed_tom[a_dict[get_time(data)]] = str(round(data['wind']['speed']))
                    wind_direct_tom[a_dict[get_time(data)]] = wind_direct_convert.convert(data['wind']['deg'])
                    if get_time(data) == '00:00':
                        t_today[3] = add_plus(str(round(data['main']['temp'])))
                        icon_today[3] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                        wind_speed_tod[3] = str(round(data['wind']['speed']))
                        wind_direct_tod[3] = wind_direct_convert.convert(data['wind']['deg'])
                if get_day(data) == day_after_tommorow and get_time(data) == '00:00':
                    t_tomorrow[3] = add_plus(str(round(data['main']['temp'])))
                    icon_tomorrow[3] = 'http://openweathermap.org/img/w/'+data['weather'][0]['icon']+'.png'
                    wind_speed_tom[3] = str(round(data['wind']['speed']))
                    wind_direct_tom[3] = wind_direct_convert.convert(data['wind']['deg'])

        for i in range(len(t_today)):
            if t_today[i] != '':
                t_today[i] = t_today[i]+'°;'+t_today[i]+'°;'+C_to_F(t_today[i])+'°;'+C_to_F(t_today[i])+'°;'+C_to_K(t_today[i])+';'+C_to_K(t_today[i])
            else:
                t_today[i] = ';;;;;'

        for i in range(len(t_tomorrow)):
            if t_tomorrow[i] != '':
                t_tomorrow[i] = t_tomorrow[i]+'°;'+t_tomorrow[i]+'°;'+C_to_F(t_tomorrow[i])+'°;'+C_to_F(t_tomorrow[i])+'°;'+C_to_K(t_tomorrow[i])+';'+C_to_K(t_tomorrow[i])
            else:
                t_tomorrow[i] = ';;;;;'
        for i in range(len(icon_today)):
            if icon_today[i] != '':
                icon_today[i] = convert(icon_today[i], icons_name)
            else:
                icon_today[i] = 'clear.png;clear.png'
        for i in range(len(icon_tomorrow)):
            if icon_tomorrow[i] != '':
                icon_tomorrow[i] = convert(icon_tomorrow[i], icons_name)
            else:
                icon_tomorrow[i] = 'na.png;na.png'
        for i in range(len(wind_speed_tod)):
            if wind_speed_tod[i] != '':
                wind_speed_tod[i] = convert_from_ms(wind_speed_tod[i])
            else:
                wind_speed_tod[i] = ';;'
        for i in range(len(wind_speed_tom)):
            if wind_speed_tom[i] != '':
                wind_speed_tom[i] = convert_from_ms(wind_speed_tom[i])
    
    time_of_day_list = (_('Night'), _('Morning'), _('Day'), _('Evening'))

    if time_update:
        print ('\033[34m>\033[0m '+_('updated on server')+' '+time_update[0]) 
    print ('\033[34m>\033[0m '+_('weather received')+' '+time.strftime('%H:%M', time.localtime()))

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w