This repository has no description
3.4 kB
81 lines
1import geoip2.database
2import fileinput
3import json
4import requests
5import os
6import random
7
8
9geoip = geoip2.database.Reader(os.environ['MAXMIND_GEOIP_DB'])
10seen = {}
11output = []
12ips = list(fileinput.input())
13if len(ips) > 5:
14 output.append('weather report.')
15 for ip in fileinput.input():
16 if "80.147.140.51" in ip:
17 output.append(
18 'Weather report for c-base.'
19 'temperature of -270 degrees, '
20 )
21 else:
22 try:
23 location = geoip.city(ip.strip())
24 if location.city.geoname_id not in seen:
25 seen[location.city.geoname_id] = True
26 weather_api_key = os.environ['OPENWEATHER_API_KEY']
27 url = (
28 f'https://api.openweathermap.org/data/2.5/onecall'
29 f'?lat={location.location.latitude}'
30 f'&lon={location.location.longitude}'
31 f'&appid={weather_api_key}'
32 f'&units=metric'
33 )
34 resp = requests.get(url)
35 weather = json.loads(resp.text)
36 output.append(
37 f'{location.city.name}, {location.country.name}. '
38 f'{weather["current"]["weather"][0]["description"]}. '
39 f'{weather["current"]["temp"]:.1f} degrees.'
40 )
41 except: # noqa E722
42 pass
43
44else:
45 for ip in ips:
46 if "80.147.140.51" in ip:
47 output.append(
48 'Weather report for c-base, space. '
49 'It is empty space outside '
50 'with a temperature of -270 degrees, '
51 'a lightspeed of 299792 kilometers per second '
52 'and a humidity of Not a Number percent. '
53 f'The probability of reincarnation is {random.randrange(0, 100)} percent. '
54 )
55 else:
56 try:
57 location = geoip.city(ip.strip())
58 if location.city.geoname_id not in seen:
59 seen[location.city.geoname_id] = True
60 weather_api_key = os.environ['OPENWEATHER_API_KEY']
61 url = (
62 f'https://api.openweathermap.org/data/2.5/onecall'
63 f'?lat={location.location.latitude}'
64 f'&lon={location.location.longitude}'
65 f'&appid={weather_api_key}'
66 f'&units=metric'
67 )
68 resp = requests.get(url)
69 weather = json.loads(resp.text)
70 output.append(
71 f'Weather report for {location.city.name}, {location.country.name}. '
72 f'It is {weather["current"]["weather"][0]["description"]} outside '
73 f'with a temperature of {weather["current"]["temp"]:.1f} degrees, '
74 f'a wind speed of {weather["current"]["wind_speed"]:.1f} meters per second '
75 f'and a humidity of {weather["current"]["humidity"]} percent. '
76 f'The probability of precipitation is {weather["hourly"][0]["pop"] * 100:.0f} percent. '
77 )
78 except: # noqa E722
79 pass
80
81print('\n'.join(output))