예제 #1
0
파일: time.py 프로젝트: Atte/berrytweaks
def application(environ, start_response):
    if environ['CONTENT_TYPE'] == 'text/plain':
        body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
        coords = (map(float, line.split(' ', 1))
                  for line in body.decode('ascii').split('\n'))
    else:
        form = environ['get_combined']()
        coords = zip(
            map(float, form['lat[]']),
            map(float, form['lng[]']),
        )

    now = datetime.utcnow().replace(microsecond=0)
    utc_now = now.replace(tzinfo=utc)

    out = []
    for lat, lng in coords:
        tz_name = tz_finder.timezone_at(lat=lat, lng=lng)
        if tz_name is None:
            out.append({
                'status': 'FAILED',
                'message': 'Unknown zone',
            })
            continue

        country_code = None
        country_name = None
        for code, zones in country_timezones.items():
            if tz_name in zones:
                country_code = code.upper()
                country_name = country_names[code]
                break

        tz = timezone(tz_name)
        try:
            tz_now = tz.normalize(utc_now.astimezone(tz))
            out.append({
                'status': 'OK',
                'zoneName': tz_name,
                'countryCode': country_code,
                'countryName': country_name,
                'abbreviation': tz.tzname(now),
                'gmtOffset': int(tz.utcoffset(now).total_seconds()),
                'timestamp': int(tz_now.timestamp()),
                'formatted': str(tz_now.replace(tzinfo=None)),
            })
        except AmbiguousTimeError:
            out.append({
                'status': 'FAILED',
                'message': 'ambiguous',
                'zoneName': tz_name,
                'countryCode': country_code,
                'countryName': country_name,
            })

    start_response('200 OK', [
        ('Content-Type', 'application/json'),
        ('Access-Control-Allow-Origin', '*'),
    ])
    yield json.dumps({'results': out}, sort_keys=True, check_circular=False)
예제 #2
0
async def set_default_city(city):
    if city.fwd_from:
        return
    if not Config.OPEN_WEATHER_MAP_APPID:
        return await edit_or_reply(
            city, "`Get an API key from` https://openweathermap.org/ `first.`")
    if not city.pattern_match.group(1):
        CITY = gvarstatus("DEFCITY") or "Delhi"
    else:
        CITY = city.pattern_match.group(1)
    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }
    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                return await edit_or_reply(city, "`Invalid country.`")
            CITY = newcity[0].strip() + "," + countrycode.strip()
    url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={Config.OPEN_WEATHER_MAP_APPID}"
    request = requests.get(url)
    result = json.loads(request.text)
    if request.status_code != 200:
        return await edit_or_reply(city, "`Invalid country.`")
    addgvar("DEFCITY", CITY)
    cityname = result["name"]
    country = result["sys"]["country"]
    fullc_n = c_n[f"{country}"]
    await edit_or_reply(city, f"`Set default city as {cityname}, {fullc_n}.`")
예제 #3
0
async def set_default_city(city):
    """ For .ctime command, change the default
        userbot country for date and time commands. """
    if not city.text.startswith("."):
        return

    if len(OWM_API) < 1:
        await city.edit(
            "**⚠️ Ottieni prima una chiave API da:** https://openweathermap.org/ "
        )
        return

    global DEFCITY
    APPID = OWM_API

    if not city.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await city.edit("**❌ Errore:** `Specifica una città.`")
            return
    else:
        CITY = city.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await city.edit("**❌ Errore:** `Nazione invalida.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await city.edit(f"**❌ Errore:** `Nazione invalida.`")
        return

    DEFCITY = CITY
    cityname = result['name']
    country = result['sys']['country']

    fullc_n = c_n[f"{country}"]

    await city.edit(
        f"**💭 Città di Default impostata su:** `{cityname}, {fullc_n}.`")
예제 #4
0
async def set_default_city(scity):
    """ For .setcity command, change the default
        city for weather command. """
    if environ.get("isSuspended") == "True":
        return
    global city_given
    if not is_mongo_alive() or not is_redis_alive():
        await scity.edit(DB_FAILED)
        return

    if OWM_API is None:
        await scity.edit(NO_API_KEY)
        return

    OpenWeatherAPI = OWM_API

    if not scity.pattern_match.group(1):
        await scity.edit("`Please specify a city to set one as default.`")
        return
    else:
        city = scity.pattern_match.group(1)
        city_given = scity.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in city:
        newcity = city.split(",")
        if len(newcity[1]) == 2:
            city = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await scity.edit(INV_PARAM)
                return
            city = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OpenWeatherAPI}'
    request = requests.get(url)
    result = loads(request.text)

    if request.status_code != 200:
        await scity.edit(INV_PARAM)
        return

    await set_weather(city)
    cityname = result['name']
    country = result['sys']['country']

    fullc_n = c_n[f"{country}"]

    await scity.edit(f"`Set default city as {cityname}, {fullc_n}.`")
예제 #5
0
async def set_default_city(city):
    """ For .ctime command, change the default
        userbot country for date and time commands. """
    if not city.text.startswith("."):
        return

    if len(OWM_API) < 1:
        await city.edit(
            "Get an API key from https://openweathermap.org/ first.")
        return

    global DEFCITY
    APPID = OWM_API

    if not city.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await city.edit("Please specify a city to set one as default.")
            return
    else:
        CITY = city.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await city.edit("Invalid country.")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await city.edit(f"{result['message']}")
        return

    DEFCITY = CITY
    cityname = result['name']
    country = result['sys']['country']

    fullc_n = c_n[f"{country}"]

    await city.edit(f"Set default city as {cityname}, {fullc_n}.")
예제 #6
0
async def set_default_city(city):
    """ For .ctime command, change the default userbot country for date and time commands. """

    if not OWM_API:
        await edit_or_reply(
            city, "`Get an API key from` https://openweathermap.org/ `first.`")
        return

    global DEFCITY
    APPID = OWM_API

    if not city.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await edit_or_reply(
                city, "`Please specify a city to set one as default.`")
            return
    else:
        CITY = city.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                await edit_or_reply(city, "`Invalid country.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}"
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await edit_or_reply(city, f"`Invalid country.`")
        return

    DEFCITY = CITY
    cityname = result["name"]
    country = result["sys"]["country"]

    fullc_n = c_n[f"{country}"]

    await edit_or_reply(city, f"`Set default city as {cityname}, {fullc_n}.`")
예제 #7
0
async def set_default_city(city):
    """ For .setcity command, change the default
        city for weather command. """
    if not is_mongo_alive() or not is_redis_alive():
        await city.edit(DB_FAILED)
        return

    if len(OWM_API) < 1:
        await city.edit(NO_API_KEY)
        return

    APPID = OWM_API

    if not city.pattern_match.group(1):
        await city.edit("`Please specify a city to set one as default.`")
        return
    else:
        CITY = city.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await city.edit(INV_PARAM)
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await city.edit(INV_PARAM)
        return

    await set_weather(CITY)
    cityname = result['name']
    country = result['sys']['country']

    fullc_n = c_n[f"{country}"]

    await city.edit(f"`Set default city as {cityname}, {fullc_n}.`")
예제 #8
0
async def set_default_city(city):
    """ For .setcity command, change the default
        city for weather command. """

    if Config.OPEN_WEATHER_MAP_APPID is None:
        await city.edit("Please set OPEN_WEATHER_MAP_APPID")
        return

    OpenWeatherAPI = Config.OPEN_WEATHER_MAP_APPID

    if not city.pattern_match.group(1):
        await city.edit("`Please specify a city to set one as default.`")
        return
    else:
        city_name = city.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in city_name:
        newcity = city_name.split(",")
        if len(newcity[1]) == 2:
            city_name = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await city.edit("Invalid parameter")
                return
            city_name = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={OpenWeatherAPI}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await city.edit("Invalid paramater")
        return

    await set_weather(city_name)
    cityname = result['name']
    country = result['sys']['country']

    fullc_n = c_n[f"{country}"]

    await city.edit(f"`Set default city as {cityname}, {fullc_n}.`")
예제 #9
0
async def set_default_city(city):
    """ .ctime komutu için, tarih ve saat komutları için varsayılan userbot ülkesini değiştirin. """
    if not OWM_API:
        await edit_or_reply(city,
                            "`Önce` https://openweathermap.org/ `adresinden bir API anahtarı alın.`")
        return
    global DEFCITY
    APPID = OWM_API
    if not city.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await edit_or_reply(city, "`Lütfen varsayılan olarak ayarlamak için bir şehir belirtin.`")
            return
    else:
        CITY = city.pattern_match.group(1)
    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }
    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await edit_or_reply(city, "`Geçersiz ülke.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()
    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)
    if request.status_code != 200:
        await city.edit(f"`Geçersiz ülke.`")
        return
    DEFCITY = CITY
    cityname = result['name']
    country = result['sys']['country']
    fullc_n = c_n[f"{country}"]
    await edit_or_reply(city, f"`Set default city as {cityname}, {fullc_n}.`")
예제 #10
0
async def get_weather(weather):
    """ .weather komutu bir bölgenin hava durumunu OpenWeatherMap üzerinden alır. """

    if not OWM_API:
        await weather.edit(
            "`Önce` https://openweathermap.org/ `adresinden bir API anahtarı almalısın.`")
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit(
                "`WEATHER_DEFCITY değişkeniyle bir şehri varsayılan olarak belirt, ya da komutu yazarken hangi şehrin hava durumunu istediğini de belirt!`"
            )
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit("`Geçersiz ülke.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(f"`Geçersiz ülke.`")
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]

    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await weather.edit(
        f"**Sıcaklık:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**En Düşük Sıcaklık:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**En Yüksek Sıcaklık:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Nem:** `{humidity}%`\n" +
        f"**Rüzgar Hızı:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Gündoğumu:** `{sun(sunrise)}`\n" +
        f"**Günbatımı:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #11
0
async def get_weather(weather):
    if weather.fwd_from:
        return
    if not Config.OPEN_WEATHER_MAP_APPID:
        return await edit_or_reply(
            weather,
            "`Get an API key from` https://openweathermap.org/ `first.`")
    input_str = "".join(weather.text.split(maxsplit=1)[1:])
    if not input_str:
        CITY = gvarstatus("DEFCITY") or "Delhi"
    else:
        CITY = input_str
    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }
    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                return await edit_or_reply(weather, "`Invalid country.`")
            CITY = newcity[0].strip() + "," + countrycode.strip()
    url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={Config.OPEN_WEATHER_MAP_APPID}"
    async with aiohttp.ClientSession() as _session:
        async with _session.get(url) as request:
            requeststatus = request.status
            requesttext = await request.text()
    result = json.loads(requesttext)
    if requeststatus != 200:
        return await edit_or_reply(weather, "`Invalid country.`")
    cityname = result["name"]
    curtemp = result["main"]["temp"]
    humidity = result["main"]["humidity"]
    min_temp = result["main"]["temp_min"]
    max_temp = result["main"]["temp_max"]
    pressure = result["main"]["pressure"]
    feel = result["main"]["feels_like"]
    desc = result["weather"][0]
    desc = desc["main"]
    country = result["sys"]["country"]
    sunrise = result["sys"]["sunrise"]
    sunset = result["sys"]["sunset"]
    wind = result["wind"]["speed"]
    winddir = result["wind"]["deg"]
    cloud = result["clouds"]["all"]
    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
    div = 360 / len(dirs)
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        return datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")

    await edit_or_reply(
        weather,
        f"🌡**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        + f"🥰**Human Feeling** `{celsius(feel)}°C | {fahrenheit(feel)}°F`\n" +
        f"🥶**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"🥵**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"☁️**Humidity:** `{humidity}%`\n" +
        f"🧧**Pressure** `{pressure} hPa`\n" +
        f"🌬**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"⛈**Cloud:** `{cloud} %`\n" + f"🌄**Sunrise:** `{sun(sunrise)}`\n" +
        f"🌅**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`\n",
    )
예제 #12
0
파일: weather.py 프로젝트: sekret666/codeaz
async def get_weather(weather):
    """  """

    if not OWM_API:
        await weather.edit(LANG['NEED_API_KEY'])
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit(LANG['NO_CITY'])
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit(LANG['INVALID_COUNTRY'])
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(LANG['INVALID_COUNTRY'])
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]

    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await weather.edit(
        f"**{LANG['TEMP']}:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**{LANG['MIN_TEMP']}:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**{LANG['MAX_TEMP']}:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**{LANG['HUMIDITY']}:** `{humidity}%`\n" +
        f"**{LANG['WIND_SPEED']}:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n"
        + f"**{LANG['SUNRISE']}:** `{sun(sunrise)}`\n" +
        f"**{LANG['SUNSET']}:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #13
0
def weather(update: Update, context: CallbackContext):
    bot = context.bot
    chat = update.effective_chat
    message = update.effective_message
    city = message.text[len("/weather "):]

    if city:
        APPID = WEATHER_API
        result = None
        timezone_countries = {
            timezone: country
            for country, timezones in c_tz.items() for timezone in timezones
        }

        if "," in city:
            newcity = city.split(",")
            if len(newcity[1]) == 2:
                city = newcity[0].strip() + "," + newcity[1].strip()
            else:
                country = get_tz((newcity[1].strip()).title())
                try:
                    countrycode = timezone_countries[f"{country}"]
                except KeyError:
                    weather.edit("`Invalid country.`")
                    return
                city = newcity[0].strip() + "," + countrycode.strip()
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={APPID}"
        request = get(url)
        result = json.loads(request.text)

        if request.status_code != 200:
            msg = "No weather information for this location!"

        else:

            cityname = result["name"]
            longitude = result["coord"]["lon"]
            latitude = result["coord"]["lat"]
            curtemp = result["main"]["temp"]
            feels_like = result["main"]["feels_like"]
            humidity = result["main"]["humidity"]
            min_temp = result["main"]["temp_min"]
            max_temp = result["main"]["temp_max"]
            country = result["sys"]["country"]
            sunrise = result["sys"]["sunrise"]
            sunset = result["sys"]["sunset"]
            wind = result["wind"]["speed"]
            weath = result["weather"][0]
            desc = weath["main"]
            icon = weath["id"]
            condmain = weath["main"]
            conddet = weath["description"]

            if icon <= 232:  # Rain storm
                icon = "⛈"
            elif icon <= 321:  # Drizzle
                icon = "🌧"
            elif icon <= 504:  # Light rain
                icon = "🌦"
            elif icon <= 531:  # Cloudy rain
                icon = "⛈"
            elif icon <= 622:  # Snow
                icon = "��"
            elif icon <= 781:  # Atmosphere
                icon = "🌪"
            elif icon <= 800:  # Bright
                icon = "☀�"
            elif icon <= 801:  # A little cloudy
                icon = "⛅�"
            elif icon <= 804:  # Cloudy
                icon = "��"

            ctimezone = tz(c_tz[country][0])
            time = (datetime.now(ctimezone).strftime("%A %d %b, %H:%M").lstrip(
                "0").replace(" 0", " "))
            fullc_n = c_n[f"{country}"]
            dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

            kmph = str(wind * 3.6).split(".")
            mph = str(wind * 2.237).split(".")

            def fahrenheit(f):
                temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
                return temp[0]

            def celsius(c):
                temp = str((c - 273.15)).split(".")
                return temp[0]

            def sun(unix):
                xx = (datetime.fromtimestamp(
                    unix, tz=ctimezone).strftime("%H:%M").lstrip("0").replace(
                        " 0", " "))
                return xx

            msg = f"*{cityname}, {fullc_n}*\n"
            msg += f"`Longitude: {longitude}`\n"
            msg += f"`Latitude: {latitude}`\n\n"
            msg += f"• **Time:** `{time}`\n"
            msg += f"• **Temperature:** `{celsius(curtemp)}°C\n`"
            msg += f"• **Feels like:** `{celsius(feels_like)}°C\n`"
            msg += f"• **Condition:** `{condmain}, {conddet}` " + f"{icon}\n"
            msg += f"• **Humidity:** `{humidity}%`\n"
            msg += f"• **Wind:** `{kmph[0]} km/h`\n"
            msg += f"• **Sunrise**: `{sun(sunrise)}`\n"
            msg += f"• **Sunset**: `{sun(sunset)}`"

    else:
        msg = "Please specify a city or country"

    delmsg = message.reply_text(
        text=msg,
        parse_mode=ParseMode.MARKDOWN,
        disable_web_page_preview=True,
    )

    cleartime = get_clearcmd(chat.id, "weather")

    if cleartime:
        context.dispatcher.run_async(delete, delmsg, cleartime.time)
예제 #14
0
async def get_weather(weather):
    """ For .weather command, gets the current weather of a city. """

    if not OWM_API:
        await weather.edit(
            "`Get an API key from` https://openweathermap.org/ `first.`")
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit("`Please specify a city or set one as default.`"
                               )
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit("`Invalid country.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(f"`Invalid country.`")
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    pressure = result['main']['pressure']
    feel = result['main']['feels_like']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']
    cloud = result['clouds']['all']
    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await weather.edit(
        f"🌡**Suhu:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" +
        f"🤔**Perasaan Manusia** `{celsius(feel)}°C | {fahrenheit(feel)}°F`\n" +
        f"🥶**Suhu Minimum:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" +
        f"🥵**Suhu Maximum:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" +
        f"🌫️**Kelembapan:** `{humidity}%`\n" + 
        f"💨**Tekanan** `{pressure} hPa`\n" + 
        f"🌬**Angin:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"☁**Awan:** `{cloud} %`\n" + 
        f"🌄**Terbit:** `{sun(sunrise)}`\n" +
        f"🌇**Terbenam:** `{sun(sunset)}`\n\n\n" + 
        f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + 
        f"`{time}`\n")
예제 #15
0
async def fetch_weather(weather):
    """ For .weather command, gets the current weather of a city. """
    if Config.OPEN_WEATHER_MAP_APPID is None:
        await weather.edit("Please set OPEN_WEATHER_MAP_APPID")
        return

    OpenWeatherAPI = Config.OPEN_WEATHER_MAP_APPID
    saved_props = await get_weather()

    if not weather.pattern_match.group(1):
        if 'weather_city' in saved_props:
            city = saved_props['weather_city']
        else:
            await weather.edit("`Please specify a city or set one as default.`"
                               )
            return
    else:
        city = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in city:
        newcity = city.split(",")
        if len(newcity[1]) == 2:
            city = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit("Invalid paramater")
                return
            city = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OpenWeatherAPI}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit("Invalid parameter")
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(fahr):
        temp = str(((fahr - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(celc):
        temp = str((celc - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        return datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")

    await weather.edit(
        f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Humidity:** `{humidity}%`\n" +
        f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Sunrise:** `{sun(sunrise)}`\n" +
        f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #16
0
async def get_weather(weather):
    """ For .weather command, gets the current weather of a city. """

    if not OWM_API:
        await weather.edit(
            "`Dapatkan API Key dari` https://openweathermap.org/ `dahulu.`")
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit(
                "`Harap tentukan kota atau tetapkan sebagai default menggunakan variabel konfigurasi WEATHER_DEFCITY.`"
            )
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                await weather.edit("`Negara tidak valid.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}"
    request = get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(f"`Negara tidak valid.`")
        return

    cityname = result["name"]
    curtemp = result["main"]["temp"]
    humidity = result["main"]["humidity"]
    min_temp = result["main"]["temp_min"]
    max_temp = result["main"]["temp_max"]
    desc = result["weather"][0]
    desc = desc["main"]
    country = result["sys"]["country"]
    sunrise = result["sys"]["sunrise"]
    sunset = result["sys"]["sunset"]
    wind = result["wind"]["speed"]
    winddir = result["wind"]["deg"]

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]

    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = 360 / len(dirs)
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await weather.edit(
        f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Humidity:** `{humidity}%`\n" +
        f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Sunrise:** `{sun(sunrise)}`\n" +
        f"**Sunset:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #17
0
async def get_weather(weather):
    """ For .weather command, gets the current weather of a city. """

    if not OWM_API:
        await weather.edit(
            "`Obtenha uma chave de API de` https://openweathermap.org/ `primeiro.`"
        )
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit(
                "`Especifique uma cidade ou defina uma como padrão usando o WEATHER_DEFCITY Var no Heroku.`"
            )
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                await weather.edit("`País inválido.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}"
    request = get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(f"`País inválido.`")
        return

    cityname = result["name"]
    curtemp = result["main"]["temp"]
    humidity = result["main"]["humidity"]
    min_temp = result["main"]["temp_min"]
    max_temp = result["main"]["temp_max"]
    desc = result["weather"][0]
    desc = desc["main"]
    country = result["sys"]["country"]
    sunrise = result["sys"]["sunrise"]
    sunset = result["sys"]["sunset"]
    wind = result["wind"]["speed"]
    winddir = result["wind"]["deg"]

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]

    dirs = ["N", "NE", "L", "SE", "S", "SO", "O", "NO"]

    div = 360 / len(dirs)
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await weather.edit(
        f"**Temperatura:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**Temp. Min.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Temp. Max.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Umidade:** `{humidity}%`\n" +
        f"**Vento:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Nascer do Sol:** `{sun(sunrise)}`\n" +
        f"**Pôr do Sol:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #18
0
async def get_weather(weather):

    if not OWM_API:
        return await weather.edit(
            "`Get an API key from` https://openweathermap.org/ `first.`")

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            return await weather.edit(
                "`Please specify a city or set one as default using the WEATHER_DEFCITY config variable.`"
            )
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                return await weather.edit("`Invalid country.`")
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}"
    request = get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        return await weather.edit("`Invalid country.`")

    cityname = result["name"]
    curtemp = result["main"]["temp"]
    humidity = result["main"]["humidity"]
    min_temp = result["main"]["temp_min"]
    max_temp = result["main"]["temp_max"]
    desc = result["weather"][0]
    desc = desc["main"]
    country = result["sys"]["country"]
    sunrise = result["sys"]["sunrise"]
    sunset = result["sys"]["sunset"]
    wind = result["wind"]["speed"]
    winddir = result["wind"]["deg"]

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]

    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = 360 / len(dirs)
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        return datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")

    await weather.edit(
        f"🏠 `{cityname}, {fullc_n}`\n" + f"🕒 `{time}`\n\n" +
        f"**{desc}**\n\n" +
        f"🌡 **Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"🥶 **Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"🥵 **Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"🌫️ **Humidity:** `{humidity}%`\n" +
        f"🌬️ **Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"🌄 **Sunrise:** `{sun(sunrise)}`\n" +
        f"🌅 **Sunset:** `{sun(sunset)}`\n")
예제 #19
0
async def get_weather(weather):
    """ For .weather command, gets the current weather of a city. """

    if not OWM_API:
        await edit_or_reply(
            weather,
            "`Get an API key from` https://openweathermap.org/ `first.`")
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await edit_or_reply(
                weather, "`Please specify a city or set one as default.`")
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                await edit_or_reply(weather, "`Invalid country.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}"
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await edit_or_reply(weather, f"`Invalid country.`")
        return

    cityname = result["name"]
    curtemp = result["main"]["temp"]
    humidity = result["main"]["humidity"]
    min_temp = result["main"]["temp_min"]
    max_temp = result["main"]["temp_max"]
    pressure = result["main"]["pressure"]
    feel = result["main"]["feels_like"]
    desc = result["weather"][0]
    desc = desc["main"]
    country = result["sys"]["country"]
    sunrise = result["sys"]["sunrise"]
    sunset = result["sys"]["sunset"]
    wind = result["wind"]["speed"]
    winddir = result["wind"]["deg"]
    cloud = result["clouds"]["all"]
    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = 360 / len(dirs)
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await edit_or_reply(
        weather,
        f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        + f"**Human Feeling** `{celsius(feel)}°C | {fahrenheit(feel)}°F`\n" +
        f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Humidity:** `{humidity}%`\n" +
        f"**Pressure** `{pressure} hPa`\n" +
        f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Cloud:** `{cloud} %`\n" + f"**Sunrise:** `{sun(sunrise)}`\n" +
        f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`\n")
예제 #20
0
async def weather_get(message: Message):
    """
    bu fonksiyon hava durumu bilgisini alabilir
    """
    OWM_API = Config.OPEN_WEATHER_MAP
    if not OWM_API:
        await message.edit(
            "<code>Hata !! API'yi şuradan alın:</code> "
            "<a href='https://openweathermap.org'>TIKLA</a> "
            "<code>& heroku config vars'a ekleyin</code> (<code>OPEN_WEATHER_MAP</code>)",
            disable_web_page_preview=True,
            parse_mode="html",
            del_in=0)
        return

    APPID = OWM_API

    if not message.input_str:
        CITY = Config.WEATHER_DEFCITY
        if not CITY:
            await message.edit(
                "`Lütfen bir şehir belirtin veya varsayılan olarak ayarlayın!`",
                del_in=0)
            return
    else:
        CITY = message.input_str

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await message.edit("`Geçersiz Ülke.`", del_in=0)
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    async with aiohttp.ClientSession() as ses:
        async with ses.get(url) as res:
            req_status = res.status
            res_text = await res.text()
    result = json.loads(res_text)

    if req_status != 200:
        await message.edit(r"`Geçersiz Ülke.. ¯\_(ツ)_/¯`", del_in=0)
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        return datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")

    await message.edit(
        f"**Sıcaklık:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" +
        f"**Min. Sıcaklık:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Max. Sıcaklık:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Nem oranı:** `{humidity}%`\n" +
        f"**Rüzgar:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Gündoğumu:** `{sun(sunrise)}`\n" +
        f"**Günbatımı:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
    await CHANNEL.log(f"`{CITY}` için hava durumu sonuçları")
예제 #21
0
async def fetch_weather(weather):
    """For .weather command, gets the current weather of a city."""
    if OWM_API is None:
        await weather.edit(NO_API_KEY)
        return

    OpenWeatherAPI = OWM_API
    saved_props = await get_weather() if is_mongo_alive() else None

    if not weather.pattern_match.group(1):
        if "weather_city" in saved_props:
            city = saved_props["weather_city"]
        else:
            await weather.edit("`Please specify a city or set one as default.`"
                               )
            return
    else:
        city = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in city:
        newcity = city.split(",")
        if len(newcity[1]) == 2:
            city = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f"{country}"]
            except KeyError:
                await weather.edit(INV_PARAM)
                return
            city = newcity[0].strip() + "," + countrycode.strip()

    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OpenWeatherAPI}"
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(INV_PARAM)
        return

    cityname = result["name"]
    curtemp = result["main"]["temp"]
    humidity = result["main"]["humidity"]
    min_temp = result["main"]["temp_min"]
    max_temp = result["main"]["temp_max"]
    desc = result["weather"][0]
    desc = desc["main"]
    country = result["sys"]["country"]
    sunrise = result["sys"]["sunrise"]
    sunset = result["sys"]["sunset"]
    wind = result["wind"]["speed"]
    winddir = result["wind"]["deg"]

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = 360 / len(dirs)
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(fahr):
        temp = str(((fahr - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(celc):
        temp = str((celc - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        suntime = datetime.fromtimestamp(unix,
                                         tz=ctimezone).strftime("%I:%M %p")
        return suntime

    await weather.edit(
        f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Humidity:** `{humidity}%`\n" +
        f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Sunrise:** `{sun(sunrise)}`\n" +
        f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #22
0
def weather(bot: Bot, update: Update):
    message = update.effective_message
    chat_id = update.effective_chat.id
    city = message.text[len('/weather '):]
    if city:
        APPID = WEATHER_API
        result = None
        timezone_countries = {
            timezone: country
            for country, timezones in c_tz.items() for timezone in timezones
        }
        if "," in city:
            newcity = city.split(",")
            if len(newcity[1]) == 2:
                city = newcity[0].strip() + "," + newcity[1].strip()
            else:
                country = get_tz((newcity[1].strip()).title())
                try:
                    countrycode = timezone_countries[f'{country}']
                except KeyError:
                    message.reply_text(tld(chat_id, "weather_invalid"))
                    return
                city = newcity[0].strip() + "," + countrycode.strip()
        url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={APPID}'
        request = get(url)
        result = json.loads(request.text)
        if request.status_code != 200:
            info = tld(chat_id, "weather_no_info")
            bot.send_message(chat_id=update.effective_chat.id,
                             text=info,
                             parse_mode=ParseMode.MARKDOWN,
                             disable_web_page_preview=True)
            return

        cityname = result['name']
        curtemp = result['main']['temp']
        humidity = result['main']['humidity']
        min_temp = result['main']['temp_min']
        max_temp = result['main']['temp_max']
        country = result['sys']['country']
        sunrise = result['sys']['sunrise']
        sunset = result['sys']['sunset']
        wind = result['wind']['speed']
        weath = result['weather'][0]
        desc = weath['main']
        icon = weath['id']
        condmain = weath['main']
        conddet = weath['description']

        if icon <= 232:  # Rain storm
            icon = "⛈"
        elif icon <= 321:  # Drizzle
            icon = "🌧"
        elif icon <= 504:  # Light rain
            icon = "🌦"
        elif icon <= 531:  # Cloudy rain
            icon = "⛈"
        elif icon <= 622:  # Snow
            icon = "��"
        elif icon <= 781:  # Atmosphere
            icon = "🌪"
        elif icon <= 800:  # Bright
            icon = "☀�"
        elif icon <= 801:  # A little cloudy
            icon = "⛅�"
        elif icon <= 804:  # Cloudy
            icon = "��"

        ctimezone = tz(c_tz[country][0])
        time = datetime.now(ctimezone).strftime("%A %d %b, %H:%M").lstrip(
            "0").replace(" 0", " ")
        fullc_n = c_n[f"{country}"]
        dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

        kmph = str(wind * 3.6).split(".")
        mph = str(wind * 2.237).split(".")

        def fahrenheit(f):
            temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
            return temp[0]

        def celsius(c):
            temp = str((c - 273.15)).split(".")
            return temp[0]

        def sun(unix):
            xx = datetime.fromtimestamp(
                unix,
                tz=ctimezone).strftime("%H:%M").lstrip("0").replace(" 0", " ")
            return xx

        if city:
            info = f"*{cityname}, {fullc_n}*\n"
            info += f"`{time}`\n\n"
            info += tld(chat_id, "weather_temp") + f"`{celsius(curtemp)}°C\n`"
            info += tld(chat_id, "weather_cond") + \
                f"`{condmain}, {conddet}` " + f"{icon}\n"
            info += tld(chat_id, "weather_hum") + f"`{humidity}%`\n"
            info += tld(chat_id, "weather_wind") + f"`{kmph[0]} km/h`\n"
            info += tld(chat_id, "weather_sunrise") + f"`{sun(sunrise)}`\n"
            info += tld(chat_id, "weather_sunset") + f"`{sun(sunset)}`"
            bot.send_message(chat_id=update.effective_chat.id,
                             text=info,
                             parse_mode=ParseMode.MARKDOWN,
                             disable_web_page_preview=True)
예제 #23
0
async def weather_get(message: Message):
    """
    this function can get weather info
    """
    OWM_API = weather.OPEN_WEATHER_MAP
    if not OWM_API:
        await message.edit(
            "<code>Oops!!get the API from</code> "
            "<a href='https://openweathermap.org'>HERE</a> "
            "<code>& add it to Heroku config vars</code> (<code>OPEN_WEATHER_MAP</code>)",
            disable_web_page_preview=True,
            parse_mode="html",
            del_in=0)
        return

    APPID = OWM_API

    if not message.input_str:
        CITY = weather.WEATHER_DEFCITY
        if not CITY:
            await message.edit(
                "`Please specify a city or set one as default!`", del_in=0)
            return
    else:
        CITY = message.input_str

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await message.edit("`Invalid country.`", del_in=0)
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    async with aiohttp.ClientSession() as ses, ses.get(url) as res:
        req_status = res.status
        res_text = await res.text()
    result = json.loads(res_text)

    if req_status != 200:
        await message.edit(r"`Invalid country.. ¯\_(ツ)_/¯`", del_in=0)
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await message.edit(
        f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Humidity:** `{humidity}%`\n" +
        f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Sunrise:** `{sun(sunrise)}`\n" +
        f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
    await CHANNEL.log(f"check `{CITY}` weather results")
예제 #24
0
async def get_weather(weather):
    """ For .weather command, gets the current weather of a city. """
    if not weather.text.startswith("."):
        return

    if len(OWM_API) < 1:
        await weather.edit(
            "`Get an API key from` https://openweathermap.org/ `first.`")
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit("`Specifica una città o mettine predefinita una.`"
                               )
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit("`Nazione Invalida.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(f"`Nazione Invalida.`")
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await weather.edit(
        f"**🌡Temperatura:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"↳__Minima:__ `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"↳__Massima:__ `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**💧Umidità:** `{humidity}%`\n" +
        f"**🌪Vento:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**🌄Alba:** `{sun(sunrise)}`\n" +
        f"**🌅Tramonto:** `{sun(sunset)}`\n\n\n"+
        f"`🏙{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #25
0
async def get_weather(weather):
    """ .weather komutu için bir şehrin güncel hava durumunu alır. """
    if not OWM_API:
        await edit_or_reply(weather,
                            "`Önce` https://openweathermap.org/ `adresinden bir API anahtarı alın.`")
        return
    APPID = OWM_API
    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await edit_or_reply(weather, "`Lütfen bir şehir belirtin veya varsayılan olarak ayarlayın.`")
            return
    else:
        CITY = weather.pattern_match.group(1)
    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }
    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit("`Geçersiz ülke.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()
    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)
    if request.status_code != 200:
        await weather.edit(f"`Geçersiz ülke.`")
        return
    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    pressure = result['main']['pressure']
    feel = result['main']['feels_like']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']
    cloud = result['clouds']['all']
    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]
    # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    #        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx
    await edit_or_reply(weather,
                        f"🌡**sıcaklık:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" +
                        f"🥰**Hissedilen** `{celsius(feel)}°C | {fahrenheit(feel)}°F`\n" +
                        f"🥶**En düşük sıcaklık.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" +
                        f"🥵**En yüksek sıcaklık.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" +
                        f"☁️**Nem:** `{humidity}%`\n" +
                        f"🧧**Basınç** `{pressure} hPa`\n" +
                        f"🌬**Rüzgar:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
                        f"⛈**Bulut:** `{cloud} %`\n" +
                        f"🌄**gündoğumu:** `{sun(sunrise)}`\n" +
                        f"🌅**Gün batımı:** `{sun(sunset)}`\n\n\n" +
                        f"**{desc}**\n" +
                        f"`{cityname}, {fullc_n}`\n" +
                        f"`{time}`\n")
예제 #26
0
async def get_weather(weather):
    """ For .weather command, gets the current weather of a city. """
    if not weather.text.startswith("."):
        return

    if len(OWM_API) < 1:
        await weather.edit(
            "Get an API key from https://openweathermap.org/ first.")
        return

    APPID = OWM_API

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit("Please specify a city or set one as default.")
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit("Invalid country.")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = requests.get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(f"{result['message']}")
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]

    fahrenheit = str(((curtemp - 273.15) * 9 / 5 + 32)).split(".")
    celsius = str((curtemp - 273.15)).split(".")

    await weather.edit(
        f"**Temperature:** {celsius[0]}°C / {fahrenheit[0]}°F\n" +
        f"**Humidity:** {humidity}%\n" + f"**Wind:** {wind} m/s\n\n\n" +
        f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #27
0
파일: weather.py 프로젝트: Robot770/limited
async def get_weather(weather):
    """ For .weather command, gets the current weather of a city. """

    if not OWM_API:
        await weather.edit(
            "`Get an API key from` https://openweathermap.org/ `first.`")
        return

    APPID = OWM_API
    result = None

    if not weather.pattern_match.group(1):
        CITY = DEFCITY
        if not CITY:
            await weather.edit(
                "`Please specify a city or set one as default using the WEATHER_DEFCITY config variable.`"
            )
            return
    else:
        CITY = weather.pattern_match.group(1)

    timezone_countries = {
        timezone: country
        for country, timezones in c_tz.items() for timezone in timezones
    }

    if "," in CITY:
        newcity = CITY.split(",")
        if len(newcity[1]) == 2:
            CITY = newcity[0].strip() + "," + newcity[1].strip()
        else:
            country = await get_tz((newcity[1].strip()).title())
            try:
                countrycode = timezone_countries[f'{country}']
            except KeyError:
                await weather.edit("`Invalid country.`")
                return
            CITY = newcity[0].strip() + "," + countrycode.strip()

    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
    request = get(url)
    result = json.loads(request.text)

    if request.status_code != 200:
        await weather.edit(f"`Invalid country.`")
        return

    cityname = result['name']
    curtemp = result['main']['temp']
    humidity = result['main']['humidity']
    min_temp = result['main']['temp_min']
    max_temp = result['main']['temp_max']
    desc = result['weather'][0]
    desc = desc['main']
    country = result['sys']['country']
    sunrise = result['sys']['sunrise']
    sunset = result['sys']['sunset']
    wind = result['wind']['speed']
    winddir = result['wind']['deg']

    ctimezone = tz(c_tz[country][0])
    time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
    fullc_n = c_n[f"{country}"]

    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

    div = (360 / len(dirs))
    funmath = int((winddir + (div / 2)) / div)
    findir = dirs[funmath % len(dirs)]
    kmph = str(wind * 3.6).split(".")
    mph = str(wind * 2.237).split(".")

    def fahrenheit(f):
        temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
        return temp[0]

    def celsius(c):
        temp = str((c - 273.15)).split(".")
        return temp[0]

    def sun(unix):
        xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
        return xx

    await weather.edit(
        f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
        +
        f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
        +
        f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
        + f"**Humidity:** `{humidity}%`\n" +
        f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
        f"**Sunrise:** `{sun(sunrise)}`\n" +
        f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
        f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
예제 #28
0
async def get_weather(weather):
    if not weather.text[0].isalpha() and weather.text[0] in ("."):
        if not OWM_API:
            await weather.edit(
                "`Get an API key from` https://openweathermap.org/ `first.`")
            return
        APPID = OWM_API
        result = None
        if not weather.pattern_match.group(1):
            CITY = DEFCITY
            if not CITY:
                await weather.edit(
                    "`Please specify a city or set one as default.`")
                return
        else:
            CITY = weather.pattern_match.group(1)
        timezone_countries = {
            timezone: country
            for country, timezones in c_tz.items() for timezone in timezones
        }
        if "," in CITY:
            newcity = CITY.split(",")
            if len(newcity[1]) == 2:
                CITY = newcity[0].strip() + "," + newcity[1].strip()
            else:
                country = await get_tz((newcity[1].strip()).title())
                try:
                    countrycode = timezone_countries[f'{country}']
                except KeyError:
                    await weather.edit("`Invalid country.`")
                    return
                CITY = newcity[0].strip() + "," + countrycode.strip()
        url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
        request = get(url)
        result = json.loads(request.text)
        if request.status_code != 200:
            await weather.edit(f"`Invalid country.`")
            return

        cityname = result['name']
        curtemp = result['main']['temp']
        humidity = result['main']['humidity']
        min_temp = result['main']['temp_min']
        max_temp = result['main']['temp_max']
        country = result['sys']['country']
        sunrise = result['sys']['sunrise']
        sunset = result['sys']['sunset']
        wind = result['wind']['speed']
        weath = result['weather'][0]
        desc = weath['main']
        icon = weath['id']
        condmain = weath['main']
        conddet = weath['description']

        if icon <= 232:  # Rain storm
            icon = "⛈"
        elif icon <= 321:  # Drizzle
            icon = "🌧"
        elif icon <= 504:  # Light rain
            icon = "🌦"
        elif icon <= 531:  # Cloudy rain
            icon = "⛈"
        elif icon <= 622:  # Snow
            icon = "��"
        elif icon <= 781:  # Atmosphere
            icon = "🌪"
        elif icon <= 800:  # Bright
            icon = "☀�"
        elif icon <= 801:  # A little cloudy
            icon = "⛅�"
        elif icon <= 804:  # Cloudy
            icon = "��"

        ctimezone = tz(c_tz[country][0])
        time = datetime.now(ctimezone).strftime("%A %d %b, %H:%M").lstrip(
            "0").replace(" 0", " ")
        fullc_n = c_n[f"{country}"]
        dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

        kmph = str(wind * 3.6).split(".")
        mph = str(wind * 2.237).split(".")

        def fahrenheit(f):
            temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
            return temp[0]

        def celsius(c):
            temp = str((c - 273.15)).split(".")
            return temp[0]

        def sun(unix):
            xx = datetime.fromtimestamp(
                unix,
                tz=ctimezone).strftime("%H:%M").lstrip("0").replace(" 0", " ")
            return xx

        await weather.edit(f"**{cityname}, {fullc_n}**\n" + f"`{time}`\n\n" +
                           f"**Temperature:** `{celsius(curtemp)}°C\n`" +
                           f"**Condition:** `{condmain}, {conddet}` " +
                           f"{icon}\n" + f"**Humidity:** `{humidity}%`\n" +
                           f"**Wind:** `{kmph[0]} km/h`\n" +
                           f"**Sunrise**: `{sun(sunrise)}`\n" +
                           f"**Sunset**: `{sun(sunset)}`")