Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 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
Ejemplo n.º 4
0
def get_weather():
    global time_of_day_list, URL, city_name, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    n = gw_vars.get('n')
    city_id = gw_vars.get('city_id')
    icons_name = gw_vars.get('icons_name')
    URL = 'http://www.yr.no/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
Ejemplo n.º 5
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
Ejemplo n.º 6
0
def get_weather():
    global time_of_day_list, URL, city_name, t_now, wind_speed_now, wind_direct_now, icon_now, icon_wind_now, time_update, text_now, press_now, hum_now, t_water_now, t_night, t_night_feel, day, date, t_day, t_day_feel, icon, icon_wind, wind_speed, wind_direct, text, t_tomorrow, t_tomorrow_feel, icon_tomorrow, wind_speed_tom, wind_direct_tom, t_today, t_today_feel, icon_today, wind_speed_tod, wind_direct_tod, chance_of_rain
    n = gw_vars.get("n")
    city_id = gw_vars.get("city_id")
    icons_name = gw_vars.get("icons_name")
    URL = "http://www.yr.no/place/%s/forecast.xml" % str(city_id)
    print("\033[34m>\033[0m " + _("Getting weather for") + " " + str(n) + " " + _("days"))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # write variables
    for i in w.keys():
        w[i] = globals()[i]
    return w
Ejemplo n.º 7
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
    
Ejemplo n.º 8
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
Ejemplo n.º 9
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
Ejemplo n.º 10
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
    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_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] = t_now[0]+'°;'+t_now[0]+'°;'+C_to_F(t_now[0])+'°;'+C_to_F(t_now[0])+'°;'+C_to_K(t_now[0])+';'+C_to_K(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] = str(round(int(press_now[0])*0.75))+' mmHg;'+str(round(int(press_now[0])*0.0295))+' inHg;'+press_now[0]+' hPa'
    
    # 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] = t_day[i]+'°;'+t_day[i]+'°;'+C_to_F(t_day[i])+'°;'+C_to_F(t_day[i])+'°;'+C_to_K(t_day[i])+';'+C_to_K(t_day[i])

    for i in range(len(t_night)):
        t_night[i] = t_night[i]+'°;'+t_night[i]+'°;'+C_to_F(t_night[i])+'°;'+C_to_F(t_night[i])+'°;'+C_to_K(t_night[i])+';'+C_to_K(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
    
Ejemplo n.º 11
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
Ejemplo n.º 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, 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