refactor: use plain http requests to get time from API

This commit is contained in:
Нориэль Крус
2023-07-02 21:46:59 +08:00
committed by GitHub
parent d56ba3e910
commit c46fc67c6c

View File

@@ -1,7 +1,6 @@
import os import os, requests
from typing import Dict from typing import Dict
from WorldTimeAPI import service as serv from datetime import datetime
from .plugin import Plugin from .plugin import Plugin
class WorldTimeApiPlugin(Plugin): class WorldTimeApiPlugin(Plugin):
@@ -13,7 +12,7 @@ class WorldTimeApiPlugin(Plugin):
wta_timezone = os.getenv('WORLDTIME_DEFAULT_TIMEZONE') wta_timezone = os.getenv('WORLDTIME_DEFAULT_TIMEZONE')
if not wta_timezone: if not wta_timezone:
raise ValueError('WORLDTIME_DEFAULT_TIMEZONE environment variable must be set to use WorldTimeApiPlugin') raise ValueError('WORLDTIME_DEFAULT_TIMEZONE environment variable must be set to use WorldTimeApiPlugin')
self.plugin_tz = wta_timezone self.defTz = wta_timezone.split('/');
def get_source_name(self) -> str: def get_source_name(self) -> str:
return "WorldTimeAPI" return "WorldTimeAPI"
@@ -21,17 +20,17 @@ class WorldTimeApiPlugin(Plugin):
def get_spec(self) -> [Dict]: def get_spec(self) -> [Dict]:
return [{ return [{
"name": "worldtimeapi", "name": "worldtimeapi",
"description": f"Get the current time from a given timezone. use 12hr time format in the response. use {self.plugin_tz} if timezone or location is not specified.", "description": f"Get the current time from a given timezone",
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": { "properties": {
"area": { "area": {
"type": "string", "type": "string",
"description": "the continent or region of the location" "description": f"the continent of timezone identifier. use {self.defTz[0]} if not specified."
}, },
"location": { "location": {
"type": "string", "type": "string",
"description": "the city" "description": f"the city/region of timezone identifier. use {self.defTz[1]} if not specified."
} }
}, },
"required": ["area", "location"], "required": ["area", "location"],
@@ -39,17 +38,22 @@ class WorldTimeApiPlugin(Plugin):
}] }]
async def execute(self, function_name, **kwargs) -> Dict: async def execute(self, function_name, **kwargs) -> Dict:
wtime = serv.Client('timezone') areaVal = kwargs.get('area', self.defTz[0])
locVal = kwargs.get('location', self.defTz[1])
requests = {
"area": kwargs['area'],
"location": kwargs['location']
}
response = wtime.get(**requests) url = f'https://worldtimeapi.org/api/timezone/{areaVal}/{locVal}'
try: try:
res = response.datetime wtr = requests.get(url).json().get('datetime')
wtr_obj = datetime.strptime(wtr, "%Y-%m-%dT%H:%M:%S.%f%z")
time_24hr = wtr_obj.strftime("%H:%M:%S")
time_12hr = wtr_obj.strftime("%I:%M:%S %p")
res = {
"24hr": time_24hr,
"12hr": time_12hr
}
except: except:
res = {"result": "No WorldTimeAPI result was found"} res = {"result": "No WorldTimeAPI result was found"}