83 lines
2.9 KiB
Python
Executable File
83 lines
2.9 KiB
Python
Executable File
#!/usr/bin/python3
|
||
"""
|
||
A simple script that sends the daily weather to a FreeMobile phone
|
||
"""
|
||
import json
|
||
import locale
|
||
import logging
|
||
import os
|
||
import pyowm
|
||
import requests
|
||
import sys
|
||
|
||
class WeatherToFreemobile():
|
||
def __init__(self, config_file):
|
||
logging.info('Load configuration from {}'.format(config_file))
|
||
with open(config_file) as configuration:
|
||
self.config = json.load(configuration)
|
||
logging.info('Setting locale')
|
||
try:
|
||
locale.setlocale(locale.LC_TIME, self.config['locale'])
|
||
except locale.Error:
|
||
logging.warning('Error setting locale {}'.format(self.config['locale']))
|
||
|
||
def send_sms_to_freemobile(self, message):
|
||
"""
|
||
Sends a SMS using the FreeMobile API
|
||
https://mobile.free.fr/moncompte/index.php?page=options
|
||
"""
|
||
data = {
|
||
'user':self.config['freemobile_user'],
|
||
'pass':self.config['freemobile_apikey'],
|
||
'msg':bytes(message,'utf-8').decode('iso-8859-1')
|
||
}
|
||
logging.debug(data)
|
||
|
||
logging.info('Contacting FreeMobile API')
|
||
r = requests.post('https://smsapi.free-mobile.fr/sendmsg', json = data)
|
||
if r.status_code == 200:
|
||
logging.info('SMS sent')
|
||
else:
|
||
logging.warning('SMS *not* sent. Status code %s', r.status_code)
|
||
|
||
def get_weather(self):
|
||
"""
|
||
Gets the current weather from OpenWeatherMap
|
||
"""
|
||
city = self.config['openweathermap_city']
|
||
apikey = self.config['openweathermap_apikey']
|
||
apilanguage = self.config['openweathermap_language']
|
||
number_of_days = self.config['number_of_days']
|
||
|
||
logging.info('Opening OpenWeatherMap API')
|
||
owm = pyowm.OWM(apikey,language=apilanguage)
|
||
|
||
fc = owm.daily_forecast(city,limit=number_of_days)
|
||
f = fc.get_forecast()
|
||
return_message=[]
|
||
for weather in f:
|
||
temp = weather.get_temperature(unit='celsius')
|
||
return_message.append(
|
||
'{} : {} (min {}ºC, max {}ºC, rain:{}mm)'.format(
|
||
weather.get_reference_time('date').strftime('%A %d').title(),
|
||
weather.get_detailed_status(),
|
||
round(float(temp['min'])),
|
||
round(float(temp['max'])),
|
||
weather.get_rain().get('all',0)
|
||
)
|
||
)
|
||
logging.info("Got the following weather: {}".format(return_message))
|
||
return "\n".join(return_message)
|
||
|
||
if __name__ == "__main__":
|
||
logging.basicConfig(level=logging.WARNING, format=' %(asctime)s - %(levelname)s - %(message)s')
|
||
if len(sys.argv) > 1:
|
||
wtf = WeatherToFreemobile(sys.argv[1])
|
||
else:
|
||
config_file = os.path.join(
|
||
os.path.dirname(os.path.realpath(sys.argv[0])),
|
||
'config.json'
|
||
)
|
||
wtf = WeatherToFreemobile(config_file)
|
||
wtf.send_sms_to_freemobile(wtf.get_weather())
|