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
Example #2
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
Example #3
0
def get_weather():
    global time_of_day_list, w, sunrise, sunset, sun_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')
    if weather_lang == 'ru':
        weather_lang = 'ua/ru'
    icons_name = gw_vars.get('icons_name')

    URL_ALL = 'https://www.gismeteo.%s/city/weekly/' % weather_lang + str(
        city_id)
    URL = URL_ALL
    URL_HOURLY = 'https://www.gismeteo.%s/city/hourly/%s' % (weather_lang,
                                                             str(city_id))
    URL_DAILY = 'https://www.gismeteo.%s/city/weekly/%s/#wweekly' % (
        weather_lang, str(city_id))

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

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

    # sun
    rise_set = re.findall('class="astronomy_value">(.*)<', source)
    if rise_set:
        if len(rise_set) == 4:
            sunrise = rise_set[0]
            sunset = rise_set[1]
            sun_duration = rise_set[2]

    #### current weather ####
    w_now = re.findall("type[A-Z].*wrap f_link", source, re.DOTALL)

    # city
    city_name = re.findall('type[A-Z].*\">(.*)<', w_now[0])

    # temperature
    t_now = re.findall('m_temp c.>([&minus;+]*\d+)<', w_now[0])
    for i in range(len(t_now)):
        if t_now[i][0] == '&':
            t_now[i] = '-' + t_now[i][7:]
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = re.findall('m_wind ms.*>(\d+)<', w_now[0])
    if wind_speed_now:
        wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    try:
        wind_direct_now = re.findall('>(.+)</dt', w_now[0])
        wind_direct_now[0] = wind_direct_now[1]
    except:
        wind_direct_now = []

    # icon
    icon_now = re.findall('url\(.*?//(.*?/icons/.*?)\)', w_now[0])
    icon_now[0] = convert(icon_now[0], icons_name)

    # wind icon
    icon_wind_now = re.findall('wind(\d)', w_now[0])
    if icon_wind_now[0] == '0':
        icon_wind_now[0] = 'None'
    else:
        icon_wind_now[0] = int(icon_wind_now[0]) * 45 + 45

    # update time
    time_update = re.findall('data-hr.* (\d?\d:\d\d)\s*</span>', source,
                             re.DOTALL)

    # weather text now
    text_now = re.findall('title=\"(.*?)\"', w_now[0])

    # pressure now
    press_now = re.findall('m_press torr\'>(\d+)<', w_now[0])
    if press_now:
        press_now[0] = convert_from_mmHg(press_now[0])

    # humidity now
    hum_now = re.findall('wicon hum".*>(\d+)<span class="unit"', w_now[0])

    # water temperature now
    try:
        t_water_now = t_now[1] + ';' + str(int(C_to_F(
            t_now[1]))) + ';' + C_to_K(t_now[1])
    except:
        pass

    #### weather to several days ####
    # all days
    w_all_list = re.findall('tbwdaily1.*?rframe wblock wdata', source,
                            re.DOTALL)
    w_all = '\n'.join(w_all_list)
    t_all = re.findall('m_temp c.>([&minus;+]*\d+)<', w_all)
    for i in range(len(t_all)):
        if t_all[i][0] == '&':
            t_all[i] = '-' + t_all[i][7:]
    # all temperature
    t = t_all[::2]
    # all temperature as feel
    t_feel = t_all[1::2]

    # night temperature
    t_night = t[::4]
    t_night_feel = t_feel[::4]
    for i in range(len(t_night)):
        t_night[i] = convert_from_C(t_night[i], t_night_feel[i])

    # day of week, date
    day = re.findall('weekday.>(.*?)<', source)
    date = re.findall('s_date.>(.*?)<', source)

    # day temperature
    t_day = t[2::4]
    t_day_feel = t_feel[2::4]
    for i in range(len(t_day)):
        t_day[i] = convert_from_C(t_day[i], t_day_feel[i])

    # weather icon day
    icons_list = re.findall('src=\".*?//(.*?/icons/.*?)\"', w_all)
    icon = icons_list[2::4]
    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)

    # wind icon
    icon_wind_list = re.findall('wind(\d)', w_all)
    icon_wind = icon_wind_list[2::4]

    # wind
    wind_speed_list = re.findall('m_wind ms.>(\d+)', w_all)
    wind_speed = wind_speed_list[2::4]
    if wind_speed:
        for i in range(len(wind_speed)):
            wind_speed[i] = convert_from_ms(wind_speed[i])
    wind_direct_list = re.findall('>(.+)</dt', w_all)
    wind_direct = wind_direct_list[2::4]
    for i in range(len(wind_direct)):
        wind_direct[i] = wind_direct[i].split('>')[-1]

    # weather text
    text_list = re.findall('cltext.>(.*?)<', w_all)
    text = text_list[2::4]

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

    if show_block_tomorrow:
        #### weather tomorrow ####
        try:
            w_tomorrow = w_all_list[1]
        except:
            f = open(os.path.join(CONFIG_PATH, 'error.html'), 'w')
            f.write(source)
            f.close()
            if timer_bool:
                print('\033[1;31m[!]\033[0m ' + _('Next try in 10 seconds'))
            return False

        # temperature
        t_tomorrow = t[4:8]
        t_tomorrow_feel = t_feel[4:8]
        for i in range(len(t_tomorrow)):
            t_tomorrow[i] = convert_from_C(t_tomorrow[i], t_tomorrow_feel[i])
        # weather icon
        icon_tomorrow = re.findall('src=\".*?//(.*?/icons/.*?)\"', w_tomorrow)
        for i in range(len(icon_tomorrow)):
            icon_tomorrow[i] = convert(icon_tomorrow[i], icons_name)
        # wind
        wind_speed_tom = re.findall('m_wind ms.>(\d+)', w_tomorrow)
        if wind_speed_tom:
            for i in range(len(wind_speed_tom)):
                wind_speed_tom[i] = convert_from_ms(wind_speed_tom[i])
        wind_direct_tom = re.findall('>(.+)</dt', w_tomorrow)
        for i in range(len(wind_direct_tom)):
            wind_direct_tom[i] = wind_direct_tom[i].split('>')[-1]

    if show_block_today:
        #### weather today ####
        w_today = w_all_list[0]
        # temperature
        t_today = t[0:4]
        t_today_feel = t_feel[0:4]
        for i in range(len(t_today)):
            t_today[i] = convert_from_C(t_today[i], t_today_feel[i])
        # weather icon
        icon_today = re.findall('src=\".*?//(.*?/icons/.*?)\"', w_today)
        for i in range(len(icon_today)):
            icon_today[i] = convert(icon_today[i], icons_name)
        # wind
        wind_speed_tod = re.findall('m_wind ms.>(\d+)', w_today)
        if wind_speed_tod:
            for i in range(len(wind_speed_tod)):
                wind_speed_tod[i] = convert_from_ms(wind_speed_tod[i])
        wind_direct_tod = re.findall('>(.+)</dt', w_today)
        for i in range(len(wind_direct_tod)):
            wind_direct_tod[i] = wind_direct_tod[i].split('>')[-1]
    ########

    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
Example #4
0
def get_weather():
    global time_of_day_list, w, sunrise, sunset, sun_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')
    if weather_lang == 'ua/ru':
        weather_lang = 'ru'
    icons_name = gw_vars.get('icons_name')

    URL_ALL = 'https://services.gismeteo.ru/inform-service/inf_chrome/forecast/?lang=%s&city=%s'%(weather_lang, str(city_id))
    
    URL = 'https://www.gismeteo.%s/city/weekly/'%weather_lang + str(city_id)
    URL_HOURLY = 'https://www.gismeteo.%s/city/hourly/%s'%(weather_lang, str(city_id))
    # URL_DAILY = 'https://www.gismeteo.%s/city/weekly/%s/#wweekly'%(weather_lang, str(city_id))

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

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

    # city
    city_name = re.findall(' name="(.*?)"', source)

    # sun
    dt1 = datetime.utcfromtimestamp(int(re.findall('<fact.*?sunrise="(.*?)"', source)[0]))
    dt2 = datetime.utcfromtimestamp(int(re.findall('<fact.*?sunset="(.*?)"', source)[0]))
    dt3 = dt2 - dt1
    sunrise = dt1.strftime('%H:%M')
    sunset = dt2.strftime('%H:%M')
    sun_duration = ':'.join(str(dt3).split(':')[:2])

    # temperature
    t_now = re.findall('<fact.*? t="(.*?)"',source)
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = re.findall('<fact.*? ws="(.*?)"', source)
    wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    s = re.findall('<fact.*? wd="(.*?)"', source)[0]
    wind_direct_now = [wind_direct_convert.convert2(s)]
    if s == '0':
        icon_wind_now = ['None']
    else:
        icon_wind_now = [int(s)*45+45]

    # icon
    icon_now = re.findall('<fact.*? icon="(.*?)"', source)
    icon_now[0] = convert(icon_now[0], icons_name)

    # update time
    time_update = re.findall('<fact.*? valid="(.*?)"', source)
    time_update[0] = time_update[0][-8:-3]

    # weather text now
    text_now = re.findall('<fact.*? descr="(.*?)"', source)

    # pressure now
    press_now = re.findall('<fact.*? p="(.*?)"', source)
    press_now[0] = convert_from_mmHg(press_now[0])

    # humidity now
    hum_now = re.findall('<fact.*? hum="(.*?)"', source)

    # water temperature now
    t_water_now = re.findall('<fact.*? water_t="(.*?)"', source)
    t_water_now = t_water_now[0]+';'+str(int(C_to_F(t_water_now[0])))+';'+C_to_K(t_water_now[0])

    #### weather to several days ####
    # night temperature
    t_night = re.findall('<day.*? tmin="(.*?)"', source)
    for i in range(len(t_night)):
        t_night[i] = convert_from_C(t_night[i], t_night[i])
    # day temperature
    t_day = re.findall('<day.*? tmax="(.*?)"', source)
    for i in range(len(t_day)):
        t_day[i] = convert_from_C(t_day[i], t_day[i])

    # day of week, date
    day = re.findall('<day.*? date="(.*?)"', source)
    day.pop(0)
    for i in range(len(day)):
        dt1 = datetime.strptime(day[i], '%Y-%m-%d')
        day[i] = dt1.strftime('%a')
    date = re.findall('<day.*? date=".*?-(.*?)"', source)
    date.pop(0)
    for i in range(len(date)):
        s = date[i].split('-')
        date[i] = s[1]+'.'+s[0]

    # weather icon day
    icon = re.findall('<day.*? icon="(.*?)"', source, re.DOTALL)
    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)

    # wind
    wind_speed = re.findall('<day.*? ws="(.*?)"', source, re.DOTALL)
    for i in range(len(wind_speed)):
        wind_speed[i] = convert_from_ms(wind_speed[i])
    wind_direct = re.findall('<day.*? wd="(.*?)"', source, re.DOTALL)
    icon_wind = []
    for i in range(len(wind_direct)):
        if wind_direct[i] == '0':
            icon_wind.append('None')
        else:
            icon_wind.append(int(wind_direct[i])*45+45)
        wind_direct[i] = wind_direct_convert.convert2(wind_direct[i])

    # weather text
    text = re.findall('<day.*? descr="(.*?)"', source,  re.DOTALL)

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

    w_today_tomorrow = re.findall('<forecast(.*?)</day>', source,  re.DOTALL)
    
    if show_block_today:
        #### weather today ####
        w_today = w_today_tomorrow[0]
        # temperature
        t_today = re.findall(' t="(.*?)"', w_today)[::2]
        for i in range(len(t_today)):
            t_today[i] = convert_from_C(t_today[i], t_today[i])

        # weather icon
        icon_today = re.findall(' icon="(.*?)"', w_today)[::2]
        for i in range(len(icon_today)):
            icon_today[i] = convert(icon_today[i], icons_name)
        # wind
        wind_speed_tod = re.findall(' ws="(.*?)"', w_today)[::2]
        if wind_speed_tod:
            for i in range(len(wind_speed_tod)):
                wind_speed_tod[i] = convert_from_ms(wind_speed_tod[i])
        wind_direct_tod = re.findall(' wd="(.*?)"', w_today)[::2]
        for i in range(len(wind_direct_tod)):
            wind_direct_tod[i] = wind_direct_convert.convert2(wind_direct_tod[i])

    if show_block_tomorrow:
        #### weather tomorrow ####
        w_tomorrow = w_today_tomorrow[1]
        # temperature
        t_tomorrow = re.findall(' t="(.*?)"', w_tomorrow)[::2]
        for i in range(len(t_tomorrow)):
            t_tomorrow[i] = convert_from_C(t_tomorrow[i], t_tomorrow[i])

        # weather icon
        icon_tomorrow = re.findall(' icon="(.*?)"', w_tomorrow)[::2]
        for i in range(len(icon_tomorrow)):
            icon_tomorrow[i] = convert(icon_tomorrow[i], icons_name)
        # wind
        wind_speed_tom = re.findall(' ws="(.*?)"', w_tomorrow)[::2]
        if wind_speed_tom:
            for i in range(len(wind_speed_tom)):
                wind_speed_tom[i] = convert_from_ms(wind_speed_tom[i])
        wind_direct_tom = re.findall(' wd="(.*?)"', w_tomorrow)[::2]
        for i in range(len(wind_direct_tom)):
            wind_direct_tom[i] = wind_direct_convert.convert2(wind_direct_tom[i])

    ########

    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
Example #5
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
Example #6
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
    
Example #7
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
Example #8
0
def get_weather():
    global w, 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)

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

    source = urlopener(URL_CURRENT, 5)
    if not source:
        return False
    #### current weather ####
    # city
    city_name = re.findall('"current-city"><h1>(.*),', source)

    celsius = re.findall('celsius.*checked', source)

    # temperature
    t_now = re.findall('<span class="temp">(.?\d+)<', source)
    if not celsius:
        t_now[0] = F_to_C(t_now[0])
    # if t_now[0][0] not in ('+', '-', '0'):
    #         t_now[0] = '+'+t_now[0]
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = re.findall("<div style=\".+\">(\d*).*</div>", source)
    if wind_speed_now:
        wind_speed_now[0] = convert_from_kmh(wind_speed_now[0])
    wind_direct_now = re.findall("arrow-lg-(.*)\.png", source)

    # icon
    icon_now = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', source)
    icon_now[0] = icon_now[0][2:]
    if len(icon_now[0])==4:
        icon_now[0]='0'+icon_now[0]
    icon_now[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+icon_now[0]+'.png'
    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('<div class="info"> <span class="cond">(.*)<', source)
    text_now[0]=text_now[0].split('<')[0]

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

        # pressure now
        press_now = re.findall('Pressure.*>(\d+)', source)
        try:
            press_now[0] = str(round(int(press_now[0])*0.75))+' mmHg;'+str(round(int(press_now[0])*0.0295))+' inHg;'+press_now[0]+' hPa'
        except:
            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="lo calendar.*</table>', source, re.DOTALL)

    # day temperature
    t_day = re.findall('<td style="font-weight:bold;">(.*)&#176;', w_all[0])
    for i in range(len(t_day)):
        # if t_day[i][0] not in ('+', '-', '0'):
        #     t_day[i] = '+' + t_day[i]
        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 style="font-weight:bold;">.*\s*<td>(.*)&#176;', w_all[0])
    for i in range(len(t_night)):
        # if t_night[i][0] not in ('+', '-', '0'):
        #     t_night[i] = '+' + t_night[i]
        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('color:.*>(.*)<br', w_all[0])
    date = re.findall('<br />([\d|.\-/]+)<', 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('src=\"(.*png)\" ', w_all[0])
    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)


    # weather text
    text = re.findall('src=.*>(.*)\r', w_all[0])

    chance_of_rain = re.findall('<td style="font-weight:bold;">.*\s*<td>.*\s*<td>(.*)<', w_all[0])
    # if end of month, get days from next month
    if len(t_day)-1<n:
        try:
            next_month = re.findall('href="(.*)&amp;view=table".*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.*</table>', source, re.DOTALL)

            # day temperature
            t_day2 = re.findall('<td style="font-weight:bold;">(.*)&#176;', w_all[0])
            for i in range(len(t_day2)):
                if t_day2[i][0] not in ('+', '-', '0'):
                    t_day2[i] = '+' + t_day2[i]
                if not celsius:
                    t_day2[i] = F_to_C(t_day2[i])
                t_day2[i] = t_day2[i]+'°;'+t_day2[i]+'°;'+C_to_F(t_day2[i])+'°;'+C_to_F(t_day2[i])+'°;'+C_to_K(t_day2[i])+';'+C_to_K(t_day2[i]) 
            t_day.extend(t_day2)

            # night temperature
            t_night2 = re.findall('<td style="font-weight:bold;">.*\s*<td>(.*)&#176;', w_all[0])
            for i in range(len(t_night2)):
                if t_night2[i][0] not in ('+', '-', '0'):
                    t_night2[i] = '+' + t_night2[i]
                if not celsius:
                    t_night2[i] = F_to_C(t_night2[i])
                t_night2[i] = t_night2[i]+'°;'+t_night2[i]+'°;'+C_to_F(t_night2[i])+'°;'+C_to_F(t_night2[i])+'°;'+C_to_K(t_night2[i])+';'+C_to_K(t_night2[i])
            t_night.extend(t_night2)

            # day of week, date
            day2 = re.findall('color:.*>(.*)<br', w_all[0])
            date2 = re.findall('<br />([\d|.\-/]+)<', 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('src=\"(.*png)\" ', w_all[0])
            for i in range(len(icon2)):
                icon2[i] = convert(icon2[i], icons_name)
            icon.extend(icon2)

            # weather text
            text2 = re.findall('src=.*>(.*)\r', w_all[0])
            if text[-1] == '':
                del text[-1]
            chance_of_rain2 = re.findall('<td style="font-weight:bold;">.*\s*<td>.*\s*<td>(.*)<', w_all[0])
            text.extend(text2)
            chance_of_rain.extend(chance_of_rain2)
        except:
            pass

    if show_block_tomorrow:
        #### weather tomorrow ####
        w_night = urlopener('http://www.accuweather.com/en/%s/overnight-weather-forecast/%s?day=2'%(city_id, city_number), 5)
        if not w_night:
            return False

        w_morning = urlopener('http://www.accuweather.com/en/%s/morning-weather-forecast/%s?day=2'%(city_id, city_number))
        if not w_morning:
            return False

        w_day = urlopener('http://www.accuweather.com/en/%s/afternoon-weather-forecast/%s?day=2'%(city_id, city_number))
        if not w_day:
            return False
        
        w_evening = urlopener('http://www.accuweather.com/en/%s/evening-weather-forecast/%s?day=2'%(city_id, city_number))
        if not w_evening:
            return False
        
        t_tomorrow=[]

        t = re.findall('<span class="temp">(.?\d+)<', w_morning)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow.append(t[0])

        t = re.findall('<span class="temp">(.?\d+)<', w_day)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow.append(t[0])

        t = re.findall('<span class="temp">(.?\d+)<', w_evening)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow.append(t[0])

        t = re.findall('<span class="temp">(.?\d+)<', w_night)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow.append(t[0])


        t_tomorrow_low=[]

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_morning)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow_low.append(t[0])

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_day)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow_low.append(t[0])

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_evening)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow_low.append(t[0])

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_night)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_tomorrow_low.append(t[0])

        
        icon_tomorrow=[]

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_morning)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        i[0] = convert(i[0], icons_name)
        icon_tomorrow.append(i[0])

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_day)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        i[0] = convert(i[0], icons_name)
        icon_tomorrow.append(i[0])

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_evening)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        i[0] = convert(i[0], icons_name)
        icon_tomorrow.append(i[0])

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_night)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        i[0] = convert(i[0], icons_name)
        icon_tomorrow.append(i[0])

        
    if show_block_today:
        #### weather today ####
        w_night = urlopener('http://www.accuweather.com/en/%s/overnight-weather-forecast/%s?day=1'%(city_id, city_number), 5)
        if not w_night:
            return False

        w_morning = urlopener('http://www.accuweather.com/en/%s/morning-weather-forecast/%s?day=1'%(city_id, city_number))
        if not w_morning:
            return False

        w_day = urlopener('http://www.accuweather.com/en/%s/afternoon-weather-forecast/%s?day=1'%(city_id, city_number))
        if not w_day:
            return False
        
        w_evening = urlopener('http://www.accuweather.com/en/%s/evening-weather-forecast/%s?day=1'%(city_id, city_number))
        if not w_evening:
            return False
        
        t_today=[]

        t = re.findall('<span class="temp">(.?\d+)<', w_morning)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today.append(t[0])

        t = re.findall('<span class="temp">(.?\d+)<', w_day)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today.append(t[0])

        t = re.findall('<span class="temp">(.?\d+)<', w_evening)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today.append(t[0])

        t = re.findall('<span class="temp">(.?\d+)<', w_night)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today.append(t[0])


        t_today_low=[]

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_morning)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today_low.append(t[0])

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_day)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today_low.append(t[0])

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_evening)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today_low.append(t[0])

        t = re.findall('<span class="lo">Lo (.?\d+)<', w_night)
        if t[0][0] not in ('+', '-', '0'):
                t[0] = '+'+t[0]
        if not celsius:
            t[0] = F_to_C(t[0])
        t[0] = t[0]+'°;'+t[0]+'°;'+C_to_F(t[0])+'°;'+C_to_F(t[0])+'°;'+C_to_K(t[0])+';'+C_to_K(t[0])
        t_today_low.append(t[0])

        
        icon_today=[]

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_morning)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        i[0] = convert(i[0], icons_name)
        icon_today.append(i[0])

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_day)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        i[0] = convert(i[0], icons_name)
        icon_today.append(i[0])

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_evening)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        i[0] = convert(i[0], icons_name)
        icon_today.append(i[0])

        i = re.findall('<div class="forecast">\s*<div class="icon (.*)"></div>', w_night)
        i[0] = i[0][2:-2]
        if len(i[0])==2:
            i[0]='0'+i[0]
        i[0] = 'http://vortex.accuweather.com/adc2010/images/icons-numbered/'+i[0]+'h.png'
        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
Example #9
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
Example #10
0
def get_weather():
    global time_of_day_list, w, sunrise, sunset, sun_duration, 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, 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')
    if weather_lang == 'ru':
        weather_lang = 'ua/ru'
    icons_name = gw_vars.get('icons_name')

    URL_ALL = 'https://www.gismeteo.%s/city/weekly/'%weather_lang + str(city_id)
    URL = URL_ALL
    print ('\033[34m>\033[0m '+_('Getting weather for')+' '+str(n)+' '+_('days'))

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

    # sun
    rise_set = re.findall('class="astronomy_value">(.*)<', source)
    if rise_set:
        if len(rise_set) == 4:
            sunrise = rise_set[0]
            sunset = rise_set[1]
            sun_duration = rise_set[2]
    
    #### current weather ####
    w_now = re.findall("type[A-Z].*wrap f_link", source, re.DOTALL)

    # city
    city_name = re.findall('type[A-Z].*\">(.*)<', w_now[0])

    # temperature
    t_now = re.findall('m_temp c.>([&minus;+]*\d+)<', w_now[0])
    for i in range(len(t_now)):
        if t_now[i][0] == '&':
            t_now[i] = '-' + t_now[i][7:]
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = re.findall('m_wind ms.*>(\d+)<', w_now[0])
    if wind_speed_now:
        wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    try:
        wind_direct_now = re.findall('>(.+)</dt', w_now[0])
        wind_direct_now[0] = wind_direct_now[1]
    except:
        wind_direct_now = []

    # icon
    icon_now = re.findall('url\(.*?//(.*?/icons/.*?)\)', w_now[0])
    icon_now[0] = convert(icon_now[0], icons_name)

    # wind icon
    icon_wind_now = re.findall('wind(\d)', w_now[0])
    if icon_wind_now[0] == '0':
        icon_wind_now[0] = 'None'
    else:
        icon_wind_now[0] = int(icon_wind_now[0])*45+45

    # update time
    time_update = re.findall('data-hr.* (\d?\d:\d\d)\s*</span>', source, re.DOTALL)

    # weather text now
    text_now = re.findall('title=\"(.*?)\"', w_now[0])

    # pressure now
    press_now = re.findall('m_press torr\'>(\d+)<', w_now[0])
    if press_now:
        press_now[0] = convert_from_mmHg(press_now[0])

    # humidity now
    hum_now = re.findall('wicon hum".*>(\d+)<span class="unit"', w_now[0])

    # water temperature now
    try:
        t_water_now = t_now[1]+';'+str(int(C_to_F(t_now[1])))+';'+C_to_K(t_now[1])
    except:
        pass

    #### weather to several days ####
    # all days
    w_all_list = re.findall('tbwdaily1.*?rframe wblock wdata', source, re.DOTALL)
    w_all = '\n'.join(w_all_list)
    t_all = re.findall('m_temp c.>([&minus;+]*\d+)<', w_all)
    for i in range(len(t_all)):
        if t_all[i][0] == '&':
            t_all[i] = '-' + t_all[i][7:]
    # all temperature
    t = t_all[::2]
    # all temperature as feel
    t_feel = t_all[1::2]

    # night temperature
    t_night = t[::4]
    t_night_feel = t_feel[::4]
    for i in range(len(t_night)):
        t_night[i] = convert_from_C(t_night[i], t_night_feel[i])

    # day of week, date
    day = re.findall('weekday.>(.*?)<', source)
    date = re.findall('s_date.>(.*?)<', source)

    # day temperature
    t_day = t[2::4]
    t_day_feel = t_feel[2::4]
    for i in range(len(t_day)):
        t_day[i] = convert_from_C(t_day[i], t_day_feel[i])

    # weather icon day
    icons_list = re.findall('src=\".*?//(.*?/icons/.*?)\"', w_all)
    icon = icons_list[2::4]
    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)

    # wind icon
    icon_wind_list = re.findall('wind(\d)', w_all)
    icon_wind = icon_wind_list[2::4]

    # wind
    wind_speed_list = re.findall('m_wind ms.>(\d+)', w_all)
    wind_speed = wind_speed_list[2::4]
    if wind_speed:
        for i in range(len(wind_speed)):
            wind_speed[i] = convert_from_ms(wind_speed[i])
    wind_direct_list = re.findall('>(.+)</dt', w_all)
    wind_direct = wind_direct_list[2::4]
    for i in range(len(wind_direct)):
        wind_direct[i] = wind_direct[i].split('>')[-1]


    # weather text
    text_list = re.findall('cltext.>(.*?)<', w_all)
    text = text_list[2::4]

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

    if show_block_tomorrow:
        #### weather tomorrow ####
        try:
            w_tomorrow = w_all_list[1]
        except:
            f = open(os.path.join(CONFIG_PATH, 'error.html'), 'w')
            f.write(source)
            f.close()
            if timer_bool:
                print ('\033[1;31m[!]\033[0m '+_('Next try in 10 seconds'))
            return False

        # temperature
        t_tomorrow = t[4:8]
        t_tomorrow_feel = t_feel[4:8]
        for i in range(len(t_tomorrow)):
            t_tomorrow[i] = convert_from_C(t_tomorrow[i], t_tomorrow_feel[i])
        # weather icon
        icon_tomorrow = re.findall('src=\".*?//(.*?/icons/.*?)\"', w_tomorrow)
        for i in range(len(icon_tomorrow)):
            icon_tomorrow[i] = convert(icon_tomorrow[i], icons_name)
        # wind
        wind_speed_tom = re.findall('m_wind ms.>(\d+)', w_tomorrow)
        if wind_speed_tom:
            for i in range(len(wind_speed_tom)):
                wind_speed_tom[i] = convert_from_ms(wind_speed_tom[i])
        wind_direct_tom = re.findall('>(.+)</dt', w_tomorrow)
        for i in range(len(wind_direct_tom)):
            wind_direct_tom[i] = wind_direct_tom[i].split('>')[-1]

    if show_block_today:
        #### weather today ####
        w_today = w_all_list[0]
        # temperature
        t_today = t[0:4]
        t_today_feel = t_feel[0:4]
        for i in range(len(t_today)):
            t_today[i] = convert_from_C(t_today[i], t_today_feel[i])
        # weather icon
        icon_today = re.findall('src=\".*?//(.*?/icons/.*?)\"', w_today)
        for i in range(len(icon_today)):
            icon_today[i] = convert(icon_today[i], icons_name)
        # wind
        wind_speed_tod = re.findall('m_wind ms.>(\d+)', w_today)
        if wind_speed_tod:
            for i in range(len(wind_speed_tod)):
                wind_speed_tod[i] = convert_from_ms(wind_speed_tod[i])
        wind_direct_tod = re.findall('>(.+)</dt', w_today)
        for i in range(len(wind_direct_tod)):
            wind_direct_tod[i] = wind_direct_tod[i].split('>')[-1]
    ########

    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
Example #11
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
Example #12
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
    
Example #13
0
def get_weather():
    global time_of_day_list, w, sunrise, sunset, sun_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')
    if weather_lang == 'ua/ru':
        weather_lang = 'ru'
    icons_name = gw_vars.get('icons_name')

    URL_ALL = 'https://services.gismeteo.ru/inform-service/inf_chrome/forecast/?lang=%s&city=%s'%(weather_lang, str(city_id))

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

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

    # city
    city_name = re.findall(' name="(.*?)"', source)

    # sun
    dt1 = datetime.utcfromtimestamp(int(re.findall('<fact.*?sunrise="(.*?)"', source)[0]))
    dt2 = datetime.utcfromtimestamp(int(re.findall('<fact.*?sunset="(.*?)"', source)[0]))
    dt3 = dt2 - dt1
    sunrise = dt1.strftime('%H:%M')
    sunset = dt2.strftime('%H:%M')
    sun_duration = ':'.join(str(dt3).split(':')[:2])

    # temperature
    t_now = re.findall('<fact.*? t="(.*?)"',source)
    t_now[0] = convert_from_C(t_now[0])

    # wind
    wind_speed_now = re.findall('<fact.*? ws="(.*?)"', source)
    wind_speed_now[0] = convert_from_ms(wind_speed_now[0])
    s = re.findall('<fact.*? wd="(.*?)"', source)[0]
    wind_direct_now = [wind_direct_convert.convert2(s)]
    if s == '0':
        icon_wind_now = ['None']
    else:
        icon_wind_now = [int(s)*45+45]

    # icon
    icon_now = re.findall('<fact.*? icon="(.*?)"', source)
    icon_now[0] = convert(icon_now[0], icons_name)

    # update time
    time_update = re.findall('<fact.*? valid="(.*?)"', source)
    time_update[0] = time_update[0][-8:-3]

    # weather text now
    text_now = re.findall('<fact.*? descr="(.*?)"', source)

    # pressure now
    press_now = re.findall('<fact.*? p="(.*?)"', source)
    press_now[0] = convert_from_mmHg(press_now[0])

    # humidity now
    hum_now = re.findall('<fact.*? hum="(.*?)"', source)

    # water temperature now
    t_water_now = re.findall('<fact.*? water_t="(.*?)"', source)
    t_water_now = t_water_now[0]+';'+str(int(C_to_F(t_water_now[0])))+';'+C_to_K(t_water_now[0])

    #### weather to several days ####
    # night temperature
    t_night = re.findall('<day.*? tmin="(.*?)"', source)
    for i in range(len(t_night)):
        t_night[i] = convert_from_C(t_night[i], t_night[i])
    # day temperature
    t_day = re.findall('<day.*? tmax="(.*?)"', source)
    for i in range(len(t_day)):
        t_day[i] = convert_from_C(t_day[i], t_day[i])

    # day of week, date
    day = re.findall('<day.*? date="(.*?)"', source)
    day.pop(0)
    for i in range(len(day)):
        dt1 = datetime.strptime(day[i], '%Y-%m-%d')
        day[i] = dt1.strftime('%a')
    date = re.findall('<day.*? date=".*?-(.*?)"', source)
    date.pop(0)
    for i in range(len(date)):
        s = date[i].split('-')
        date[i] = s[1]+'.'+s[0]

    # weather icon day
    icon = re.findall('<day.*? icon="(.*?)"', source, re.DOTALL)
    for i in range(len(icon)):
        icon[i] = convert(icon[i], icons_name)

    # wind
    wind_speed = re.findall('<day.*? ws="(.*?)"', source, re.DOTALL)
    for i in range(len(wind_speed)):
        wind_speed[i] = convert_from_ms(wind_speed[i])
    wind_direct = re.findall('<day.*? wd="(.*?)"', source, re.DOTALL)
    icon_wind = []
    for i in range(len(wind_direct)):
        if wind_direct[i] == '0':
            icon_wind.append('None')
        else:
            icon_wind.append(int(wind_direct[i])*45+45)
        wind_direct[i] = wind_direct_convert.convert2(wind_direct[i])

    # weather text
    text = re.findall('<day.*? descr="(.*?)"', source,  re.DOTALL)

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

    w_today_tomorrow = re.findall('<forecast(.*?)</day>', source,  re.DOTALL)
    
    if show_block_today:
        #### weather today ####
        w_today = w_today_tomorrow[0]
        # temperature
        t_today = re.findall(' t="(.*?)"', w_today)[::2]
        for i in range(len(t_today)):
            t_today[i] = convert_from_C(t_today[i], t_today[i])

        # weather icon
        icon_today = re.findall(' icon="(.*?)"', w_today)[::2]
        for i in range(len(icon_today)):
            icon_today[i] = convert(icon_today[i], icons_name)
        # wind
        wind_speed_tod = re.findall(' ws="(.*?)"', w_today)[::2]
        if wind_speed_tod:
            for i in range(len(wind_speed_tod)):
                wind_speed_tod[i] = convert_from_ms(wind_speed_tod[i])
        wind_direct_tod = re.findall(' wd="(.*?)"', w_today)[::2]
        for i in range(len(wind_direct_tod)):
            wind_direct_tod[i] = wind_direct_convert.convert2(wind_direct_tod[i])

    if show_block_tomorrow:
        #### weather tomorrow ####
        w_tomorrow = w_today_tomorrow[1]
        # temperature
        t_tomorrow = re.findall(' t="(.*?)"', w_tomorrow)[::2]
        for i in range(len(t_tomorrow)):
            t_tomorrow[i] = convert_from_C(t_tomorrow[i], t_tomorrow[i])

        # weather icon
        icon_tomorrow = re.findall(' icon="(.*?)"', w_tomorrow)[::2]
        for i in range(len(icon_tomorrow)):
            icon_tomorrow[i] = convert(icon_tomorrow[i], icons_name)
        # wind
        wind_speed_tom = re.findall(' ws="(.*?)"', w_tomorrow)[::2]
        if wind_speed_tom:
            for i in range(len(wind_speed_tom)):
                wind_speed_tom[i] = convert_from_ms(wind_speed_tom[i])
        wind_direct_tom = re.findall(' wd="(.*?)"', w_tomorrow)[::2]
        for i in range(len(wind_direct_tom)):
            wind_direct_tom[i] = wind_direct_convert.convert2(wind_direct_tom[i])

    ########

    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
Example #14
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