Commit d345ca4a authored by Otthorn's avatar Otthorn 🤔

no more use of global variable in weather_bot

parent bd111eb1
......@@ -74,6 +74,5 @@ envs3
*.swp
# Senible data storage
*.env
citations.txt
*.txt
*.ini
import requests
import configparser
from time import strftime
from matrix_bot_api.matrix_bot_api import MatrixBotAPI
from matrix_bot_api.mregex_handler import MRegexHandler
from matrix_bot_api.mcommand_handler import MCommandHandler
def query_weather(query):
url = "http://api.openweathermap.org/data/2.5/weather?appid={}&q={}".format(appid, query)
json_data = requests.get(url).json()
# check for potential errors in contacting API
code = json_data['cod']
if str(code) != "200": # fix strange API behaviour
return "API error " + str(code)
# import all of the variables
weather_main = json_data['weather'][0]['main']
weather_description = json_data['weather'][0]['description']
temp = kelvin_to_celsius(json_data['main']['temp'])
pressure = json_data['main']['pressure']
humidity = json_data['main']['humidity']
temp_min = kelvin_to_celsius(json_data['main']['temp_min'])
temp_max = kelvin_to_celsius(json_data['main']['temp_max'])
wind_speed = json_data['wind']['speed']
clouds = json_data['clouds']['all']
country = json_data['sys']['country']
name = json_data['name']
# create a summary for the weather
summary = """ {}, {} : {}
{:.1f}°C ({:.1f}°C - {:.1f}°C), wind {} m/s, clouds {}%, {} hPa""".format(name,
country, weather_description, temp, temp_min, temp_max, wind_speed,
clouds, pressure)
return summary
def kelvin_to_celsius(T):
"""Convert Kelvin (K) to degree Celsius (°C)"""
return float(T) - 273
def weather_callback(room, event):
args = event['content']['body'].split()
query = " ".join(args[1:])
# Print monitoring information
print("[{}] WEATHER called with query={} in room={}".format(strftime("%d/%m/%Y %H:%M:%S"), query, room.display_name))
summary = query_weather(query)
room.send_text(summary)
def main():
# Load configuration
config = configparser.ConfigParser()
config.read("config.ini")
username = config.get("Weather", "username")
password = config.get("Weather", "password")
server = config.get("Weather", "server")
global appid
appid = config.get("Weather", "appid")
# Start bot
bot = MatrixBotAPI(username, password, server)
# Create the handlers
weather_handler = MCommandHandler("weather", weather_callback)
bot.add_handler(weather_handler)
# Start polling
bot.start_polling()
print("weather_bot started")
while True:
input()
if __name__ == "__main__":
main()
import requests
import configparser
from time import strftime
from matrix_bot_api.matrix_bot_api import MatrixBotAPI
from matrix_bot_api.mregex_handler import MRegexHandler
from matrix_bot_api.mcommand_handler import MCommandHandler
# Inherit the MatrixBotAPI Class to overload it
class MatrixBotAPIWithKey(MatrixBotAPI):
def __init__(self, username, password, server, api_key, rooms=None):
super().__init__(username, password, server, rooms=None)
self.api_key = api_key
def query_weather(self, query):
appid = self.api_key
url = "http://api.openweathermap.org/data/2.5/weather?appid={}&q={}".format(appid, query)
json_data = requests.get(url).json()
# check for potential errors in contacting API
code = json_data['cod']
if str(code) != "200": # fix strange API behaviour
return "API error " + str(code)
# import all of the variables
weather_main = json_data['weather'][0]['main']
weather_description = json_data['weather'][0]['description']
temp = kelvin_to_celsius(json_data['main']['temp'])
pressure = json_data['main']['pressure']
humidity = json_data['main']['humidity']
temp_min = kelvin_to_celsius(json_data['main']['temp_min'])
temp_max = kelvin_to_celsius(json_data['main']['temp_max'])
wind_speed = json_data['wind']['speed']
clouds = json_data['clouds']['all']
country = json_data['sys']['country']
name = json_data['name']
# create a summary for the weather
summary = """ {}, {} : {}
{:.1f}°C ({:.1f}°C - {:.1f}°C), wind {} m/s, clouds {}%, {} hPa""".format(name,
country, weather_description, temp, temp_min, temp_max, wind_speed,
clouds, pressure)
return summary
def weather_callback(self, room, event):
args = event['content']['body'].split()
query = " ".join(args[1:])
# Print monitoring information
print("[{}] WEATHER called with query={} in room={}".format(strftime("%d/%m/%Y %H:%M:%S"), query, room.display_name))
summary = self.query_weather(query)
room.send_text(summary)
def kelvin_to_celsius(T):
"""Convert Kelvin (K) to degree Celsius (°C)"""
return float(T) - 273
def main():
# Load configuration
config = configparser.ConfigParser()
config.read("config.ini")
username = config.get("Weather", "username")
password = config.get("Weather", "password")
server = config.get("Weather", "server")
appid = config.get("Weather", "appid")
# Start bot
bot = MatrixBotAPIWithKey(username, password, server, appid)
# Create the handlers
weather_handler = MCommandHandler("weather", bot.weather_callback)
bot.add_handler(weather_handler)
# Start polling
bot.start_polling()
print("weather_bot started")
while True:
input()
if __name__ == "__main__":
main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment