aboutsummaryrefslogtreecommitdiff
path: root/actions/weather.py
blob: c652d778cdbf919c1774ea399f863b79d411b8c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import urllib
from urllib.request import urlopen, Request
from urllib.parse import quote
import ssl
from datetime import datetime
import json


key = open("./weatherkey", "r").read().strip()
codes = json.loads(open("./weatherconditions.json", "r").read().strip())


def temp(t):
    return str(t).replace(".", ",").replace(",0", "")


def direction(t):
    if t == "N":
        return "du nord"
    elif t == "S":
        return "du sud"
    elif t == "W":
        return "de l'ouest"
    elif t == "E":
        return "de l'est"
    elif t == "SE":
        return "du sud-est"
    elif t == "NE":
        return "du nord-est"
    elif t == "SW":
        return "du sud-ouest"
    elif t == "NW":
        return "du nord-ouest"


def localizedcode(sel, day):
    now = datetime.now()
    time = int(now.strftime("%H"))

    for code in codes:
        if code['code'] == sel:
            if day == "1":
                return code['languages'][8]['day_text']
            else:
                return code['languages'][8]['night_text']


# noinspection PyUnresolvedReferences
def _action_weather(_input):
    try:
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE

        ip = urlopen(Request("https://ip.me", headers={"User-Agent": "curl/0.0.0"}), context=ctx).read().decode("utf-8")\
            .strip()
        location = json.loads(urlopen(Request("https://ipinfo.io/" + ip + "/json", headers={"User-Agent": "curl/0.0.0"}),
                                      context=ctx).read().decode("utf-8").strip())
        weather = json.loads(urlopen(Request(f"https://api.weatherapi.com/v1/current.json?key={key}&q="
                                             f"{quote(location['city'])}", headers={"User-Agent": "curl/0.0.0"}),
                                      context=ctx).read().decode("utf-8").strip())
        say(f"Actuellement, à {weather['location']['name']}, il fait {temp(weather['current']['temp_c'])} degrés,"
            f"ressenti {temp(weather['current']['feelslike_c'])} degrés, avec un temps"
            f"{localizedcode(weather['current']['condition']['code'], weather['current']['is_day'])}. Le vent souffle à"
            f"{temp(weather['current']['wind_kph'])} kilomètre heure, en direction"
            f"{direction(weather['current']['wind_dir'])}")
    except urllib.error.URLError:
        say("Désolé, je ne parviens pas à accéder à Internet en ce moment. Vérifiez que votre appareil dispose d'une"
            "connexion Internet stable et réessayez.")
    return