bitbot-3.11-fork/modules/user_time.py

77 lines
2.4 KiB
Python
Raw Normal View History

#--depends-on commands
#--depends-on location
import datetime, enum
import pytz
2019-04-28 11:12:00 +00:00
from src import ModuleManager, utils
NOLOCATION_USER = "%s doesn't have a location set"
NOLOCATION_NAME = "Unknown location '%s'"
class LocationType(enum.Enum):
USER = 1
NAME = 2
2019-04-28 11:12:00 +00:00
class Module(ModuleManager.BaseModule):
_name = "Time"
2019-07-27 20:09:45 +00:00
def _find_setting(self, event):
query = None
target_user = None
2019-07-27 20:09:45 +00:00
2019-04-28 11:12:00 +00:00
if event["args"]:
query = event["args"]
if len(event["args_split"]) == 1 and event["server"].has_user_id(
event["args_split"][0]):
target_user = event["server"].get_user(event["args_split"][0])
else:
target_user = event["user"]
if target_user:
location = target_user.get_setting("location", None)
if location:
return (LocationType.USER, target_user.nickname,
location["timezone"])
if query:
location = self.exports.get_one("get-location")(query)
if location:
return (LocationType.NAME, location["name"],
location["timezone"])
else:
return LocationType.NAME, event["args"], None
2019-04-28 11:12:00 +00:00
2019-07-27 20:09:45 +00:00
@utils.hook("received.command.time")
@utils.kwarg("help", "Get the time for you or someone else")
@utils.kwarg("usage", "[nickname]")
@utils.kwarg("require_setting", "location")
@utils.kwarg("require_setting_unless", "1")
def time(self, event):
type, name, timezone = self._find_setting(event)
if not timezone == None:
dt = datetime.datetime.now(tz=pytz.timezone(timezone))
2019-11-03 12:48:50 +00:00
utc_offset = (dt.utcoffset().total_seconds()/60)/60
tz = "UTC"
2019-11-03 12:50:47 +00:00
if not utc_offset == 0.0:
if utc_offset > 0:
2019-11-01 16:06:35 +00:00
tz += "+"
2019-11-03 12:48:50 +00:00
tz += "%g" % utc_offset
human = utils.datetime_human(dt)
out = None
if type == LocationType.USER:
2019-11-01 16:06:35 +00:00
out = "Time for %s: %s %s" % (name, human, tz)
else:
2019-11-01 16:06:35 +00:00
out = "It is %s in %s %s" % (human, name, tz)
event["stdout"].write(out)
2019-04-28 11:12:00 +00:00
else:
out = None
if type == LocationType.USER:
out = NOLOCATION_USER
else:
out = NOLOCATION_NAME
event["stderr"].write(out % name)