Skip to content

Commit 39efba4

Browse files
committed
Preliminary round of cleanup in time.py
1 parent 4090e5b commit 39efba4

File tree

1 file changed

+51
-27
lines changed

1 file changed

+51
-27
lines changed

core/time.py

+51-27
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,89 @@
1-
'''
1+
"""
22
UserFriendlyTime by Rapptz
33
Source:
44
https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/utils/time.py
5-
'''
5+
"""
66

77
import datetime
88
import parsedatetime as pdt
99
from dateutil.relativedelta import relativedelta
1010
from discord.ext import commands
1111
import re
1212

13+
1314
class ShortTime:
14-
compiled = re.compile("""(?:(?P<years>[0-9])(?:years?|y))? # e.g. 2y
15-
(?:(?P<months>[0-9]{1,2})(?:months?|mo))? # e.g. 2months
16-
(?:(?P<weeks>[0-9]{1,4})(?:weeks?|w))? # e.g. 10w
17-
(?:(?P<days>[0-9]{1,5})(?:days?|d))? # e.g. 14d
18-
(?:(?P<hours>[0-9]{1,5})(?:hours?|h))? # e.g. 12h
19-
(?:(?P<minutes>[0-9]{1,5})(?:minutes?|m))? # e.g. 10m
20-
(?:(?P<seconds>[0-9]{1,5})(?:seconds?|s))? # e.g. 15s
15+
compiled = re.compile("""
16+
(?:(?P<years>[0-9])(?:years?|y))? # e.g. 2y
17+
(?:(?P<months>[0-9]{1,2})(?:months?|mo))? # e.g. 9mo
18+
(?:(?P<weeks>[0-9]{1,4})(?:weeks?|w))? # e.g. 10w
19+
(?:(?P<days>[0-9]{1,5})(?:days?|d))? # e.g. 14d
20+
(?:(?P<hours>[0-9]{1,5})(?:hours?|h))? # e.g. 12h
21+
(?:(?P<minutes>[0-9]{1,5})(?:minutes?|m))? # e.g. 10m
22+
(?:(?P<seconds>[0-9]{1,5})(?:seconds?|s))? # e.g. 15s
2123
""", re.VERBOSE)
2224

2325
def __init__(self, argument):
2426
match = self.compiled.fullmatch(argument)
2527
if match is None or not match.group(0):
2628
raise commands.BadArgument('invalid time provided')
2729

28-
data = { k: int(v) for k, v in match.groupdict(default=0).items() }
30+
data = {k: int(v) for k, v in match.groupdict(default='0').items()}
2931
now = datetime.datetime.utcnow()
3032
self.dt = now + relativedelta(**data)
3133

34+
3235
class HumanTime:
3336
calendar = pdt.Calendar(version=pdt.VERSION_CONTEXT_STYLE)
3437

3538
def __init__(self, argument):
3639
now = datetime.datetime.utcnow()
3740
dt, status = self.calendar.parseDT(argument, sourceTime=now)
3841
if not status.hasDateOrTime:
39-
raise commands.BadArgument('invalid time provided, try e.g. "tomorrow" or "3 days"')
42+
raise commands.BadArgument(
43+
'invalid time provided, try e.g. "tomorrow" or "3 days"'
44+
)
4045

4146
if not status.hasTime:
4247
# replace it with the current time
43-
dt = dt.replace(hour=now.hour, minute=now.minute, second=now.second, microsecond=now.microsecond)
48+
dt = dt.replace(hour=now.hour,
49+
minute=now.minute,
50+
second=now.second,
51+
microsecond=now.microsecond)
4452

4553
self.dt = dt
4654
self._past = dt < now
4755

56+
4857
class Time(HumanTime):
4958
def __init__(self, argument):
5059
try:
5160
o = ShortTime(argument)
52-
except Exception as e:
61+
except:
5362
super().__init__(argument)
5463
else:
5564
self.dt = o.dt
5665
self._past = False
5766

67+
5868
class FutureTime(Time):
5969
def __init__(self, argument):
6070
super().__init__(argument)
6171

6272
if self._past:
6373
raise commands.BadArgument('this time is in the past')
6474

75+
6576
class UserFriendlyTime(commands.Converter):
6677
"""That way quotes aren't absolutely necessary."""
6778
def __init__(self, converter=None):
68-
if isinstance(converter, type) and issubclass(converter, commands.Converter):
79+
if isinstance(converter, type) and issubclass(converter,
80+
commands.Converter):
6981
converter = converter()
7082

71-
if converter is not None and not isinstance(converter, commands.Converter):
83+
if converter is not None and not isinstance(converter,
84+
commands.Converter):
7285
raise TypeError('commands.Converter subclass necessary.')
73-
86+
self.dt = self.arg = None
7487
self.converter = converter
7588

7689
async def check_constraints(self, ctx, now, remaining):
@@ -84,21 +97,23 @@ async def check_constraints(self, ctx, now, remaining):
8497
return self
8598

8699
async def convert(self, ctx, argument):
100+
remaining = ''
87101
try:
88102
calendar = HumanTime.calendar
89103
regex = ShortTime.compiled
90104
self.dt = now = datetime.datetime.utcnow()
91105

92106
match = regex.match(argument)
93107
if match is not None and match.group(0):
94-
data = { k: int(v) for k, v in match.groupdict(default=0).items() }
108+
data = {k: int(v) for k, v in
109+
match.groupdict(default='0').items()}
95110
remaining = argument[match.end():].strip()
96111
self.dt = now + relativedelta(**data)
97112
return await self.check_constraints(ctx, now, remaining)
98113

99-
100114
# apparently nlp does not like "from now"
101-
# it likes "from x" in other cases though so let me handle the 'now' case
115+
# it likes "from x" in other cases though
116+
# so let me handle the 'now' case
102117
if argument.endswith('from now'):
103118
argument = argument[:-8].strip()
104119

@@ -123,28 +138,36 @@ async def convert(self, ctx, argument):
123138
return await self.check_constraints(ctx, now, argument)
124139

125140
if begin not in (0, 1) and end != len(argument):
126-
raise commands.BadArgument('Time is either in an inappropriate location, which ' \
127-
'must be either at the end or beginning of your input, ' \
128-
'or I just flat out did not understand what you meant. Sorry.')
141+
raise commands.BadArgument(
142+
'Time is either in an inappropriate location, which must '
143+
'be either at the end or beginning of your input, or I '
144+
'just flat out did not understand what you meant. Sorry.')
129145

130146
if not status.hasTime:
131147
# replace it with the current time
132-
dt = dt.replace(hour=now.hour, minute=now.minute, second=now.second, microsecond=now.microsecond)
148+
dt = dt.replace(hour=now.hour,
149+
minute=now.minute,
150+
second=now.second,
151+
microsecond=now.microsecond)
133152

134153
# if midnight is provided, just default to next day
135154
if status.accuracy == pdt.pdtContext.ACU_HALFDAY:
136155
dt = dt.replace(day=now.day + 1)
137156

138-
self.dt = dt
157+
self.dt = dt
139158

140159
if begin in (0, 1):
141160
if begin == 1:
142161
# check if it's quoted:
143162
if argument[0] != '"':
144-
raise commands.BadArgument('Expected quote before time input...')
163+
raise commands.BadArgument(
164+
'Expected quote before time input...'
165+
)
145166

146167
if not (end < len(argument) and argument[end] == '"'):
147-
raise commands.BadArgument('If the time is quoted, you must unquote it.')
168+
raise commands.BadArgument(
169+
'If the time is quoted, you must unquote it.'
170+
)
148171

149172
remaining = argument[end + 1:].lstrip(' ,.!')
150173
else:
@@ -158,6 +181,7 @@ async def convert(self, ctx, argument):
158181
traceback.print_exc()
159182
raise
160183

184+
161185
def human_timedelta(dt, *, source=None):
162186
now = source or datetime.datetime.utcnow()
163187
if dt > now:
@@ -190,4 +214,4 @@ def human_timedelta(dt, *, source=None):
190214
elif len(output) == 2:
191215
return f'{output[0]} and {output[1]}{suffix}'
192216
else:
193-
return f'{output[0]}, {output[1]} and {output[2]}{suffix}'
217+
return f'{output[0]}, {output[1]} and {output[2]}{suffix}'

0 commit comments

Comments
 (0)